/**
 * @author tparent
 * @title snippetManager
 * @usage $(div).setupSnippets()
 *        $(div).switchSnippets()
 * 
 */

(function($){
    /*
     * function: setupSnippets()
     * usage   : setupSnippets(options)
     *           options = array of settings values, to override the defaults
     *           
     */
    $.fn.setupSnippets = function(options){

        options = $.extend({
            titleTag: this.attr('titleTag') || 'h3',
            timelineClass:  this.attr('timelineClass') || 'timeline',
            timelineImageClass: this.attr('timelineImageClass') || 'timeline-bar',
            endClass: this.attr('endClass') || 'end',
            timestampClass: this.attr('timestampClass') || 'timestamp',
            bubbleClass: this.attr('bubbleClass') || 'bubble',
            inactivePointerClass: this.attr('inactivePointerClass') || 'snippet',
            activePointerClass: this.attr('activePointerClass') || 'active-snippet',
            markerClass: this.attr('markerClass') || 'marker'
        }, options || {});
        
        return this.each(function() {
            var $this = $(this);

            var timeline = $('.'+options.timelineClass, $this);
            var timelineOffsets = timeline.offset({border: true, padding: true});
            var timestampNodes = $('.'+options.timestampClass, timeline);
            
            /* convert the time of the total clip ('[hh]:mm:ss') into seconds */
        	var timelineEnd = getTimeInSeconds($('.'+options.endClass,timeline).html());
            
            /* create an object of the timeline image, and get its position on the page. The snippet
             *   pointers will be positioned based on this value.
             */
        	var timelineImage = $('.'+options.timelineImageClass,timeline);
            var timelineImageOffsets = timelineImage.position();
    
        	/* For each .timestamp, we need to get the position of its pointer on the timeline.
    	     *    We can do this by getting the timestamp of the current .timestamp, divide that by
        	 *    the end time of the entire clip (create a percentage), and then use that to calculate
        	 *    the left CSS value of the pointer.
        	 */
            
            /* BUT FIRST, we need to check if we actually have any timestamp nodes.  There are
             *    occasions where you won't - for example, if the search result was returned in
             *    the title rather than in the actual talky-talky.
             */
            if(timestampNodes.length == 0) {
                // First, we need to create an empty timeline div.
                timelineImage.before("<div class='"+options.timestampClass+"' title='0:00'></div>");
                // Then, we'll fill it with the description from the bubble.
                myNewCopy = $('.'+options.bubbleClass+' .wrapper', $this).html()
                $("."+options.timestampClass, timeline).append(myNewCopy).bind("click", function(){
        	location.href = $(this).children('a:first').attr('href');
        });
                // And finally, we'll fill the timestampNodes so the .each to follow won't die.
                timestampNodes = $('.'+options.timestampClass, timeline);
            }
            // if(window.console) console.log();
            
            timestampNodes.each( function(index) {

                mySnippet = $(this);
				
                /* convert the passed timestamp '[hh]:mm:ss' into seconds */
            	var snippetTime = getTimeInSeconds(mySnippet.attr("title"));
                var snippetPosition = mySnippet.position();
                /* For each timestamp node, we should create the timeline pointer anchor dynamically,
                 * as well as hiding the paragraph in this timestamp. The net result is that we have
                 * a timestamp div with a pointer showing and the textual content hidden.            */
               mySnippet.addClass(options.inactivePointerClass);
               mySnippetsPointerLink = mySnippet.children('p').children('a:first').attr('href');
               mySnippet.prepend("<a href='"+mySnippetsPointerLink+"'>.</a>");
               mySnippet.children('p').hide();
    
                /* Now, we need to calculate the position of the timestamp div. Given that its visible content
                 *   consists of the pointer, the net result is that we're setting the left edge of the pointer.
                 */
                var positionInPercent = (snippetTime/timelineEnd <= 1) ? snippetTime/timelineEnd : 1;
                var horizontalPosition = Math.round(timelineImage.width() * positionInPercent)+timelineImageOffsets.left-(parseInt(mySnippet.width())/2);
                var verticalPosition = parseInt(timelineImageOffsets.top) - parseInt(mySnippet.height()-2);
                // if (window.console) console.log("Position on bar: "+positionInPixels+"px ("+positionInPercent+"%) -- timeline is:"+timelineImage.width()+", Image left edge is at: "+timelineImageOffsets.left );
        
                mySnippet.css("left", horizontalPosition + "px").css("top", verticalPosition+"px");
                mySnippetOffsets = mySnippet.position();
                
                // console.log('Ideal left of clip marker: '+mySnippet.css("left") +'; Actual left: '+mySnippetOffsets.left );
            
                mySnippet.bind("mouseover", function () {
                    switchSnippets(this);
                });
            });
            /* OK, now that we have all the calculations done, we'll create the bubble class, inserted
             *     between the title and the timeline classes.
             */
           // timeline.before("<div class='"+options.bubbleClass+"'><div id='"+timeline.attr('id')+"_wrapper'></div></div>");
                      
           /* ... and last, set the first (or only) timeStamp node to be displayed in the bubble initially */
           switchSnippets(timestampNodes[0]);
        });
        
            /* switchSnippets()
     *    Class to toggle snippets. The passed snippet will be made the active snippet, and the current
     *    active snippet will be made inactive. In addition, the mouseover action is disabled for the current
     *    active snippet, and is re-enabled for the inactivated snippet.
     */
    function switchSnippets(snippet) {
        var $snippet = $(snippet);
        
        /* First, we get the current active snippet, bind the mouseover event, and switch it to inactive */
        $snippet.siblings('.'+options.activePointerClass)
                 .bind('mouseover',function(){
                    switchSnippets(this);
                 })
                 .removeClass(options.activePointerClass)
                 .addClass(options.inactivePointerClass);
        /* Next, we get the passed snippet, unbind the mouseover event, and switch it to active */
        $snippet.unbind('mouseover')
                 .removeClass(options.inactivePointerClass)
                 .addClass(options.activePointerClass);
        /* And last, we dump the contents of the 'p' tag in the passed div to the wrapper class. */
        $('.'+options.bubbleClass+' div', $snippet.parent().parent()).html($('p', $snippet).html()).unbind("click").bind("click", function(){
        	location.href = $(this).children('a:first').attr('href');
        });
        return false;
    };
            
    function getTimeInSeconds(myTime) {
        var myTimeArray = [];
        var myTimeLength = 0;
        var i,j = 0;
    
        // Take the myTime string and split it into an array
        myTimeArray = myTime.split(":");
    
        for (i=myTimeArray.length-1, j=1; i>=0; i=i-1, j=j*60) {
            myTimeLength += myTimeArray[i]*j-0;
        }
        return myTimeLength;
    };

    };

})(jQuery);
