/* tooltips */
(function($){
    $.fn.extend({
    "cfTip": function(options) {
        if(options === 'remove') {
        return this.each(function(){
            var tooltip = $(this).data('cfTip');
            if(tooltip) {
            tooltip.remove();
            $(this).data('cfTip', false);
            }
        });
        }
        options = $.extend({
        type: 'normal',
        scope: 'body',
        tabs: false,
        templates: '#cfTip-templates' ,
        orientation: 'right',
        leftOffset: 0,
        arrowOffset: 0
        }, options);
        
        return this.each(function(){
        var $this           = $(this),
            tooltipTemplate = $(options.templates).find('.tooltip-container'),
            tooltip;
        
        // If a tooltip doesn't already exist, create one
        if (!$this.data('cfTip')) {
            
            // Clone the template without any event handlers
            tooltip = tooltipTemplate.clone();
            
            // Store two-way references in the tooltip and the attached element
            $this.data('cfTip', tooltip);
            tooltip.data('tooltipInstance', this);
            
            // Add the tooltip to the dom (watchout for uls or other invalid children)
            $(options.scope).append(tooltip);
            
            // Choose our orientation (haha)
            var positionObject = {};
            if (options.orientation === 'right') {
            positionObject = {
                "position" : "absolute",
                "z-index"  : 9999,
                "left"     : ($this.offset().left+$this.outerWidth()+options.leftOffset) + 'px',
                "top"      : ($this.offset().top-32) + 'px'
            };
            }
            else if (options.orientation === 'top'){
            positionObject = {
                "position" : "absolute",
                "z-index"  : 9999,
                "left"     : ($this.offset().left+options.leftOffset) + 'px',
                "top"      : ($this.offset().top-(options.height+39)) + 'px'
            };
            
            tooltip.find('.t-arrow').css({
                "margin-top": (options.height+9)+'px',
                "margin-left": (30-options.leftOffset)+'px'
            });
            }
            
            // Depending on a fixed height - set it or dont
            if (options.height) {
            positionObject.height = options.height+'px';
            } else {
            positionObject.height = 'auto';
            }
            
            // Make sure it's the only tooltip open if that's the way it's gonna be
            if (options.solo) {
            $('.tooltip-container:visible').hide();
            }
            
            // Use our setup to create and show the element on the screen
            tooltip
            .addClass('t-'+options.type)
            .addClass('t-orien-'+options.orientation)
            .data('cfTip.options', options)
            .find('.t-content')
                .html((options.content || $(this).attr('title') || "-"))
                .css("height", positionObject.height)
                .end()
            .show()
            .css(positionObject)
            .hover(function(){
                $(this).addClass('tooltipHovered');
            },function(){
                $(this).removeClass('tooltipHovered');
            });
            
            // If this is a tabbed tooltip, activate the tab clicking functionality
            // also change any ids so there are no duplicates
            if (options.tabs) {
            tooltip.find('.t-tab').each(function(){
                // Clone the template, but change the ids
                var $this = $(this),
                newID = $this.attr('id') + (+new Date());
                
                // Update the link to reflect this change
                $this.parent().find('.top-tabs a[href*='+$this.attr('id')+']').attr('href', '#'+newID);
                
                // Update the actual id
                $this.attr('id', newID);
            });//.closest('.tooltip-tabs-container').tabs();
            }
            
        }
        });
    }
    });
})(jQuery);


// Form tooltips
$(function(){        
    $('body').append(
    $('<div id="cfTip-templates" style="display:none;" />')
        .html('<div class="tooltip-container"><div class="t-top"></div><div class="t-arrow"></div><div class="t-content"></div><div class="t-bottom"></div></div>'+
        '<div class="tooltip-tabs-container">'+
                '<div class="tooltip_left">'+
                '<img src="assets/images/mark.jpg" width="8" alt="" />'+
                '</div>'+
                '<div class="tooltip_right">'+
                '<div class="tooltip_title">'+
                'OUR APOLOGIES'+
                '</div>'+
                '<div class="tooltip_content">'+
                "We are unable to find the eCode you have entered in our system. Please use the 'Forgot your eCode' link or call {phone} for assistance." +
                '</div>'+
                '</div>'+
                '<div style="clear:both;"></div>'+
            '</div>'
        )
    );   
    
    $('.top-tabs a').bind('click', function(){
    var $this = $(this),
    // Get the tab that we want as a string
    loc = $this.attr('href').substring(1),
    
    // Get our parent container
    tabContainer = $this.closest('.t-content');
    
    // show the related block that was clicked
    tabContainer.find('.t-tab.'+loc).show();
    // hide any blocks that are not that block
    tabContainer.find('.t-tab:not(.'+loc+')').hide();
    
    // stop the click from going through
    return false;
    });
    
    // Handle the scroll events
    $('.subgroup_body').scroll(function(){
    $('.tooltip-container').each(function(){
        var tip = $(this).data('tooltipInstance');
        if(tip) {
        $(tip).cfTip('remove');
        }
    });
    });
});

// Ticker Tooltips
$(function(){
    
    // returns the html
    function getGraphContainer(graph_name, unique) {
    var chartContainer = $('<div id="'+unique+'" class="'+graph_name+'" />');
    return chartContainer;
    }
    
    $('#change-ticker li').hover(function(){
    var $this = $(this),
        index = $this.parent().find('li').index(this),
        win_offset = $this.offset().left,
        win_width  = $(window).width(),
        graph      = $this.attr('rel');
    
    $this.cfTip({
        type:'error',
        scope: 'body',
        tabs: true,
        orientation: 'top',
        height:300,
        solo: true,
        leftOffset: -1 * Math.round(190 * (win_offset/win_width)), // calculate the window offset at display time
        // You can pass any html here, so instead of a template, you could pass in
        // whatever markup is needed to create the tabs or any content you want,
        // this shows the generic tabs that I put in the templates
        content: (($this.attr('rel')) ? getGraphContainer(graph, 'graph-'+$this.data('')) : $('#cfTip-templates .tooltip-tabs-container').clone())
    });
    
    // Create Graph if needed
    if (graph) {
        if (graph === 'pie_chart') {
        var r = Raphael('graph-'+$this.data(''), 230, 120);
        r.g.txtattr.font = "11px 'Fontin Sans', Fontin-Sans, sans-serif";
        
        var pie = r.g.piechart(105, 60, 50, [55, 20, 13, 32, 5, 1, 2, 10]);
        pie.hover(function () {
            this.sector.stop();
            this.sector.scale(1.1, 1.1, this.cx, this.cy);
            if (this.label) {
            this.label[0].stop();
            this.label[0].scale(1.5);
            this.label[1].attr({"font-weight": 800});
            }
        }, function () {
            this.sector.animate({scale: [1, 1, this.cx, this.cy]}, 500, "bounce");
            if (this.label) {
            this.label[0].animate({scale: 1}, 500, "bounce");
            this.label[1].attr({"font-weight": 400});
            }
        });
        }
        else if (graph === 'horiz_bar_chart') {
        var bgraphs = [
            {
                title : 'Dollars vs. Euros',
                bars  : [[35], [10]]
            }
            ],
            count = bgraphs.length;
            
            var r = Raphael('graph-'+$this.data(''), 210, 30),
            fin = function () {
                this.flag = r.g.popup(((this.bar.x-20) > 0) ? this.bar.x-20 : 5, this.bar.y, formatNumber(this.bar.value+"") || "0", 3, 2).insertBefore(this);
            },
            fout = function () {
                this.flag.animate({opacity: 0}, 300, function () {this.remove();});
            };
            
            r.g.hbarchart(10, 5, 140, 22, bgraphs[0]['bars']).hover(fin, fout);
        }
        else if (graph === 'bubble_chart') {
        // use raw raphael to do bubble charts
        var paper = new Raphael('graph-'+$this.data(''), 250,250);
        
        var flag;
        var circle1 = paper.circle(105, 105, 90).attr({fill: "#436521", stroke: "#333333", "stroke-width": 2}).hover(
               function(){ flag = paper.g.popup(100, 50, "5/5ths"); flag.insertAfter(this);},
               function(){ flag.animate({opacity: 0}, 300, function () {this.remove();});}
        );
        var label1 = paper.text(30,30, 'Outer Circle');
        
        // The Fraction that the bubble needs to represent
        var fraction = 2/5;
        
        var flag2;
        var circle2 = paper.circle(105, 105, fraction*90).attr({fill: "#FFFFFF", stroke: "#333333", "stroke-width": 1}).hover(
               function(){ flag2 = paper.g.popup(115, 115, "2/5ths"); flag.insertAfter(this);},
               function(){ flag2.animate({opacity: 0}, 300, function () {this.remove();});}
        );
        var label2 = paper.text(90,90, 'Inner Circle');
        
        
        }
    }
    },function(){
    $this = $(this),
    
    // Get the tooltip instance
    thisTooltip = $($this.data('cfTip'));
    
    setTimeout(function(){
        // Check if the user is hovering over the tooltip
        if(!thisTooltip.hasClass('tooltipHovered')){
        // If not, then remove it
        $this.cfTip('remove');
        } else {
        // If so, delay the removal until they stop hovering
        thisTooltip.mouseleave(function(){
            $this.cfTip('remove');
        });
        }
    },50);
    });
});