// Note: Uses Prototype Window library 
// http://prototype-window.xilinus.com/index.html

TOF.ConsRegistry.PopupMap = function(){
	  var initMapIntervalId = null;
	  var mapType;
		var portal;
    
		function sleep(delay){
		    var start = new Date().getTime();
		    while (new Date().getTime() < start + delay);
		}
		// Used when a new element is added to the DOM via AJAX
		// and needs some javascript processing after it's added		
		function callWhenItemAvailable(func, dom_id){
			new PeriodicalExecuter(function(pe){
					var item = $(dom_id);
					if(item != null && item.getWidth() != 0){
				    pe.stop();
						func(dom_id);
					}
				}, 0.5);
		}
	
		// loop until popup_div is available
		function initPopupMap(mapDivId){
		    if($(mapDivId)){
					 var popupMap;

					 if(typeof initialSites != 'undefined'){
					   popupMap = TOF.ConsRegistry[mapType].init(mapDivId, portal, initialSites);
			     }
					 else{
					   popupMap = TOF.ConsRegistry[mapType].init(mapDivId, portal);
					 }
					 rpm = popupMap.referencePointManager;		
		    }
		}

		
		// specifies width and height of contents, and the width of the window
		function calculateMapDimensions(){
		  var minWinWidth = 550; // minimum usable width (determined through trial and error based on infowindow size)
			var minMapHeight = 423; // maintaining a 1.3 aspect ratio
			
			var winWidthPct = 0.95; // window width percent of browser size
			var mapSizePct = 0.95;  // map percent of popup window
			var mapHeightPct = 0.73; // map height percent of browser size

			var pageSize = WindowUtilities.getPageSize();

			var windowWidth = parseFloat(pageSize.windowWidth) * winWidthPct;
			if(windowWidth < minWinWidth){windowWidth = minWinWidth;}
						
			var mapWidth = windowWidth * mapSizePct;
			var mapHeight = parseFloat(pageSize.windowHeight) * mapHeightPct;

			if(mapHeight < minMapHeight){mapHeight = minMapHeight;}
			
			if(Prototype.Browser.IE){
				mapHeight = mapHeight - 50;
			}

			return {mapWidth: parseInt(mapWidth), mapHeight: parseInt(mapHeight), windowWidth: parseInt(windowWidth)};
		}
	
		// TOF.ConsRegistry.PopupMap.create("popup_map", "ProjectMap", "popup_map", "USA");
		function create(url, map_type, mapDivId, portal_name){
			 mapType = map_type;
			 portal = portal_name || 'USA';
			
			 var mDim = calculateMapDimensions();

			 var destroyFn = function(){};
			 if(mapType == "BrowseMapEnhanced"){
			   destroyFn = function(){
				   rpm = browseMap.referencePointManager;
				 };
			 }
			
		   Dialog.alert({url: url, options: {parameters: {width: mDim.mapWidth, height : mDim.mapHeight} }}, 
		    		    	  {className:"crwindow", width: mDim.windowWidth, zIndex: 10001, okLabel: "Close", 
										 closable: true, destroyOnClose: true, 
										 onDestroy: destroyFn});


		    callWhenItemAvailable(initPopupMap, mapDivId);
		    return false;
		}
	
		return { create: create, initPopupMap : initPopupMap};
}();