// Line below adds intellisense for ESRI scripts to Visual Studio 2008
/// <reference path="../../esriscripts/references.js" />

// TODO: Localization - Create javascript file with text variables, one file for each language, include correct file in page.prerender.

var maptipBlankImage = "/aspnet_client/ESRI/WebADF/images/pixel.gif";
var nextExtendedWindowIndex = 0;
var lastExtendIndex = -1;
var lastHoverIndex = -1;
var lastExtendMapId = "";
var extendVisible = false;
var hoverVisible = false;
var maptipXOffset, maptipYOffset;
var maptipString = "";
var mapTipDragMaxTop = 0;
var mapTipDragMaxBottom = 0;

//var clickIconPrompt = "Click icon for more information."
//var clickHoverPrompt = "Click pop-up for more information."

var mt_panel = null;
var mt_panelDragIndex = 0;
var mt_delay = 2000;
var mt_checkLoad = null;
var esriMTCloseImage = null;
var esriMTCallbackCount = 0;

var mapTipInit = new Array();
var mapTipInitCtl = new Array();

// create a definition object for a MapTips control instance
function MTT_createMapTipDefinition(controlID, buddyControlID, defaultImagePath, hoverImagePath, selectImagePath, classPrefix, callbackInvocation, mapTipsString, closeImage, iconWidth, iconHeight, mapTipWidth, mapTipHeight, showIcons, zoomInPixelBufferAroundIcon, bufferZoneSize, allowStickyTips, divzindex, showHeader, keepMapTipsOnTopOfMap) {
	MapTipCollections[controlID] = new MapTipsCollectionObject(controlID, buddyControlID, defaultImagePath, hoverImagePath, selectImagePath, classPrefix, callbackInvocation, closeImage, iconWidth, iconHeight, mapTipWidth, mapTipHeight, showIcons, zoomInPixelBufferAroundIcon, bufferZoneSize, allowStickyTips, divzindex, showHeader, keepMapTipsOnTopOfMap);
	maptips = MapTipCollections[controlID];
	esriMTCloseImage = closeImage;
	MapTipCollectionNames[MapTipCollectionNames.length] = controlID;
    maptipsActive = true;
	if (mapTipsString!=null && mapTipsString.length>0)
	{
	    //window.setTimeout("MapTipCollections['" + controlID + "'].addMapTips(\"" + mapTipsString + "\");", 1000);
	    mapTipInit.push(mapTipsString);
	    mapTipInitCtl.push(controlID);

	    Sys.Application.add_load(InitializeMapTips);
	}
}

// Add map tips
function InitializeMapTips()
{
    Sys.Application.remove_load(InitializeMapTips); // Otherwise function keeps getting called on partial postbacks
    for (var i = 0; i < mapTipInit.length; ++i)
    {
        var tipInit = mapTipInit[i];
        if (tipInit != null)
        {
            var ctlId = mapTipInitCtl[i];
            MapTipCollections[ctlId].addMapTips(tipInit);
        }
    }
}

function mtt_map_panning(map)
{
    mtt_hidemaptips(map);
}

function mtt_map_zoomStart(map)
{
    mtt_hidemaptips(map);
}

function mtt_hidemaptips(map)
{
    var div = document.getElementById(map._containerDiv.id + "_maptipstask");
    if(div)
    {
        div.innerHTML = "";
    }
}

function mtt_map_extentChanged(map)
{
}

// object for requesting and displaying MapTips
function MapTipsCollectionObject(controlID, buddyControlID, defaultImagePath, hoverImagePath, selectImagePath, classPrefix, callbackInvocation, closeImage, iconWidth, iconHeight, mapTipWidth, mapTipHeight, showIcons, zoomInPixelBufferAroundIcon, bufferZoneSize, allowStickyTips, divzindex, showHeader, keepMapTipsOnTopOfMap) {
	this.id = controlID;
	this.mapId = buddyControlID;
	this.map = null;
	this.defaultImage = defaultImagePath;
	this.hoverImage = hoverImagePath;
	this.clickImage = selectImagePath;
	this.closeImage = closeImage;
	this.classPrefix = classPrefix;
	this.callbackFunctionString = (callbackInvocation==null) ? "" : callbackInvocation;
	this.enabled = true;
	this.extendedVisible = new Array();
	this.divHolder = null;
	this.type = "point";
	this.mapTipItems = new Array();
	this.mapTipItemIDs = new Array();
	this.requestedMapTipTiles = new Object();
	this.appCallbackCount = 0;
    this.iconWidth = iconWidth;
    this.iconHeight = iconHeight;
    this.mapTipWidth = mapTipWidth;
    this.mapTipHeight = mapTipHeight;
    this.showHotspotIcons = showIcons;
    this.zoomInPixelBufferAroundIcon = zoomInPixelBufferAroundIcon;
    this.bufferZoneSize = bufferZoneSize;
    this.allowStickyTips = allowStickyTips;
    this.divzindex = divzindex;
    this.showHeader = showHeader;
    this.keepMapTipsOnTopOfMap = keepMapTipsOnTopOfMap;
	
	this.setMap = function() {
		//this.map = Maps[this.mapId];
        this.map = $find(this.mapId);
        this.map.remove_panning(mtt_map_panning);
        this.map.remove_zoomStart(mtt_map_zoomStart);
        this.map.remove_extentChanged(mtt_map_extentChanged);
        this.map.add_panning(mtt_map_panning);
        this.map.add_zoomStart(mtt_map_zoomStart);
        this.map.add_extentChanged(mtt_map_extentChanged);
	}
	
	this.requestMapTips = function(mapId) {
	    if (this.mapId==mapId) {
	        this.setMap();
	        var context = this.id;
	        var argument = "";
	        var s = this.map.getViewTilesString();
	        var mts = s.split("|");
	        var i = 0;
	        for (var i=0;i<mts.length;i++) {
	            if (this.requestedMapTipTiles[mts[i]]==null) {
	                var mtxy = mts[i].split(",");
	                argument = "EventArg=MapTips&column=" + mtxy[0] + "&row=" + mtxy[1];
	                this.requestedMapTipTiles[mts[i]] = mts[i];
    	            
	    // Debug stuff to be removed, or at least commented out
   	    if (checkForFormElement(document, 0, "MapDebugBox")) document.forms[0].MapDebugBox.value += "Request: " + this.id + ": " +  argument + "\n"; 
       	
	                eval(this.callbackFunctionString);
	            }
	        }
	        window.setTimeout("MapTipCollections['" + this.id + "'].createPageDivs();",mt_delay);
	    }
	}
	
	this.addMapTips2 = function(response) {
	    // skip the first three elements
	    var paramArray = response.split(":::");
	    for (var i=3;i<paramArray.length;i++) {
	        if (paramArray[i]!=null && paramArray[i].length>0) {
	            var mt = paramArray[i].split("///");
	            this.mapTipItemIDs[this.mapTipItemIDs.length] = mt[2];
	            //MapTipItemObject(mapId, index, left, top, headerText, content, extendedContent)
	            var newTip = new MapTipItemObject(paramArray[1], mt[2], mt[0], mt[1], mt[3], "", mt[4], this.iconWidth, this.iconHeight);
	            /// Added lines below to include individual icons for each map tip
	            if(mt.length > 5) {
	                newTip.setImages(mt[5], mt[6], mt[7], mt[8], mt[9], mt[10], mt[11], mt[12], mt[13], mt[14], mt[15], mt[16], mt[17], mt[18], mt[19], mt[20]);
	            }
	            ///
	            this.mapTipItems[mt[2]] = newTip;
	       } 
	    }
	    this.createPageDivs();
	}

    this.addMapTips = function(response)
    {
	    this.paramArray = unescape(response).split(":::");
	    this.startIndex = 3;
	    this.addMapTips3();
    }
    
    this.paramArray = null;
    this.startIndex = null;
    
    this.addMapTipsDelayed = function(paramArray, startIndex, delay) {
        this.paramArray = paramArray;
        this.startIndex = startIndex;
        window.setTimeout("MapTipCollections['" + this.id + "'].addMapTips3();", delay);
    }

	this.addMapTips3 = function() {
	    if (maptipHoverPanel==null){ 
	        setupMapTipPanels(this.mapTipWidth, this.mapTipHeight, this.classPrefix, "point", this.bufferZoneSize, this.divzindex, this.showHeader, this.keepMapTipsOnTopOfMap);
	    }
	    if (this.map==null) this.setMap();
	    if (this.map==null) return;
	    var div = document.getElementById(this.map._containerDiv.id + "_maptipstask");
	    if(!(div))
	    {
            div = document.createElement("div");
            div.id = this.map._containerDiv.id + "_maptipstask";
            var container = this.map._containerDiv.parentNode;
            if(container.tagName.toLowerCase() == 'a')
                container = container.parentNode;
            container = container.parentNode;
            container.appendChild(div);
	    }
	    
	    //if (
        this.mapTipItemIDs = new Array();
        this.mapTipItems = null;
        this.mapTipItems = new Array();
        
        this.requestedMapTipTiles = new Object();
		var s = "";
		if (div!=null) {
		    div.style.visibility = "visible";
		    //div.innerHTML = "";
		}
	
//		this.map.getTopLeftTile();
//		var left = this.map.currentLeftColumn * this.map.tileWidth + this.map.currentXOffset;
//		var top = this.map.currentTopRow * this.map.tileHeight + this.map.currentYOffset;
//		var right = left + this.map.viewWidth;
//		var bottom = top + this.map.viewHeight;

		var left = 0;
		var top = 0;
		var right = left + this.map._mapsize[0];
		var bottom = top + this.map._mapsize[1];

	    for (var i=this.startIndex;i<this.paramArray.length;i++) {
	        if (this.paramArray[i]!=null && this.paramArray[i].length>0) {
	            var mt = this.paramArray[i].split("///");
	            this.mapTipItemIDs[this.mapTipItemIDs.length] = mt[2];
	            //MapTipItemObject(mapId, index, left, top, headerText, content, extendedContent)
	            var newTip = new MapTipItemObject(this.id, mt[2], mt[0], mt[1], mt[3], "", mt[4], this.iconWidth, this.iconHeight);
	            /// Added lines below to include individual icons for each map tip
	            if(mt.length > 5) {
	                newTip.setImages(mt[5], mt[6], mt[7], mt[8], mt[9], mt[10], mt[11], mt[12], mt[13], mt[14], mt[15], mt[16], mt[17], mt[18], mt[19], mt[20]);
	            }
	            ///
	            this.mapTipItems[mt[2]] = newTip;
	            //MapTipItemObject(mapId, index, left, top, headerText, content, extendedContent)
	            maptip = this.mapTipItems[mt[2]];
			    x = maptip.left;
			    y = maptip.top;
			    tipId = 'MapTipHotSpot_' + this.id + '_' + maptip.index;
			    //tipId = '<div id="MapTipHotSpotImg_' + this.id + '_' + maptip.index;
    			
			    mtimg = document.getElementById(tipId);
			    //if (x>left && x<right && y>top && y<bottom) {
			        //if (mtimg==null)
			        var imgSrc = this.defaultImage;
			        if(maptip.iconImage != "") imgSrc = maptip.iconImage;
			        var x = maptip.left + getIconXOffset(this.map, maptip.iconAnchorPoint, maptip.defaultIconWidth);
			        var y = maptip.top + getIconYOffset(this.map, maptip.iconAnchorPoint, maptip.defaultIconHeight);
			        s += '<div id="' + tipId + '" onmouseover="MapTipCollections[\'' + this.id + '\'].showTip(\'' + maptip.index +'\',' + this.showHotspotIcons + ',event)" onmouseout="return MapTipIconMouseOut(\'' + this.id + '\');" onmousedown="MapTipCollections[\'' + this.id + '\'].click(\'' + maptip.index +'\',' + this.showHotspotIcons + ',event)" style="position: absolute; left: ' + x + 'px; top: ' + y + 'px;"><div id="MapTipHotSpotImg_' + this.id + '_' + maptip.index + '" name="MapTipHotSpotImg_' + this.id + '_' + maptip.index + '" class="MapTipIcon"';
		            s += ' style="width: ' + maptip.defaultIconWidth + 'px; height: ' + maptip.defaultIconHeight + 'px;';
			        if(this.showHotspotIcons)
			            s += ' background-image: url(\'' + imgSrc + '\');'
			        s += '"><div class="MapTipIconText" id="MapTipHotSpotText_' + this.id + '_' + maptip.index + '" name="MapTipHotSpotText_' + this.id + '_' + maptip.index + '">' + maptip.iconText + '</div></div></div>\n';
		            this.extendedVisible[maptip.index] = false;
		        //}
		     }
	    }
		if (s.length>0) {
		    if (div!=null) {
		        div.style.display = "";
		        if (esriMTCallbackCount == esriCurrentResponseCount) {
		            var s2 = ""; //div.innerHTML;
		            div.innerHTML = s2 + s;
		        } else 
		            div.innerHTML = s; 
		    }
		}
        else if ( div != null )
            div.style.display = "none";
        esriMTCallbackCount = esriCurrentResponseCount; 
	}

    this.ZoomToPoi = function(index)
    {
        var mt = this.mapTipItems[index];
		var box = calcElementPosition(mt.divId);		
		// For some reason, the box data structure's properties return undefined, so we use global variables set by calcElementPosition instead.
		var x = eLeft - this.map.containerLeft;
		var y = eTop - this.map.containerTop;
        var oldMode = this.map.mode;
        this.map.mode = 'MapZoomIn';
        zoomToBoxBugfixed(this.mapId, x-this.zoomInPixelBufferAroundIcon, y-this.zoomInPixelBufferAroundIcon, x+this.iconWidth+this.zoomInPixelBufferAroundIcon, y+this.iconHeight+this.zoomInPixelBufferAroundIcon);
        this.map.mode = oldMode;
    }
   
	this.showTip = function(index, showHotspotIcons, e) {
		//if ((this.enabled) && (!hoverVisible)){
		if (this.enabled) {
			getXY(e);
			if (index!=lastExtendIndex)
			{
				if(lastHoverIndex > -1 && lastHoverIndex != index)
    		        this.setIcon(lastHoverIndex, maptip.iconImage, this.defaultImage, maptip.defaultIconWidth, maptip.defaultIconHeight, maptip.iconAnchorPoint, maptip.iconText, !showHotspotIcons);
				mt_manager.show(this, index, "hover");
			}
			if ((index!=lastExtendIndex)) {
		        this.setIcon(index, maptip.iconHoverImage, this.hoverImage, maptip.hoverIconWidth, maptip.hoverIconHeight, maptip.iconAnchorPoint, maptip.hoverIconText, !showHotspotIcons);
				lastHoverIndex = index;
			}
			//hoverVisible=true;
		}
	}
	
	this.hide = function(which) {
		mt_manager.hide(which);
		if (lastExtendIndex!=lastHoverIndex  && this.type.toLowerCase()=="point") {
		    this.setIcon(lastHoverIndex, maptip.iconImage, this.defaultImage, maptip.defaultIconWidth, maptip.defaultIconHeight, maptip.iconAnchorPoint, maptip.iconText);
		}
	}

    this.setIcon = function(index, icon, icon2, iconWidth, iconHeight, iconAnchorPoint, iconText, dontSetIcon)
    {
        if(icon != "" || icon2 != "") {
//		    var imgObj = document.images["MapTipHotSpotImg_" + this.id + "_" + index];
//		    if (imgObj!=null) {
//		        if(icon != "")
//		            imgObj.src = icon;
//		        else
//		            imgObj.src = icon2;
//		    }
		    var imgSpan = document.getElementById("MapTipHotSpotImg_" + this.id + "_" + index);
		    if (imgSpan!=null) {
		        imgSpan.style.width = iconWidth + 'px';
		        imgSpan.style.height = iconHeight + 'px';
                if(!(dontSetIcon)) {
		            if(icon != "")
		                imgSpan.style.backgroundImage = "url('" + icon + "')";
		            else
		                imgSpan.style.backgroundImage = "url('" + icon2 + "')";
		        }
		    }
		    var imgDiv = document.getElementById("MapTipHotSpot_" + this.id + "_" + index);
		    if(imgDiv)
		    {
		        imgDiv.style.left = (maptip.left + getIconXOffset(this.map, iconAnchorPoint, iconWidth)) + 'px';
		        imgDiv.style.top = (maptip.top + getIconYOffset(this.map, iconAnchorPoint, iconHeight)) + 'px';
 		    }
	        if(iconText)
	        {
		        var txtDiv = document.getElementById("MapTipHotSpotText_" + this.id + "_" + index);
		        if(txtDiv) {
		            txtDiv.innerHTML = iconText;
		        }
		    }
		}
    }
    	
	this.click = function(index, showHotspotIcons, e) {
	    if(!this.allowStickyTips) return false;
		getXY(e);
		if (!this.extendedVisible[index]) {
			this.resetDefaultIcons();
			mt_manager.show(this, index, "extended");
			lastExtendIndex=index;
			extendVisible = true;
			mt_manager.windowIndex++;
			if (mt_manager.windowIndex==mt_manager.maxExtendedWindows) mt_manager.windowIndex = 0;
			this.hide("hover");
			if (this.type.toLowerCase()=="point") {
			    this.setIcon(index, maptip.iconClickImage, this.clickImage, maptip.clickIconWidth, maptip.clickIconHeight, maptip.iconAnchorPoint, maptip.iconText, !showHotspotIcons);
			}
		}
		
	}
	
	this.resetDefaultIcons = function() {
		if (this.defaultImage!="" && this.type.toLowerCase()=="point") {
			var imgObj
			for (var i=0;i<this.mapTipItemIDs.length;i++) {
			    var mtip = this.mapTipItems[this.mapTipItemIDs[i]];
			    this.setIcon(this.mapTipItemIDs[i], mtip.iconImage, this.defaultImage, mtip.defaultIconWidth, mtip.defaultIconHeight, mtip.iconAnchorPoint, mtip.iconText);
			}		
		}
	}
	
	this.hideIcons = function(iconDiv) {
		if (iconDiv!=null) iconDiv.style.visibility = "hidden";
	}
	
	this.showIcons = function() {
		if (iconDiv!=null) iconDiv.style.visibility = "visible";
	}
	

}// MapTipCollectionObject

function MapTipItemObject(mapId, index, left, top, headerText, content, extendedContent, iconWidth, iconHeight) {
	this.mapId = mapId
	this.index = index;
	this.shape = "point";
	this.left = left - Math.ceil(iconWidth/2);
	this.top = top - Math.ceil(iconHeight/2);
	this.headerText = headerText;
	this.content = (content!=null && content.length>0) ? content : "";
	this.extendedContent = (extendedContent!=null && extendedContent.length>0) ? extendedContent : "";
	/// Added line below, to always show extended content:
	this.content = this.extendedContent;
	///
	this.iconText = "";
	this.iconImage = "";
	this.iconHoverImage = "";
	this.iconClickImage = "";
	this.divId = "MapTipHotSpot_" + this.mapId + "_" + this.index;
	this.imageId = "MapTipHotSpotImage_" + this.mapId + "_" + this.index;
		
	this.setImages = function(iconImage, iconHoverImage, iconClickImage, iconText, defaultIconWidth, defaultIconHeight, hoverIconWidth, hoverIconHeight, clickIconWidth, clickIconHeight, iconAnchorPoint, topLeftArrowIcon, topRightArrowIcon, bottomRightArrowIcon, bottomLeftArrowIcon, hoverIconText) {
		// these must be set before the item is added to the collection
		this.iconImage = iconImage;
		this.iconHoverImage = iconHoverImage;
		this.iconClickImage = iconClickImage;
		this.iconText = iconText;
        this.defaultIconWidth        = defaultIconWidth;
        this.defaultIconHeight       = defaultIconHeight;
        this.hoverIconWidth          = hoverIconWidth;
        this.hoverIconHeight         = hoverIconHeight;
        this.clickIconWidth          = clickIconWidth;
        this.clickIconHeight         = clickIconHeight;
        this.iconAnchorPoint         = iconAnchorPoint;
        this.topLeftArrowIcon        = topLeftArrowIcon;
        this.topRightArrowIcon       = topRightArrowIcon;
        this.bottomRightArrowIcon    = bottomRightArrowIcon;
        this.bottomLeftArrowIcon     = bottomLeftArrowIcon;
    	this.hoverIconText = hoverIconText;
	}
}

function MapTipWindowObject(width, height, classPrefix, type, bufferZoneSize, divzindex, showHeader, keepMapTipsOnTopOfMap) {
	this.width = width;
	this.height = height;
	this.showHeader = showHeader;
	this.bufferZoneSize = bufferZoneSize;
    this.divzindex = divzindex;
	this.type = type;
	this.hoverHeight = height;
	this.extendedHeight = height;
	this.classPrefix = classPrefix;
	this.containerClass = this.classPrefix + "MapTipContainer";
	this.hoverContainerClass = this.classPrefix + "MapTipHoverContainer";
	this.stickyContainerClass = this.classPrefix + "MapTipStickyContainer";
	this.hoverHeaderClass = this.classPrefix + "MapTipHoverHeader";
	this.stickyHeaderClass = this.classPrefix + "MapTipStickyHeader";
	this.hoverContentClass = this.classPrefix + "MapTipHoverContents";
    this.stickyContentClass = this.classPrefix + "MapTipStickyContents";
    this.hoverContentClassNoHeader = this.classPrefix + "MapTipHoverContentNoHeader";
	this.closeClass = this.classPrefix + "MapTipClose";
	this.maxExtendedWindows = 10;
	this.windowIndex = 0;
	this.closeButtonImage = esriMTCloseImage;
	this.keepMapTipsOnTopOfMap = keepMapTipsOnTopOfMap;
	
	this.hoverDivObject = null;
	this.hoverDivId = "MapTipHoverContainerDiv";
	this.hoverInnerDivId = "MapTipHoverInnerContainerDiv";
	this.hoverHeaderCell = null;
	this.hoverHeaderId= "MapTipHoverHeaderDiv";
	this.hoverContentCell = null;
	this.hoverContentId = "MapTipHoverContentDiv";
	this.bufferLeftId = "MapTipBufferLeftDiv";
	this.bufferRightId = "MapTipBufferRightDiv";
	this.bufferTopId = "MapTipBufferTopDiv";
	this.bufferBottomId = "MapTipBufferBottomDiv";
	this.extendedDivObject = new Array();
	this.extendedDivId = new Array();
	this.extendedHeaderCell = new Array();
	this.extendedHeaderId = new Array();
	this.extendedContentCell = new Array();
	this.extendedContentId = new Array();
	this.extendedIndex = new Array();

	this.createDivs = function(styleSheet) {
	    var s = '<div onmouseout="return MapTipHoverInfoMouseOut(event);" id="' + this.hoverDivId + '" class="' + this.containerClass + '" style="position: absolute; left: 0px; top: 0px; visibility: hidden; ';
	    if((this.divzindex) && (this.divzindex != '')) s += 'z-index: ' + this.divzindex + '; ';
	    s += '">';
	    s += '     <table border="0" cellpadding="0" cellspacing="0"> ';
        s += '        <tr><td><div style="height: ' + this.bufferZoneSize + 'px;"></div></td><td><img id="' + this.hoverDivId + '_toparrow" style="visibility: hidden;"></td><td></td></tr>';
        s += '        <tr><td><div style="width: ' + this.bufferZoneSize + 'px;"></div></td>';
        if(this.showHeader)
        {
            s += '      <td>';
            s += '          <div id="' + this.hoverInnerDivId + '" style="width: ' + this.width + 'px; height: ' + this.height + 'px;" class="' + this.hoverContainerClass + '">';
		    s += '            <div class="' + this.hoverHeaderClass +'" style="width: ' + this.width + 'px; " id="' + this.hoverHeaderId + '" >';
		    //                   Header
		    s += '           </div>';
		    s += '          <div class="' + this.hoverContentClass + '" style="width: ' + this.width + 'px;" id="' + this.hoverContentId + '" >';
		    //	                 Content Content Content Content Content  
		    s += '          </div>';
            s += '      </div></td>';
		}
		else
		{
            s += '      <td><div id="' + this.hoverContentId + '" style="width: ' + this.width + 'px; height: ' + this.height + 'px;" class="' + this.hoverContentClassNoHeader + '"></div></td>';
		}
        s += '      <td><div style="width: ' + this.bufferZoneSize + 'px;"></div></td></tr>';
        s += '        <tr><td><div style="height: ' + this.bufferZoneSize + 'px;"></div></td><td><img id="' + this.hoverDivId + '_bottomarrow" style="visibility: hidden;"></td><td></td></tr>';
        s += '</table></div>';
	    
	    for (var i=0;i<this.maxExtendedWindows;i++) {
	        s +=  '<div id="MapTipExtendedContainerDiv_' + i + '" class="' + this.stickyContainerClass + '" style="position: absolute; left: 0px; top: 0px; width: ' + this.width + 'px; ';
    	    if((this.divzindex) && (this.divzindex != ''))
    	        s += 'z-index: ' + ((this.divzindex*1) + i ) + '; ';
    	    else
    	        s += 'z-index: ' + (20000 + i ) + '; ';
	        s += 'visibility: hidden;" onmouseover="return MapTipsExtendedContentMouseOver(' + i + ');" onmousedown="return MapTipsExtendedContentMouseDown(event,' + i + ');">';
			s +=  '        <div class="' + this.stickyHeaderClass + '" style="width: ' + this.width + 'px;" id="MapTipExtendedHeaderCell_' + i + '" onmousedown="return MapTipsExtendedHeaderMouseDown(event,' + i + ');">';
		    //                     Header
			s +=  '        </div>';

		    s +=  '    <div class="' + this.stickyContentClass + '"  id="MapTipExtendedContentCell_' + i +'" >';
			    //    Content Content Content Content Content Content Content Content Content Content Content 
		    s +=  '    </div>';
		    //s +=  '    <div style="position: absolute; left: 0px; top: 0px; cursor: move;"><img src="' + maptipBlankImage + '" width="250" height="25" hspace="0" vspace="0" /></div>';
			s +=  '    <div  id="MapTipExtendedCloseCell_' + i + '" class="' + this.closeClass + '">';
			s +=  '	        <img src="' + esriMTCloseImage + '" alt="Close" hspace="0" vspace="0" border="0" align="middle"  onmousedown="closeExtendedMapTip(' + i + ')" onmouseover="this.style.cursor=\'pointer\'" />';
			s +=  '    </div>';
	        s +=  '</div>';

		    this.extendedDivObject[i] = null;
		    this.extendedDivId[i] = "MapTipExtendedContainerDiv_" + i;
		    this.extendedHeaderCell[i] = null;
		    this.extendedHeaderId[i] = "MapTipExtendedHeaderCell_" + i;
		    this.extendedContentCell[i] = null;
		    this.extendedContentId[i] = "MapTipExtendedContentCell_" + i;
		    this.extendedIndex[i] = -1;
	    }
        
        
	    var style = "background-color: transparent; position: absolute;";
        addDiv("MapTipPanelHolder", s, 0, 0, 1, 1, "visible", style)
    	
	    //document.writeln(s);
	    if (!isIE) 
		    window.setTimeout("mt_manager.setObjects();",100);
	    else 
		    this.setObjects();
	}
	
	this.setObjects = function() {
		this.hoverDivObject = document.getElementById(this.hoverDivId);
		maptipHoverPanel = this.hoverDivObject;
		this.hoverHeaderCell = document.getElementById(this.hoverHeaderId);
		this.hoverContentCell = document.getElementById(this.hoverContentId);
		for (var i=0;i<this.maxExtendedWindows;i++) {
			this.extendedDivObject[i] = document.getElementById(this.extendedDivId[i]);
			this.extendedHeaderCell[i] = document.getElementById(this.extendedHeaderId[i]);
			this.extendedContentCell[i] = document.getElementById(this.extendedContentId[i]);
		}
		
		if (this.type.toLowerCase()!="point")
			hideLayer("MapTipLayerDiv_" + maptips.id);

	}

	this.setPosition = function (maptipItem , which) {
		var left, top, x, y;
		var box = calcElementPosition(maptipItem.divId);		
		// For some reason, the box data structure's properties return undefined, so we use global variables set by calcElementPosition instead.
		x = eLeft - this.bufferZoneSize;
		y = eTop;

        var mp = MapTipCollections[maptipItem.mapId].map;
        var w = this.width + this.bufferZoneSize*2;
        var h, divObject;
		if (which.toLowerCase()=="extended"){
            // Extended maptip doesn't have buffer zone so we adjust coordinates and size so that it appears in the same spot
            h = this.extendedHeight + this.bufferZoneSize;
            w -= this.bufferZoneSize;
            divObject = this.extendedDivObject[this.windowIndex];
            x += this.bufferZoneSize;
            y += this.bufferZoneSize;
        }
        else {
            h = this.hoverHeight + this.bufferZoneSize*2;
			divObject = this.hoverDivObject;
        }
        
        var align = 'left';
        var valign = 'top';
        if(x + w > mp.width*1 + mp.containerLeft && this.keepMapTipsOnTopOfMap)
        {
            left = eLeft - w + this.bufferZoneSize + 1*maptipItem.hoverIconWidth; //mp.width*1 + mp.containerLeft - w;
            align = 'right';
        }
		else 
			left = x;
		if (y + h > mp.height*1 + mp.containerTop && this.keepMapTipsOnTopOfMap)
		{
			top = y - h + 1*maptipItem.hoverIconHeight; //mp.height*1 + mp.containerTop - h;
            valign = 'bottom';
	    }
		else 
			top = y;
		divObject.style.left = left + "px";
		divObject.style.top = top + "px";

        // Show arrow icon
        var icon = maptipItem.topLeftArrowIcon;
        if(align == 'right' && valign == 'top')
            icon = maptipItem.topRightArrowIcon;
        else if(align == 'right' && valign == 'bottom')
            icon = maptipItem.bottomRightArrowIcon;
        if(align == 'left' && valign == 'bottom')
            icon = maptipItem.bottomLeftArrowIcon;
        if(icon == '')
            return;
        this.hideArrows();
        var arrow = document.getElementById(this.hoverDivId + '_toparrow');
        if(valign == 'bottom')
            arrow = document.getElementById(this.hoverDivId + '_bottomarrow');
        arrow.src = icon;
        arrow.style.visibility = 'visible';
        arrow.parentNode.style.textAlign = align;
	}

    this.hideArrows = function()
    {
        var topArrow = document.getElementById(this.hoverDivId + '_toparrow');
        if(topArrow) topArrow.style.visibility = 'hidden';       
        var bottomArrow = document.getElementById(this.hoverDivId + '_bottomarrow');
        if(bottomArrow) bottomArrow.style.visibility = 'hidden';
    }
    	
	this.show = function(maptipCollection, index, which) {
		maptip = maptipCollection.mapTipItems[index];
		if (maptip!=null) {
		    if( !(maptip.content) || (maptip.content == '')) {
		        this.hide();
		        return;
		    }
		    this.setHeader(maptip.headerText, which);
		    this.setExtendedContent(maptip.extendedContent);
		    this.setContent(maptip.content, this.type);		
		    if (which!=null && which.toLowerCase()=="extended") {
			    //var content = maptip.content + maptip.extendedContent;

			    this.setPosition(maptip, "extended");
			    showLayer(this.extendedDivId[this.windowIndex]);
			    this.extendedIndex[this.windowIndex] = index
			    maptips.extendedVisible[index] = true;
			    lastExtendIndex = index;
			    lastExtendMapId = maptipCollection.id;
			    extendVisible = true;
    			
		    } else {
			    //window.status = "hoverVisible=" + hoverVisible;
			    if (!maptips.extendedVisible[index]) {
			    //this.hoverDivObject.onmousedown = hoverClick;
			    if(this.hoverHeaderCell)
			        this.hoverHeaderCell.onmousedown = hoverClick;
			    lastHoverIndex = index;
			    this.setPosition(maptip, "hover");
			    showLayer(this.hoverDivId);
			    hoverVisible = true;
			    }
		    }
		}
	}
	
	this.showAt = function(x, y, which) {
		if (which!=null && which.toLowerCase()=="extended") {
			this.extendedDivObject[this.windowIndex].style.left = x + "px";
			this.extendedDivObject[this.windowIndex].style.top = y + "px";
			showLayer(this.extendedDivId[this.windowIndex]);
			extendVisible = true;

		} else {
			this.hoverDivObject.style.left = x + "px";
			this.hoverDivObject.style.top = y + "px";
			showLayer(this.hoverDivId);
		}
	}
	
	this.setHeader = function(header, which) {
	    if(!(this.showHeader)) return;
		if (which!=null && which.toLowerCase()=="extended")
			this.extendedHeaderCell[this.windowIndex].innerHTML = header;
		else 
			this.hoverHeaderCell.innerHTML = header;
	}
	
	this.setContent = function(content, type) {
		/// Commented out lines below, as we always show extended content:
//		if (type=="point")
//			content += clickIconPrompt;
//		else 
//			content += "<br>" + clickHoverPrompt;
	///
		this.hoverContentCell.innerHTML = content;
	}
	
	this.setExtendedContent = function(content) {
		//alert(content);
		this.extendedContentCell[this.windowIndex].innerHTML = content;
		
	}
	
	this.hide = function(which, index) {
	    this.hideArrows();
		if (which!=null && which.toLowerCase()=="extended") {
			index = (index!=null) ? index : this.windowIndex;
			hideLayer(this.extendedDivId[index]);
			MapTipCollections[lastExtendMapId].extendedVisible[this.extendedIndex[n]] = false;
			extendVisible = false;
			//if (
		} else {
			//window.status = "mt_manager.hide()";
			hideLayer(this.hoverDivId);
			hoverVisible = false;
		}
	}
	
	this.hideAll = function(iconDiv) {
	    this.hideArrows();
		hideLayer(this.hoverDivId);
		hoverVisible = false;
		for (var i=0;i<this.maxExtendedWindows;i++) {
			hideLayer(this.extendedDivId[i]);
			maptips.extendedVisible[this.extendedIndex[i]] = false;
		}
		extendVisible = false;
		if (iconDiv!=null) {
			maptips.hideIcons(iconDiv);
		} else {
			maptips.resetDefaultIcons();
		}
	}
	
	this.bringToFront = function(index) {
		var zc = 20000;
		for (var i=0;i<this.maxExtendedWindows;i++) {
			if (i==index) {
				this.extendedDivObject[i].style.zIndex = 20000 + this.maxExtendedWindows;
			} else {
				this.extendedDivObject[i].style.zIndex = zc;
				zc++;
			}
		}
	}
	
	this.showClickIcon = function(index) {
		maptips.resetDefaultIcons();
		if (this.type.toLowerCase()=="point") {
		    maptips.setIcon(this.extendedIndex[index], maptip.iconClickImage, maptips.clickImage, maptip.clickIconWidth, maptip.clickIconHeight, maptip.iconAnchorPoint, maptip.iconText);
		}
	}
}

// object for managing MapTips popups
function MapTipsPanelManagerObject() {

}

function closeExtendedMapTip(n) {
	hideLayer("MapTipExtendedContainerDiv_" + n);
	MapTipCollections[lastExtendMapId].extendedVisible[mt_manager.extendedIndex[n]] = false;
	MapTipCollections[lastExtendMapId].resetDefaultIcons();
	extendVisible = false;
	lastExtendIndex = -1;
}

function dragMapTipStart(e, manager, index) {
	getXY(e);
	mt_manager = manager;
	mt_panelDragIndex = index;
	mt_panel = mt_manager.extendedDivObject[index];	
	//mt_panel = mt_manager.extendedHeaderCell[index];
	mt_panel.onmousemove = dragMapTipMove;
	mt_panel.onmouseup = dragMapTipEnd;
	var box = calcElementPosition(manager.extendedHeaderId[index]);
	maptipXOffset = mouseX-box.left;
	maptipYOffset = mouseY-box.top;
	tempMouseMove = document.onmousemove;
	tempMouseUp = document.onmouseup;
	document.onmousemove = dragMapTipMove;
	document.onmouseup = dragMapTipEnd;
    mapTipDragMaxRight = getWinWidth() - 5;
    mapTipDragMaxBottom = getWinHeight() - 5;

	return false;
}

function dragMapTipMove(e) {
	getXY(e);
	if (mouseX < 5) mouseX = 5;
	if (mouseY < 5) mouseY = 5;
	if (mouseX > mapTipDragMaxRight) mouseX = mapTipDragMaxRight;
	if (mouseY > mapTipDragMaxBottom) mouseY = mapTipDragMaxBottom;
	mt_panel.style.left = (mouseX-maptipXOffset) + "px";
	mt_panel.style.top = (mouseY-maptipYOffset) + "px";
	return false;
}

function dragMapTipEnd(e) {
	//mt_panel = mt_manager.extendedHeaderCell[mt_panelDragIndex];
	mt_panel.onmousemove = null;
	mt_panel.onmouseup = null;
	document.onmousemove = null;
	document.onmouseup = null;
    return false;
}

function setupMapTipPanels(width, height, classPrefix, type, bufferZoneSize, divzindex, showHeader, keepMapTipsOnTopOfMap) {
    //alert("setupMapTipPanels()");
    mt_manager = new MapTipWindowObject(width, height, classPrefix, type, bufferZoneSize, divzindex, showHeader, keepMapTipsOnTopOfMap);
    mt_manager.createDivs();
}

function hoverClick(e) {
	maptips.click(lastHoverIndex, e);
	return false;
}

// Identical to function zoomToBox in display_map.js except exchanged typo ztop for top.
function zoomToBoxBugfixed(controlName, left, top, right, bottom) {
    //alert(controlName);
    map = $find(controlName);
    //map = Maps[controlName];
    if (map!=null) {
	    map.xMin=left;
	    map.yMin=top; //ztop;
	    map.xMax=right;
	    map.yMax=bottom;
	    postBack(controlName, 'DragRectangle');
	} else
	    alert(controlName + " not found.");
}

function ZoomToPoi(controlID, index)
{
    MapTipCollections[controlID].ZoomToPoi(index);
}

function MapTipsExtendedContentMouseOver(id)
{
    mt_manager.bringToFront(id);
    mt_manager.showClickIcon(id);
    return false;
}

function MapTipsExtendedContentMouseDown(event, id)
{
    //return dragMapTipStart(event,mt_manager,id);
}

function MapTipsExtendedHeaderMouseDown(event, id)
{
    return dragMapTipStart(event,mt_manager,id);
}

function MapTipIconMouseOut(id)
{
    //MapTipCollections[id].hide('hover');
    return true;
}

function MapTipHoverInfoMouseOut(e)
{
    if( typeof( e ) == "undefined" && typeof( window.event ) != "undefined" )
        e = window.event;
    if(e == null) return;
    var hide = true;
    var element = e.toElement;
    if(element == null && e.relatedTarget) element = e.relatedTarget;
    //if(element == null) alert('e.toElement is null!');
    while(element != null)
    {
        //alert('To element: ' + element.id + ' (' + element.tagName+')');
        if(element.id == mt_manager.hoverHeaderId || element.id == mt_manager.hoverContentId || element.id == mt_manager.hoverDivId)
        {
            hide = false;
            element = null;
        }
        else
        {
            if(element.parentElement)
                element = element.parentElement;
            else if(element.parentNode)
                element = element.parentNode;
            else
                element = null;
        }
    }
    if(hide)
    {
        mt_manager.hide();
    }
    return true;
}

function MTT_GetCheckBoxStates(checkBoxIds, categories)
{
    var ids = checkBoxIds.split(';');
    var cats = categories.split(';');
    var eventArg = 'Operation=Update';
    for(var i = 0; i < ids.length; i++)
    {
        var c = document.getElementById(ids[i]);
        if(c)
            eventArg += '&Cat' + cats[i] + '=' + c.checked;
    }
    return eventArg;
}

function getIconXOffset(map, anchorPoint, iconWidth)
{
    var gridXOffset = 0; //map.gridXOffset 
    if(anchorPoint == 'Center' || anchorPoint == 'Default')
        return 0-iconWidth/2-gridXOffset;
    else if(anchorPoint == 'TopLeft')
        return 0-gridXOffset;
    else if(anchorPoint == 'TopRight')
        return 0-iconWidth-gridXOffset;
    else if(anchorPoint == 'BottomRight')
        return 0-iconWidth-gridXOffset;
    else if(anchorPoint == 'BottomLeft')
        return 0-gridXOffset;
    else
        return 0-iconWidth/2-gridXOffset;
}

function getIconYOffset(map, anchorPoint, iconHeight)
{
    var gridYOffset = 0; //map.gridYOffset 
    if(anchorPoint == 'Center' || anchorPoint == 'Default')
        return 0-iconHeight/2-gridYOffset;
    else if(anchorPoint == 'TopLeft')
        return 0-gridYOffset;
    else if(anchorPoint == 'TopRight')
        return 0-gridYOffset;
    else if(anchorPoint == 'BottomRight')
        return 0-iconHeight-gridYOffset;
    else if(anchorPoint == 'BottomLeft')
        return 0-iconHeight-gridYOffset;
    else
        return 0-iconHeight/2-gridYOffset;
}