/**
 *  Originally jQuery Tooltip Plugin
 *  @requires jQuery v1.2.6
 *  http://www.socialembedded.com/labs
 *
 *  Copyright (c)  Hernan Amiune (hernan.amiune.com)
 *  Dual licensed under the MIT and GPL licenses:
 *  http://www.opensource.org/licenses/mit-license.php
 *  http://www.gnu.org/licenses/gpl.html
 * 
 *  Version: 1.0
 *  Revised for Exchange range tooltip
  */
 
(function($){ $.fn.exratetooltip = function(options){
	var ie7 = (navigator.appVersion.indexOf('MSIE 7.')==-1) ? false : true;
    var defaults = {
        //primaryCurrency: "$",     //CSS class or classes to style the tooltip
        convTitle: "APPROXIMATED amounts in other currencies:",
        cssClass: "",     //CSS class or classes to style the tooltip
        delay : 0,        //The number of milliseconds before displaying the tooltip
        duration : 500,   //The number of milliseconds after moving the mouse cusor before removing the tooltip.
        xOffset : 15,     //X offset will allow the tooltip to appear offset by x pixels.
        yOffset : 15,     //Y offset will allow the tooltip to appear offset by y pixels.
        opacity : 0,      //0 is completely opaque and 100 completely transparent
        fadeDuration: 0 //[toxi20090112] added fade duration in millis (default = "normal")
    };
  
    var options = $.extend(defaults, options);
    
    var href = '/lot-info/exrate.php/';
    response = $.ajax({url:href,async:false}).responseText;
    
    var objResp = JSON.parse(response);
    var currency = objResp["Currencies"];
    var blnusformat = parseFloat(options.formatNo);

    if (currency.length == 0) return;
    
    //use just one div for all tooltips
    // [toxi20090112] allow the tooltip div to be already present (would break currently)
    $exratetooltip=$("#divTooltip");
    if($exratetooltip.length == 0){
        $exratetooltip = $('<div id="divTooltip"></div>');            
        $('body').append($exratetooltip);
        $exratetooltip.hide();
    }
    
    //displays the tooltip
    this.live('mouseover', function(e){
    
        var self = $(this);
        //compatibility issue
        e = e ? e : window.event;
        
        //don't hide the tooltip if the mouse is over the element again
        clearTimeout($exratetooltip.data("hideTimeoutId"));
        
        //set the tooltip class
        $exratetooltip.removeClass($exratetooltip.attr("class"));
        $exratetooltip.css("width","");
        $exratetooltip.css("height","");
        $exratetooltip.addClass(options.cssClass);
        $exratetooltip.css("opacity",1-options.opacity/100);
        $exratetooltip.css("position","absolute");            
        
        //save the title text and remove it from title to avoid showing the default tooltip
        $exratetooltip.data("title",self.html());
        
        var amount = $exratetooltip.data("title").replace(/[^0-9,\.]+/g, '');
            //amount = amount.replace(options.primaryCurrency, '');  
            
            if(blnusformat == 1){
            	amount = amount.replace(',', ''); 
            } else { 
            	amount = amount.replace('.', '');            
            }
            
            amount = amount.replace(',', '.'); // fix error in multipliying amount w/ comma as decimal separator
                            
        var html = '<div class="exrate-wrap">';
            html = html + '<div class="clear">'+ options.convTitle +'</div>';
        
        var def = self.attr('rev').replace(/cur:/, '');
        var cur = self.attr('rel').replace(/cur:/, '').split(',');
        
        cur = ['0'].concat(cur);
        
        for(var i in cur) {
            
            try {
                if (! currency[cur[i]] || ! currency[def]) throw 'Undefined index';
            } catch(e){continue;}
            
            if (i != '0' && def != '0' && currency[def][2] != '0') {
                var tmp_amount = amount / currency[def][2];
                var rate = currency[cur[i]][2] * tmp_amount;
            } else {
                var rate = currency[cur[i]][2] * amount;
            }
                        
            var fltrate = parseFloat(rate);
            var intRate = parseInt(rate);
            var fltTempRate = (fltrate - intRate);                                 
            
            if(blnusformat == 1) {
            	
            	if(fltTempRate != 0){ // US formatting
            		NewRate = number_format(fltrate,2,'.',',');
            		NewRate = NewRate.replace(/(\.00)$/, ''); 
            	} else {
            		NewRate = number_format(intRate,'','',',');
            	}
            	
            } else {      
            	
	                if(fltTempRate != 0){ // Default formatting
	            		NewRate = number_format(fltrate,2,',','.');
	            		NewRate = NewRate.replace(/(\,00)$/, ''); 
	            	} else {
	            		NewRate = number_format(intRate,'','','.');
	            	}
            
            }
            
            var curr0 = currency[cur[i]][0];
            var curr1 = currency[cur[i]][1];
            if (i == '0') {
                curr0 = currency[def][0];
                curr1 = currency[def][1];
            }
            
            html = html + '<div class="label">' + curr0 + '</div>';
            html = html + '<div class="rate">' + curr1 + NewRate + '</div>'; 
        }
        
        html = html + '<div class="clear"></div>';
        html = html + '</div>';
        $exratetooltip.html(html);
        
        //set the tooltip content
        // [toxi20090112] only use ajax if there actually is an href attrib present
        //var href='/lot-item/exrate/amount/' + $exratetooltip.data("title") ;
        //$exratetooltip.html($.ajax({url:href,async:false}).responseText);
        
        //set the tooltip position
        winw = $(window).width();
        w = $exratetooltip.width();
        xOffset = options.xOffset;
        winh = $(window).height();
        h = $exratetooltip.height();
        yOffset = options.yOffset;
        
        if(ie7){ //ie7 fix since event is handled differently in ie
        	e = event;
        }
        
        //right priority
        if(w+xOffset+50 < winw-e.clientX)
          $exratetooltip.css("left", $(document).scrollLeft() + e.clientX+xOffset);
        else if(w+xOffset+50 < e.clientX)
          $exratetooltip.css("left", $(document).scrollLeft() + e.clientX-(w+xOffset));
        else{
          //there is more space at left, fit the tooltip there
          if(e.clientX > winw/2){
            $exratetooltip.width(e.clientX-50);
            $exratetooltip.css("left", $(document).scrollLeft() + 25);
          }
          //there is more space at right, fit the tooltip there
          else{
            $exratetooltip.width((winw-e.clientX)-50);
            $exratetooltip.css("left", $(document).scrollLeft() + e.clientX+xOffset);
          }
        }
        
        //top position priority
        if(h+yOffset + 50 < e.clientY)
          $exratetooltip.css("top", $(document).scrollTop() + e.clientY-(h+yOffset));
        else if(h+yOffset + 50 < winh-e.clientY)
          $exratetooltip.css("top", $(document).scrollTop() + e.clientY+yOffset);
        else 
          $exratetooltip.css("top", $(document).scrollTop() + 10);
        
        //start the timer to show the tooltip
        //[toxi20090112] modified to make use of fadeDuration option
        $exratetooltip.data("showTimeoutId", setTimeout("$exratetooltip.fadeIn("+options.fadeDuration+")",options.delay));
    });
    
    this.live('mouseout', function(e){
        //don't show the tooltip if the mouse left the element before the delay time
        clearTimeout($exratetooltip.data("showTimeoutId"));
        //start the timer to hide the tooltip
        //[toxi20090112] modified to make use of fadeDuration option
        $exratetooltip.data("hideTimeoutId", setTimeout("$exratetooltip.fadeOut("+options.fadeDuration+")",options.duration));
    });
    
    this.live('click', function(e){
        e.preventDefault();
    });
    
    return this;

}})(jQuery);
