﻿String.prototype.trim = function() {
   return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

// jQuery Plug-In for centering a window
$.fn.centerInClient = function(options) {
   /// <summary>Centers the selected items in the browser window. Takes into account scroll position.
   /// Ideally the selected set should only match a single element.
   /// </summary>    
   /// <param name="fn" type="Function">Optional function called when centering is complete. Passed DOM element as parameter</param>    
   /// <param name="forceAbsolute" type="Boolean">if true forces the element to be removed from the document flow 
   ///  and attached to the body element to ensure proper absolute positioning. 
   /// Be aware that this may cause ID hierachy for CSS styles to be affected.
   /// </param>
   /// <returns type="jQuery" />
   var opt = { forceAbsolute: false,
      container: window,    // selector of element to center in
      completeHandler: null
   };
   $.extend(opt, options);

   return this.each(function(i) {
      var el = $(this);
      var jWin = $(opt.container);
      var isWin = opt.container == window;

      // force to the top of document to ENSURE that 
      // document absolute positioning is available
      if (opt.forceAbsolute) {
         if (isWin)
            el.remove().appendTo("body");
         else
            el.remove().appendTo(jWin.get(0));
      }

      // have to make absolute
      el.css("position", "absolute");

      // height is off a bit so fudge it
      var heightFudge = isWin ? 2.0 : 1.8;

      var x = (isWin ? jWin.width() : jWin.outerWidth()) / 2 - el.outerWidth() / 2;
      var y = (isWin ? jWin.height() : jWin.outerHeight()) / heightFudge - el.outerHeight() / 2;

      el.css("left", x + jWin.scrollLeft());
      el.css("top", y + jWin.scrollTop());

      // if specified make callback and pass element
      if (opt.completeHandler)
         opt.completeHandler(this);
   });
}


///////////////////////////////////////
if (typeof IMV_GLO === "undefined") {
   var IMV_GLO = {};
}


IMV_GLO.namespace = function (ns_string) {
   var parts = ns_string.split('.'),
      parent = IMV_GLO,
      i;

   // strip redundant leading global
   if (parts[0] === "IMV_COTX") {
      parts = parts.slice(1);
   }

   for (i = 0; i < parts.length; i += 1) {
      // create a property if it doesn't exist
      if (typeof parent[parts[i]] === "undefined") {
         parent[parts[i]] = {};
      }
      parent = parent[parts[i]];
   }
   return parent;
};



/////////////////////////////////////////////////////////////
// getHighDepth
/////////////////////////////////////////////////////////////
// INPUTS
// 	strDepthSel : the string denoting the delimiter to get the higest depth for, if none, it defaults to a property of hghDpth
//		by class
//		var arrHde = $('.floating');
//		var arrHde = $('*');
// OUTPUTS 
// 		none
// RETURN
// 		the intger value of the highest depth// 		the intger value of the highest depth + 1
/////////////////////////////////////////////////////////////
IMV_GLO.getHighDepth = function(strDepthSel) {

	var intCurHighDepth = 0; // the current highest depth
	var strHighObjId = ""; // the highest depth id

	if (strDepthSel=='') {
		strDepthSel = '[hghDpth|="1"]';
	}

	var arrHde = $(strDepthSel);
	var intNumberofElements = arrHde.length;

	for (i=0;i<intNumberofElements;i++)
	{
		if (parseInt(arrHde[i].style.zIndex)>intCurHighDepth) {
			intCurHighDepth = parseInt(arrHde[i].style.zIndex);
			strHighObjId = arrHde[i].id;
		}
	}
//	window.alert("intCurHighDepth:" + intCurHighDepth);
	return intCurHighDepth;
}

// 		the intger value of the highest depth + 1
IMV_GLO.getHigherDepth = function(strDepthSel) {
	var intCurHighDepth = 0;
	intCurHighDepth = parseInt(IMV_GLO.getHighDepth(strDepthSel) + 1);
	return intCurHighDepth;
}


///////////////////////////////////////////////////
// class for alertProperties
///////////////////////////////////////////////////
IMV_GLO.genAlertParams = function()
{
	var strAlertMsg = '';  // the body message of the alert
	var strAlertMsgHeadline = '';  // the headline for the top bar, if any
	var strTargetObjId = ''; // the target object | if '' then create one
	var strCloseAction = ''; // the action on close
	var strBG =''; // background - true renders semi-opaque
	var width = 0; // fixed width
	var height = 0; // fixed height
	var strScrollType = ""; // fixed height
	var booDragBar = false; // fixed height
	
	this.strAlertMsg=strAlertMsg;
	this.strAlertMsgHeadline=strAlertMsgHeadline;
	this.strTargetObjId=strTargetObjId;
	this.strCloseAction=strCloseAction;
	this.strBG=strBG;
	this.width=width;
	this.height=height;
	this.strScrollType = strScrollType;
	this.booDragBar = booDragBar;
	
	this.genAlert = function() {
		IMV_GLO.funGenAlert(this);
	};

}


///////////////////////////////////////////////////
// funGenericAlert - script to pop a box by id and populate with html
//
// assumes jquery UI
//	INPUTS
//		strAlertMsg : string : the message
//		strTargetObjId : string : the id of the object
// 	strCloseAction : string to control the close action - 
//			clsTopBtn (close button) on the top.
//       clsBtn (close button)
//			fdOt(fade out)
//			cls_LvCnt (prepends close button but leaves the content)
//    strBG : string : 
//       undefined || '' - if the arg is omitted or empty string no background div is rendered
//       'true' - uses default transparent.png to 'subdue' background content
//       any other string value - assumes is a path to an alternate background image (not validated)
//	OUTPUTS
//		none
///////////////////////////////////////////////////
IMV_GLO.funGenAlert = function(objGaParams) {

	var strAlertMsg = objGaParams.strAlertMsg;
	var strTargetObjId = objGaParams.strTargetObjId;
	var strCloseAction = objGaParams.strCloseAction;
	var strBG = objGaParams.strBG;

   var strCloseBtn = '';

	// get the highest depthSelParams
	var intHightDepth = parseInt(IMV_GLO.getHigherDepth(''));

	// create a background semi-opaque div
	// if the close action is not 'fdOt' and strBG!='' create a background div
	if (strCloseAction != 'fdOt' && (strBG != '' && strBG!=undefined)) {
	   // create background div
	   var objBG;
	   objBG = document.getElementById(strTargetObjId + "_BG");

	   if (!objBG) {
		  objBG = document.createElement('DIV');
		  objBG.id = strTargetObjId + "_BG";
		  objBG.style.padding = '0px';
		  objBG.style.margin = '0px';
		  objBG.style.height = $(document).height() + 'px';
		  objBG.style.width = $(document).width() + 'px';
		  document.body.appendChild(objBG);
		  $('#' + strTargetObjId + "_BG").toggleClass('alrtBG');

		  if (strBG != 'true') {
			 //assume the value of strBG is a background image path
			 objBG.style.backgroundImage = "url(" + strBG + ")";
		  }
		 objBG.hghDpth=1;
		 objBG.style.zIndex = intHightDepth;
		 intHightDepth ++;
		 
	   } else {
		  objBG.style.height = $(document).height() + 'px';
		  objBG.style.width = $(document).width() + 'px';
	   }

	 // make visible
	 objBG.style.visibility = 'visible';
	 objBG.style.display = 'block';

   }

	//////////////////////////////////////////////////////////////////
	// create the actual box
	// get the element FIRST
	var objGenAlrt;
	objGenAlrt = document.getElementById(strTargetObjId);


	if (!objGenAlrt) {
			booAlreadyExisted = false;			
			// create the element
			$('body').append('<div hghDpth=\'1\' id=\'' + strTargetObjId +  '\' class=\'alrtHid\' style=\'padding:0px; position:absolute; z-index:' + intHightDepth + ';\'></div>');
			objGenAlrt = document.getElementById(strTargetObjId);
	} else {
		booAlreadyExisted = true;
		if (strAlertMsg == '') {
			strAlertMsg = objGenAlrt.innerHTML;
			objGaParams.strAlertMsg = strAlertMsg;
		}
	}

	objGenAlrt.style.zIndex = intHightDepth;
	
	if  (objGaParams.strScrollType!='') {
		strAlertMsg = '<div id="' + strTargetObjId + '_inner" style="overflow:auto; background-color:#FFF; height:100%; text-align:left;">' + strAlertMsg + '</div>';
	}

	// none - no close action specified
	if (strCloseAction!='none') {
	   // set a close button
	   switch (strCloseAction) {
		  case 'clsTopBtn':
		  
			// small square close button on the top
			strHandle = strTargetObjId + '_display_box_handle';

			objHandleTest = document.getElementById(strHandle);
			// if ((!objHandleTest)) {
				strCloseBtn = '<div class="stdBoxOrHead" id="' + strHandle + '" style="overflow-x:hidden; overflow-y:hidden; cursor:pointer;">';
				strCloseBtn = strCloseBtn + '<img src="http://www.drbicuspid.com/images/buttons/square/close.png" alt="close" border="0" onclick="funGenHidObj(\'' + strTargetObjId + '\');" style="cursor:pointer;float:right;">';
				strCloseBtn = strCloseBtn + objGaParams.strAlertMsgHeadline;
				strCloseBtn = strCloseBtn + '</div>';

				if ((typeof jQuery.ui.draggable != 'undefined') && (objGaParams.booDragBar==true)) {

					$('#' + strTargetObjId ).draggable({ 
						handle: '#' + strHandle,
						start: function() {
						this.style.zIndex=IMV_GLO.getHigherDepth('');
						},
						stop: function() {
							// keep stuff from going off the sides permanently
							curTop = $(objGenAlrt).offset().top;
							if (curTop<0) {
								$(objGenAlrt).offset({ top: 10 });
							}
							curLeft = ($(objGenAlrt).offset().left + $(objGenAlrt).width());
							if (curLeft<0) {
								$(objGenAlrt).offset({ left: ($(objGenAlrt).width()*-1 + 160) });
							}

						}
					});
					$('#' + strTargetObjId ).click(function() {
						this.style.zIndex=IMV_GLO.getHigherDepth('');
					});

				}
			// }
			 break;
		  case 'clsBtn':
			 // large close button centered on the bottom
			 strCloseBtn = '<div align=center><img src=\'http://www.drbicuspid.com/images/buttons/close.gif\' onClick=\"funGenHidObj(\'' + strTargetObjId + '\')\" id=\'alertCloseButton\' style=\'cursor:pointer; margin: 12px;\'></div>';
			 break;
		  case 'cls_LvCnt':
			 // close button on the right top
			 // strCloseBtn = '<div align=right><img src=\'/images/buttons/square/close.png\' onClick=\"funGenHidObj(\'' + strTargetObjId + '\')\" id=\'alertCloseButton\' style=\'cursor:pointer; margin: 2px;\'></div>';
			 strCloseBtn = '';
			 break;
		  default:
			 strCloseBtn = '';
			 break;
	  }

		// fdOt - fade out
		if (strCloseAction=='fdOt') {
			// fafe out box
			 setTimeout(function(){
				  $('#' + strTargetObjId).fadeOut(1000,function(){});
			 },1000);
		}
	}
	
	
	// set the inner html
	switch (strCloseAction) {
	   case 'clsTopBtn':
		  objGenAlrt.innerHTML = strCloseBtn + strAlertMsg;
		  break;
	   case 'clsBtn':
		objGenAlrt.innerHTML = strAlertMsg + strCloseBtn;
		  break;
	   case 'cls_LvCnt':
		objGenAlrt.innerHTML = objGenAlrt.innerHTML;
		  break;
	   default:
		  objGenAlrt.innerHTML = strAlertMsg + strCloseBtn;
		  break;
   }

	// height and width
	if (objGaParams.width!=0) {
		objGenAlrt.style.width=objGaParams.width + 'px';
	}
	if (objGaParams.height!=0) {
		objGenAlrt.style.height=objGaParams.height + 'px';
	}
   scrlTop = $(window).scrollTop();
   intLeft = Math.round(($(window).width() - $(objGenAlrt).width()) / 2);
   intTop = Math.round(($(window).height() - $(objGenAlrt).height()) / 2) + scrlTop;
   if (intTop<scrlTop) {
	   intTop = scrlTop + 2;
   }


	// make visible
	objGenAlrt.style.left = intLeft + 'px';
	objGenAlrt.style.top = intTop + 'px';

	objGenAlrt.style.visibility = 'visible';
	$(objGenAlrt).fadeIn(500);

	// set the height of the inner div if there is one
	if  (objGaParams.strScrollType!='') {
		innerDiv=$("#" + strTargetObjId + "_inner");
		dragBar = $("#" + strTargetObjId + '_display_box_handle');

		intInnerDivHeight= $(objGenAlrt).innerHeight();
		innerDiv.height(intInnerDivHeight-dragBar.innerHeight());
	}
}

// hides the object passed to it by name
function funGenHidObj(strElementName) {

	objGenAlrt = document.getElementById(strElementName);
	$(objGenAlrt).fadeOut(500, function(){
	});

   //get the background div and hide it
	var objBG;
	objBG = document.getElementById(strElementName + "_BG");
	if (objBG) {
		$(objBG).fadeOut(500);
	}

}

function makeDebugWindow(whatToPutInThere) {
		objImvDebug = new IMV_GLO.genAlertParams();
	
		objImvDebug.strTargetObjId = 'imvDebug';
		objImvDebug.strAlertMsg = whatToPutInThere;
	
		objImvDebug.strCloseAction = 'clsTopBtn';
		objImvDebug.width = 400; // full screen?
		objImvDebug.height = 400;
		objImvDebug.booDragBar = true;
		objImvDebug.strScrollType = 'auto';
		objImvDebug.genAlert();
}




