var dcache = {};
var show_pop_over = function(elt) {
    $this = $(elt);
    $href = $this.attr("href")
    if(/scid=([0-9]+)/.test($href)) {
        $scid = $href.match(/scid=([0-9]+)/)[1] + "-stock"
    } else if(/mfid=([0-9]+)/.test($href)) {
        $scid = $href.match(/mfid=([0-9]+)/)[1] + "-mf"
    } else {
        return;
    }

    $name = $this.parent().text().trim()
    $chg_str = $this.parents("tr:first").find(".chg_str").html()
    $attach_to = $this.parents("td:first")
    display_pop_over($scid, $name, $chg_str, $attach_to);
}
var construct_pop_over = function ($scid, $name, $chg_str) {
    $cntr = $("<div/>").addClass("ss watch_popup")

    $top_sec = $("<div/>").addClass("topsec clearfix")
    $sec1 = $("<div/>").addClass("sec1")
    $sec1.append($("<h3/>").text("Price Performance Chart"))
    $sec1.append($("<h2/>").text(($name.length > 20 ? $name.substr(0,18)+".." : $name).toUpperCase()))
    $sec2 = $("<div/>").addClass("sec2")
    $sec2.append($("<p/>").text("3-month chg"))
    $sec2.append($("<p/>").addClass("bold").html($chg_str))

    $sec1.appendTo($top_sec)
    $sec2.appendTo($top_sec)
    $top_sec.appendTo($cntr)
    $chrt_cntr = $("<div/>").addClass("chart")

    $("<p/>").append($("<span/>").addClass("ss watch_chart_icon small")).append(" Price Performance (Rs.)").appendTo($chrt_cntr);

    $chrt = $("<div/>").addClass("chart_content").attr("style", "width:240px;height:160px;margin:0 auto;")
    $chrt.appendTo($chrt_cntr);
    $chrt_cntr.appendTo($cntr)
    $bot_div = $("<div/>").addClass("ss watch_popup_bottom").text(" ")
    $bot_div.appendTo($cntr)
    return $cntr;
}
var existing_watch_pop_over = null;
var display_pop_over = function($scid, $name, $chg_str, $attach_to) {
    existing_watch_pop_over && existing_watch_pop_over.remove()
    if (dcache[$scid]) {
        $cntr = construct_pop_over($scid, $name, $chg_str)
        $cntr.appendTo($attach_to)
        $.plot($cntr.find("div.chart_content"),
                [{
                    data : dcache[$scid],
                    color: "#5699E1"
                }],{ xaxis: { mode: "time" , ticks : 3}, series: { lines : { lineWidth : 4} } }
        );
        existing_watch_pop_over = $cntr;
    } else {
        fetch_chart_data($scid, function() {
            display_pop_over($scid, $name, $chg_str, $attach_to)
        })
    }
}

var fetch_chart_data = function($scid, $callback) {
    $.get("/watchlist/get_chart_data_for_stock", {"scid":$scid}, function(res) {
        $data = eval("(" + res + ")");
        var datum = []
        for ($i = 0; $i < $data["labels"].length; $i++) {
            datum.push([$data["labels"][$i],$data["points"][$i]])
        }
        dcache[$scid] = datum;
        if ($callback) $callback.call()
    })
}
//bind the events
$("a.trig_po").live("mouseover",function() {
    show_pop_over(this)
}).live("mouseout",function(){
    $(this).parents("td:first").find(".watch_popup").remove()
})

