/*
 * danielBox 1.1 
 * Last Rev Date: 2009-05-05 
 * 
 * By Daniel Lowetz (www.daniellowetz.com)
 *
 * Renders a pop-up box out of an <a> tag.
 * 
 * User Defined Parameters:
 *   -Thumbnail Mode: true = creates thumbnails out of href url
 *   -Thumbnail Max Width/Height: scales the thumbnails
 *   -Box Initial Width/Height: sets the minimum dimensions of the box before animating 
 *   -Image Max Width/Height: scales the images to not exceed specified dimensions
 *   -Background Color: sets the bg color of the box
 *   -Add Button: true = replace content <a> is wrapping with a button graphic
 *   -Button Image: path to image file for "add button"
 *   -Close Button: true = incude a button graphic to close box.  defaults to text "close"
 *   -Preload Image: path to graphic displayed while box is loading main image
 *   -Rounded Corners: true = CSS rounded corners (does not work with IE)
 *   -Corner Radius: corner radius for rounded corners
 *   -Center Screen: true = open box in center of screen.  false = open from point of mouse click
 *   -Y-Axis Offset: used to adjust vertical placement of box
 */

(function($) {
	$.fn.danielPop = function(options) {
		// Default Parameters
		var defaults = {
			openOn:"", //choose "click" or "mouseover"
			thumbNails: true, //turn auto thumbnail mode on or off
			headerText: false, //Makes a header out of the "alt" attr of the <a> tag
			thumbMaxWidth: 90, //max width of thumbnail - if object is an image
			thumbMaxHeight: 90, //max height of thumbnail - if object is an image
			initWidth: 150, //width of pop-up box before photo loads
			initHeight: 150, //height of pop-up box before photo loads
			imgMaxWidth: 500, //max width of image after animation
			imgMaxHeight: 500, //max height of image after animation
			bgColor: "#FFF", //pop-up background color 
			addButton: true, //replace linked text with a graphic
			buttonImage: "../js/danielPop/qmark.gif", //path to button graphic
			closeButton: true, //include a close button in upper right corner of box
			preloadImage: "../js/danielPop/circleloader.gif", //path to preload graphic
			roundCorners: true, //turn rounded corners on of (no rounded corners in IE)
			cornerRadius: 10, //set radius for rounded corners
			centerScreen: false, //true = opens in center of screen.  false = opens relative to mouse position
			followMouse: true, //true = box will follow the mouse while mouse id over the <a> tag
			yOffset: 0 // vertical offset adjustment for where the box will open		
        }; 
		
        var options = $.extend(defaults, options);
		
		return this.each(function(i){
			obj = $(this);
//------------------detect browser---------------------------------------------------------------		
	if (jQuery.browser.msie) {
		var vsn=parseInt(jQuery.browser.version);
		if(vsn>=8) {
    		msie6=false;
			msie7=false;
			msie8=true;		
		}else if(vsn>=7&&vsn<8){
			msie6=false;
			msie7=true;
			msie8=false;
		}else if(vsn>=5&&vsn<7){
			msie6=true;
			msie7=false;
			msie8=false;
		}
	}else{
		msie6=false;
		msie7=false;
		msie8=false;
	}
//----------------------------Pre-Defining Some Variables--------------------------------------
	var trigEvent=options.openOn;
	boxW=options.initWidth;
	boxH=options.initHeight;
	resW=screen.width;
	resH=screen.height;
	maxW=options.imgMaxWidth;
	maxH=options.imgMaxHeight;
	var objClass=obj.attr('class');
	var openedBox;
	var timgW;
	var timgH;
	var i=jQuery('body a').index(this);  //getting the index of each object, which will be used as a unique identifier
	var thisIndex=i;  //just giving it another name so it makes more sense in the code

	if(trigEvent=='mouseover'){ 
			obj.click(function(){return false});
	}
//----------------------------Creating Thumbnails-----------------------------------------------
	if(options.thumbNails){  //if thumbnail mode is set to "true"
		var photoTarget=jQuery(this).attr('href');
		var thisImg=jQuery(this);
		//preload the images and then proceed once loaded
		var thumbImg = new Image(); 
		jQuery(thumbImg).load(function(){
			tmaxW=options.thumbMaxWidth;
			tmaxH=options.thumbMaxHeight;
			timgW=thumbImg.width;
			timgH=thumbImg.height;
			if(timgW>tmaxW){timgH=timgH*(tmaxW/timgW); timgW=tmaxW;};
			if(timgH>tmaxH){timgW=timgW*(tmaxH/timgH); timgH=tmaxH;};
			thumbImg.width=timgW;
			thumbImg.height=timgH;
			jQuery(this).attr("border","0");
			jQuery(this).attr('id','link'+i); //asign the uniq ID (used to differentiate each image) 
			thisImg.html(thumbImg); //replaces old content wrapped by <a> with new thumbnail img
			//if thumbnail dimension is less than minimum intial box, set initial box to thumb size
			if(timgW<boxW){boxW=timgW;} 
			if(timgH<boxH){boxH=timgH;}
		}).attr('src',photoTarget);
	}else if(!obj.children('img').length&&options.addButton){ 
	//if thumbNails "false", addButton "true", and <a> tag is not already wrapping an <img>, replace text with button
		jQuery(this).html('<img id="link'+i+'"src="'+options.buttonImage+'" border="0" align="absbottom" alt="help"/>');
	}else{
		//if thumbNails and addButton "false" asign the uniq ID to the <a> tag
		jQuery(this).attr('id','link'+i);
	}

//-----------------------Object Click Event-----------------------------------------------------
	obj.bind(trigEvent,function(e){
		
		//function called to close the box
		function closeBox(ob){
			closeTarget='#img_'+ob;  // close the box based on its ID
			jQuery('#img_'+ob).animate({top:-25},{
				queue:false,complete:function(){
					jQuery('#img_'+ob).hide(); //hide the header after it is slid up
					jQuery(closeTarget).next('div').children('img').animate({
						width:"0px",
						height:"0px",
						opacity:0
					},{
						queue:false,
						complete:function(){
						jQuery(closeTarget).parent().remove();
						}
					},1000);
				}
			},300);	
		};			   
//-------------------------------------------------------------------------------			   
		if(trigEvent=='mouseover'){ 
			$('body').bind('mouseover',function(e){
				var clickId=e.target.id;
				
				// the next line is mostly for IE.  IE allow the mouse to overlap the newly created boxelement for a split 
				// second before repositioning it.  this gives a false mouseout detection and instantly closes the new box.
				// supplying a list of elements to ignore is messy, but does the trick.
				if((clickId!='photoBox')&&(clickId!='img_'+thisIndex)&&(clickId!='photoBoxInner')&&(clickId!='loader')&&(clickId!='closeCnt')&&(clickId!='loadImg')&&(clickId!='close')){
					jQuery('#img_'+thisIndex).parent('#photoBox').remove();
				}
			});
		}
		
		if(!jQuery('#img_'+thisIndex).length){
			if(jQuery('#photoBox').length){ 
				jQuery('#photoBox img').stop({clearQueue:true, gotoEnd:false});
				//jQuery(img).attr('src','');
				jQuery('#photoBox').remove();
			}
			
			var photoUrl=jQuery(this).attr('href');
			
			//include header text
			if(options.headerText){
				if(jQuery(this).attr('alt')){ //if alt attr exsists
					var photoAlt=jQuery(this).attr('alt');
				}else{
					var photoAlt='';
				}
				//create the DIV for the header text
				photoText='<div id="pt" style="position:absolute;top:0;left:0;height:20px;"><span id="photoText">'+photoAlt+'</span></div>';
			}else{
				photoText='';
			}
			//Open in center of screen?
			if(options.centerScreen!=false){
				posX=(resW-boxW)/2;
				posY=(resH-boxH)/2;
			}else{
				// get coordinates of mouse click
				posX=e.pageX+10;
				posY=e.pageY-options.yOffset;
			};
			
			//rounded corners?
			if(options.roundCorners){
				rad=options.cornerRadius;
				photoBoxStyle='-webkit-border-radius:'+rad+'px;-khtml-border-radius:'+rad+'px;-moz-border-radius:'+rad+'px;border-radius:'+rad+'px;';
			}else{
				photoBoxStyle='';	
			}
			
			//include close button in upper right corner?
			if((options.closeButton)&&(!options.followMouse)){
				closeButton='<img style="margin-bottom:2px;" src="../js/danielPop/cross.gif" alt="Close"/>';
				closeButtonHeight=22;//used when calculating dimensions of box  
			}else{
				closeButton='';
				closeButtonHeight=0;
			}
			
			//HTML for the box
			jQuery('body').prepend('<div id="photoBox" style="position:absolute;background-color:'+options.bgColor+';border:solid 1px #000;'+photoBoxStyle+'z-index:4000;padding:5px;font-family:Verdana, Arial, Helvetica, sans-serif;"><div class="boxHead" id="img_'+thisIndex+'" style="position:relative;top:-25px;left:0;height:20px;width:100%;visibility:hidden;"><div id="closeCnt" style="position:absolute;top:0;right:0;"><span id="close">'+closeButton+'</span></div></div><div align="center" id="photoBoxInner"><div id="loader" style="height:'+boxH+'px;width:'+boxW+'px;"><img id="loadImg" style="margin-top:'+(boxH-32)/2+'px;" src="'+options.preloadImage+'" alt="Loading"/></div></div></div>');
			
			if(msie6){
				//IE6 Begins the box animation at full width, unless you...
				jQuery('.boxHead').css("width","1%");
			}
		
			//position the starting point of the modal
			jQuery('#photoBox').css({"top":posY, "left":posX});
			
			//if follow mouse set true
				if(options.followMouse){
					$(document).bind('mousemove',function(e){				 
						var mx=e.pageX;
						var my=e.pageY-options.yOffset;
						jQuery('#img_'+thisIndex).parent('#photoBox').css({"top":my,"left":mx+10});
					});
				}
			//preload the image
			var img = new Image();
  			jQuery(img).load(function(){
				var imgW=img.width;
				var imgH=img.height;
				if(imgW>maxW){imgH=imgH*(maxW/imgW); imgW=maxW;};
				if(imgH>maxH){imgW=imgW*(maxH/imgH); imgH=maxH;};
				img.width=boxW;
				img.height=boxH;
				
				if(options.centerScreen!=false){
					posX=(resW-imgW)/2;
					posY=(resH-imgH)/2;
				};
				
				//positioning the box accordingly
				jQuery('#photoBox').css({"top":posY,"left":posX});
      			jQuery(this).hide();
      			
				jQuery('#photoBoxInner').html(this);
				jQuery(this).fadeIn().animate({
					width:imgW,
					height:imgH
				},{
					queue:false,
					complete:function(){
						
						jQuery('#close').css("cursor","pointer");
						jQuery('#close').hover(function(){$(this).css("color","#FF0000");},function(){$(this).css("color","#000000");});
						jQuery('#close').click(function(){closeBox(thisIndex);});
			      		
						//getting coordinates to determine where box is on screen
						if(trigEvent!='mouseover'){
							var padding=jQuery('#photoBox').css("padding"); //get padding attr of box to figure into X-Y cords 
							padding=padding.substr(0,padding.length-2)*2;
							var top=Math.round(posY);
							var right=Math.round(posX+imgW+padding)+2; //add 2 to account for 1px border on each side
							var bottom=Math.round(posY+imgH+closeButtonHeight+padding);
							var left=Math.round(posX);
						}
						//tweaking some CSS for Internet Explorer...
						if(msie8){
			   				jQuery('.boxHead').css({"margin":"0 0 2px 0"});
							jQuery('#pt').css("overflow","hidden");
						}else if(msie7||msie6){
							//IE7 insists on having a fixed width for the boxHead element.  Very unfortunate.
							jQuery('.boxHead').css({"width":imgW,"margin":"0 0 2px 0"});
						}
						
						//Firefox has trouble animating rounded corners on an element containing a hidden element.  Applying CSS here fixes.
						jQuery('#photoBox').css("overflow","hidden");
						jQuery('.boxHead').css("visibility","visible");
					
						jQuery('#img_'+thisIndex).prepend(photoText);
						//animate the header so it slides down form top
						jQuery('#img_'+thisIndex).animate({top:0},300);
						
						//detect if mouse is clicked outside of box
						$(document).bind('mouseup',function(e){				 
							var clickId=e.target.id;
							//alert(clickId+' : '+thisIndex);  //just a test
							if(clickId!='link'+thisIndex){
								mx=e.pageX;
								my=e.pageY;
								if(mx<left||mx>right||my<top||my>bottom){
									closeBox(thisIndex);
								}
							}
						});
						
					}
				});
			}).attr('src', photoUrl);		
		}
		return false;
	});
//----------------------------------------------------------------------------------------------------------			
		});
	};		
})(jQuery);							
