var renderers = new Array();
var cacheQueue = new Array();

var trend_renderer = function(cell, oldValue, newValue, trend, type) {
    if (oldValue.search(/img/i) > 0) {
        return '<img src="images/trend_' + newValue + '.gif" width="13" alt="Trend"/>';
    }
    return newValue;
};

renderers.push(trend_renderer);

var posBlinkColor = "#F0E291";
var negBlinkColor = "#F0E291";

function updateListingList(transport) {
    var data = transport.responseText.evalJSON();
    if (data.changedData != "") {
        updateListings(data.caches);
    }
}

function updateListings(values) {
    var highlightedElements = new Array();
    try {
        values.each(function(o) {
            if (o.data) {
                o.data.changedData.each(function(listing) {
                    listing.fields.each(function(f) {
                        //loop through all caches defined

                        for (var cq = 0; cq < cacheQueue.length; cq++) {
                            //check if the field to update exists in the table associated with the cache
                            var cellKey;
                            var cellNode;
                            //heatmap cache uses id!
                            if (cacheQueue[cq] == "heatmapCache") {
                                cellKey = "#n" + listing.lid + f.fid.strip();
                                cellNode = $$(cellKey)[0];
                            } else {
                                cellKey = "n" + listing.lid + f.fid.strip();
                                cellNode = $$('td.' + cellKey)[0];
                            }
                            if(cellNode != undefined && cellNode.className.indexOf("barChart") == -1){
                                if (cellNode) {
                                    //if the value is in a subcell, define this one as the element to be updated
                                    var oldValue = cellNode.innerHTML;
                                    var newValue;
                                    for (var k = 0; k < renderers.length; k++) {
                                        newValue = renderers[k](cellNode, oldValue, f.val, f.trend, f.e);
                                    }
                                    if (newValue) {
                                        cellNode.innerHTML = newValue;
                                        //var style = cellNode.style.backgroundColor;
                                        cellNode.setStyle({backgroundColor: (f.trend > 0) ? posBlinkColor : negBlinkColor});
                                        highlightedElements.push(cellNode); //tranHR.RgbToHex(style,false)]);

                                        if (cellNode.hasClassName("pos") || cellNode.hasClassName("neg") || cellNode.hasClassName("eq")) {
                                            cellNode.removeClassName("pos");
                                            cellNode.removeClassName("neg");
                                            cellNode.removeClassName("eq");
                                            var calc_value = parseFloat(newValue.replace(/\'/, ""));
                                            if (calc_value > 0) cellNode.addClassName("pos");
                                            if (calc_value < 0) cellNode.addClassName("neg");
                                            if (calc_value == 0) cellNode.addClassName("eq");
                                        }
                                    }
                                }
                            }
                        }

                    });
                });
            }
        });
    } catch(e) {
    }
//    should solve the multi threading issue!
    fadeOut.waiting(1500, highlightedElements);

}

var tranHR = {
    base:16,
    toString:Object.prototype.toString,
    map:function(array, base, callback) {
        var value;
        if (this.toString.call(array).toLowerCase().indexOf("array") > -1) {
            value = callback.call(this, array, base);
        }

        return value;
    },
    toParseInt:function(value, base) {
        return parseInt(value, base);
    },

    RgbToHex:function(rgb, plainStr) {
        var getMatch,x,i = 0;
        var sure = rgb.replace(/(rgba|rgb)?([\(\)])?/g, "");
        if (getMatch = sure.match(/(?:\d{1,3}(\.\d+)?)/g)) {
            if (getMatch.length > 3) {
                x = getMatch.pop();
                if (x == '0') {
                    return plainStr ? "FFFFFF" : "#FFFFFF";
                }
            }
            var fixR = this.map(getMatch, this.base, function(value, base) {
                var len = value.length,curValue = [],intRgb,result;
                if (len !== 3) {
                    return;
                }
                for (; i < len; i++) {
                    intRgb = (+value[i]).toString(this.base);
                    if (intRgb.length < 2) {
                        intRgb = "0" + intRgb;
                    }
                    curValue[curValue.length] = intRgb;
                }
                return result = curValue;
            });
        }
        if (!getMatch) {
            return "";
        }
        return getMatch = (plainStr ? fixR.join("") : "#" + fixR.join("")).toUpperCase();
    }
};


Function.prototype.waiting = function(wait) {
    var thisFunction = this;
    var thisArgs = new Array();
//
    for (var index = 1; index != arguments.length; index++)
        thisArgs.push(arguments[index]);

    window.setTimeout(function() {
        thisFunction.apply(thisFunction, thisArgs);
    }, wait);
};

function fadeOut(highlightedElements) {
    for (var i = 0; i < highlightedElements.length; i++) {
        highlightedElements[i].setStyle({backgroundColor: ""});
    }
}
var cacheUpdaters = new Array();

function updateValues(cacheNames) {
    if (cacheNames != undefined) {
        var cache = "utils/jspf/pullData.jspf?cachename=";
        cache += cacheNames.join(";");
        cacheQueue = cacheNames;
        cacheUpdaters.push(new Ajax.PeriodicalUpdater("", cache, {
            frequency:10,
            decay:1.0,
            onSuccess: function(transport) {
                var data = transport.responseText.evalJSON();
                if (data.changedData != "") {
                    updateListings(data.caches);
                }
            },
            onError: function(transport) {
            }
        }));
    }
}

function handlePush(pushing, savePush) {
    if (pushing) {
        var subscribe = new Array();
        ['listingCache','currencyCache','heatmapCache','listingFlopCache','listingTopCache'].each(function(n) {
            if ($$("." + n).size() > 0) {
                subscribe.push(n);
            }
        });
        updateValues(subscribe);
        window.setInterval("updateChart();", 120000);
    } else {
        for (var i = 0; i < cacheUpdaters.length; i++) {
            cacheUpdaters[i].stop();
        }
        cacheUpdaters = new Array();
        cacheQueue = new Array();

    }
    if (savePush) {
        new Ajax.Request(savePush.substring(3), {
            parameters:{push:pushing,do_rd:'no'},
            onSuccess:function(n) {
                var result;
                if (pushing) result = "true"; else result = "false"; //IE-bug
                new Ajax.Updater("autoupdate", "utils/jspf/autoUpdatePanel.jspf");
            }
        });
    }
}
