//START APPLICATION SETTINGS
//There are no hard-coded size values outside of this block and the stylesheet.
//There should be no need to modify the code outside of this section. 
// KM: fix values if header size changes
//EVERYTHING BUT THE MAP
var notMap = 365; // WAS 340

//EVERYTHING BUT THE SIDEBAR PANEL
var notPanel = 120; // WAS 100
var jitkHeaderHeight; 

var jitkDefaultAccordionWidth = 300;

//SOME STARTING VALUE
var winH = 0;

//THE BOTTOM MARGIN OF THE PAGE
var bottomMargin = 5;

//STARTING VALUE FOR THE HEIGHT OF THE RESULTS BOX. THIS IS THE AREA THAT SCALES
var resultsBoxH = 176;

//THE HEIGHT OF OTHER RESULTS BOX CONTENT THAT DOESN'T SCALE (TABS, BORDER, MARGIN, ETC.)
//var resultsOtherH = 53;
var resultsOtherH = 23;

//MAP HEADER HEIGHT
var mapHeaderH = 30;

//INITIAL LEFT PANEL WIDTH
var leftPanel = 300;


//INCLUDES SCALE BAR AND CONTROLS TO THE RIGHT OF THE TOOLBAR
var toolbarW = 76;

//THE HEIGHT (INCLUDING MARGIN) OF A COLLAPSED accordion
var accordionHeight = 27;

//USE SMOOTHSWAP AND SMOOTHMODIFY FUNCTIONS 'true|false'
var useAnimation = 'false';

//USE DRAGGABLE BORDERS BETWEEN ACCORDIONS AND RESULTS 'true|false'
var useActiveBorders = 'true';


var overviewMapSpaceHeight = 235;

//HEIGHT OF THE OVERVIEW MAP ITSELF
var overviewMapHeight = 160;


var targ;

var jitkViewer_nonMapHeight = 141;
var jitkViewer_nonMapWidth = 372;
var jitkViewer_zeroSize = 0;
var jitkViewer_mapBorderWidth = 13;
var jitkViewer_resizeCounter = 0;
var jitkViewer_rightBuffer = 275; // Buffer to leave on right when sliding the toolbar right

// this global array is used to store the selected tab of any given task window
var jitkTaskWindowSelectedTabs = new Array();

//INITIALIZE SOME VARIABLES WE'LL NEED LATER
var leftItemsW = leftPanel + toolbarW;
var newMapHeight = 0;
var newHeight = resultsBoxH;
var v_startpos, v_diffpos=0;
var h_startpos, h_diffpos=0;
var v_allowed = false;
var h_allowed = false;
var showResults = true;
var iInitAccordianWidth = 0;
var init_leftPanel = leftPanel;
var init_overviewMapSpaceHeight = overviewMapSpaceHeight;

//ARE WE USING EXPLORER?
var isIE = navigator.appName.indexOf("Microsoft")!=-1;

// MG: remove flickering of background images that appears when hovering a link
try {
	document.execCommand("BackgroundImageCache", false, true);
} catch(err) {}

//ABSTRACTED CONNECT EVENT FUNCTION FOR ANY BROWSER
function connectEvent(element, event, handler) {
	if (isIE) {
		element.attachEvent("on" + event, handler);
	} else {
		element.addEventListener(event, handler, false);
	}
}

//ABSTRACTED DISCONNECT EVENT FUNCTION FOR ANY BROWSER
function disconnectEvent(element, event, handler) {
	if (isIE) {
		element.detachEvent("on" + event, handler);
	} else {
		element.removeEventListener(event, handler, false);
	}
}	


function updateOV(ovWidth, actionOV) {
	
	var ovWdLeft = (leftPanel - ovWidth )/2;   
    if (ovWdLeft < 0) ovWdLeft = - ovWdLeft; 
    
   	if(actionOV!=null && actionOV == "reset") {
	   	document.getElementById("overviewMap").style.padding = "0px 0px";
	   	document.getElementById("overviewMapBox").style.padding = "5px 6px 5px 6px";
   	} else {
   		//document.getElementById("overviewMap").style.left = 5 + ovWdLeft  +  "px";
		//document.getElementById("overviewMap").style.width = "274px";
		document.getElementById("overviewMapBox").style.padding = "5px 6px 204px";
	
    }

            	
}

//
// Purpose: Resizes map width and height.
//
function jitkViewer_resizeMap(iWidth, iHeight) {
	var map = EsriControls.maps['map1'];
	
  	if (iWidth != map.bounds.width || iHeight != map.bounds.height) {
    	map.resize(iWidth, iHeight);
	}
}

//
// Purpose: Resize map width only.
//
function jitkViewer_resizeMapWidth(iWidth) {
	var map = EsriControls.maps['map1'];
	
  	if (iWidth != map.bounds.width) {
  		var iHeight = map.bounds.height;
    	map.resize(iWidth, iHeight);
	}
}



//
// Purpose: Resize map height only.
//
function jitkViewer_resizeMapHeight(iHeight) {
	var map = EsriControls.maps['map1'];
	
  	if (iHeight != map.bounds.height) {
  		var iWidth = map.bounds.width;
    	map.resize(iWidth, iHeight);
	}
}



//
// Purpose: Resizes map width and height.
//
function jitkViewer_addMapHeight(iHeightDiff) {
	var map = EsriControls.maps['map1'];
	
  	if (iHeightDiff != 0) {
  		var iHeight = map.bounds.height + iHeightDiff;
  		var iWidth = map.bounds.width;  	
    	map.resize(iWidth, iHeight);
	}
}

//
// Purpose: Add the following value to the map width.
//
function jitkViewer_addMapWidth(iWidthDiff) {
	var map = EsriControls.maps['map1'];
	
  	if (iWidthDiff != 0) {
  		var iHeight = map.bounds.height;
  		var iInitWidth = map.bounds.width + iWidthDiff;
  		map.resize(iInitWidth, iHeight);
    	
    
	}
}

function hEndPos(p) {
	if (h_allowed) {
		h_allowed = false; 
		
		var sEndAccordianWidth = document.getElementById("accordions").style.width
		var iEndAccordianWidth = sEndAccordianWidth.substring(0, sEndAccordianWidth.indexOf("px"));
		var iWidthDiff = iInitAccordianWidth - iEndAccordianWidth;		
		var sEndAccordianWidth = document.getElementById("accordions").style.width		
		jitkViewer_addMapWidth(iWidthDiff);							
	}	      
	return false;
}


//STORES THE STARTING DRAG VALUE FOR HBAR (BETWEEN LEFT PANELS AND MAP)
function hPosition(p) {

	var sInitAccordianWidth = document.getElementById("accordions").style.width
	iInitAccordianWidth = sInitAccordianWidth.substring(0, sInitAccordianWidth.indexOf("px"));
	//document.onmouseup = new Function("h_allowed = false; return false;")
	document.onmouseup = hEndPos;
	document.onmousemove = hNewPos;
	if (!document.all){
	     h_startpos = p.screenX + h_diffpos;
	}    
	else{
	   h_startpos = event.clientX + h_diffpos;
	}
	   h_allowed = true;
	return false;
}


//OPENS OR CLOSES THE OVERVIEW MAP AND THE SPACE IT SITS IN, RE-SCALES THE ACCORDIONS TO FIT
function setOverviewMap(status) {
	var ie6Adjustment = 0;
	if (jQuery.browser.msie) {
		if (parseInt(jQuery.browser.version,10) == 6) {
			ie6Adjustment = 7;
		} else if (parseInt(jQuery.browser.version,10) == 7) {
			ie6Adjustment = 4;	
		}
	}
	if (status == "open"){
		overviewMapSpaceHeight = init_overviewMapSpaceHeight;
		document.getElementById('overviewMapContainerPanel').style.display = "block";
		scaleboxes();
	} 
	if (status == "closed"){
	  	overviewMapSpaceHeight = 0;
		document.getElementById('overviewMapContainerPanel').style.display = "none";
		newHeight = (winH - notPanel - ie6Adjustment);
		resizeAccordions(newHeight);
		//scaleboxes();
	}
	if (status == "min"){
		if(overviewMapSpaceHeight == init_overviewMapSpaceHeight){
	  		overviewMapSpaceHeight = 10;
			currentHeight = (winH - notPanel) - init_overviewMapSpaceHeight;
			newHeight = (winH - notPanel - ie6Adjustment) - overviewMapSpaceHeight;
			resizeAccordions(newHeight);
		}
	}
	if (status == "max"){
		if(overviewMapSpaceHeight != init_overviewMapSpaceHeight){
			currentHeight = (winH - notPanel) - overviewMapSpaceHeight;
			newHeight = (winH - notPanel - ie6Adjustment) - init_overviewMapSpaceHeight;
		  	overviewMapSpaceHeight = init_overviewMapSpaceHeight;
			resizeAccordions(newHeight);
		}
	}
    // KM: added
    renewSettingsMenu();
}



//ADJUSTS WIDTH OF ACCORDIONS WITH HBAR DRAG
//MAP AND RESULTS RESIZE NATURALLY TO FIT AVAILABLE WIDTH.
function hNewPos(p) {

	var iWinWidth = 0;
	var pageBounds = EsriUtils.getPageBounds();
	var iMaxXPos = pageBounds.width - jitkViewer_rightBuffer;
	
	if (h_allowed) {
		if (navigator.appName == "Netscape") {
			h_endpos = p.screenX;
			iWinWidth = window.innerWidth;
		}
		
		if (navigator.appName.indexOf("Microsoft") != -1) {
			iWinWidth = document.body.offsetWidth;
			h_endpos = event.clientX;
		}
		
		var iWidthWithoutLeftPanel = iWinWidth - leftItemsW;
		var iPrevDiffPos = h_diffpos;
		h_diffpos = h_startpos - h_endpos;
		
		// If the bar has not been moved beyond the maximum point to the right
		if ( (-h_diffpos < iWidthWithoutLeftPanel)  
			&& (h_diffpos < leftPanel) 
			&& (h_endpos < iMaxXPos) ) {
			
			document.getElementById("accordions").style.width = leftPanel - h_diffpos + "px";
			
			var rightPanelLeft = $("#accordions").width() + $("#toolbar").width() + $("#vbar").width();
			$("#rightPanel").css("left",rightPanelLeft);
			if (h_diffpos <=0) updateOV(leftPanel - h_diffpos);
			
		}
		else {
			h_diffpos = iPrevDiffPos;
		}
	}
}


//SNAPS THE LEFT PANEL OPEN TO "P" VALUE PASSED IN.
//USED BY "MINIMIZE" AND "OPEN-WIDE" CONTROL BUTTONS
function hPositionJump(p) {

	var newAccordionWidth = parseInt(p,10);
	var accordionWidth = $("#accordions").width();
	var accordionWidthDiff = accordionWidth - newAccordionWidth;

	if (accordionWidthDiff != 0) {
		jitkViewer_addMapWidth(accordionWidthDiff);
	
		var mapDisclaimerWidth = $("#mapDisclaimer").width();
		var toolbarWidth = $("#toolbar").width();
		var vbarWidth = $("#vbar").width();
		var mapContainerWidth = $("#mapContainer").width();
		var mapWidth = EsriControls.maps['map1'].bounds.width;
		var mapSpacingWidth = mapContainerWidth - mapWidth;
		//var windowWidth = $(document).width();
		var windowWidth = $("#topmenu").outerWidth({margin:true});
		var notMapWidth = newAccordionWidth + toolbarWidth + vbarWidth + mapSpacingWidth + 1;
		var rightPanelLeft = newAccordionWidth + toolbarWidth + vbarWidth;
	    
	    var newMapWidth = windowWidth - notMapWidth;
	    
		var newMapContainerWidth = newMapWidth + mapSpacingWidth;
		
		$("#rightPanel").css("left",rightPanelLeft);
	
		$("#map > div").width(newMapWidth);
		$("#mapDisclaimer").width((mapDisclaimerWidth == 0) ? 150 : mapDisclaimerWidth);
		$("#mapContainer").width(newMapContainerWidth);
		$("#mapHeader").width(newMapContainerWidth);
		
		
		$("#resultsContainer").width(newMapContainerWidth);
		$("#resultsBox").width("100%");
	
		if (newAccordionWidth == 0) {
			$("#accordions").width(newAccordionWidth);
			$("#accordions").hide();
		} else {
			$("#accordions").width(newAccordionWidth);
			updateOV(newAccordionWidth);
			$("#accordions").show();
		}
			
		h_allowed = false;
	}
	return false;
}


//HIDES OR SHOWS THE LEFT PANEL ITEMS BASED ON "P" VALUE PASSED IN.
//THIS IS USED BY THE CLOSE (X) BUTTON AND THE REOPEN PANEL MENU ITEM
function accordDisplay(p) {
	switch (p) {
		case "none":
            // KM: added
            renewSettingsMenu();
			return hPositionJump(0);
			break;
		case "reset":
            // KM: added
            renewSettingsMenu();        
			return hPositionJump(jitkDefaultAccordionWidth);
			break;
		case "max":
            // KM: added
            renewSettingsMenu();        
			return hPositionJump(400);
			break;
		case "min":
            // KM: added
            renewSettingsMenu();        
			return hPositionJump(0);
			break;
	}
}



//FUNCTIONS FOR RESULTS AREA DISPLAY BUTTONS
function jitkViewer_displayResults(p) {
	
	if(p == "none") {
		//document.getElementById("map").style.display = "block";
		document.getElementById("mapHeader").style.display = "block";
		document.getElementById("mapContainer").style.display = "block";
		document.getElementById("resultsBox").style.display = p;
		document.getElementById("resultsContainer").style.display = p;
		document.getElementById("hbar").style.display = p;
		showResults = false;
		mapHeight = winH - notPanel - mapHeaderH;
		smoothModify('map', 'height', document.getElementById("map").style.height.slice(0, -2), mapHeight, 100);
		
		jitkViewer_resizeMapHeight(mapHeight);
	
	} else if(p == "block") {
		//document.getElementById("map").style.display = "block";
		document.getElementById("mapHeader").style.display = "block";
		document.getElementById("mapContainer").style.display = "block";
		document.getElementById("resultsContainer").style.display = "block";
		document.getElementById("resultsBox").style.display = "block";
		document.getElementById("hbar").style.display = "block";
		showResults = true;
		mapHeight = winH - notMap - v_diffpos;
		smoothModify('map', 'height', document.getElementById("map").style.height.slice(0, -2), mapHeight, 100);
		
		jitkViewer_resizeMapHeight(mapHeight);
	
	} else if(p == "max") {
		setTimeout("document.getElementById('mapHeader').style.display = 'none'", 800);
		setTimeout("document.getElementById('mapContainer').style.display = 'none'", 800);
		showResults = true;
		mapHeight = winH - notMap - v_diffpos;
		v_diffpos = v_diffpos + mapHeight + mapHeaderH + bottomMargin;
		mapHeight = 0;
		if(document.getElementById("resultsBox").style.height.slice(0, -2) != "") {
			rFrom = document.getElementById("resultsBox").style.height.slice(0, -2);
		} else {
			rFrom = 0;
		}
		smoothModify('map', 'height', document.getElementById("map").style.height.slice(0, -2), mapHeight, 100);
		smoothModify('resultsBox', 'height', rFrom, resultsBoxH + v_diffpos, 100);
	
	} else if(p == "min") {
		document.getElementById("map").style.display = "block";
		document.getElementById("mapHeader").style.display = "block";
		document.getElementById("mapContainer").style.display = "block";
		showResults = true;
		mapHeight = (winH - notMap) - v_diffpos;
		resultsAreaH = resultsBoxH + resultsOtherH + v_diffpos;
		v_diffpos =  v_diffpos - resultsAreaH;
		mapHeight = mapHeight + resultsAreaH;
		if(document.getElementById("map").style.height.slice(0, -2) != "") {
			mFrom = document.getElementById("map").style.height.slice(0, -2);
		} else {
			mFrom = 0;
		}
		smoothModify('map', 'height', mFrom, mapHeight, 200);
		smoothModify('resultsBox', 'height', document.getElementById("resultsBox").style.height.slice(0, -2), 0, 200);
		
		jitkViewer_resizeMapHeight(mapHeight);
	
	} else if(p == "reset") {
		document.getElementById("map").style.display = "block";
		document.getElementById("mapHeader").style.display = "block";
		document.getElementById("mapContainer").style.display = "block";
		document.getElementById("resultsContainer").style.display = "block";
		document.getElementById("resultsBox").style.display = "block";
		document.getElementById("hbar").style.display = "block";
		showResults = true;
			
		var rbHeight = document.getElementById("resultsBox").style.height.slice(0, -2);
		if(rbHeight == 0) {
			v_diffpos = 0;
			mapHeight = winH - notMap;
			
			smoothModify('map', 'height', document.getElementById("map").style.height.slice(0, -2), mapHeight, 100);
			smoothModify('resultsBox', 'height', rbHeight, resultsBoxH, 200);
			
		} else {
			mapHeight = winH - notMap - v_diffpos;
			smoothModify('map', 'height', document.getElementById("map").style.height.slice(0, -2), mapHeight, 100);
			smoothModify('resultsBox', 'height', rbHeight, rbHeight, 200);
		}
		
		jitkViewer_resizeMapHeight(mapHeight);
	}
	
	h_allowed = false;
    // KM: added
    renewSettingsMenu();
	return false;
}


//STORES THE STARTING DRAG VALUE FOR VBAR (BETWEEN MAP AND RESULTS)
function vPosition(p) {
	//document.onmouseup = new Function("v_allowed = false; return false;")
	document.onmouseup = vEndPos;
	document.onmousemove = vNewPos;
	if (navigator.appName=="Netscape") {
		v_startpos = p.screenY + v_diffpos;
	}
	if (navigator.appName.indexOf("Microsoft")!=-1) {
		v_startpos = event.clientY + v_diffpos;
	}
	v_allowed = true;
	return false;
}


//ADJUSTS HEIGHT OF MAP AND RESULTS WITH VBAR DRAG
function vNewPos(p) {
	if (v_allowed) {
		if (!document.all)
			v_endpos = p.screenY;
		else
			v_endpos = event.clientY;
			v_diffpos = v_startpos- v_endpos;
		var mapHeight = winH - notMap;
		if (v_diffpos > -(resultsBoxH) && v_diffpos < mapHeight) {
			//REOPEN MAP IF HIDDEN
			document.getElementById("mapHeader").style.display = "block";
			document.getElementById("mapContainer").style.display = "block";
			document.getElementById("resultsContainer").style.display = "block";
			document.getElementById("resultsBox").style.display = "block";
			document.getElementById("map").style.height = mapHeight - v_diffpos + "px";
			document.getElementById("resultsBox").style.height = resultsBoxH + v_diffpos + "px";
		}
	}
}


function vEndPos(p) {
	if (v_allowed) {
		v_allowed = false;
		var sMapDivHeight = document.getElementById("map").style.height
		var iMapDivHeight = sMapDivHeight.substring(0, sMapDivHeight.indexOf("px"));
		
		if (iMapDivHeight <= 0) {
			iMapDivHeight = jitkViewer_zeroSize;
		}else {
			jitkViewer_resizeMapHeight(iMapDivHeight);
		}
	}

	document.onmouseup = new Function("v_allowed = false; return false;")	
	return false;
}


//ATTACHES FUNCTIONS TO RESIZE BARS & SCALES PAGE ELEMENTS 
function setevent() {

	jitkHeaderHeight = $("topmenu").height() + $("header").height();
	
	 //CONNECT ACTIONBULDER FUNCTION TO ELEMENTS THAT REQUEST IT
	var buildActions = getElementIdByAttributeValue('actionBuilder', 'true');
	for (i=0; i<buildActions.length; ++i) {
		thisElement = document.getElementById(buildActions[i]);
		thisAction = thisElement.getAttribute("onthis");
		connectEvent(thisElement, thisAction, actionBuilder);
	}

	//GRAB THE HORIZONTAL BAR TO CHANGE THE VERTICAL POSITION OF ELEMENTS ON THE PAGE
	if (useActiveBorders == "true") {
		connectEvent(document.getElementById("hbar"), "mousedown", vPosition);
		connectEvent(document.getElementById("hbar"), "dblclick", resultsView);
	} else {
		document.getElementById("hbar").style.cursor = "default";
	}

	//GRAB THE VERTICAL BAR TO CHANGE THE HORIZONTAL POSITION OF ELEMENTS ON THE PAGE
	if (useActiveBorders == "true") {
		connectEvent(document.getElementById("vbar"), "mousedown", hPosition);
		connectEvent(document.getElementById("vbar"), "dblclick", accordionHide);
	} else {
		document.getElementById("vbar").style.cursor = "default";
	}
	 
		
	
	//RUN SCALE FUNCTION ON RESIZE
	window.onresize = scaleboxes;
	//AND GO AHEAD AND RUN IT NOW ON LOAD
	scaleboxes();
	
	
	//INITIATE THE FADE AWAY EFFECT ON THE "FADER" DIV OVERLAY
	setTimeout("smoothModify('fader', 'opacity', 100, 0, 1000)", 1000);
	
	//HIDE RESULTS DISPLAY
	jitkViewer_displayResults('min');
	
	//SHOW ACCORDIAN SET
	swapAccordSet('accordianMapContents');
	
	// add onclick handler to menu so that it automatically shows as the top-most element
	if (!$.browser.msie) {
		$("#nav").mouseover(function(){
			if (taskWindowManager.windows[taskWindowManager.windowIds[0]] != null) {
				var win = taskWindowManager.windows[taskWindowManager.windowIds[0]];
				$("#nav").css("z-index",win.jitkGetGlobalZIndex()+1);			
	  		}
		});
	}
			
}


function resultsView() {
	resultsDisplay("max");
	disconnectEvent(document.getElementById("hbar"), "dblclick", resultsView);
	connectEvent(document.getElementById("hbar"), "dblclick", resultsHide);
}

function resultsHide() {
	resultsDisplay("min");
	disconnectEvent(document.getElementById("hbar"), "dblclick", resultsHide);
	connectEvent(document.getElementById("hbar"), "dblclick", resultsView);
}

function accordionView() {
	accordDisplay('reset');
	disconnectEvent(document.getElementById("vbar"), "dblclick", accordionView);
	connectEvent(document.getElementById("vbar"), "dblclick", accordionHide);
}

function accordionHide() {
	hPositionJump(0);
	disconnectEvent(document.getElementById("vbar"), "dblclick", accordionHide);
	connectEvent(document.getElementById("vbar"), "dblclick", accordionView);
}



function scaleboxes() {
	//alert('scaleboxes');
	var iResultBoxHeight = resultsBoxH + v_diffpos;
	var iAccordianWidth = leftPanel - h_diffpos;

	if (iResultBoxHeight <= 0) {
		iResultBoxHeight = jitkViewer_zeroSize;
	}
	
	if (iAccordianWidth <= 0) {
		iAccordianWidth = jitkViewer_zeroSize;
	}
	
	// Disabled by new version of Steve's code
	//document.getElementById("resultsBox").style.height = iResultBoxHeight + "px";
	document.getElementById("accordions").style.width = leftPanel - h_diffpos  + "px";

	//GET CURRENT WINDOW HEIGHT
	if (parseInt(navigator.appVersion)>3) {
		if (navigator.appName=="Netscape") {
			winH = window.innerHeight;
		}
		if (navigator.appName.indexOf("Microsoft")!=-1) {
			winH = document.body.offsetHeight;
		}
	}
		// Resize the map
	if (showResults == true) {
		mapHeight = winH - notMap - v_diffpos;
		
		if (mapHeight <= 0) {
			mapHeight = jitkViewer_zeroSize;
		}
		
		document.getElementById("map").style.height = mapHeight  + "px";
	}
	else {
		mapHeight = winH - notPanel - mapHeaderH;
		
		if (mapHeight <= 0) {
			mapHeight = jitkViewer_zeroSize;
		}	
		
		document.getElementById("map").style.height = mapHeight  + "px";
   }		
		
	//SCALE LEFT PANEL
	var panelHeight = (winH - notPanel) - overviewMapSpaceHeight - bottomMargin;
	if (panelHeight<=0) panelHeight = jitkViewer_zeroSize;
	resizeAccordions(panelHeight);

	//SCALE THE VBAR
	var vbarHeight = winH - notPanel;
	var vbar = document.getElementById('vbar');

	var iVBarHeight = vbarHeight + bottomMargin;
	
	if (iVBarHeight <= 0) {
		iVBarHeight = jitkViewer_zeroSize;
	}
	
	vbar.style.height = iVBarHeight + "px";
	
	var hControlsHeight = vbarHeight + bottomMargin;
	var hControls = document.getElementById('hControls');	
	
	if (hControlsHeight <= 0) {
		hControlsHeight = jitkViewer_zeroSize;
	}
	
	hControls.style.height = hControlsHeight/2 + "px";

	//SCALE THE TOOLBAR
	var toolbarHeight = winH - notPanel;
	var toolbar = document.getElementById('toolbar');
	
	var iToolbarHeight = toolbarHeight + bottomMargin;
	
	if (iToolbarHeight <= 0) {
		iToolbarHeight = jitkViewer_zeroSize;
	}
	
	toolbar.style.height = iToolbarHeight + "px";

	//SCALE THE RIGHT PANEL
	var mapHeight = winH - notPanel;


	var mapDisclaimerWidth = $("#mapDisclaimer").width();
	var accordionWidth = $("#accordions").width();
	var toolbarWidth = $("#toolbar").width();
	var vbarWidth = $("#vbar").width();
	var mapContainerWidth = $("#mapContainer").width();
	var mapSpacingWidth = 12;
	var windowWidth = $("#topmenu").outerWidth({margin:true});
	var notMapWidth = accordionWidth + toolbarWidth + vbarWidth + mapSpacingWidth + 1;

	var newMapWidth = windowWidth - notMapWidth;
	var newMapContainerWidth = newMapWidth + mapSpacingWidth;

	var rightPanelTop = $("#topmenu").outerHeight({margin:true}) + $("#header").outerHeight({margin:true});
	var rightPanelLeft = accordionWidth + toolbarWidth + vbarWidth;
	$("#rightPanel").css("top",rightPanelTop);
	$("#rightPanel").css("left",rightPanelLeft);


	$("#map > div").width(newMapWidth);
	$("#mapDisclaimer").width((mapDisclaimerWidth == 0) ? 150 : mapDisclaimerWidth);
	$("#mapContainer").width(newMapContainerWidth);
	$("#mapHeader").width(newMapContainerWidth);
	
	$("#resultsBox").width(newMapWidth-1);
	$("#resultsContainer").width(newMapContainerWidth);

	
	//var rightPanel = document.getElementById('rightPanel');
	//if(rightPanel <=0) rightPanel = jitkViewer_zeroSize;
	//rightPanel.style.height = panelHeight + "px";

	//INITIALIZE OVERVIEW MAP
	//var overviewMap = document.getElementById('overviewMap');
	//overviewMap.style.height = overviewMapHeight + "px";

	//ATTACH HOVER STATE & SWAP FUNCTION TO TOOLBAR IMAGES
	//THIS FUNCTION MAY BE DELETED IN FINAL DEPLOYMENT
	/*
	var x = document.getElementById('buttonset').childNodes;
	for(i = 0; i < x.length; i++){
		if(x[i].nodeName == 'A'){
			a = x[i].firstChild.src;
			overimg = new Array();
			overimg = a.split('.');
			filename = overimg[0] + "U.jpg";
			x[i].firstChild.setAttribute("srcover", filename);
			x[i].firstChild.onmouseover = function(){
				this.setAttribute("oldsrc", this.src);
				this.src=this.getAttribute("srcover");
				this.blur();
			}
			x[i].firstChild.onmouseout = function(){
				this.src=this.getAttribute("oldsrc");
				this.blur();
			}
		}
	} 
	*/
	//END SWAP FUNCTION
	
	// IE6 only: reduce the width of #resultsBox by 1px to work-around scroll hack
	if ($.browser.msie) {
		$("#resultsBox").width($("#resultsBox").width() - 1);
	}

	/*
	//IE ONLY. SETS SOME ELEMENTS TO "UNSELECTABLE" THIS AVOIDS
	//OCCASIONAL "FLASHING" ARTIFACTS WHEN DRAGGING PANELS
	if (navigator.appName.indexOf("Microsoft")!=-1) {
		var noSelect = new Array("toolbar","hControls","vbar","rightPanel","mapHeader","elevatorBox")
		for (i=0; i<noSelect.length; ++i) {
			$("#"+noSelect[i]).attr("unselectable", "on");
		}
	}
	*/
	
	jitkViewer_resizeCounter++;
	setTimeout('jitkViewer_throttleResize(' + jitkViewer_resizeCounter + ')', 750);
} //END SCALEBOXES

function jitkViewer_throttleResize(iLocalResizeCounter) {
  	if (iLocalResizeCounter == jitkViewer_resizeCounter) {
		jitkViewer_sizeMapToPage();
	}
  
  	return true;
}

function jitkViewer_sizeMapToPage() {
	//alert('jitkViewer_sizeMapToPage');
	var b = EsriUtils.getPageBounds();
   	var iWidth = b.width - leftItemsW + h_diffpos + jitkViewer_mapBorderWidth - 27;
   	
   	// The ADF Map control will break if the width is any less than 1
   	if (iWidth <= 0) {
   		iWidth = 1;
   	}
   	
	var sMapDivHeight = document.getElementById("map").style.height
	var iMapDivHeight = sMapDivHeight.substring(0, sMapDivHeight.indexOf("px"));
		
	// The ADF Map control will break if the height is any less than 1
	if (iMapDivHeight <= 0) {
		iMapDivHeight = 1;
	}
   	
   	jitkViewer_resizeMap(iWidth, iMapDivHeight);
}



//THESE FUNCTIONS CONTROL THE FADE FOR THE PAGE CONTENT
//changes the opacity for different browsers
function changeOpac(opacity, id) {
	var object = document.getElementById(id).style; 
	object.opacity = (opacity / 100);
	object.MozOpacity = (opacity / 100);
	object.KhtmlOpacity = (opacity / 100);
	object.filter = "alpha(opacity=" + opacity + ")";
}

//adjust the timing of the fade
function blendDiv(divid, millisec) {
	var speed = Math.round(millisec / 100);
	var timer = 1;
	changeOpac(100, divid);
	var i = 100;
	while(i>0){
		setTimeout("changeOpac(" + i + ",'" + divid + "')",(timer * speed));
		timer++;
		i--;
	}
	setInterval( "hideFader('" + divid + "')", (timer * speed));
}

//hide the fader div when it's done
function hideFader(divid) {
 	document.getElementById(divid).style.display = "none";
}


function resizeAccordions(panelHeight) { 
	//RESIZE ACCORDION SETS
	var x = document.getElementById('accordions').childNodes;
	for(i = 0; i < x.length; i++){
		if(x[i].nodeName == 'DIV'){		
			if(x[i].id != 'overviewMapContainerPanel'){
				//x[i].style.height = panelHeight + "px";
				y = x[i].childNodes
				//LOOP THROUGH MY ACCORDION PANELS - HOW MANY DO WE HAVE?
				var myPanels = 0;
				for(j = 0; j < y.length; j++){
					if(y[j].nodeName == 'DIV'){	
						myPanels = myPanels + 1;
					}
				}
			}
			//NOW RUN BACK THROUGH AND SET OUR HEIGHTS
			var inactiveaccordionHeight = myPanels*accordionHeight;
			lPanelHeight = panelHeight - inactiveaccordionHeight;
			if (lPanelHeight<=0) lPanelHeight = jitkViewer_zeroSize;
			for(j = 0; j < y.length; j++){
				if(y[j].nodeName == 'DIV'){	
					if(y[j].id != 'overviewMap'){
						//if(y[j].style.display == "block") {
							//smoothModify(y[j].id, 'height', y[j].style.height.slice(0, -2), lPanelHeight, 100);
						//} else {
                            // KM: pridejau 23, po susiskleidziancio meniu pasalinimo atsirado tarpas
							//y[j].style.height = lPanelHeight+23 + "px";
                            // buvo +3 
                            y[j].style.height = lPanelHeight-4 + "px";
						//}
					}
				}
				if(y[j].nodeName == 'H1'){
			   	    connectEvent(document.getElementById(y[j].id), "click", swapPanel);
				}
			}
		}
	}
}


//DISPLAYS ACTIVE PANEL HIGHLIGHTS ACTIVE H1
function swapPanel(p) {
   var currentP;
	if (!e) var e = window.event;
  if (e){
  if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	if (targ){
	if (targ.nodeType == 3) // defeat Safari bug
		targ = targ.parentNode;
	p = targ.id;
    }
   } 
	//HIDE ALL PANELS
	var ele = document.getElementById(p + "Panel");
 //if (ele!=null) { 
	var x = ele.parentNode.childNodes;
	for(i = 0; i < x.length; i++){
		if(x[i].nodeName == 'DIV'){
			if(x[i].style.display == "block") {
				var lPanelHeight = x[i].style.height.slice(0,-2);
				currentP = x[i].id;
			}
		}
	}
 		
	//CLEAR ALL H1 ON CLASS REF	  
	var x = ele.parentNode.childNodes;
	for(i = 0; i < x.length; i++){
		if(x[i].nodeName == 'H1'){		
			x[i].className = "off";
			connectEvent(document.getElementById(x[i].id), "click", swapPanel);
		}
	}
 //}
	
	//OPEN MY PANEL & CLOSE OPEN PANEL
	var myPanel = p + "Panel";
	smoothSwap(currentP, myPanel, 'height', lPanelHeight, 0, 50);

	//SET ON CLASS
	document.getElementById(p).className = "on";
	disconnectEvent(document.getElementById(p), "click", swapPanel);
	//REMOVE FOCUS
	document.getElementById(p).blur();
}


//DISPLAYS SELECTED ACCORDION SET
function swapAccordSet(p) {
	//HIDE ALL ACCORDION SETS
	var x = document.getElementById(p).parentNode.childNodes;
	for(i = 0; i < x.length; i++){
		if(x[i].nodeName == 'DIV'){	
			if(x[i].id != 'overviewMapContainerPanel'){	
				x[i].style.display = "none";
			}
		}
	}
	//OPEN MY ACCORDION SET
	document.getElementById(p).style.display = "block";

	var x = document.getElementById(p).childNodes;
	for(i = 0; i < x.length; i++){
		if(x[i].nodeName == 'DIV'){
			if(x[i].style.display == "block") {
				currentP = x[i].id;
			}
		}
	}
}

//DISPLAYS ACTIVE RESULTS & HIGHLIGHTS ACTIVE RESULTS TAB
function swapResults(p) {
	//HIDE ALL PANELS
	var x = document.getElementById('resultsBox').childNodes;
	for(i = 0; i < x.length; i++){
		if(x[i].nodeType == 1){		
			x[i].style.display = "none";
		}
	}
	
	//CLEAR ALL TAB ON CLASS REF
	var x = document.getElementById('resultsTabs').childNodes;
	for(i = 0; i < x.length; i++){
		if(x[i].nodeType == 1){		
			x[i].className = "none";
		}
	}
	
	//OPEN MY PANEL
	document.getElementById(p + "Results").style.display = "block";
	//SET ON CLASS
	document.getElementById(p).className = "on";
	//REMOVE FOCUS
	document.getElementById(p).blur();
}

//BUILD A FUNCTION FOR AN ELEMENT USING ITS ATTRIBUTES
function actionBuilder(e) {
	if (!e) var e = window.event;
	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	if (targ.nodeType == 3) // defeat Safari bug
		targ = targ.parentNode;
	thisId = targ.id;
	theseArgs = "";
	thisElement = document.getElementById(thisId);
	thisFunction = thisElement.getAttribute("function");
	theseArgs = thisElement.getAttribute("arguments");
	
	eval(thisFunction +'("' + theseArgs +'")');
}



//PUSH OUT AN ARRAY OF ELEMENTS THAT MATCH THIS ATTR/VAL PAIR
function getElementIdByAttributeValue(a, v) {
    var ar = new Array();
    var ac = document.getElementsByTagName('*');
    for (i=0; i<ac.length; i++){
		if (ac[i].getAttribute(a) == v){
			ar.push(ac[i].id);
		}
	}
    return ar;
}



//SMOOTHLY CHANGES CSS VALUES
function smoothModify(id, prop, from, to, millisec) {
	var speed = Math.round(millisec / 100);
	var timer = 1;
	if (useAnimation == "true") {
		if(from > to){
			while(from >= to){
				delta = from - to;
				step = delta % 10;
				if (step == 0){
					setTimeout("doModify('"+id+"','"+prop+"',"+from+")",(timer * speed));
				}
				timer++;
				from--;
			}
		}
		if(to > from){
			while(to >= from){
				delta = to - from;
				step = delta % 10;
				if (step == 0){
					setTimeout("doModify('"+id+"','"+prop+"',"+from+")",(timer * speed));
				}
				timer++;
				from++;
			}
		}
	} else {
		doModify(id,prop,to);
	}
}

//SMOOTHLY SWAPS CSS VALUES OF 2 ELEMENTS
function smoothSwap(id1, id2, prop, id1val, id2val, millisec) {
	var speed = Math.round(millisec / 100);
	var timer = 1;
	startID2 = id2val;
	if (useAnimation == "true") {
		while(id1val >= startID2){
			delta = id1val - startID2;
			step = delta % 10;
			if (step == 0){
				setTimeout("doModify('"+id1+"','"+prop+"',"+id1val+")",(timer * speed));
				setTimeout("doModify('"+id2+"','"+prop+"',"+id2val+")",(timer * speed));
			}
			timer++;
			id2val++;
			id1val--;
		}
	} else {
		doModify(id1,prop,id2val);
		doModify(id2,prop,id1val);
	}
}

//USED BY SMOOTHMODIFY 7 SMOOTHSWAP FUNCTIONS TO CHANGE CSS VALUES BY ONE STEPPING 
function doModify(id, prop, to) {
	if(to == 0){
		document.getElementById(id).style.display = "none";
	} else {
		document.getElementById(id).style.display = "block";
	}
	if(prop == "opacity"){
		document.getElementById(id).style.opacity = (to / 100);
		document.getElementById(id).style.MozOpacity = (to / 100);
		document.getElementById(id).style.KhtmlOpacity = (to / 100);
		document.getElementById(id).style.filter = "alpha(opacity=" + to + ")";
	} else {
		document.getElementById(id).style[prop] =  to + "px";
	}
}

//DROP-DOWN MENU IE6 SUPPORT
//This code fixes the hover state of the drop-down menu in IE. IE6 only recognizes the :hover psudoclass for A tags so a class assignment is swapped on the LI tag to replicate hover functionality.
sfHover = function() {
	var sfEls = document.getElementById("nav").getElementsByTagName("LI");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" sfhover";
			if (taskWindowManager.windows[taskWindowManager.windowIds[0]] != null) {
				var win = taskWindowManager.windows[taskWindowManager.windowIds[0]];
				$("#nav").css("z-index",win.jitkGetGlobalZIndex()+1);			
	  		}
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
		}
	}
}


if (window.attachEvent) { 
	window.attachEvent("onload", sfHover);
}
//END DROP-DOWN MENU IE6 SUPPORT


/**
 * show task window loading indicator (needs to find the window object first)
 */
function JitkShowLoading(el, taskId) {
	var win = JitkGetTaskWindowId(taskId);
	if (win != null) {
		win.submit(el);
	}
}

/**
 * set the selected tab of a task window 
 * !!! only use this function when a different task than the currently active one is needed !!!
 * the actual assignment happens automatically through the JitkShowLoading function upon submitting the task to the server
 */
function JitkSetSelectedTab(taskId, selectedTab) {
	var win = JitkGetTaskWindowId(taskId);
	if (win != null) {
		win.setSelectedTab(selectedTab);
	}
}

/**
 * show/hide task window message (needs to find the window object first)
 */
function JitkShowMessage(taskId, type, text) {
	var win = JitkGetTaskWindowId(taskId);
	if (win != null) {
		win.showMessage(type, text);
	}
}
function JitkHideMessage(taskId) {
	var win = JitkGetTaskWindowId(taskId);
	if (win != null) {
		win.hideMessage();
	}
}

/**
 * show/hide loading indicator (without submitting the form)
 */
function JitkShowLoadingIndicator(taskId) {
	var win = JitkGetTaskWindowId(taskId);
	if (win != null) {
		win.showLoading();
	}
}
function JitkHideLoadingIndicator(taskId) {
	var win = JitkGetTaskWindowId(taskId);
	if (win != null) {
		win.hideLoading();
	}
	$("#"+taskId+" img").ifixpng();
}

/**
 * adjust the task window size manually
 */
function JitkAdjustWindowSize(taskId) {
	var win = JitkGetTaskWindowId(taskId);
	if (win != null) {
		win.fit();
	}
}

/**
 * find the task window object of a given task cell id 
 */
function JitkGetTaskWindowId(taskId) {
	if (taskWindowManager) {
		var win;
		win = taskWindowManager.windows["win_EsriTaskCell_"+taskId];
		if (win != null) {
			return win;
		} else {
			win = taskWindowManager.windows["win_"+taskId];
			if (win != null) {
				return win;
			} else {
				win = taskWindowManager.windows[taskId];
				if (win != null) {
					return win;
				}
			}
		}
	}
	return null;
}

function jitkDisableButton(buttonId) {
	$("#"+buttonId).fadeTo(1, 0.5);
}
function jitkEnableButton(buttonId) {
	$("#"+buttonId).fadeTo(1, 1);
}

/* FIX IE6 dragging issue */
// introduce global variables that save the current state of the floating window
var jitkSavedTarget = null;
var jitkDragOK = false;
var jitkDragXoffset = 0;
var jitkDragYoffset = 0; 

// on mouse move handler
function JitkMoveHandler(e) {
	if (e == null) { e = window.event } 
	if (e.button <= 1 && jitkDragOK) {
		jitkSavedTarget.style.left = e.clientX - jitkDragXoffset + 'px';
		jitkSavedTarget.style.top = e.clientY - jitkDragYoffset + 'px';
		return false;
	}
}

// on mouse up handler
function JitkDragCleanup(e) {
	
	if(e == null) {
		e = window.event;
	}
	
	var iBelowMenu = 32;
	if(e.button <= 1 && jitkDragOK && e.clientY < iBelowMenu) {
        jitkSavedTarget.style.top = iBelowMenu + 'px';
    }
    
	document.onmousemove = null;
	document.onmouseup = null;
	jitkDragOK = false;
}

// prototype the mouseInteraction member function of jitk_jquery_ui_mouse.js with IE6 specific code
(function($) {
	$.extend($.ui.mouseInteraction.prototype, {
		
		destroy: function() { $(this.element).unbind('mousedown.draggable'); },
		trigger: function() { return this.click.apply(this, arguments); },
		click: function(e) {
			
			if(
				   e.which != 1 //only left click starts dragging
				|| $.inArray(e.target.nodeName.toLowerCase(), this.options.dragPrevention) != -1 // Prevent execution on defined elements
				|| (this.options.condition && !this.options.condition.apply(this.options.executor || this, [e, this.element])) //Prevent execution on condition
			) return true;
			
			var self = this;
			var initialize = function() {
				self._MP = { left: e.pageX, top: e.pageY }; // Store the click mouse position
				if ((jQuery.browser.msie) && (parseInt(jQuery.browser.version,10) == 6)) {
					if (self.element.className.indexOf("ui-draggable") != -1) {
						jitkSavedTarget = self.element;       
						jitkDragOK = true;
						jitkDragXoffset = e.clientX-parseInt(self.element.style.left);
						jitkDragYoffset = e.clientY-parseInt(self.element.style.top);
						document.onmousemove = JitkMoveHandler;
						document.onmouseup = JitkDragCleanup;
						return false;
					}
				} else {
					$(document).bind('mouseup.draggable', function() { return self.stop.apply(self, arguments); }).bind('mousemove.draggable', function() { return self.drag.apply(self, arguments); });
				}
			};

			if(this.options.delay) {
				if(this.timer) clearInterval(this.timer);
				this.timer = setTimeout(initialize, this.options.delay);
			} else {
				initialize();
			}
			
			return false;
			
		},
		stop: function(e) {
			var o = this.options;
			if(!this.initialized) return $(document).unbind('mouseup.draggable').unbind('mousemove.draggable');

			if(this.options.stop) this.options.stop.call(this.options.executor || this, e, this.element);
			$(document).unbind('mouseup.draggable').unbind('mousemove.draggable');
			this.initialized = false;
			return false;
		},
		drag: function(e) {
			var o = this.options;
			if ($.browser.msie && !e.button) return this.stop.apply(this, [e]); // IE mouseup check
			
			if(!this.initialized && (Math.abs(this._MP.left-e.pageX) >= o.distance || Math.abs(this._MP.top-e.pageY) >= o.distance)) {
				if(this.options.start) this.options.start.call(this.options.executor || this, e, this.element);
				this.initialized = true;
			} else {
				if(!this.initialized) return false;
			}

			if(o.drag) o.drag.call(this.options.executor || this, e, this.element);
			return false;
			
		}
	});
})(jQuery);
