var aliases = new Ext.util.MixedCollection();
var lastAuctionInfo = new Ext.util.MixedCollection();
var lastTimeInfoList = new Ext.util.MixedCollection();
var lastBidAgentInfo = new Ext.util.MixedCollection();
var fastUpdateInterval = 2000;
var slowUpdateInterval = 15000;
var updateTimeInterval = new Ext.util.MixedCollection();
var minBidList = new Ext.util.MixedCollection();
var updateTimeout = new Ext.util.MixedCollection;
var currencies = new Ext.util.MixedCollection();
var userId;
var auctionIds;
var statusUpdateTimeout;
var statusUpdateInterval = 15000;
var auctionStatusList = new Ext.util.MixedCollection();
var auctionImages = new Ext.util.MixedCollection();
var displayImageIndex = new Ext.util.MixedCollection();

function activateAuction(auctionId, minBid, currency, isRunning) {
    deActivateAuction(auctionId);
    currencies.add(auctionId, currency);
    minBidList.add(auctionId, minBid);
    aliases.add(auctionId, new Array());
    auctionStatusList.add(auctionId, isRunning);
    getAuctionInfo(auctionId);
    updateTime(auctionId);
}

function deActivateAuction(auctionId) {
    lastAuctionInfo.removeKey(auctionId);
    lastTimeInfoList.removeKey(auctionId);
    minBidList.removeKey(auctionId);
    window.clearTimeout(updateTimeout.key(auctionId));
    updateTimeout.removeKey(auctionId);
    window.clearTimeout(updateTimeInterval.key(auctionId));
    updateTimeInterval.removeKey(auctionId);
    aliases.removeKey(auctionId);
    auctionImages.removeKey(auctionId);
    displayImageIndex.removeKey(auctionId);
}

function deActivateAllAuctions() {
    lastAuctionInfo.clear();
    minBidList.clear();
    for (i = 0; i < updateTimeout.getCount(); i++)
        window.clearTimeout(updateTimeout.itemAt(i));
    updateTimeout.clear();
    for (i = 0; i < updateTimeInterval.getCount(); i++)
        window.clearTimeout(updateTimeInterval.itemAt(i));
    updateTimeInterval.clear();
    aliases.clear();    
}

function decodeJSON(stringData) {
    try {
        return Ext.util.JSON.decode(stringData);
    }
    catch (err) {
        yt_alert('ERROR', 'Could not decode ' + stringData + '\n\n The error was: ' + err.description);
    }
}

function quickButtonClick(auctionId, amount) {
    var maxBid = parseInt(getMaxBid(auctionId));
    var currentValue = parseInt(document.getElementById('bidInput_' + auctionId).value);
    if (isNaN(currentValue))
        currentValue = 0;
    var currentBid = maxBid > 0 ? maxBid : lastAuctionInfo.key(auctionId).StartPrice.Amount;
    var newBid = currentBid + parseInt(amount);
    if (currentValue >= currentBid)
        newBid = currentValue + parseInt(amount);

    document.getElementById('bidInput_' + auctionId).value = newBid;
}

function createBid(auctionId) {
    var bid =
  {
      'Amount': document.getElementById('bidInput_' + auctionId).value,
      'Auction': { 'Id': auctionId }
  };
    return bid;
}



function submitBid(auctionId, url) {
    if (!yt_LoggedOn) {
        redirectLogin(auctionId);
        return;
    }
    bid = createBid(auctionId);
    var currentMaxBid = getMaxBid(auctionId);
    var currentMaxBidOwner = getMaxBidOwner(auctionId);
    var valid = true;
    var errorHeader = '';
    var error = '';

    if (bid.Amount > currentMaxBid && yt_CurrentUserId == currentMaxBidOwner) {
        valid = false;
        errorHeader = 'Fel uppstod n&#228;r budet lades';
        error = 'Du har redan h&#246;gsta bud. Vill du l&#228;gga ditt bud &#228;nd&#229;?';
    }

    if (valid) {
        setTimeout("submitBidCallback(" + auctionId + ",'" + url + "')", 10);
        return;
    }

    yt_confirm(errorHeader, error, function(btn) {
        if (btn == 'yes') {
            setTimeout("submitBidCallback(" + auctionId + ",'" + url + "')", 10);
        } 
    });
}

function submitBidCallback(auctionId, url) {
    bid = createBid(auctionId);
    Ext.Ajax.request({
        url: url,
        params: { bid: Ext.util.JSON.encode(bid) },
        method: 'POST',
        success: function(result, request) {
            var bidResult = decodeJSON(result.responseText);
            if (!bidResult.Result)
                yt_alert('Fel uppstod n&#228;r budet lades', bidResult.Message);
            getBids(auctionId);
        },
        failure: function(result, request) {
            yt_alert('Misslyckades', result.responseText);            
        }
    });
}




function getBids(auctionId) {
    Ext.Ajax.request({
        url: 'GetBids.rails',
        params: {
            id: auctionId,
            latestBid: getMaxBid(auctionId)
        },
        method: 'GET',
        timeout: 4000,
        disableCaching: true,
        success: getBids_callback
    });
}

function getMaxBid(auctionId) {
    var result = 0;
    if (document.getElementById('maxBid_' + auctionId))
        result = parseInt(document.getElementById('maxBid_' + auctionId).value);
    return isNaN(result) ? 0 : result;
}
function getMaxBidOwner(auctionId) {
    var result = 0;
    if (document.getElementById('maxBidOwner_' + auctionId))
        result = parseInt(document.getElementById('maxBidOwner_' + auctionId).value);
    return isNaN(result) ? 0 : result;
}

function setMaxBid(auctionId, newBid) {
    if (document.getElementById('maxBid_' + auctionId))
        document.getElementById('maxBid_' + auctionId).value = newBid.Amount;
    if (document.getElementById('maxBidOwner_' + auctionId))
        document.getElementById('maxBidOwner_' + auctionId).value = newBid.UserId;    
}
    

function getBids_callback(result) {
    var bidsInfo = decodeJSON(result.responseText);
    if (!bidsInfo || bidsInfo.Bids.length == 0)
        return;
    var bids = bidsInfo.Bids;
    var auctionId = bidsInfo.AuctionId;
    var bidsDiv = document.getElementById("bidsTable_" + auctionId);
    if (bidsDiv) {
        initBidderNumbers(bidsInfo.BidderIds, auctionId);
        for (i = 0; i < bids.length; i++) {
            bid = bids[i];
            var bidderAlias = (bid.UserId == userId) ? 'Mitt bud' : 'Budgivare ' + getBidderNumber(bid.UserId, auctionId);
            var image = document.createElement("img");
            image.style.width = "8px";
            image.style.height = "11px";
            image.src = yt_StaticWebPath + '/content/images/bidder1.png';
            var bidDiv = document.createElement("div");
            bidDiv.setAttribute('id', 'bid_' + auctionId + '_' + bid.Amount);
            bidDiv.className = (bid.UserId == userId) ? 'myBidder' : 'bidder';
            if (bidsDiv.hasChildNodes()) {
                //Only append bid if it doesn't exist yet
                if (!document.getElementById('bid_' + auctionId + '_' + bid.Amount))
                    bidsDiv.insertBefore(bidDiv, bidsDiv.firstChild);
            }
            else
                bidsDiv.appendChild(bidDiv);
            bidDiv.appendChild(image);
            fixPNG(image);
            bidDiv.innerHTML += "&nbsp;" + bidderAlias + ": " + bid.Amount;
        }
    }
    if(bids.length > 0)
        setMaxBid(auctionId, bids[bids.length - 1]);
    if (getMaxBid(auctionId) >= getBidAgentValue(auctionId))
        disableBidAgent(auctionId);
    update('maxBidLabel_' + auctionId, bids[bids.length - 1].Amount + " " + currencies.key(auctionId));
    update('reached_' + auctionId, bidsInfo.AcceptValueReached ? " <img src='" + yt_StaticWebPath + "/content/images/check.png' onload='fixPNG(this);'/>" : "");
    update('col_maxbid_' + auctionId, bids[bids.length - 1].Amount + " " + currencies.key(auctionId));
    update('col_accept_value_' + auctionId, bidsInfo.AcceptValueReached ? "Uppnått <img src='" + yt_StaticWebPath + "/content/images/check.png' align='texttop' onload='fixPNG(this);'/>" : "Ej uppnått");
    update('col_bidders_' + auctionId, bidsInfo.BidderCount);
}

function initBidderNumbers(userIds, auctionId) {
    for (var i = 0; i < userIds.length; i++)
        getBidderNumber(userIds[i], auctionId);
}
//returns an assigned number for the bidder
function getBidderNumber(userId, auctionId) {
    for (var i = aliases.key(auctionId).length; i--; i >= 0)
        if (aliases.key(auctionId)[i] == userId)
        return i + 1;

    aliases.key(auctionId).push(userId);
    return aliases.key(auctionId).length;
}

function cloneTimeSpan(timespan) {
    this.Days = timespan.Days;
    this.Hours = timespan.Hours;
    this.Minutes = timespan.Minutes;
    this.Seconds = timespan.Seconds;
    this.TotalSeconds = timespan.TotalSeconds;
    this.TotalHours = timespan.TotalHours;
}

function updateTime(auctionId) {
    if (lastTimeInfoList.key(auctionId) != null) {
        try {
            var timeLeft = lastTimeInfoList.key(auctionId);
            var hoursLeft = timeLeft.TotalHours;

            if (hoursLeft < 0)
                update('timeLeft_' + auctionId, "00:00"); // prevent -1 values from being shown
            else if (hoursLeft <= 1)
                update('timeLeft_' + auctionId, ("0" + timeLeft.Minutes).slice(-2) + ":" + ("0" + timeLeft.Seconds).slice(-2));
            else if (hoursLeft < 24)
                update('timeLeft_' + auctionId, ("0" + (timeLeft.Hours)).slice(-2) + ":" + ("0" + timeLeft.Minutes).slice(-2) + ":" + ("0" + timeLeft.Seconds).slice(-2));
            else if (hoursLeft)
                update('timeLeft_' + auctionId, timeLeft.Days + "d, " + timeLeft.Hours + " " + "h");

            var img = document.getElementById('countdownImage_' + auctionId);
            if (timeLeft.TotalSeconds >= 0 && timeLeft.TotalSeconds <= 60) {
                if (img) {
                    img.src = yt_StaticWebPath + '/Content/images/countdown/' + yt_CurrentBrandingFolderName + '/' + timeLeft.Seconds + '.png';
                    img.style.display = '';
                    fixPNG(img);
                }
                if (timeLeft.TotalSeconds <= 0) {
                    closeAuction(auctionId);
                    return;
                }
            } else {
                if (img)
                    img.style.display = 'none';
            }
            timeSynchronizer(auctionId);            

        } catch (e) {
            yt_alert('ERROR', 'Could not update time!\n\n The error was: ' + e);
        }
    }
    updateTimeInterval.add(auctionId, window.setTimeout('updateTime(' + auctionId + ')', 1000));
}

function timeSynchronizer(auctionId) {
    var currLastTimeInfo;
    if (lastTimeInfoList.key(auctionId) != null) {
        
        currLastTimeInfo = lastTimeInfoList.key(auctionId);
        currLastTimeInfo.TotalSeconds -= 1;
        currLastTimeInfo.Seconds -= 1;
                
        if (currLastTimeInfo.Seconds < 0) {
            currLastTimeInfo.Seconds = 59;
            currLastTimeInfo.Minutes -= 1;
        }

        if (currLastTimeInfo.Minutes < 0) {
            currLastTimeInfo.Minutes = 59;
            currLastTimeInfo.Hours -= 1;
        }

        if (currLastTimeInfo.Hours < 0) {
            currLastTimeInfo.Minutes = 0;
            currLastTimeInfo.Hours = 0;
            currLastTimeInfo.Seconds = 0;
        }
    }    
}

function getAuctionInfo(auctionId) {
    window.clearTimeout(updateTimeout.key(auctionId));
    Ext.Ajax.request({
        url: 'GetAuctionInfo.rails',
        params: { id: auctionId },
        method: 'GET',
        timeout: 6000,
        disableCaching: true,
        success: getAuctionInfo_callback,
        failure: function(result,request) {
            window.clearTimeout(updateTimeout.key(auctionId));
            updateTimeout.removeKey(auctionId);
            updateTimeout.add(auctionId, window.setTimeout('getAuctionInfo(' + auctionId + ')', nextUpdateInterval(auctionId)));    
        }
    });    
}

function getAuctionInfo_callback(result) {
    try {
        var auctionInfo = decodeJSON(result.responseText);
        if (auctionInfo != null) {
                
            var auctionId = auctionInfo.AuctionId;
            if (lastAuctionInfo != null && auctionInfo.IsRunning != auctionStatusList.key(auctionId)) {
                auctionStatusList.add(auctionId, auctionInfo.IsRunning);
                if(auctionInfo.IsRunning)
                    startAuction(auctionId);
                if (!auctionInfo.IsRunning)
                    closeAuction(auctionId);
                return;
            }
            if (auctionInfo.MaxBid > 0 && auctionInfo.MaxBid > getMaxBid(auctionId))
                getBids(auctionId);

            if (lastTimeInfoList.key(auctionId) == null)
                lastTimeInfoList.add(auctionId, auctionInfo.TimeLeft);
            lastAuctionInfo.add(auctionId, auctionInfo);
            if (Math.abs(auctionInfo.TimeLeft.TotalSeconds - lastTimeInfoList.key(auctionId).TotalSeconds) >= 2) {
               lastTimeInfoList.add(auctionId, auctionInfo.TimeLeft);                
            }

            update('numberOfBidAgents_' + auctionId, auctionInfo.BidAgentsCount);
            update('bidagents_' + auctionId, auctionInfo.BidAgentsCount > 0 ? auctionInfo.BidAgentsCount : '');
        }
    } finally {
        window.clearTimeout(updateTimeout.key(auctionId));
        updateTimeout.removeKey(auctionId);
        updateTimeout.add(auctionId, window.setTimeout('getAuctionInfo(' + auctionId + ')', nextUpdateInterval(auctionId)));
    }
    
}

function enableBidAgent(auctionId, url) {
    if (!yt_LoggedOn) {
        redirectLogin(auctionId);
        return;
    }
    var bidAgentId = 0;
    if (document.getElementById('bidAgentId_' + auctionId))
        bidAgentId = document.getElementById('bidAgentId_' + auctionId).value;

    var bidAgentValue = parseInt(getBidAgentValue(auctionId));
    if (isNaN(bidAgentValue) || bidAgentValue == 0) {
        yt_alert('Fel uppstod n&#228;r budagenten aktiverades', 'V&#228;nligen ange ett v&#228;rde');
        return;
    }

    var maxBid = parseInt(getMaxBid(auctionId));
    if (bidAgentValue <= maxBid) {
        yt_alert('Fel uppstod n&#228;r budagenten aktiverades', 'V&#228;rdet p&#229; budagenten m&#229;ste vara st&#246;rre &#228;n det h&#246;gsta budet');
        return;
    }

    var buyNowPrice = parseInt(get_value("buyNowPrice_" + auctionId));
    if (bidAgentValue > buyNowPrice) {
        yt_alert('Fel uppstod n&#228;r budagenten aktiverades', 'Du kan inte l&#228;gga en budagent med ett h&#246;gre v&#228;rde &#228;n det fasta priset p&#229; detta objekt.');
        return;
    }

    var bidAgentEnabledInput = document.getElementById("bidAgentEnabledValue_" + auctionId);
    if (bidAgentEnabledInput)
        bidAgentEnabledInput.value = bidAgentValue;
            
    var bidAgent =
				{

				    'Id': bidAgentId,
				    'MaxAmount': bidAgentValue,
				    'Auction': { 'Id': auctionId }
				};

    Ext.Ajax.request({
        url: url,
        params: { BidAgent: Ext.util.JSON.encode(bidAgent) },
        method: 'GET',
        timeout: 8000,
        disableCaching: true,
        success: enableBidAgent_callBack
    });
}

function getBidAgentValue(auctionId) {
    return getIntegerValue('bidAgentValue_' + auctionId);
}

function enableBidAgent_callBack(result) {
    var bidAgentResult = decodeJSON(result.responseText);
    if (!bidAgentResult.Result) {
        yt_alert('Fel uppstod n&#228;r budagenten aktiverades', bidAgentResult.Message);
        return;
    }
    document.getElementById('bidAgentId_' + bidAgentResult.AuctionId).value = bidAgentResult.BidAgentId;
    hide('bidAgentButtonId_' + bidAgentResult.AuctionId);
    show('bidAgentDisableButtonId_' + bidAgentResult.AuctionId);
    hide('bidAgentInput_' + bidAgentResult.AuctionId);
    show('bidAgentEnabledInput_' + bidAgentResult.AuctionId);
    show('bidAgentEnabledText_' + bidAgentResult.AuctionId);
    hide('bidAgentDisabledText_' + bidAgentResult.AuctionId);
    hide('watchedAuctionsImage_' + bidAgentResult.AuctionId);
    show('bidAgentImage_' + bidAgentResult.AuctionId);
    getBids(bidAgentResult.AuctionId);
}

function getIntegerValue(elementName){
    if (!document.getElementById(elementName))
        return 0;

    var value = parseInt(document.getElementById(elementName).value);
    return isNaN(value) ? 0 : value;   
}

function disableBidAgent(auctionId) {
    var bidAgentId = 0;
    if (getBidAgentValue(auctionId) == 0)
        return;
    if (document.getElementById('bidAgentId_' + auctionId))
        bidAgentId = document.getElementById('bidAgentId_' + auctionId).value;

    var bidAgent =
				{

				    'Id': bidAgentId,
				    'Auction': { 'Id': auctionId }
				};

    Ext.Ajax.request({
        url: yt_WebRootPath + '/buyer/bidding/DisableBidAgent.rails',
        params: { BidAgent: Ext.util.JSON.encode(bidAgent) },
        method: 'GET',
        timeout: 8000,
        disableCaching: true,
        success: disableBidAgent_callBack
    });
}

function disableBidAgent_callBack(result) {
    var bidAgentResult = decodeJSON(result.responseText);
    if (!bidAgentResult.Result) {
        yt_alert('Fel uppstod n&#228;r budagenten avaktiverades', bidAgentResult.Message);
        return;
    }
    show('bidAgentButtonId_' + bidAgentResult.AuctionId);
    hide('bidAgentDisableButtonId_' + bidAgentResult.AuctionId);
    show('bidAgentInput_' + bidAgentResult.AuctionId);
    hide('bidAgentEnabledInput_' + bidAgentResult.AuctionId);
    hide('bidAgentEnabledText_' + bidAgentResult.AuctionId);
    show('bidAgentDisabledText_' + bidAgentResult.AuctionId);
    hide('bidAgentImage_' + bidAgentResult.AuctionId);
    if (getIntegerValue('auctionWatchedHidden_' + bidAgentResult.AuctionId))
        show("watchedAuctionsImage_" + bidAgentResult.AuctionId);
}

function submitSearch() {
    deActivateAllAuctions();
    Ext.Ajax.request({
        form: "searchForm",
        success: searchSuccess,
        failure: searchFailure
    });
}

function searchSuccess(result, request) {
    var listDiv = document.getElementById("listInfoSpan");
    listDiv.innerHTML = result.responseText;
    stopOnclick(get_value("auctionIdsHidden").split(","));
    enableCompanyToolTips();
}

function searchFailure(result, request) {
    var listDiv = document.getElementById("listInfoSpan");
    listDiv.innerHTML = "Hittade inget";
}

function view_expand(auctionId, minBid, currency, isRunning) {
    var maxBid = document.getElementById('maxBid_' + auctionId).value;
    var expand = document.getElementById("expand_" + auctionId);
    if (!expand) return;
    if (!expand.style.display.length) {
        deActivateAuction(auctionId);
        hide(expand.id);
        hide("hideexpand_" + auctionId);
        show("viewexpand_" + auctionId);
        hide("details_" + auctionId);
        show("goodsImage_" + auctionId);
        document.getElementById("auctionrow_" + auctionId).className = "odd";
        set_image_src('activeimage_' + auctionId, yt_StaticWebPath + '/Content/images/auctionsnow.gif');
        return;
    }
    show("hideexpand_" + auctionId);
    hide("viewexpand_" + auctionId);
    show("progressexpand_" + auctionId);
    hide("expanddetails_" + auctionId);
    show("expand_" + auctionId);
    hide("goodsImage_" + auctionId);
    document.getElementById("auctionrow_" + auctionId).className = "selected";
    setTimeout("load_expand(" + auctionId + ");", 100);
    setTimeout("activateAuction(" + auctionId + ", " + minBid + ", '" + currency + "', " + isRunning + ");", 200);
}

function view_details(auctionId, url) {
    var details = document.getElementById("details_" + auctionId);
    if (!details) return;
    if (!details.style.display.length) {
        details.style.display = "none";
        document.getElementById("hidedetails_" + auctionId).style.display = "none";
        document.getElementById("viewdetails_" + auctionId).style.display = "";
        return;
    }
    document.getElementById("hidedetails_" + auctionId).style.display = "";
    document.getElementById("viewdetails_" + auctionId).style.display = "none";
    document.getElementById("progressdetails_" + auctionId).style.display = "";
    document.getElementById("detailsdetails_" + auctionId).style.display = "none";
    document.getElementById("details_" + auctionId).style.display = "";
    setTimeout("load_details(" + auctionId + ",'" + url + "');", 100);    
}

function get_value(id, def) {
    var elem = document.getElementById(id);
    return (elem != null ? elem.value : def);
}

function load_expand(auctionId) {
    var expand = document.getElementById("expanddetails_" + auctionId);
    var progressExpand = document.getElementById("progressexpand_" + auctionId);
    var url = get_value("url_expand");
    if (!url.length) url = "AuctionExpanded.rails";
    Ext.Ajax.request({
        url: url,
        params: { id: auctionId },
        method: "GET",
        success: function(result, request) {
            progressExpand.style.display = "none";
            expand.innerHTML = result.responseText;
            expand.style.display = "";
            set_image_src('activeimage_' + auctionId, yt_StaticWebPath + '/Content/images/auctionsnowselected.png');
            var resultExpandedActiveScript = document.getElementById("result_expanded_active_script_" + auctionId);
            if (resultExpandedActiveScript)
                eval(resultExpandedActiveScript.innerHTML);
            enableUserToolTip(auctionId);
            enableAuctionToolTips(auctionId);
            fixPNG(document.getElementById('activeimage_' + auctionId));
        },
        failure: function(result, request) {
            progressExpand.style.display = "none";
            expand.style.display = "none";
            yt_alert("Misslyckades", result.responseText);
            deActivateAuction(auctionId);
            expand.style.display = "none";
            document.getElementById("expand_" + auctionId).style.display = "none";
            document.getElementById("hideexpand_" + auctionId).style.display = "none";
            document.getElementById("viewexpand_" + auctionId).style.display = "";
            document.getElementById("details_" + auctionId).style.display = "none"
            document.getElementById("auctionrow_" + auctionId).className = "odd";
            set_image_src('activeimage_' + auctionId, yt_StaticWebPath + '/Content/images/auctionsnow.gif');
        }
    });
}

function load_details(id, url) {
    var details = document.getElementById("detailsdetails_" + id);
    var progressDetails = document.getElementById("progressdetails_" + id);
    Ext.Ajax.request({
        url: url,
        method: "GET",
        success: function(result, request) {
            progressDetails.style.display = "none";
            details.innerHTML = result.responseText;
            details.style.display = "";
            var infoBoxScript = document.getElementById("infoBoxScript_" + id);
            if (infoBoxScript)
                eval(infoBoxScript.innerHTML);
            var goodsIdInput = document.getElementById("goodsId_" + id);
            goodsId = goodsIdInput.value;
            runScript("goodsImagesScript_" + goodsId);
        },
        failure: function(result, request) {
            progressDetails.style.display = "none";
            details.style.display = "none";
            yt_alert("Misslyckades", result.responseText);
        }
    });
}

function runScript(scriptId) {
    var scriptToRun = document.getElementById(scriptId);
    if (scriptToRun) {
        var headTag = document.getElementsByTagName('head')[0];
        var script = document.createElement('script');
        script.id = scriptId;
        script.type = 'text/javascript';
        script.src = scriptToRun.src;
        headTag.appendChild(script);
    }
}


function getAuctionStatuses() {
    var auctionIdField = document.getElementById('auctionIdsHidden');
    if (auctionIdField)
        auctionIds = auctionIdField.value.split(",");
    if (auctionIds && (auctionIds.length > 0) && !isNaN(parseInt(auctionIds[0]))) {
        Ext.Ajax.request({
            url: "GetAuctionStatuses.rails",
            params: { auctionIds: Ext.util.JSON.encode(auctionIds) },
            method: "GET",
            success: function(result, request) {
                resultList = decodeJSON(result.responseText)
                for (var i = 0; i < resultList.length; i++) {
                    var image = document.getElementById('activeimage_' + resultList[i].AuctionId);
                    if (image) image.style.display = (resultList[i].IsRunning ? '' : 'none');
                    image = document.getElementById('purchaseimage_' + resultList[i].AuctionId);
                    if (image) image.style.display = (resultList[i].IsWon ? '' : 'none');
                    if(resultList[i].SaleId > 0)
                        insertSaleId(resultList[i].AuctionId, resultList[i].SaleId)
                }
            },
            failure: function(result, request) {
            }
        });
    }
    // start new request. This is better than setInterval because this will not stack up if the server was busy
    window.clearTimeout(statusUpdateTimeout);
    statusUpdateTimeout = window.setTimeout(getAuctionStatuses, statusUpdateInterval);
}

function reloadAuction(auctionId) {
    load_expand(auctionId);
    window.clearTimeout(statusUpdateTimeout);
    statusUpdateTimeout = window.setTimeout(getAuctionStatuses, 1000);
    //deActivateAuction(auctionId);
}

function update(id, html) {
    var elem = document.getElementById(id);
    if (elem) elem.innerHTML = html;
}

function hide(id) {
    var elem = document.getElementById(id);
    if (elem) elem.style.display = "none";
}

function show(id) {
    var elem = document.getElementById(id);
    if (elem) elem.style.display = "";
}

function _watchAuction(id, type) {
    Ext.Ajax.request({
        url: "AddWatch.rails",
        params: { id: Ext.util.JSON.encode(id) },
        method: "GET",
        success: function(result, request) {
            var watchResult = decodeJSON(result.responseText);
            if (!watchResult.Result) {
                yt_alert("Misslyckades", result.responseText);
                return;
            }
            hide("progress_" + type + "_" + id);
            hide("auction_" + id);
            show("unwatch_" + id);
            var list = document.getElementById("watchedauctions");
            if (list) {
                var a = document.getElementById("auction_" + id);
                var html = a.innerHTML;
                a.parentNode.removeChild(a);
                list.innerHTML = "<div id='auction_" + id + "'>" + html + "</div>" + list.innerHTML;
            }
            set_value("auctionWatchedHidden_" + id, "1");
            hide("btn_watch_" + id);
            show("btn_unwatch_" + id);
            var img = document.getElementById('bidAgentImage_' + id);
            if (img && img.style.display.length)
                show('watchedAuctionsImage_' + id);
        },
        failure: function(result, request) {
            hide("progress_" + type + "_" + id);
            show("watch_" + id);
            yt_alert("Misslyckades", result.responseText);
        }
    });
}

function watchAuction(id, type) {
    if (!yt_LoggedOn) {
        redirectLogin(id);
        return;
    }
    hide("watch_" + id);
    show("progress_" + type + "_" + id);
    setTimeout("_watchAuction(" + id + ",'" + type + "');", 300);
}

function _removeWatch(id, type) {
    Ext.Ajax.request({
        url: "RemoveWatch.rails",
        params: { id: Ext.util.JSON.encode(id) },
        method: "GET",
        success: function(result, request) {
            var removeResult = decodeJSON(result.responseText);
            if (!removeResult.Result) {
                yt_alert("Misslyckades", result.responseText);
                return;
            }
            hide("progress_" + type + "_" + id);
            hide("auction_" + id);
            show("watch_" + id);
            var list = document.getElementById("currentauctions");
            if (list) {
                var a = document.getElementById("auction_" + id);
                var html = a.innerHTML;
                a.parentNode.removeChild(a);
                list.innerHTML = "<div id='auction_" + id + "'>" + html + "</div>" + list.innerHTML;
            }
            set_value("auctionWatchedHidden_" + id, "0");
            show("btn_watch_" + id);
            hide("btn_unwatch_" + id);
            var img = document.getElementById('bidAgentImage_' + id);
            if (img && img.style.display.length)
                hide('watchedAuctionsImage_' + id);
        },
        failure: function(result, request) {
            hide("progress_" + type + "_" + id);
            show("unwatch_" + id);
            yt_alert("Misslyckades", result.responseText);
        }
    });
}

function removeWatch(id, type) {
    if (document.getElementById("remove_watch"))
        yt_confirm(
            'Bevakning',
            'Vill du ta bort bevakningen av detta objekt?',
            function(btn) {
                if (btn != 'yes') return;
                hide("remove_watch");
                setTimeout("_removeWatch(" + id + ",'" + type + "');", 300);
            });
    else {
        hide("unwatch_" + id);
        show("progress_" + type + "_" + id);
        setTimeout("_removeWatch(" + id + ",'" + type + "');", 300);
    }
}

function _removeBidAgent(auctionId, bidAgentId, url) {
    Ext.Ajax.request({
        url: url,
        params: { auctionId: Ext.util.JSON.encode(auctionId), bidAgentId: Ext.util.JSON.encode(bidAgentId) },
        method: 'GET',
        success: function(result, request) {
            var removeResult = decodeJSON(result.responseText);
            if (!removeResult.Result) {
                yt_alert("Misslyckades", result.responseText);
                return;
            }
            document.location.reload();
        },
        failure: function(result, request) {
            hide("progress2_" + auctionId);
            show("removeagent_" + auctionId);
            yt_alert("Misslyckades", result.responseText);
        }
    });
}

function removeBidAgent(auctionId, bidAgentId, url) {
    hide("removeagent_" + auctionId);
    show("progress2_" + auctionId);
    setTimeout("_removeBidAgent(" + auctionId + "," + bidAgentId + "," + url + ");", 300);
}

function _showImages(auctionId, auctionInfo, url) {
    Ext.Ajax.request({
        url: url,
        params: { auctionId: Ext.util.JSON.encode(auctionId) },
        method: "GET",
        success: function(result, request) {
            auctionImages.add(auctionId, decodeJSON(result.responseText));
            showImagesSuccess(auctionId, auctionInfo);
        },
        failure: function(result, request) {
        }
    });
}

function showImages(auctionId, auctionInfo, url) {
    if (auctionImages.key(auctionId) == null) {
        _showImages(auctionId, auctionInfo, url);
        return;
    }
    showImagesSuccess(auctionId, auctionInfo);
}

function showImagesSuccess(auctionId, auctionInfo) {
    displayImageIndex.add(auctionId, 0);
    showImage(auctionId, 0);
    var win = new Ext.Window({
        width: 620,
        height: 530,
        title: auctionInfo,
        closeAction: 'hide',
        autoScroll: true,
        modal: true,
        border: false,
        bodyBorder: false,
        contentEl: 'imagePreview_' + auctionId
    });
    win.show();    
}

function showImage(auctionId, direction) {
    images = auctionImages.key(auctionId);
    var currentIndex = displayImageIndex.key(auctionId);
    var newIndex = currentIndex + direction;
    if (newIndex < 0)
        newIndex = images.length - 1;
    if (newIndex >= images.length)
        newIndex = 0;

    displayImageIndex.add(auctionId, newIndex);
    images = auctionImages.key(auctionId);
    var imageDiv = document.getElementById('imagePreview_' + auctionId);
    var largeImage = document.getElementById("largeImage_" + auctionId);
    var originalLink = document.getElementById("originalLink_" + auctionId);
    largeImage.src = images[newIndex].Path + "&width=600&height=500";
    originalLink.href = images[newIndex].Path;
}


function reset_select(id, index) {
    var elem = document.getElementById(id);
    if (elem && elem.selectedIndex) {
        elem.selectedIndex = index;
        return;
    }
    elem = combobox_list ? combobox_list.key(id) : null;
    if (elem)
        elem.reset();
}

function reset_check(id) {
    var elem = document.getElementById(id);
    if (elem) elem.checked = false;
}

function reset_value(id) {
    var elem = document.getElementById(id);
    if (elem) elem.value = "";
}

function set_value(id, value) {
    var elem = document.getElementById(id);
    if (elem) elem.value = value;
}

function set_image_src(id, src) {
    var elem = document.getElementById(id);
    if (!elem || !elem.src) return;
    elem.src = src;
}

function reset_search() {
    reset_value("searchCriteria_AuctionFrom");
    reset_value("searchCriteria_AuctionTo");
    reset_select("searchCriteria_BodyType", 0);
    reset_value("searchCriteria_Brands", 0);
    reset_select("searchCriteria_Company_Id", 0);
    reset_value("searchCriteria_FreeText");
    reset_select("searchCriteria_GoodsTypeId", 0);
    reset_value("searchCriteria_LocationCity", 0);
    reset_select("searchCriteria_MilageFrom", 0);
    reset_select("searchCriteria_MilageTo", 0);
    reset_select("searchCriteria_Model", 0);
    reset_select("searchCriteria_ModelYearFrom", 0);
    reset_select("searchCriteria_ModelYearTo", 0);
    reset_select("searchCriteria_PriceFrom", 0);
    reset_select("searchCriteria_PriceTo", 0);
    reset_select("searchCriteria_Rows", 1);
    reset_value("searchCriteria_Company_Name");
    reset_check("searchCriteria_ShowEndedAuctions");
}

function submitPageRequest(pageItemIndex, pageSize) {
    deActivateAllAuctions();
    Ext.Ajax.request({
    url: 'RenderSearchPage.rails',
        params: { pageItemIndex: Ext.util.JSON.encode(pageItemIndex), pageSize: Ext.util.JSON.encode(pageSize) },
        method: 'GET',
        success: searchSuccess,
        failure: searchFailure
    });
}

function submitSortRequest(ordering, searchDescending, url) {
    deActivateAllAuctions();
    Ext.Ajax.request({
    url: url,
    params: { ordering: Ext.util.JSON.encode(ordering), searchDescending: Ext.util.JSON.encode(searchDescending) },
        method: 'GET',
        success: searchSuccess,
        failure: searchFailure
    });
}


function view_menu(goods_id, goods_type, sale_id) {
    var popmenu = new Ext.menu.Menu({ items: [
            { href: Ext.get("url_edit").getValue().replace("GOODS_TYPE", goods_type).replace("GOODS_ID", goods_id), text: "Ändra" },
            { href: Ext.get("url_finance").getValue().replace("SALE_ID", sale_id), text: "Betalning" }
        ]
    });
    popmenu.show("goods_" + goods_id);
}

function enableUserToolTip(auctionId) {
    var htmlContent = '';
    if (document.getElementById('userHtml_' + auctionId))
        htmlContent = document.getElementById('userHtml_' + auctionId).innerHTML;
    if (document.getElementById('userInfoDiv_' + auctionId))
        var tt = new Ext.ToolTip({
            target: 'userInfoDiv_' + auctionId,
            html: htmlContent,
            dismissDelay: 0
        });
}

function insertSaleId(auctionId, saleId) {
    var saleLink = document.getElementById('purchaseLink_' + auctionId);
    if (!saleLink)
        return;

    saleLink.href = replaceQueryString(saleLink.href, 'id', saleId);
    return;
}

function closeAuction(auctionId) {
    show('closeProgress_' + auctionId);
    Ext.Ajax.request({
        url: 'CloseAuction.rails',
        params: { id: Ext.util.JSON.encode(auctionId) },
        method: 'GET',
        success: function(result, request) {
            setTimeout("reloadAuction(" + auctionId + ");", 2000);
        },
        failure: function(result, request) {
            setTimeout("reloadAuction(" + auctionId + ");", 2000);
        }
    });
}

function startAuction(auctionId) {
    hide('timer_' + auctionId);
    show('startProgress_' + auctionId);
    Ext.Ajax.request({
        url: 'StartAuction.rails',
        params: { auctionId: Ext.util.JSON.encode(auctionId) },
        method: 'GET',
        success: function(result, request) {
            setTimeout("reloadAuction(" + auctionId + ");", 500);
        },
        failure: function(result, request) {
            setTimeout("reloadAuction(" + auctionId + ");", 500);
        }
    });
}

function setView(id) {
    hide("largeSelected");
    hide("mediumSelected");
    hide("smallSelected");
    show("large");
    show("medium");
    show("small");
    hide(id);
    show(id + "Selected");
}

function changeView(id, url) {
    setView(id);
    if (typeof (url) == "undefined") {
        set_value("listStyle", id);
        submitSearch();
    } else {
        deActivateAllAuctions();
        Ext.Ajax.request({
            url: url,
            success: searchSuccess,
            failure: searchFailure
        });
    }
}

function viewLarge(url) {
    changeView("large", url);
}

function viewMedium(url) {
    changeView("medium", url);
}

function viewSmall(url) {
    changeView("small", url);
}

function advanced() {
    var elem = document.getElementById("advanced_1");
    elem.style.display = (elem.style.display.length ? "" : "none");
    elem = document.getElementById("advanced_2");
    elem.style.display = (elem.style.display.length ? "" : "none");
    if (elem.style.display.length) {
        hide("advancedContract");
        show("advancedExpand");
        reset_search();
    } else {
        hide("advancedExpand");
        show("advancedContract");
    }
}

function buy(id, url) {
    if (!yt_LoggedOn) {
        redirectLogin(id);
        return;
    }
    yt_confirm(
        'K&#246;p nu',
        'Vill du k&#246;pa bilen f&#246;r det fasta priset?' + '<br/>' + parseInt(get_value('buyNowPrice_' + id)) + ' SEK',
        function(btn) {
            if (btn != 'yes') return;
            Ext.Ajax.request({
                url: "buy.rails?id=" + id,
                method: "GET",
                success: function(result, request) {
                    var buyResult = decodeJSON(result.responseText);
                    if (!buyResult.Result) {
                        yt_alert("Misslyckades", buyResult.Message);
                        return;
                    }
                    getAuctionInfo(id);
                },
                failure: function(result, request) {
                    yt_alert("Failed", result.responseText);
                }
            });
        }
    );
}

function fetchModels() {
    var brands = get_value("searchCriteria_Brands", "");
    if (!brands) return;
    var models = combobox_list.key("searchCriteria_Model");
    if (!models) return;
    models.store.load({ params: 'brands=' + brands, callback: resetModels });
}

function resetModels() {
    var models = combobox_list.key("searchCriteria_Model");
    if (!models) return;
    models.reset();
}

function toggleView(elem, url) {
    elem.src = url;
}

function enableCompanyToolTips() {
    var companyList = document.getElementById('company_list');
    if (companyList) {
        var list = companyList.value.split(',');
        for (var id = 0; id < list.length; id++) {
            var elem = document.getElementById('companyHtml_' + list[id].split('_')[1]);
            var htmlContent = elem ? elem.innerHTML : '';
            elem = document.getElementById('companyInfoDiv_' + list[id]);
            if (elem) {
                new Ext.ToolTip({
                    target: 'companyInfoDiv_' + list[id],
                    html: htmlContent,
                    dismissDelay: 0
                });
            }
        }
    }
}

function enableAuctionToolTips(id) {
    var elem = document.getElementById('auctionInfoDiv_' + id);
    if (elem) {
        new Ext.ToolTip({
            autoLoad: { url: 'statistics.rails', params: 'id=' + id },
            autoHeight: true,
            width: 120,
            dismissDelay: 0,
            listeners: { beforeshow: function (ctrl) {
                if (ctrl.rendered)
                    ctrl.getUpdater().update({ url: 'statistics.rails?id=' + id });
            }},
            target: 'auctionInfoDiv_' + id
        });
    }
}

function nextUpdateInterval(auctionId) {
    if (lastTimeInfoList.key(auctionId) != null) {
        var timeLeft = lastTimeInfoList.key(auctionId);
        return (timeLeft.Days == 0 && timeLeft.Hours == 0 && timeLeft.Minutes < 5) ? fastUpdateInterval : slowUpdateInterval;
    }
    return slowUpdateInterval;
}

function _buyForAcceptPrice(id) {
    Ext.Ajax.request({
        form: "formBuyForAcceptPrice",
        success: function(result, request) {
            hide("accept_progress_" + id);
            show("accept_btn_" + id);
            var result = decodeJSON(result.responseText);
            if (!result.Result)
                yt_alert('Fel uppstod n&#228;r budet lades', result.Message);
            else
                reloadAuction(id);
        },
        failure: function(result, request) {
            hide("accept_progress_" + id);
            show("accept_btn_" + id);
            yt_alert('Misslyckades', result.responseText);
        }
    });
}

function buyForAcceptPrice(id, price) {
    hide("accept_btn_" + id);
    show("accept_progress_" + id);
    yt_confirm("K&#246;p bilen", String.format("&#196;r du s&#228;ker p&#229; att du vill k&#246;pa bilen f&#246;r reservationspriset: {0}?", price), function(btn) {
        if (btn == 'yes') {
            setTimeout("_buyForAcceptPrice(" + id + ")", 200);
            return;
        }

        show("accept_btn_" + id);
        hide("accept_progress_" + id);
    
    });  
    
}