/*
Copyright (c) 2007, Waleed Abdulla. All rights reserved.
Code licensed under the MIT License:

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/



// Don't forget to put "javascript:" before the code to tell the 
// browser that this is JS code not a URL.

// Put all functions and variables under one object to reduce
// possibility of name collisions with the main page.
var tracker={};

// The ID of the status message div.
tracker.divID = "divCommentTracker";

// The starting point. 
tracker.main = function()
{
    // Get thread id from the URL.
    var regUrl = /info\/(\w+)\/comments/;
    var match = regUrl.exec(window.location.href);
    if (match)
    {
        tracker.track(match[1]);
    }
    else
    {
        tracker.message("Opps. You must be on a Reddit thread page to track it.", "#A00", 0);
    }
}

// This is where most of the work is done.
tracker.track = function(threadID)
{
    var minutesElapsed = -1; // Minutes since the last time the  
                             // bookmarklet was clicked.
                             // -1 means that it has not been clicked before.
    var now = new Date();    // The time right now.
    var newComments = 0;     // No. of new comments since last click.

    // Get the time when the bookmarklet was clicked last from the cookie (if available).
    // Note: I store these values in the form: "TT" + threadID + "=" + timeValue. 
    //       Example: TT62055=2xm8c
    var regCookie = new RegExp("TT" + threadID + "=(\\d+)");
    match = regCookie.exec(document.cookie);
    if (match)
    {
        var lastTime = new Date(parseInt(match[1],10));
        var one_minute = 1000*60;
        minutesElapsed = Math.ceil((now.getTime() - lastTime.getTime()) / one_minute);
    }

    // Save the current time in the cookie.
    var expire = new Date();
    expire.setTime(now.getTime() + 1000 * 60 * 60 * 24 * 5);    // expires in 5 days, do not keep too many cookies around.
    document.cookie = "TT" + threadID + "=" + escape(now.getTime()) + ";expires=" + expire.toGMTString();
    
    // Did we get a value for minutesElapsed?
    if (minutesElapsed == -1)
    {
        // No, this is the first click.
        tracker.message("Started tracking.", "#000", 0);
        return;
    }
    

    // Find the comments that were added since last time.
    // A quick and dirty way is to get all <span> elements that have
    // the class "little", and within those, filter only the ones 
    // that have a string in the form 2 minutes ago, or 16 hours ago, 
    // or 12 days ago.
    
    // Get all span elements.
    var spans = document.getElementsByTagName("span");

    // Regular expression to test for class name and time string (e.g. 3 minutes ago).
    var regClass = new RegExp("\\blittle\\b");
    var regTime = /((\d+)\sminute[s]?\sago)|((\d+)\shour[s]?\sago)|((\d+)\sday[s]?\sago)/;
    
    for (var i=0; i < spans.length; i++)
        if(regClass.test(spans[i].className))
        {
            var match = regTime.exec(spans[i].innerHTML);
            if (match)
            {
                // Extract the time in minutes. 
                var minutes = parseInt("0" + match[2],10) + (60 * parseInt("0" + match[4],10)) + (24 * 60 * parseInt("0" + match[6],10));

                // If this comment is newer than our minutesElapsed value, highlight it.
                if (minutes < minutesElapsed)
                {
                    // Make the comment text bold.
                    spans[i].parentNode.style.fontWeight="bold";
                    
                    // Increment newComments counter.
                    newComments++;
                }
            }
        }
        
    // Show message.
    if (newComments == 0)
        tracker.message("Nothing new.", "#888", 1);
    else
        tracker.message(newComments + " new comment(s).", "#000", 0);
}

// Show a div and show the given message in it.
tracker.message = function(message, color, ad)
{
    // Show the status div.
    var sd = document.getElementById(tracker.divID)
    if (!sd)
    {
        var style = "position:absolute;top:50px;right:10px;background-color:#C6DEF7;cursor:default;font:normal 14px arial;padding:10px;z-index:999999;text-align:left;border:2px dotted #336699;";
        
        sd = document.createElement("div");
        sd.id = tracker.divID;
        sd.style.cssText = style;
        document.body.appendChild(sd);
    }

    var html = "<a style=\"position:absolute;top:0px;right:3px;\" href=\"javascript:tracker.hide();\">x</a><div style=\"color:" + color + ";\">" + message;
    if (ad)
        html += "<br/><br/><a style=\"font-size:10px;color:#08F;\" href=\"http://zooov.com/break\">Break Time? :)</a>";
    html += "</div>";
    
    sd.innerHTML = html;
}


// Hide the status div.
tracker.hide = function()
{
    var sd = document.getElementById(tracker.divID)
    if (sd)
        sd.parentNode.removeChild(sd);
}



// Start executing.
tracker.main();

// Since this is a bookmarklet, we want the overall expression 
// to return void so the browser does not try to go to a new page.
void(0);
