/*
 * jQuery clueTip plugin
 * Version 0.2  (05/16/2007)
 * @requires jQuery v1.1.1
 * @requires Dimensions plugin 
 *
 * 
 * Copyright (c) 2007 Karl Swedberg
 * Inspired by Cody Lindley's jTip (http://www.codylindley.com)
 * Thanks to Shelane Enos for the feature ideas 
 * Thanks to Jonathan Chaffer, as always, for the help.
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 */


(function($) { 
    
  var $cluetip, $cluetipInner, $cluetipOuter, $triggerEvent, $triggerTime;

  $.fn.cluetip = function(options) {
    
    // set up default options
    var defaults = {
      width: 275,
      local: false,
      attribute: 'rel',
      titleAttribute: 'title',
      hoverClass: '',
      waitImage: '../styles/wait.gif',
      sticky: false,
      activation: 'hover',
      closePosition: 'top',
      closeText: 'Close',
      truncate: '',
      dataType: 'html',
      pngFix: false,
      ajaxProcess: function(data) {
        data = $(data).not('style, meta, link, script, title');
        return data;
        }
    };
    
    return this.each(function() {
      
      $.extend(defaults, options);

      // create the cluetip divs
      if (!$cluetip) {
        $cluetipInner = $('<div id="cluetip-inner" class="clearfix"></div>');
        $cluetipOuter = $('<div id="cluetip-outer"></div>')
        .append($cluetipInner);
        
        $cluetip = $('<div></div>')
          .attr({'id': 'cluetip'})
          .css({position: 'absolute'})
        .append($cluetipOuter)
        .appendTo('body')
        .hide();
      }
     /* if (defaults.pngFix) {
        $('#cluetip').pngfix();
      }*/
      var $this = $(this);      
      var tipAttribute = $this.attr(defaults.attribute);
      if (!tipAttribute) return true;
      
      // vertical measurements
      var tipHeight, wHeight;
      var sTop, offTop, posY;

      // horizontal measurements
      var tipWidth = parseInt(defaults.width, 10);
      var offWidth = this.offsetWidth;
      var offLeft, posX, docWidth;
      
      var tipTitle = (defaults.attribute != 'title') ? $this.attr(defaults.titleAttribute) : '';
      var localContent;
      
      // close cluetip and reset title attribute if one exists
      var cluetipClose = function() {
       // $cluetipOuter.css('backgroundImage', 'url(' + defaults.waitImage + ')');
        $cluetipInner.empty().parent().parent().hide();
        if (tipTitle) {
          $this.attr('title', tipTitle);
        }
      };

      var cluetipShow = function(bpY) {
        tipHeight = $cluetip.outerHeight();
        //console.log($cluetipInner.find('img').height());
        //console.log($cluetipInner.height())

        if ($this.css('display') == 'block') {
          $cluetip.css({top: ((bpY-(tipHeight/2)) - 10) + 'px'});
          //console.log(((bpY-(tipHeight/2)) - 10));

        }
        else {
          $cluetip.css({top: (posY-(tipHeight/2)) + 'px'});
          //console.log((posY-(tipHeight/2)));
        }

        if (defaults.truncate) {
          var $truncloaded = $cluetipInner.text().slice(0,defaults.truncate) + '...';
          $cluetipInner.html($truncloaded);
        }
		
		// get lightbox hight
		var lbHeight = $("div#lightbox").height();
		//console.log(wHeight);
        //console.log(lbHeight);
        //console.log(tipHeight);
        //console.log(posY);
        //console.log(sTop);
        if ( (posY-(tipHeight/2)) + tipHeight > ((sTop + wHeight)-lbHeight) ) {
          	$cluetip.css({top: (((sTop + wHeight)-lbHeight) - tipHeight - 2)-10 + 'px'});
          	//console.log('adjusting bottom:'+(((sTop + wHeight)-lbHeight) - tipHeight - 2));
          	
        	
        } 
        
        if ( (posY-(tipHeight/2)) < sTop ) {
        	 $cluetip.css({top: sTop+10 + 'px'});
        	//console.log('top alignment:' +posY);
            // console.log((tipHeight/2)+','+posY+','+sTop+','+((posY-(tipHeight/2))));

        }
		//console.log((posY-(tipHeight/2)) + ',' +sTop);
        if (defaults.sticky) {
          var $closeLink = $('<a href="#" id="cluetip-close">' + defaults.closeText + '</a>');
          (defaults.closePosition == 'bottom') ? $cluetipInner.append($closeLink) : $cluetipInner.prepend($closeLink);
          $closeLink.click(function() {
            cluetipClose();
            return false;
          });
        }
        if (tipTitle) { 
          $cluetipInner.append('<h3 id="cluetip-title">' + tipTitle + ' <span class="grey">click for more information</span></h3>');
        }
        $cluetip.show();
       // $cluetipOuter.css('backgroundImage', 'none');         
      };

      
// ACTIVATION ...

// activate by click
    if (defaults.activation == 'click'||defaults.activation == 'toggle') {
      $this.toggle(function(event) {
        activate(event);
        this.blur();
        return false;
      }, function(event) {
        inactivate(event);
        this.blur();
        return false;
      });

    } else {
      $this.click(function() {
        if (tipAttribute == $this.attr('href')) {
          return false;
        }
      });
    
      $this.mouseover(function(event) {
        $triggerEvent = event;
        window.clearTimeout($triggerTime);
        $triggerTime = window.setTimeout(delayedactive,400);
        $this.mouseout(function(){
        	window.clearTimeout($triggerTime);
        	 $this.unbind('mouseout');
        	// console.log('no timeout');
        });
        //activate(event);
      }); 
    /*  $this.mouseout(function(event) {
      	if ($('#cluetip').mouseover() == false) {
        	inactivate(event);
        }
      });*/
    }
//activate clueTip      
	var delayedactive = function() {
		$this.unbind('mouseout');
		activate($triggerEvent);
	}

      var activate = function(event) {
        if (tipAttribute == $this.attr('href')) {
          $this.css('cursor', 'help');
        }
        if (tipTitle) {
          $this.removeAttr('title');          
        }
        if (defaults.hoverClass) {
          $this.addClass(defaults.hoverClass);
        }
        
        sTop = $(document).scrollTop();
        offTop = $this.offset().top;
        offLeft = $this.offset().left;
        docWidth = $(document).width();
        /*posX = (offWidth > offLeft && offLeft > tipWidth)
          || offLeft + offWidth + tipWidth > docWidth 
          ? offLeft - tipWidth - 15 
          : offWidth + offLeft + 15;*/
          posX = offWidth + offLeft + 15;
          posflag = false;
          if (offWidth > offLeft && offLeft > tipWidth) {
          	posflag = false;
          } else if (offLeft + offWidth + tipWidth > docWidth) {
          	posflag = true;
          }
          
          
        posY = (offTop+46);
		//console.log(tipHeight);
        //$cluetip.css({width: defaults.width});
        $cluetip.css({width: '277px'});
        if ($this.css('display') != 'block' && posX >=0) {
        	if(-offLeft > (posX - tipWidth + 45)) {
        	 $cluetip.css({left: (posX-110) + 'px'});
        	} else {
         	 $cluetip.css({left: (posX-tipWidth+45) + 'px'});
         	}
          //console.log((posX-tipWidth+45));
         // $('.col858').prepend('1-'+(posX-45)+'  ...');
        } else {
          if (event.pageX + tipWidth > docWidth) {
          	//$('#navigation').after('1');
          	 if (posflag) {
            	posX = offLeft - tipWidth - 15 + 45;
            }
            $cluetip.css({left: (posX+93) + 'px'});
            //$('#navigation').after('2-'+(posX+93)+'  ...');
          } else if(-offLeft > (posX - tipWidth + 45)) {
			//$('#navigation').after('2');
          	$cluetip.css({left: (posX-110) + 'px'});
          
          } else {
          	
           // $('#navigation').after('3');
            if (posflag) {
            	posX = offLeft - tipWidth - 15 +45;
            	$cluetip.css({left: (posX+93) + 'px'});
            } else {
            	$cluetip.css({left: (posX-tipWidth+45) + 'px'});
            }
            //$('#navigation').after('3-'+(posX-tipWidth+45)+'  ...');
          }
         
          var pY = posY;
         
        }
       // $('#navigation').after(' --- ');
      //    $('#navigation').after($cluetip.css('left')+',');
        //  $('#navigation').after(offLeft+',');
       //   $('#navigation').after(posX+',');
        wHeight = $(window).height();
		var lastevent;
		var oT = offTop;
		var oL = offLeft;
		
		/// new mousmove event added for each rollover.... which element can we bind this to
		/// maybe canvas and then remove before adding again
		//$this.unbind();
		$('body').unbind();
		$('body').mousemove(function(e) {
			var tx = e.pageX;
			var ty = e.pageY;
			if (tx < oL || tx > oL+93 || ty < oT || ty > oT+93) {
			//	console.log('calling inactivate');
				inactivate(lastevent);
			//	lastevent = null;
			}
			
		//console.log(($this.parent().attr('href')));	
		var link = $this.parent().attr('href');	
		if(link != null) {
			$cluetip.click(function(){
				document.location.href=link;
			});	
		} else {
			$cluetip.unbind();
		}
			//$('.col858').prepend(offLeft+':'+e.pageX+','+offTop+':'+e.pageY);
			
			//console.log(offLeft+':'+e.pageX+','+offTop+':'+e.pageY);
		});
		
// load external file via ajax
        if (!defaults.local && tipAttribute.indexOf('#') != 0) {

          $.ajax({
            url: tipAttribute,
            success: function(data) {
              $cluetipInner.html(defaults.ajaxProcess(data));
              cluetipShow(pY);
            }
          });

// load an element from the same page
        } else if (defaults.local && tipAttribute.indexOf('#') == 0){
          var localContent = $(tipAttribute).html();
          $cluetipInner.html(localContent);
          cluetipShow(pY);
        }
      };
 // on mouseout...    
      var inactivate = function() {
        if (defaults.sticky == false) {
          cluetipClose();
        };
        if (defaults.hoverClass) {
          $this.removeClass(defaults.hoverClass);
        }
      };
      
    });
  };  
  
})(jQuery);


$(document).ready(function(){
	
	/*image popup clue tip */
	$("div#main").find('.img').find("img").each(function(){
		$(this).cluetip({attribute:'id',width:'277px'});
	});
	
});
