//////////////////////////////////////////////////////
//Written by Kevin Green - May-August/2008
//kevin.m.green[at]uscg.mil
//Description: Creates windows that float with different options
//////////////////////////////////////////////////////

//Modifications:

//July 14, 2008 2:05 PM - by KG
//1. Added comments

//////////////////////////////////////////////////////

//used to keep track of select boxes in here
var selectArray = new Array();
var selectArrayEnd=0;

//keeps track of the windows that are created
var windowArray = new Array();
var windowArrayEnd=0;

//haha yeah this is a 
var intervaltracker; //tracks periods of checking if we're hitting a select box
var zIndexCounter=1; //raises windows and increments their z-index

//get all select elements and stick their sizes, locations in an array
$(document).ready(function(){
	$("select").each(function(){
		var tempPos = $(this).offset();
		selectArray[selectArrayEnd]={left:tempPos.left, top:tempPos.top, width:$(this).outerWidth(), height:$(this).outerHeight(), obj:this};
		$.log("Select found: "+selectArray[selectArrayEnd].width+"x"+selectArray[selectArrayEnd].height+" @ "+selectArray[selectArrayEnd].left+","+selectArray[selectArrayEnd].top+"");
		selectArrayEnd++;
	});						   
	$.log("Found "+selectArrayEnd+" select boxes to dodge");

});


//used for debugging. feel free to remove this
jQuery.log = function(message) {
  if(window.console) 
     console.debug(message);

};


//dodgeSelectBoxes
function dodgeSelectBoxes(){


	if(selectArrayEnd==0 || !$.browser.msie){
		return;
	}

var thewindow;

var i=0;
while(i<selectArrayEnd)
{

	var nm=0;
	while(nm<windowArrayEnd)
	{
	thewindow=windowArray[nm];
	
		if(thewindow&&thewindow!=null)
		{
		var tbofs=$(thewindow).offset();
		thewindow = {height:($(thewindow).outerHeight()),width:($(thewindow).outerWidth()),left:tbofs.left,top:tbofs.top}
		
		
		
			if(((thewindow.width+thewindow.left)>=selectArray[i].left && (selectArray[i].left+selectArray[i].width)>=thewindow.left)
			&&((thewindow.height+thewindow.top)>=selectArray[i].top && (selectArray[i].top+selectArray[i].height)>=thewindow.top))
			{
				$(selectArray[i].obj).css("visibility","hidden");
				nm++;
				break;
			}else{
					$(selectArray[i].obj).css("visibility","visible");
			}//endelse
		}//endif
		
	$(selectArray[i].obj).css("visibility","visible");
	nm++;
	}//endwhile2
i++;
}//endwhile1


clearTimeout(intervaltracker);
}//end dodge function



var uniquecounter=0;
//options are self explanatory. there really isn't much reason to edit this I hope.
jQuery.fn.windowMaker = function(settings) {
  settings = jQuery.extend({
	 ajax:false,				/*use ajax or not*/
	 ajaxMethod:"get",			/*default ajax method*/
     skin: "default",			/*skin folder name*/
	 skinXMLurl:"",				/*skin folder location*/
     contents: "Loading",		/*html contained within or the url*/
	 draggable: true,			/*can we drag it. setting to false will disable certain other optios like transparentDrag */
	 position: "absolute",		/*relative position to an element or an absolute position to begin*/
	 relativeTo: "",			/*defaults to relative to...everything-ish*/
	 offsetX: 5,				/*offset x*/
	 offsetY: 5,				/*offset y*/
	 offsetXunits:"px",
	 offsetYunits:"px",
	 paddingunits:"px",
 	 heightunits:"px",
	 widthunits:"px",
	 width:"",					/*set absolute width*/
	 height:"",					/*set absolute height*/
	 grow:true,					/*Attempt to detect and grow to content size*/
	 scrolling: "auto", 		/*what to do with content that exceeds the maximum height/width*/
	 dragTransparency:1.0, 		/*The window set window drag transparency*/
	 dodgeSelects:true,			/*this hides select boxes underneath layer to get around IE 6 display glitches.*/
	 title: "Window Maker",		/*this is the title you want your window to have*/
	 margin: 5,							/*margin of the container window*/		
	 padding: 3,						/*padding of " ... " */	
	 controlsColor:"#FFFFCC",			/* The color of the title and close controls with default skins*/
	 backgroundColor:"#333333",			/* The color of the dialog with default skins*/
	 contentTextColor:"#333333",		/* The color of the content text with default skins*/
 	 contentBackgroundColor:"#FFFFCC",	/* The color of the content background with default skins*/
	 hoverColor:"#dd0000",				/*what will the closer do when we hover on it*/
	 windowBorder:"none",				/*self explanatory*/
	 contentBorder:"none",				/*self explanatory*/
	 side:"auto"							/*which side to default aligning to*/
  }, settings);


	//create the window and it's elements
	var thebox 		=	document.createElement("div");
	var thetitle	=	document.createElement("div");
	var thecloser	=	document.createElement("a");
	var thecontent	=	document.createElement("div");

	var boxCSS={
        backgroundColor: settings.backgroundColor,
        color: settings.controlColor,
		opacity: 1.0,
		margin: settings.margin,
		padding: settings.padding+settings.paddingunits,
		position: settings.position,
		zIndex: "200",
		left:"-1000px",
		top:"-1000px",
		display:"block",
		border: settings.windowBorder,
		fontFamily:"Arial",
		fontSize: "12px"
	};
	
	var cur="move";
	if(!settings.draggable)
		cur="default";
	
	
	var closerCSS={
		color: settings.controlsColor,
		float: "right",
		textDecoration: "none",
		border: "0px solid green"
	};
	
	var contentCSS={
		width: settings.width+settings.widthunits,
		height: settings.height+settings.heightunits,
		overflow: settings.scrolling,
		clear: "both",
		border: settings.contentBorder,
		color: settings.contentColor,
		backgroundColor:settings.contentBackgroundColor
	};
	
	

	//make id's unique and apply the css objects to each element
	var seconds = (new Date()).getTime() + (new Date()).getMilliseconds();
	var packageID = "thebox-"+seconds;
	
	$(thebox).attr("id",packageID);
	$(thebox).css(boxCSS);
	$(thebox).attr("arraykey",windowArrayEnd);
	$(thebox).click(function(){$(this).css("zIndex","200"+(zIndexCounter++));});
	
	
	$(thetitle).attr("id","thetitle-"+seconds);
	$(thetitle).html(settings.title);
	
	$(thecloser).attr("id","thecloser-"+seconds);
	$(thecloser).css(closerCSS);
	//add content to the closing link
	$(thecloser).html("X");
	$(thecloser).attr("href","#");
	

	
	//////////////////////////////////////////////
	/////Close function
	$(thecloser).click(function(){
		$(thebox).hide(200,function(){
				$(thebox).css("left","-1000px").css("width","5px");	
				windowArray[parseInt($(this).attr("arraykey"))]=null;
				document.body.removeChild(thebox);			
				dodgeSelectBoxes();
				
		});
		return false;
	});
	//end close function
	/////////////////////////////////////////////
	
	
	$(thecontent).attr("id","thecontent-"+seconds);
	$(thecontent).css(contentCSS);
	
	
	//add content to the content box
	if(!settings.ajax)
		$(thecontent).html(settings.contents);
	else{
			$(thecontent).html("<p><center><img src='images/ajax-loader.gif' alt='loading' /><br>Loading News..</center></p>");
		
			$.ajax({
			type: settings.ajaxMethod,
			url: settings.contents,
			dataType: "text",
			success: function(html) {
				$(thecontent).html(html);
			},//end success
			error: function(XMLHttpRequest, textStatus, errorThrown){
				$(thecontent).html("<p><center>Error</center></p>");
			}//end error
			
			});//end ajax 		
	}//end else
	
		//$.log("attributes set. ");
	
	//add to the document
	thebox.appendChild(thetitle);
	thebox.appendChild(thecloser);
	thebox.appendChild(thecontent);
	
	

	
	document.body.appendChild(thebox);
	
	
	
	
	////////////////////////////////////////////
	//set up title bar css now after others are added
	//because it has to dynamically resize itself to find.
	var titleWidth = parseInt(settings.width-$(thecloser).outerWidth()-5);
	
	//$.log("outer width of closer: "+$(thecloser).outerWidth());
	
	var titleCSS={
		float:	"left",
		color: settings.controlsColor,
		fontWeight: "bold",	
		border: "0px solid red",
		width: titleWidth+"px",
		cursor:cur,
		overflow:"hidden"
	};
	
	
	$(thetitle).css(titleCSS);
	
	
	
	
	

	//$.log("objects added");
	
	//now we need to calculate its position and size

	
	//calculate position. default to just slightly to right or left of element, but mostly to the right
	
	if(settings.relativeTo=="" || settings.relativeTo=="me"){
		settings.relativeTo=this;
	}
		
	//first get relative element width
	var elementdimensions={width:$(settings.relativeTo).outerWidth(),	height:$(settings.relativeTo).outerHeight()};
	//$.log("relativeTo info retrieved");	
	
	var documentdimensions = {width:$(document.body).outerWidth(),	height:$(document.body).outerHeight()};//self explanatory
	var elementlocation = $(settings.relativeTo).offset(); //locate the anchor element in the document
	
	//finally, we need the width of the window itself.
	var windowdimensions = {width:$(thebox).outerWidth(),	height:$(thebox).outerHeight()};
	var half_thewidth = windowdimensions.width/2; //used below. basically, if position.left + half_thewidth > document.width/2, 
									//then go left. otherwise go right.\

	var windowlocation={top:"",left:""};
	
	var direction="right";
	
	//$.log("Box dimensions: "+windowdimensions.width+"x"+windowdimensions.height);	
	//$.log("Half the width: "+half_thewidth);	
	//$.log("Document dimensions: "+documentdimensions.width+"x"+documentdimensions.height);	
	//$.log("Anchor element dimensions: "+elementdimensions.width+"x"+elementdimensions.height);
	//$.log("Anchor element position: "+elementlocation.left+","+elementlocation.top);
	
	
	//if box ground grow to fix content
	if(settings.grow){
		var contentdimensions={width:$(thecontent).outerWidth(),	height:$(thecontent).outerHeight()};
		//$.log("content dimensions: "+contentdimensions.width+"x"+contentdimensions.height);
		windowdimensions.width=contentdimensions.width;
		windowdimensions.height=contentdimensions.height+($(thetitle).outerHeight());
		
	}
	
	
	
	//if auto choosing sides, we need to do some math to do it. described just above btw
	if(settings.side=="auto"){
		
		//if over halfway (go left)
		if((settings.relativeTo != document.body) && 
		   parseInt(elementlocation.left+elementdimensions.width+windowdimensions.width) > documentdimensions.width)
		{
			direction="left";
		}//endif
		//else (go right)	
	}//endif
	else
		direction=settings.side;
		
	//$.log("Going "+direction);	
	
	if(direction=="left" && elementlocation.left-windowdimensions.width < 5)//going left
		windowlocation.left=0-settings.offsetX+settings.offsetXunits;
	else if(direction=="left"){
		windowlocation.left=parseInt(elementlocation.left-windowdimensions.width-(2*settings.padding)-settings.offsetX)+settings.offsetXunits;
	}else if(settings.relativeTo!=document.body)//going right
	{
		windowlocation.left = parseInt(elementlocation.left+elementdimensions.width+settings.offsetX)+settings.offsetXunits;
	}
	else//on main body still going right
	{
		windowlocation.left = settings.offsetX+settings.offsetXunits;
	}
	
	windowlocation.top=parseInt(elementlocation.top+settings.offsetY)+settings.offsetYunits;
	
	//$.log( parseInt(elementlocation.left+elementdimensions.width+windowdimensions.width));
	
	
	//$.log("Box location: "+windowlocation.left+","+windowlocation.top);	
	

	//setting final location settings
	$(thebox).css({left:windowlocation.left,top:windowlocation.top});
	$(thebox).css({height:windowdimensions.height,width:windowdimensions.width});


	//alert debug
	//$.log("attempting to make draggable "+packageID);


	//stop the bubbling from the links to the underlying floating div
	$("#"+packageID+" a").mousedown(function(event){
	// $.log("clicked");
	event.stopPropagation();
	return false;
	});
	
	

	
	//configure dragging
	if(settings.draggable){
	//make it draggable
	var dragsettings={	
	dragPrevention: "a,input,textarea,#thecontents-"+seconds,
	handle: "#thetitle-"+seconds,
	opacity: settings.dragTransparency,
	start:function(e,ui){
		$(thebox).css("zIndex","400"+(zIndexCounter++));
	},
	stop:function(e,ui){
		$(thebox).css("zIndex","200"+(zIndexCounter++));
	},
	drag: function(e,ui){
			intervaltracker=setTimeout("dodgeSelectBoxes();",50);
		}
	};
	$("#thetitle-"+seconds).mousedown(function(){
		$(thebox).draggable(dragsettings);				   
	}).mouseup(function(){$(thebox).draggable("destroy")});
	
	}//endif


	



	windowArray[windowArrayEnd]=thebox;
	windowArrayEnd++;


	//hide selectors here
	dodgeSelectBoxes();



	return {self:this, window:thebox, content: thecontent, title: thetitle, closer:thecloser};

};//end windowmaker
