$(function() {    
    var reset = function(el, blur, callback, startValue) {
        el = $(el);
        var resetValue = el.data("resetValue");
        var currentValue = el.attr("value");

        if (blur) {
            if (currentValue == "") {
                if (callback) {
                    callback(el);
                }
                $(el).val(resetValue);
            }            
        } else {
            if (!resetValue) {
                el.data("resetValue", currentValue);
            }
            if ((resetValue || currentValue) == currentValue && (currentValue.indexOf("...") >= 0 || currentValue == startValue)) {
                $(el).val("");
            }
        }
    };    

    $("input").focus(function() {
        reset(this, false, false, $(this).val());
        $(this).css({ color: "#333333" });
    }).blur(function() {
        reset(this, true, function(el) { $(el).css({ color: "#999999" }); });              
    });
    
    $("#scroller li a").hover(function() {
        var offset = $(this).offset(); 
        $("<div/>", {
            id: "activeHover",
            css: {
                left: offset.left - 79, 
                top: offset.top + 52,
                position: "absolute",
                zIndex: 99
            }
        }).html($(this).next(".description").show()).appendTo(document.body);
    }, function() {
        $("#activeHover").remove().children().hide().insertAfter($(this));   
    });
    
    (function() {
        var arrowAnimating = false;
        var slide = function(direction) {
            var scroller = $("#scroller ul");
            var position = parseInt(scroller.css("left").replace("px", ""));
            var movement = -(direction * 511);
            var count = $("#scroller li").length;

            if (position + movement >= 0) {
                $("#arrowLeft a").addClass("disabled");
            } else {
                $("#arrowLeft a").removeClass("disabled");                
            }
            
            if (count <= 6 + (-((position + movement) / 490) * 7)) {
                $("#arrowRight a").addClass("disabled");
            } else {
                $("#arrowRight a").removeClass("disabled");                
            }

            if (position + movement <= 0 && count > -1 + (-((position + movement) / 490) * 7)) {
                if (!arrowAnimating) {
                    arrowAnimating = true;
                    scroller.animate({ left: ["+=" + movement, "swing"] }, 500, function() {
                        arrowAnimating = false;
                    });
                }           
            }

            $(this).blur();
        };

        var selected = $("#scroller a.selected");
        if (selected.length > 0) {
            var position = Math.floor((parseInt(selected.attr("id").replace("vid-", "")) - 1) / 7);
            if (position > 0) {
                slide(position);
            }
        }
        
        $("#arrowLeft a").click(function() { slide.call(this, -1) });
        $("#arrowRight a").click(function() { slide.call(this, 1) });
    })();
});

Raphael.fn.drawGrid = function (x, y, w, h, wv, hv, color) {
    color = color || "#000";
    var path = ["M", x, y, "L", x + w, y, x + w, y + h, x, y + h, x, y],
        rowHeight = h / hv,
        columnWidth = w / wv;
    for (var i = 1; i < hv; i++) {
        path = path.concat(["M", x, y + i * rowHeight, "L", x + w, y + i * rowHeight]);
    }
    for (var i = 1; i < wv; i++) {
        path = path.concat(["M", x + i * columnWidth, y, "L", x + i * columnWidth, y + h]);
    }
    return this.path(path.join(",")).attr({stroke: color});
};

//
// Below is taken from an awesome Raphael Demo
//
$(function () {
    $("#data").css({
        position: "absolute",
        left: "-9999em",
        top: "-9999em"
    });
});

$(function () {
    // Grab the data
    var labels = [], data = [];
    $("#data tfoot th").each(function () {
        labels.push($(this).html());
    });
    $("#data tbody td").each(function () {
        data.push($(this).html());
    });
    
    // Draw
    var width = 956,
        height = 200,
        leftgutter = 0,
        bottomgutter = 20,
        topgutter = 20,
        colorhue = .92 || Math.random(),
        color = "hsb(" + [colorhue, 1, 1] + ")",
        r = Raphael("holder", width, height),
        txt = {font: '10px Fontin-Sans, Arial', fill: "#fff"},
        txt1 = {font: '10px Fontin-Sans, Arial', fill: "#fff"},
        txt2 = {font: '10px Fontin-Sans, Arial', fill: "#000"},
        X = (width - leftgutter) / labels.length,
        max = Math.max.apply(Math, data),
        Y = (height - bottomgutter - topgutter - 50) / max,
        lastValue = labels[labels.length - 1];

    var getTheDate = function(day) {
        var d = new Date();
        var text = "";
        var month = d.getMonth() + 1;
        var year = d.getFullYear();
        
        if (lastValue != 1 && d.getDate() == 1) { //thanks to @evanjacobs
            month = month - 1;
        }
        
        if (day > lastValue) {
            if (month > 1) {
                month = month - 1;
            } else {
                month = 12;
                year = year - 1;
            }
        }
        
        return [month, day, year];
    };     
       
    r.drawGrid(leftgutter + X * .5, topgutter, width - leftgutter - X, height - topgutter - bottomgutter - 50, 10, 10, "#222");
    var path = r.path().attr({stroke: color, "stroke-width": 4, "stroke-linejoin": "round"}),
        bgp = r.path().attr({stroke: "none", opacity: .3, fill: color}).moveTo(leftgutter + X * .5, height - bottomgutter - 50),
        frame = r.rect(10, 10, 110, 80, 5).attr({fill: "#000", stroke: "#474747", "stroke-width": 2}).hide(),
        label = [],
        is_label_visible = false,
        leave_timer,
        blanket = r.set();
    label[0] = r.text(70, 9, "x page views").attr(txt).hide();
    label[1] = r.text(70, 40, "x x 2010").attr(txt1).attr({fill: color}).hide();
    label[2] = r.image("/wp-content/themes/us/images/na.png", 10, 10, 48, 36).hide();

    for (var i = 0, ii = labels.length; i < ii; i++) {
        var y = Math.round(height - bottomgutter - 50 - Y * data[i]),
            x = Math.round(leftgutter + X * (i + .5)),
            t = r.text(x, height - 56, labels[i]).attr(txt).toBack();
        bgp[i == 0 ? "lineTo" : "cplineTo"](x, y, 10);
        path[i == 0 ? "moveTo" : "cplineTo"](x, y, 10);
        var dot = r.circle(x, y, 5).attr({fill: color, stroke: "#000"});
        blanket.push(r.rect(leftgutter + X * i, 0, X, height - bottomgutter - 50).attr({stroke: "none", fill: "#fff", opacity: 0}));
        var rect = blanket[blanket.length - 1];
        (function (x, y, data, lbl, dot) {
            var date = getTheDate(lbl);
            var id = date[2] + "" + date[0] + "" + lbl;
            var timer, i = 0;
            $(rect.node).hover(function () {
                clearTimeout(leave_timer);
                var newcoord = {x: +x + 7.5, y: y - 19};
                if (newcoord.x + 100 > width) {
                    newcoord.x -= 114;
                }

                var item = $("#footerImages .img-" + id + " img");
                var img = "/wp-content/themes/us/images/na.png";
                if (item.length > 0) {
                    $(this).css({ cursor: "pointer" });
                    img = item.first().attr("src");
                }

                frame.show().animate({x: newcoord.x, y: newcoord.y}, 200 * is_label_visible);
                label[0].attr({text: data + " page view" + ((data % 10 == 1) ? "" : "s")}).show().animateWith(frame, {x: +newcoord.x + 55, y: +newcoord.y + 12}, 200 * is_label_visible);
                label[1].attr({text: getTheDate(lbl).join("/")}).show().animateWith(frame, {x: +newcoord.x + 55, y: +newcoord.y + 27}, 200 * is_label_visible);
                var imgSpeed = 200;
                if (img != "/wp-content/themes/us/images/na.png") {
                    imgSpeed = 200;
                    label[2].attr({ x: -50, y: 75 });
                }
                label[2].attr({src: img }).show().animateWith(frame, {x: newcoord.x + 30, y: +newcoord.y + 37}, imgSpeed * is_label_visible);
                dot.attr("r", 7);
                is_label_visible = true;
            }, function () {
                dot.attr("r", 5);
                leave_timer = setTimeout(function () {
                    frame.hide();
                    label[0].hide();
                    label[1].hide();
                    label[2].hide();
                    is_label_visible = false;
                    // r.safari();
                }, 1);
            }).click(function() {
                var url = $("#footerImages .img-" + id).first().attr("href");
                var img = "";
                if (url) {
                    document.location.href = url;
                }
            });
        })(x, y, data[i], labels[i], dot);
    }
    bgp.lineTo(x, height - bottomgutter - 50).andClose();
    frame.toFront();
    label[0].toFront();
    label[1].toFront();
    label[2].toFront();
    blanket.toFront();
});

