var de_months = ["Jan", "Feb", "Mär", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"];
var de_months_long = ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"];
var de_days = ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"];
var de_days_long = ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"];
var plots = {};
var previous_item, selected_item;


function array_search(needle, haystack) {
    var i;
    
    for (i in haystack) {
        if (haystack[i] == needle)
            return i;
    }
    
    return -1;
}


function cb_reciprocal() {
    var plotid = $(this).parents(".plot").get(0).id;
    var plot = $("#" + plotid + " .graph");
    
    plots[plotid].reciprocal = !plots[plotid].reciprocal;
    
    for (x in plots[plotid].data)
        for (y in plots[plotid].data[x].data)
            if (plots[plotid].data[x].data[y][1] != null)
                plots[plotid].data[x].data[y][1] = 1e8 / plots[plotid].data[x].data[y][1];
    
    if (plots[plotid].reciprocal)
        $.extend(true, plots[plotid].options, {yaxis: {tickFormatter: suffix_formatter_reciprocal}});
    else
        $.extend(true, plots[plotid].options, {yaxis: {tickFormatter: suffix_formatter}});
    
    plots[plotid].data.reverse();
    make_legend(plotid);
    plots[plotid].data.reverse();
    
    plots[plotid].plot = $.plot(plot, filter_data(plotid), plots[plotid].options);
}


function date_formatter(val, axis) {
    var d = new Date(val);
    var span = axis.max - axis.min;
    
    var timeUnitSize = {
        "second": 1000,
        "minute": 60 * 1000,
        "hour": 60 * 60 * 1000,
        "day": 24 * 60 * 60 * 1000,
        "month": 30 * 24 * 60 * 60 * 1000,
        "year": 365.2425 * 24 * 60 * 60 * 1000
    };
    
    var t = axis.tickSize[0] * timeUnitSize[axis.tickSize[1]];
    var span = axis.max - axis.min;
    
    if (t < timeUnitSize.minute)
        fmt = "%h:%M:%S";
    else if (t < timeUnitSize.day) {
        if (span < 2 * timeUnitSize.day)
            fmt = "%h:%M";
        else
            fmt = "%d. %b %h:%M";
    }
    else if (t < timeUnitSize.month)
        fmt = "%d. %b";
    else if (t < timeUnitSize.year) {
        if (span < timeUnitSize.year)
            fmt = "%b";
        else
            fmt = "%b %y";
    }
    else
        fmt = "%y";
    
    return format_date(d, fmt, de_months);
}


function filter_data(plotid) {
    var data = [], x;
    
    for (x in plots[plotid].data)
        if (!sites[plots[plotid].data[x].lps_site]["hide_" + plots[plotid].type])
            data.push(plots[plotid].data[x]);
    
    if (data[data.length - 1].lps_site == 0)
        data[data.length - 1].data = get_average_data(data.slice(0, -1));
    
    return data;
}


function format_date(d, fmt, monthNames) {
    var r = [];
    var escape = false;
    if (monthNames == null)
        monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    for (var i = 0; i < fmt.length; ++i) {
        var c = fmt.charAt(i);
        
        if (escape) {
            switch (c) {
            case 'h': c = "" + d.getUTCHours(); break;
            case 'H': c = left_pad(d.getUTCHours()); break;
            case 'M': c = left_pad(d.getUTCMinutes()); break;
            case 'S': c = left_pad(d.getUTCSeconds()); break;
            case 'd': c = "" + d.getUTCDate(); break;
            case 'm': c = "" + (d.getUTCMonth() + 1); break;
            case 'y': c = "" + d.getUTCFullYear(); break;
            case 'b': c = "" + monthNames[d.getUTCMonth()]; break;
            }
            r.push(c);
            escape = false;
        }
        else {
            if (c == "%")
                escape = true;
            else
                r.push(c);
        }
    }
    return r.join("");
}


function format_hint_reciprocal(x, y) {
    var date = new Date(item.datapoint[0]);
    
    date = de_days_long[date.getUTCDay()] + ", " + date.getUTCDate() + ". " + de_months_long[date.getUTCMonth()] +
        " " + date.getUTCFullYear() + " " + left_pad(date.getUTCHours()) + ":" + left_pad(date.getUTCMinutes());
    
    return "<div><strong>" + number_format(Math.round(y * 1e6)) + " Lose/€</strong><br />" + date + "</div>";
}


function get_average_data(data) {
    var averages = [],
        dates = [],
        date, last_val, sum, values, x, y, z;
    
    for (x in data) {
        for (y in data[x].data) {
            if (!in_array(data[x].data[y][0], dates))
                dates.push(data[x].data[y][0]);
        }
    }
    
    dates.sort(function(a, b) { return a - b; });
    
    for (x in dates) {
        values = [];
        
        for (y in data) {
            last_val = null;
            
            for (z in data[y].data) {
                if (data[y].data[z][0] > dates[x])
                    break;
                
                last_val = data[y].data[z][1];
            }
            
            if (last_val != null)
                values.push(last_val);
        }
        
        if (values.length) {
            sum = 0;
            for (y in values)
                sum += values[y];
            averages.push([dates[x], sum / values.length]);
        }
    }
    
    return averages;
}


function get_formatted_legend_price(point, reciprocal) {
    var date = new Date(point[0]),
        value = point[1];
    
    date = de_days[date.getUTCDay()] + ", " + date.getUTCDate() + ". " + de_months_long[date.getUTCMonth()] +
        " " + date.getUTCFullYear() + " " + left_pad(date.getUTCHours()) + ":" + left_pad(date.getUTCMinutes());
    if (reciprocal)
        value = (value / 1e6).toFixed(2).toString().replace(".", ",") + " Mio./€";
    else
        value = value.toFixed(2).toString().replace(".", ",") + " ct./Mio.";
    
    return {
        date : date,
        value : value
    };
}


function get_readable_colour(col){
    var r, g, b;
    
    r = parseInt("0x" + col.substr(1, 2));
    g = parseInt("0x" + col.substr(3, 2));
    b = parseInt("0x" + col.substr(5, 2));
    
    if (r + g + b >= 382) {
        return "black";
    } else {
        return "white";
    }
}


function get_rel_diff(data) {
    var first, last, changed, type, x;
    
    last = data[data.length - 1][1];
    
    if (last == null)
        return "";
    
    for (x in data) {
        if (data[x][1] != null) {
            first = data[x][1];
            break;
        }
    }
    
    changed = Math.round((last / first - 1) * 1e4) / 1e2;
    
    if (changed > 0) {
        changed = "+" + changed.toFixed(2).toString();
        type = "change_plus";
    } else if (changed < 0) {
        changed = "−" + Math.abs(changed).toFixed(2).toString();
        type = "change_minus";
    } else {
        changed = "±" + changed.toFixed(2).toString();
        type = "change_none";
    }
    changed = changed.replace(".", ",");
    
    return "<span class='" + type + "'>" + changed + " %</span>";
}


function get_skeleton_other(label, plotid) {
    var str = '<div class="plot" id="' + plotid + '">';
    str += '<h3>' + label + '</h3>';
    str += '<div class="graph" style="width:100%"></div>';
    str += '<br /><form action=""><div><button class="reset" disabled="disabled" style="width:10em" type="button">Herauszoomen</button></div></form>';
    str += '</div>';
    str += '';
    
    return str;
}


function get_skeleton_sites(label, plotid) {
    var str = '<div class="plot" id="' + plotid + '">';
    str += '<h3>' + label + '</h3>';
    str += '<div class="sidebar">';
    str += '<div class="legend"></div>';
    str += '<div class="options">';
    str += '<form action=""><label class="reciprocal"><input type="checkbox" /> Zeige Mio./€ statt ct./Mio.</label><br />';
    str += '<button class="reset" disabled="disabled" type="button">Herauszoomen</button></form>';
    str += '</div>';
    str += '<div class="infobox"></div>';
    str += '</div>';
    str += '<div class="graph"></div>';
    str += '</div>';
    str += '';
    
    return str;
}


function get_weekend_areas(axes) {
    var markings = [];
    var d = new Date(axes.xaxis.min);
    // go to the first Saturday
    d.setUTCDate(d.getUTCDate() - ((d.getUTCDay() + 1) % 7))
    d.setUTCSeconds(0);
    d.setUTCMinutes(0);
    d.setUTCHours(0);
    var i = d.getTime();
    do {
        // when we don't set yaxis the rectangle automatically
        // extends to infinity upwards and downwards
        markings.push({ xaxis: { from: i, to: i + 2 * 24 * 60 * 60 * 1000 } });
        i += 7 * 24 * 60 * 60 * 1000;
    } while (i < axes.xaxis.max);

    return markings;
}


function in_array(needle, haystack) {
    return array_search(needle, haystack) >= 0;
}


function left_pad(n) {
    n = "" + n;
    return n.length == 1 ? "0" + n : n;
}


function make_default_plot(plotid, tooltip, clickable) {
    if (plots[plotid] == undefined)
        return;
    
    var plot = $("#" + plotid + " .graph");
    
    plots[plotid].plot = $.plot(plot, plots[plotid].data, plots[plotid].options);
    
    plot
        .bind("plotselected", function (event, ranges) {
            // clamp the zooming to prevent eternal zoom
            if (ranges.xaxis.to - ranges.xaxis.from < 0.00001)
                ranges.xaxis.to = ranges.xaxis.from + 0.00001;
            if (ranges.yaxis.to - ranges.yaxis.from < 0.00001)
                ranges.yaxis.to = ranges.yaxis.from + 0.00001;
            
            // do the zooming
            plots[plotid].plot = $.plot(plot, plots[plotid].data,
                $.extend(true, {}, plots[plotid].options, {
                    xaxis: { min: ranges.xaxis.from, max: ranges.xaxis.to },
                    yaxis: { min: ranges.yaxis.from, max: ranges.yaxis.to }
                })
            );

            $("#" + plotid + " .reset").removeAttr("disabled");
        });
    
    if (tooltip) {
        plot.bind("plothover", function (event, pos, item) {
            if (item) {
                if (!previous_item || previous_item.datapoint != item.datapoint) {
                    previous_item = item;
                    
                    $("#tooltip").remove();
                    
                    $("<div id='tooltip'>" + tooltip(item) + "</div>").css({
                        top: item.pageY + 15,
                        left: item.pageX + 15
                    }).appendTo("body").fadeIn(200);
                }
            }
            else {
                $("#tooltip").remove();
                previous_item = null;
            }
        })
        .mouseout(function () {
            if (previous_item)
                plots[plotid].plot.unhighlight(previous_item.seriesIndex, previous_item.dataIndex);
            if (selected_item) {
                plots[plotid].plot.unhighlight(selected_item.seriesIndex, selected_item.dataIndex);
                selected_item = null;
            }
            plot.trigger("plothover");
        });
    }
    
    if (clickable) {
        plot.bind("plotclick", function (event, pos, item) {
            if (item) {
                if (selected_item) {
                    if (selected_item.datapoint != item.datapoint) {
                        plots[plotid].plot.unhighlight(selected_item.seriesIndex, selected_item.dataIndex);
                        plots[plotid].plot.highlight(item.seriesIndex, item.dataIndex);
                    }
                } else {
                    plots[plotid].plot.highlight(item.seriesIndex, item.dataIndex);
                }
                
                selected_item = item;
            } else {
                if (selected_item) {
                    plots[plotid].plot.unhighlight(selected_item.seriesIndex, selected_item.dataIndex);
                    selected_item = null;
                }
            }
        });
    }
    
    $("#" + plotid + " .reset").click(function() {
        $("#" + plotid + " .reset").attr("disabled", "disabled");
        this.blur();
        plots[plotid].plot = $.plot(plot, plots[plotid].data, plots[plotid].options);
    });
}


function make_legend(plotid) {
    legend = $("#" + plotid + " .legend");
    $("#" + plotid + " .legend *").unbind();
    
    var data, fragments = [], hide_details, last_idx, last_pos = 0, last_val, now, out, pos_str, price, site, then;
    
    
    var average = plots[plotid].data[0];
    
    if (plots[plotid].reciprocal)
        price = (average.data[average.data.length - 1][1] / 1e6).toFixed(2).toString().replace(".", ",") + " <span>Mio./€</span>";
    else
        price = average.data[average.data.length - 1][1].toFixed(2).toString().replace(".", ",") + " <span>ct./Mio.</span>";
    
    then = get_formatted_legend_price(average.data[0], plots[plotid].reciprocal);
    now = get_formatted_legend_price(average.data[average.data.length - 1], plots[plotid].reciprocal);
    
    out  = "<li class='site0'>";
    out += "<div class='head'><div class='price'>" + price + "</div>";
    out += "<span class='rank' style='background-color:" + average.color + "'></span>";
    out += sites[average.lps_site].name
    out += "</div>";
    out += "<div class='details'>";
    out += "<span class='rank' style='background-color:" + average.color + "'></span>";
    out += sites[average.lps_site].name + "<br />";
    out += "<div class='old'><strong>" + then.value + "</strong> &nbsp;" + then.date + "</div>";
    out += "<div><strong>" + now.value + "</strong> &nbsp;" + now.date + "</div>";
    out += "(" + get_rel_diff(average.data) + ")<br />";;
    out += "";
    out += "";
    out += "</div>";
    out += "</li>";
    
    fragments.push(out);
    
    
    for (x in plots[plotid].data) {
        site = sites[plots[plotid].data[x].lps_site];
        data = plots[plotid].data[x].data;
        last_idx = data.length - 1;
        
        if (site.id == 0 || data == undefined || !data)
            continue;
        
        if (data[last_idx][1] == last_val) {
            if (last_val == null) {
                price = "–";
                pos_str = "";
            } else {
                pos_str = price = '"';
            }
        } else {
            last_pos += 1;
            pos_str = last_pos;
            last_val = data[last_idx][1];
            
            if (last_val == null) {
                price = "–";
                pos_str = "";
            } else {
                if (plots[plotid].reciprocal)
                    price = (last_val / 1e6).toFixed(2).toString().replace(".", ",") + " <span>Mio./€</span>";
                else
                    price = last_val.toFixed(2).toString().replace(".", ",") + " <span>ct./Mio.</span>";
            }
        }
        
        var text_color = get_readable_colour(site.color);
        
        if (data[0][1] != null && data[data.length - 1][1] != null) {
            hide_details = false;
            then = get_formatted_legend_price(data[0], plots[plotid].reciprocal);
            now = get_formatted_legend_price(data[data.length - 1], plots[plotid].reciprocal);
        } else {
            hide_details = true;
        }
        
        if (site["hide_" + plots[plotid].type])
            out = "<li class='site" + site.id + " deactivated' title='Du hast den Preisverlauf dieser Loseseite in der Grafik ausgeblendet.'>";
        else
            out = "<li class='site" + site.id + "'>";
        out += "<a class='head' href='seite/" + site.id + "/" + plots[plotid].type + "/'>";
        out += "<div class='price'>" + price + "</div>";
        out += "<span class='rank' style='background-color:" + site.color + ";color:" + text_color + "'>" + pos_str + "</span>";
        out += site.name + "</a>";
        out += "<div class='details'>";
        out += "<span class='rank' style='background-color:" + site.color + ";color:" + text_color + "'>" + last_pos + "</span>";
        out += "<a href='seite/" + site.id + "/" + plots[plotid].type + "/'>" + site.name + "</a>";
        if (site["amount_" + plots[plotid].type]) {
            var amount = site["amount_" + plots[plotid].type];
            if (amount >= 1e3)
                amount = (amount / 1e3).toFixed(1).toString().replace(".", ",") + " Mrd.";
            else
                amount = amount + " Mio.";
            out += "<div class='amount'>Derzeit gehandelte Menge:<br /><strong>" + amount + " Lose</strong></div>";
        }
        
        if (!hide_details) {
            out += "<div class='old'><strong>" + then.value + "</strong> &nbsp;" + then.date + "</div>";
            out += "<div><strong>" + now.value + "</strong> &nbsp;" + now.date + "</div>";
            out += "(" + get_rel_diff(data) + ")<br />";
        }
        
        out += "</div>";
        out += "<div class='sitepos'>" + plots[plotid].data[x].lps_site + "</div>";
        out += "</li>";
                
        fragments.push(out);
    }
    
    legend.html("<ul>" + fragments.join("") + "</ul>");
    
    $("#" + plotid + " .legend .head")
        .mouseenter(function(e) {
            $("#" + plotid + " .legend .head").removeClass("selected");
            $(this).addClass("selected");
            $("#" + plotid + " .infobox").html($(".details", $(this).parent()[0]).html());
        })
        .click(function(e) {
            e.preventDefault();
            
            var x = parseInt($(".sitepos", $(this).parent()[0]).html());
            
            var site = sites[x],
                type = plots[plotid].type,
                togglestr;
            
            if (site["hide_" + plots[plotid].type])
                togglestr = "<a class='toggle activate'>Preisverlauf aktvieren</a>";
            else
                togglestr = "<a class='toggle deactivate'>Preisverlauf deaktvieren</a>";
            
            $("<div id='legendpopup'><a class='visit' href='seite/" + site.id + "/" + type + "/'>Zu " + site.name + " …</a>" +
                togglestr + "</div>").css({
                top: e.pageY - 15,
                left: e.pageX - 15
            }).appendTo("#content").fadeIn(200).mouseleave(function() {
                $(this).remove()
            });
            
            $("#legendpopup .toggle").click(function() {
                if (site["hide_" + plots[plotid].type]) {
                    site["hide_" + plots[plotid].type] = false;
                    $("#" + plotid + " .legend .site" + site.id)
                        .attr("title", "")
                        .removeClass("deactivated");
                } else {
                    site["hide_" + plots[plotid].type] = true;
                    $("#" + plotid + " .legend .site" + site.id)
                        .attr("title", "Du hast den Preisverlauf dieser Loseseite in der Grafik ausgeblendet.")
                        .addClass("deactivated");
                }
                $("#legendpopup").remove();
                
                plots[plotid].plot = $.plot($("#" + plotid + " .graph"), filter_data(plotid), plots[plotid].options);
            });
        }
    );
    
    /*
    $("#" + plotid + " .legend .head").mouseleave(function(e) {
        
    });
    */
    $("#" + plotid + " .legend .site0 .head").trigger("mouseenter");
}


function make_sites_data(type) {
    var data = [];
    var last, average = null;
    
    for (x in sites) {
        if (sites[x].hide || !sites[x]["data_" + type])
            continue
        
        if (sites[x].id == 0) {
            average = x;
            continue;
        }
        
        data.push(
            {
                color  : sites[x].color,
                data   : sites[x]["data_" + type],
                lines  : { show : true },
                points : { show : false },
                lps_site : x
            }
        );
    }
    
    if (average != null) {
        data.push({
            color    : "#000000",
            data     : sites[average]["data_" + type],
            lines    : { show : true, lineWidth: 4 },
            points   : { show : false },
            lps_site : 0
        });
    }
    
    return data;
}


function make_sites_plot(type, title, reverse) {
    var plotid = period + "_" + type;
    var sort_data = function(a, b) {
        a = a.data;
        b = b.data;
        
        if (!a.length || !b.length)
            return 0;
        
        if (a[a.length - 1][1] == null && b[b.length - 1][1] != null)
            return 1;
        
        if (a[a.length - 1][1] != null && b[b.length - 1][1] == null)
            return -1;
        
        var data = a[a.length - 1][1] - b[b.length - 1][1];
        
        if (!data)
            data = a[0][1] - b[0][1];
        
        return data;
    };
    
    var default_options = {
        grid: { clickable: true, hoverable: true },
        selection: { mode: "xy" },
        xaxis: { mode: "time", tickFormatter: date_formatter },
        yaxis: { tickDecimals: 1, tickFormatter: suffix_formatter }
    };
    
    plots[plotid] = {
        data       : make_sites_data(type),
        options    : $.extend(true, {}, default_options, options),
        type       : type,
        reciprocal : false
    };
    
    var average = plots[plotid].data.pop();
    
    plots[plotid].data.sort(sort_data);
    if (reverse)
        plots[plotid].data.reverse();
    
    $("#plots").append(get_skeleton_sites(title, plotid));
    $("#" + plotid + " .reciprocal input").click(cb_reciprocal);
    
    var tooltip = function(item) {
        var content, same_price_sites = [];
        
        for (x in plots[plotid].data) {
            var data = plots[plotid].data[x];
            
            for (y in data.data)
                if (data.data[y][0] > item.datapoint[0])
                    break;
            
            y--;
            
            if (y < 0)
                y = 0;
            if (y > data.data.length - 1)
                y = data.data.length - 1;
            
            if (data.data[y][1] != null && data.data[y][1].toFixed(2) == item.datapoint[1].toFixed(2)) {
                same_price_sites.push("<span class='sitecolorbox' style='background-color:" + sites[data.lps_site].color + "'></span> " +
                    sites[data.lps_site].name);
            }
        }
        
        same_price_sites.reverse();
        
        var this_date = new Date(item.datapoint[0]),
            this_value = item.datapoint[1];
        
        if (plots[plotid].reciprocal)
            this_value = number_format(Math.round(this_value)) + " Lose/€";
        else
            this_value = this_value.toFixed(2).toString().replace(".", ",") + " Cent/Mio.";
        
        this_date = de_days_long[this_date.getUTCDay()] + ", " + this_date.getUTCDate() + ". " + de_months_long[this_date.getUTCMonth()] +
            " " + this_date.getUTCFullYear() + " " + left_pad(this_date.getUTCHours()) + ":" + left_pad(this_date.getUTCMinutes());
        
        if (selected_item && selected_item.datapoint != item.datapoint) {
            var then_date = new Date(selected_item.datapoint[0]),
                then_value = selected_item.datapoint[1];
            
            if (plots[plotid].reciprocal)
                then_value = number_format(Math.round(then_value)) + " Lose/€";
            else
                then_value = then_value.toFixed(2).toString().replace(".", ",") + " Cent/Mio.";
            
            then_date = de_days_long[then_date.getUTCDay()] + ", " + then_date.getUTCDate() + ". " + de_months_long[then_date.getUTCMonth()] +
                " " + then_date.getUTCFullYear() + " " + left_pad(then_date.getUTCHours()) + ":" + left_pad(then_date.getUTCMinutes());
            
            if (selected_item.datapoint[0] < item.datapoint[0]) {
                var fake_series = [selected_item.datapoint, item.datapoint];
                
                content = "<div class='top old'><strong>" + then_value + "</strong> &nbsp; " + then_date + "</div>";
                content += "<strong>" + this_value + "</strong> &nbsp; " + this_date + "<br />";
                content += "(" + get_rel_diff(fake_series) + ")<br />";
                content += "<div class='siteslist'>" + same_price_sites.join("<br />") + "</div>";
            } else {
                var fake_series = [item.datapoint, selected_item.datapoint];
                
                content = "<div class='top'><strong>" + this_value + "</strong> &nbsp; " + this_date + "</div>";
                content += "<div class='old'><strong>" + then_value + "</strong> &nbsp; " + then_date + "</div>";
                content += "(" + get_rel_diff(fake_series) + ")<br />";
                content += "<div class='siteslist'>" + same_price_sites.join("<br />") + "</div>";
            }
        } else {
            content = "<strong>" + this_value + "</strong><br />";
            content += this_date + "<br />";
            content += "<div class='siteslist'>" + same_price_sites.join("<br />") + "</div>";
        }
        
        
        return content;
    }
    
    plots[plotid].data.unshift(average);
    make_legend(plotid);
    plots[plotid].data.reverse();
    make_default_plot(plotid, tooltip, true);
}


function number_format(num) {
    var sign = "";
    if (num < 0)
        sign = "-";
    
    num = Math.abs(num);
    
    var orig = num = num.toString();
    var end = num.indexOf(".");
    
    if (end != -1)
        num = num.substring(0, end);
    
    var result = "";
    
    for (var i = num.length - 3; i > 0; i -= 3)
        result = "." + num.substring(i, i + 3) + result;
    result = num.substring(i, i + 3) + result;
    
    if (end == -1)
        return sign + result;
    else
        return sign + result + "," + orig.substring(end + 1);
}


function suffix_formatter(val, axis) {
    return val.toFixed(axis.tickDecimals).toString().replace(".", ",") + " ct";
}


function suffix_formatter_reciprocal(val, axis) {
    return (val / 1e6).toFixed(1).toString().replace(".", ",") + " Mio.";
}


function tooltip_daily_lose(item) {
    var date = new Date(item.datapoint[0]);
    
    date = de_days_long[date.getUTCDay()] + ", " + date.getUTCDate() + ". " + de_months_long[date.getUTCMonth()] +
        " " + date.getUTCFullYear();
    
    return "<div><strong>" + number_format(item.datapoint[1]) + " Lose</strong><br />" + date + "</div>";
}


function tooltip_default_lose(item) {
    var date = new Date(item.datapoint[0]);
    
    date = de_days_long[date.getUTCDay()] + ", " + date.getUTCDate() + ". " + de_months_long[date.getUTCMonth()] +
        " " + date.getUTCFullYear() + " " + left_pad(date.getUTCHours()) + ":" + left_pad(date.getUTCMinutes());
    
    return "<div><strong>" + number_format(item.datapoint[1]) + " Lose</strong><br />" + date + "</div>";
}


function tooltip_default_price(item) {
    var date = new Date(item.datapoint[0]);
    
    date = de_days_long[date.getUTCDay()] + ", " + date.getUTCDate() + ". " + de_months_long[date.getUTCMonth()] +
        " " + date.getUTCFullYear() + " " + left_pad(date.getUTCHours()) + ":" + left_pad(date.getUTCMinutes());
    
    return "<strong>" + item.datapoint[1].toFixed(2).toString().replace(".", ",") + " Cent/Mio.</strong><br />" + date;
}


function tooltip_monthly_lose(item) {
    var date = new Date(item.datapoint[0]);
    
    date = de_months_long[date.getUTCMonth()] + " " + date.getUTCFullYear();
    
    return "<strong>" + number_format(item.datapoint[1]) + " Lose</strong><br />" + date;
}


$(function() {
    $("#navigation > li > a").mousemove(function(e) {
        if ($(this).siblings().css("display") == "block")
            return;
        
        $("#navigation > li > a").removeClass("highlight");
        $("#navigation ul").hide();
        $(this)
            .addClass("highlight")
            .siblings().show();
    });
    
    if (typeof period == "undefined")
        return;
    
    make_sites_plot("buy", title + " – Verkauf");
    $("#plots").append("<div class='sep'><br /><br /></div>");
    make_sites_plot("sell", title + " – Ankauf", true);
    $("#plots").append('<p style="color:#999;text-align:right">Auflösung: ' + resolution + '</p>');
});
