﻿// ParcelViewer startup.js

// Global variables used throughout this javascript file
var map;
var reloadTimer = null;
var resizeMap = true;

var disableToolDocking = false;
var original_disableToolDocking = false;

var defaultSplitterLeft = 340;

//default values
var offsetHeight = 0;
var offsetWidth = 0;

/************************************************************************************/
//This is how the 2 functions below calculate the needed values under the hood
//Note that map is a global reference to the MapsDirect map control that is defined in the startup function
//var ddMapCenter = MapsDirect.Converter.mapUnitPointToDDPoint(map, map.get_extent().get_centerPoint());
//var scaleLevel = get_G_VE_ZoomLevelNearestScale(map.get_scale());
/************************************************************************************/
function showGoogle(mapType) {
    var url = getGoogleURL(map);

    if (!mapType) {
        mapType = "m";
    }
    url += "&t=" + mapType;

    window.open(url, "googleMaps");
};

function showBing(mapType) {
    var url = getBingURL(map);

    if (!mapType) {
        mapType = "r";
    }
    url += "&style=" + mapType;

    window.open(url, "bingMaps");
};

// function run at startup
function startUp() 
{          
    map = $find(mapId); 
	pushpinPanel = $find(pushpinPanelId);

	//SET THIS TO TRUE TO PREVENT DYNAMIC TILE GENERATION DURING SCROLLWHEEL ZOOMING	
    map.useSimpleZoom=true;
    
	map.add_requestTiles(showLoading);
	map.add_requestTilesComplete(hideLoading);
	// set the default click tool to the identify tool
	
	document.body.focus();
	
	if(typeof wvsAppCustomStartup == 'function') { 
        wvsAppCustomStartup(map); 
    } 
    
     // set window resize event handler
	window.onresize = AdjustMapSizeHandler; 
	
	AdjustMapSize(); 
	AdjustMapSize();  	
};


  

// handler for window resize
function AdjustMapSizeHandler(e) {
    window.clearTimeout(reloadTimer);
	reloadTimer = window.setTimeout("AdjustMapSize(true);",500);
};

var notWhitespace = /\S/;
function cleanWhitespace(node) {
  for (var x = 0; x < node.childNodes.length; x++) {
	var childNode = node.childNodes[x]
	if ((childNode.nodeType == 3)&&(!notWhitespace.test(childNode.nodeValue))) {
	// that is, if it's a whitespace text node
	  node.removeChild(node.childNodes[x])
	  x--
	}
	if (childNode.nodeType == 1) {
		// elements can have text child nodes of their own
	  cleanWhitespace(childNode)
	}
  }
};

// function for adjusting element sizes when brower is resized
function AdjustMapSize() {
    var screenBounds = getClientBounds();
    
    // status bar 
    var statusBar = $get("statusBar");
    var statusBounds = Sys.UI.DomElement.getBounds(statusBar);
    
    var tabs = $find(tabContainerId);
    var tabsBounds = Sys.UI.DomElement.getBounds($get(tabContainerId));

    
    var ajaxProgress = $get("ajaxProgress");
    ajaxProgress.style.width = screenBounds.width + "px";
    ajaxProgress.style.height = (screenBounds.height - parseInt(ajaxProgress.style.top)) + "px";
    $get("ajaxProgressTable").style.top = ((parseInt(ajaxProgress.style.height)/2) - 20) + "px";
    
    var mapArea = map.get_element();
    
    // move the slitter
    var splitter = $get("splitter");
    //splitter.style.left = (tabBounds.x + tabBounds.width) + "px";

    var splitterBounds = Sys.UI.DomElement.getBounds(splitter);

    //calculate effective tab area width
    MapD.Debug.trace("offsetWidth->" + offsetWidth);
    var tabAreaWidth = $get("tabArea").style.display=="none" ? 0 : parseInt($get("tabArea").style.width);
    
	// calc dimensions needed for map
    var mapWidth = screenBounds.width - tabAreaWidth - parseInt($get("splitter").style.width) - offsetWidth;
    
    MapD.Debug.trace("mapWidth: " + mapWidth);
    MapD.Debug.trace(screenBounds.width + " - " + tabAreaWidth + " - " + parseInt($get("splitter").style.width) + " - " + offsetWidth);
    
    if (isDefined("customOffsetHeight")) {
        if (customOffsetHeight) {
            offsetHeight = customOffsetHeight;
            MapD.Debug.trace("customOffsetHeight->" + offsetHeight);
        }
    } else {
        MapD.Debug.trace("NO customOffsetHeight: Defaulting to ->" + offsetHeight);
    }

    var mapHeight = screenBounds.height + screenBounds.scrollHeight - offsetHeight;
    MapD.Debug.trace("screenBounds.height (" + screenBounds.height + ") + screenBounds.scrollHeight (" + screenBounds.scrollHeight + ") - offsetHeight (" + offsetHeight + ") = mapHeight (" + mapHeight + ")");
	
    if (mapWidth < 5) mapWidth = 200;
    if (mapHeight < 400) mapHeight = 400;
    
	// set map size	 	
	map.resize(mapWidth, mapHeight, true);
    var mapBounds = Sys.UI.DomElement.getBounds(mapArea);

    //alert("map.resize() called for width:" + mapWidth + ",height:"+mapHeight + ".  mapBounds.width:" + mapBounds.width + ", mapBounds.height:" + mapBounds.height);
    
	var tabContent = $get("tabContent");
	var tabContentBounds = Sys.UI.DomElement.getBounds(tabContent);
        
    var taskResults = $find(taskResultsId);
    //taskResults.set_width(tabContentBounds.width);
    taskResults.set_width(tabAreaWidth)
    
    taskResults.set_height(mapHeight + statusBounds.height);

    for (var i = 0; i < tabs.get_tabs().length; i++) {
        //var idealHeight = screenBounds.height - tabsBounds.y - 40;
        //tabs.get_tabs()[i].get_element().style.height = (screenBounds.height - tabsBounds.y - 40) + "px";
        tabs.get_tabs()[i].get_element().style.height = mapHeight + statusBounds.height + 50 + "px"; //the 50 is the height of the toolmenu (~40) plus a 10 pixel buffer
    }
    
    //allow space for opacity slider
    var opacitySliderVerticalPixelsNeeded=40;
    
    var toc = $find(tocId);
    toc.set_width(taskResults.get_width());
    toc.set_height(taskResults.get_height()-opacitySliderVerticalPixelsNeeded);
    
    // splitter height    
    $get("splitter").style.height = (mapHeight + 14) + "px";
    		
	 var zoomSlider = $get(zoomSliderId);
	 var zoomZoomSliderBounds = Sys.UI.DomElement.getBounds(zoomSlider);	 
	 zoomSlider.style.position = "absolute";
	 zoomSlider.style.top = "20px";
	 zoomSlider.style.left = (mapWidth - 50) + "px";
	 
    var cacheButtons = $get(cachedButtonListId);
    var cacheButtonsBounds = Sys.UI.DomElement.getBounds(cacheButtons);
    cacheButtons.style.top = "20px";
    cacheButtons.style.left = (mapWidth - cacheButtonsBounds.width - zoomZoomSliderBounds.width - 40) + "px";
	 
	 var ovmap = $get("ovmap");
	 var ovmapBounds = Sys.UI.DomElement.getBounds(ovmap); 	 
	 ovmap.style.top = (mapHeight - parseInt(ovmap.style.height) - 2) + "px";
	 ovmap.style.left = (mapWidth - parseInt(ovmap.style.width) - 2) + "px";
	 
	 var ovmapButton = $get("ovmapButton");
	 ovmapButton.style.top = (mapHeight - parseInt(ovmapButton.style.height)) + "px";
	 ovmapButton.style.left = (mapWidth - parseInt(ovmapButton.style.width)) + "px";

	 map.recalculateOffsets();
	 
    return false;
};

function showLoading() {
    //alert('loading');
    $get("loadingImage").style.visibility = "visible";
};


function hideLoading() {
   $get("loadingImage").style.visibility = "hidden";
};

function Mod(X, Y) {
	return X - Math.floor(X / Y) * Y;
};

function HideOverviewMap(){
	var ovmap = $get("ovmap");
	var ovmapButton = $get("ovmapButton");
	if(ovmap.style.display == 'none'){
		ovmap.style.display = ''; 			
		ovmapButton.src = ovmapButton.src.replace('up', 'down');
	}else{
		ovmap.style.display = 'none';
		ovmapButton.src = ovmapButton.src.replace('down', 'up');
	}
	return false;
};

function toggleHelpPanel(link, panelId){
	var panel = $get(panelId);
	if(panel.style.display == "none"){
		link.innerHTML = "hide help";
		panel.style.display = "block";
	}else{
		link.innerHTML = "show help";
		panel.style.display = "none";
	}
	return false;
};

function SwitchTab(tabName){
	SetTab('TOC', (tabName == 'toc' ? true : false));
	SetTab('Results', (tabName == 'results' ? true : false));
    SetTab('DockedTools', (tabName == 'DockedTools' ? true : false));
    
    //handle docked tools area
	if (floatingPanelManager && floatingPanelManager.dockedPanelsCounter) {
    
        var panelCount = floatingPanelManager.dockedPanelsCounter['tabContentDockedTools'];
        if (!panelCount)
            panelCount=0;
            
        //alert("count:"+panelCount);
        var theTab = $get('tabDockedTools');
        var theTabLabel = $get('tabLinkDockedTools');
        theTabLabel.innerHTML="Active Tools";

        if (theTab) {
            if (panelCount<1) {
                theTab.className = 'tabHidden';
                theTabLabel.innerHTML="";
            } 
        }
    }

    map.recalculateOffsets();
};

function SetTab(tabName, isVisible){
    var tab = $get('tab' + tabName);
    if(tab != null){
	    var className = isVisible ? 'tabOn' : 'tabOff';
	    tab.className = className;
	    $get('tabLink' + tabName).className = className;
	    $get('tabContent' + tabName).style.display = isVisible ? 'block' : 'none';
	}
};

function printBubble(optionIndex, parcelId){
	$get(hdnBubbleParcelOptionIndexId).value = optionIndex;
	$get(hdnBubbleParcelIDId).value = parcelId;
	$get(btnPrintBubbleId).click();
	return false;
};

function GetParcelDetails(optionIndex, parcelId){
    showDetailsTab();
	$get(pageUpdateProgressId).style.display = '';
	$get(hdnBubbleParcelOptionIndexId).value = optionIndex;
	$get(hdnBubbleParcelIDId).value = parcelId;
	$get(btnGetParcelDetailsId).click();	
	return false;
};

function GetBufferedFeature(layerId, featureId, distance){
	SwitchTab("results"); 
	$get(hdnBufferLayerId).value = layerId;
	$get(hdnBufferFeatureId).value = featureId;
	$get(hdnBufferDistanceId).value = distance;
	$get(btnBufferSearchId).click();
	return false;
};   

function BeginRequestHandler(sender, args)        
{ 
	if(args.get_postBackElement().id == btnSearchId 
		|| args.get_postBackElement().id == gvResultsId)
	{      
		$get(pageUpdateProgressId).style.display = '';
	}
};
        
function EndRequestHandler(sender, args)        
{            
	var updateProgress1 = $get(pageUpdateProgressId);            
	updateProgress1.style.display = (updateProgress1.style.display == '') ? 'none' : '';        
};

function selectedItemChanged(sender, e)
{
	$get(hdnPanelResultsTableId).value = e.table;
	$get(hdnPanelResultsIDId).value = e.id;
	$get(btnGetPanelResultsId).click();
	e.cancel = true;
};

var ie7warningIssued = false;
function displayExcel(url){	
	if(url.substring(0, 5) == "ERROR") {
		alert(url);
	}else{
	    if (Sys.Browser.agent == Sys.Browser.InternetExplorer && Sys.Browser.version >= 7 && !ie7warningIssued) {
	        //ie7warningIssued=true;
	        alert("You appear to be using Internet Explorer 7+ which, by default, will block Excel spreadsheet files from opening.  Please press your CTRL key then close this alert box.  Do not release the CTRL key until you are presented with the option to Open or Save the file.");
	    } 
		var tmp = window.open(url, 'excel', '', '');
		//window.setTimeout(
		//if (!tmp) alert("Your browser appears to be equipped with a popup blocker.  If you are using Internet Explorer 7, please retry the link while holding the CTRL key down (do not release the key until the document has opened)");
	}
};

function displayPDF(url){	
	if(url.substring(0, 5) == "ERROR"){
		alert(url);
	}else{
		window.open(url, 'pdf', '', '');
	}
};


function hideTabs(){
	// Hide the results and details tab. This must be done client side or the gridview breaks			
	var tabs = $find(tabContainerId);
	
	tabs.get_tabs()[1].set_enabled(false);  
	if(tabs.get_activeTabIndex() == 0){          
		tabs.get_tabs()[2].set_enabled(false);
	}			 
	tabs.add_activeTabChanged(tabChanged);
    Sys.Application.remove_load(hideTabs);
    
};

function showMapTab() {
    $find(tabContainerId).set_activeTabIndex(3);
    window.setTimeout("AdjustMapSize(true);", 500);
	return false;
}

function showSearchTab(){
    var tabs = $find(tabContainerId);
    // set the results tab to enabled or the gridview will allow paging/sorting. Must be a issue between the gridview and tab control
    tabs.get_tabs()[1].set_enabled(true);
    tabs.set_activeTabIndex(1); 
               
};

 function showDetailsTab(){
    var tabs = $find(tabContainerId);
    // set the results tab to enabled or the gridview will allow paging/sorting. Must be a issue between the gridview and tab control
    //tabs.get_tabs()[1].set_enabled(true);
    tabs.get_tabs()[2].set_enabled(true);
    tabs.set_activeTabIndex(2);
               
};

var basicIdentify = null;
function tabChanged(sender, e){
	var tabs = $find(tabContainerId);
	if(tabs.get_activeTabIndex() == 3) {
	    reloadTimer = window.setTimeout("AdjustMapSize();",200);
	    
	    if (basicIdentify  != null) {
	         $find(basicIdentifyId).submit(basicIdentify.x, basicIdentify.y, basicIdentify.layer);
	        basicIdentify = null;
	    }
	}else{
		floatingPanelManager.closeAll();
	}
};

function highlightParcel(geometry, extent, id){
	var map = $find(mapId);
	var feature = new MapsDirect.Vector.Feature();
    feature.geometry = MapsDirect.Geometry.Packer.unpack(map, "polygon", geometry); 
    feature.geometry.id = "Parcel_" + id;
    feature.extent = extent;
    feature.extent.expand(25);
    map.graphicsLayers["tools"].addItem(feature, true);
}

function SetSearchInput(ddl, span) {
    var box = document.getElementById(span);
    if(box){
	    if(ddl.options[ddl.selectedIndex].value == 'Between'){
		    box.style.display = 'block';
	    }else{
		    box.style.display = 'none';
	    }
    } 
};

function ClearSearchInput(){
	var panel = document.getElementById(phSearchControlsId);
	var elements = panel.getElementsByTagName('input');
	for(i=0; i<elements.length; i++)
	{
		elm = elements[i];
		if (elm.type == "text")
		{
			elm.value = '';
		}
	}
	elements = panel.getElementsByTagName('select');
	for(i=0; i<elements.length; i++ )
	{	
		elements[i].selectedIndex = 0;
		elements[i].click();
	}		
	return false;
};
		
function createEmailLink(name, domain, suffix){
	var u_a="mail"
	var u_b="to:"
	var u_c="@"
	domain += "." + suffix;
	document.write('<a href="'+ u_a + u_b + name + u_c + domain + '">' + name + u_c + domain + '</a>');
};

function enableLogin(cb){
	for( var i=0; i<document.forms[0].elements.length; i++ ){
		eName = document.forms[0].elements[i].name;		
	    if(document.forms[0].elements[i].id.indexOf('btnEnterSite') > -1)
	    {
			document.forms[0].elements[i].disabled  = !cb.checked;
			return;
		}
	}
};

function bufferSearchClicked(){
    SwitchTab('results');
    $find(taskResultsId).showProgressControl();
};

function GridViewMouseOver(row){
    row.oldColor = row.style.backgroundColor;
    row.style.backgroundColor = "#ffffcc";
};

function GridViewMouseOut(row){
    row.style.backgroundColor = row.oldColor;
};


//splitter stuff
function toggleTabArea(){
	var tabArea = $get("tabArea");
	var splitter = $get("splitter");
	var splitterButton = $get("splitterButton");
	
	if(tabArea.style.display != "none"){
	    tabAreaExpandedWidth = tabArea.style.width;
		tabArea.style.display = "none";
		
		splitterButton.style.display = "";
		splitterExpandedLeft = splitter.style.left;
		splitterExpandedWidth = splitter.style.width;
		splitterExpandedCursor = splitter.style.cursor;
		splitterExpandedOnmousedown = splitter.onmousedown;
		splitter.style.left = "0px";
		splitter.style.width = "23px";
		splitter.style.cursor = "default";
		splitter.onmousedown = null;
		
		original_disableToolDocking = disableToolDocking;
		disableToolDocking = true;
	} else {
		splitterButton.style.display = "none";
		splitter.style.width = "5px";
		//splitter.style.width = splitterExpandedWidth;
		splitter.style.left = splitterExpandedLeft;
		splitter.style.cursor = splitterExpandedCursor;
		splitter.onmousedown = splitterExpandedOnmousedown;
		
	    tabArea.style.width = tabAreaExpandedWidth;
		tabArea.style.display = "";
		
		disableToolDocking = original_disableToolDocking;
	}
	AdjustMapSize();
};

var splitterHalfWidth = 0;
var splitterZIndex;
var splitter;
var tabArea;
var splitterEventCounter;

//TODO: this should be calculated
var tabContainerPadding=8;

function splitterMouseDown()
{
    splitterEventCounter=0;
	splitter = $get("splitter");
	splitterHalfWidth  = parseInt(splitter.style.width) / 2;
	splitter.style.backgroundColor = "#333333";
	splitterZIndex = splitter.style.zIndex;
	splitter.style.zIndex = 9999999;
	tabArea = $get("tabArea"); 
	
	document.onmousemove = splitterMouseMove;
	document.onmouseup = splitterMouseUp;
	
	//prevent text selection
	disableSelection(document.body);
	
	
	return false;
};

function splitterMouseMove(e)
{
    splitterEventCounter++;
    if (splitterEventCounter%3!=0)
        return;
        
	if(!e)	e = window.event;
	var x = getMouseX(e);

    
    //MapD.Debug.trace("splitterMouseMove: x=" + x);
	if(x > 200 && x < 800) {
	
		splitter.style.left = (x - splitterHalfWidth - tabContainerPadding) + "px";
		tabArea.style.width = splitter.style.left;
		var width = parseInt(splitter.style.left);
        $find(taskResultsId).set_width(width);
        $find(tocId).set_width(width);
    }
	return false;
};


function splitterMouseUp(e)
{
	if(!e)	e = window.event;
	var x = getMouseX(e);
	splitter.style.backgroundColor = "";
	splitter.style.zIndex = splitterZIndex;
	
	var setSplitterLeftTo = (x - splitterHalfWidth - tabContainerPadding);
	splitter.style.left = setSplitterLeftTo>0?setSplitterLeftTo:0+ "px";
	
	document.onmousemove = null;
	document.onmouseup = null;
	
	// move the tab area
    var tabArea = $get("tabArea"); 
    var width = parseInt(splitter.style.left);
    tabArea.style.width = splitter.style.left;
    $find(taskResultsId).set_width(width);
    $find(tocId).set_width(width);
    
    AdjustMapSize();
    
    //TODO: get this into a control
    if (googleStreetViewControl) {
        if (googleStreetViewControl.GStreetviewPanorama) {
            //alert("checking size for GSV");
            var tmp = window.setTimeout("googleStreetViewControl.GStreetviewPanorama.checkResize();", 1);
        }
        if (googleStreetViewControl.GMap) {
            //alert("checking size for GMap");
            var tmp = window.setTimeout("googleStreetViewControl.GMap.checkResize();", 1);
            //googleStreetViewControl.GMap.checkResize();
        }
    }

	//enable text selection
	enableSelection(document.body);

	return false;
};


function setSplitterWidth(width) {

    //alert("setSplitterWidth:"+width);
    // move the tab area
    var splitter = $get("splitter");
    var tabArea = $get("tabArea"); 
    
    tabArea.style.width = width + "px";
    splitter.style.left = width + "px";
    
    //alert("splitter.style.left:"+splitter.style.left);
    
    $find(taskResultsId).set_width(width);
    $find(tocId).set_width(width);
    
    AdjustMapSize();
    
    //TODO: get this into a control
    if (googleStreetViewControl) {
        if (googleStreetViewControl.GStreetviewPanorama) {
            //alert("checking size for GSV");
            googleStreetViewControl.GStreetviewPanorama.checkResize();
        }
        if (googleStreetViewControl.GMap) {
            //alert("checking size for GMap");
            googleStreetViewControl.GMap.checkResize();
        }
    }
        
	return false;
};

function isDefined(variable){ 
	return (typeof(window[variable]) != "undefined");
};

function switchSearchCriteria(listBoxId){
	var listBox = document.getElementById(listBoxId);
	var selectedValue = listBox[listBox.selectedIndex].value;					
	var div = null;	
	for(var i = 0; i < listBox.options.length; i++)
	{	
		div = document.getElementById(listBox[i].value);
		
		if (div)
		    div.style.display = 'none';
	}			
	div = document.getElementById(selectedValue);
	
	if (div)
	    div.style.display = 'block';
	return false;	
};

function dockedPanelOpened(key) {
    if (floatingPanelManager && floatingPanelManager.dockedPanelsCounter) {
        //alert( key + " opened");
        var panelCount = floatingPanelManager.dockedPanelsCounter['tabContentDockedTools'];

        if (panelCount) {
            //alert("count:"+panelCount);
            
            var theTab = $get('tabLinkDockedTools');
            
            if (theTab) {
                theTab.innerHTML="Active Tools";
                SwitchTab('DockedTools');
                
                if (key=="profile") {
                    setSplitterWidth(430);
                } else {
                
                    //May not want to keep this
                    //it will reset the width of the left panel back to a default value if it has
                    //deviated by more than 10 pixels from the initial setting
                    var splitter = $get("splitter");
                    var width = parseInt(splitter.style.left);
                    
                    if (Math.abs(width - defaultSplitterLeft) > 10) {
                        setSplitterWidth(defaultSplitterLeft);
                    }
                }
            } else {
                //alert("tabLinkDockedTools not found");
            }
        }
    }
    
    if (key=="google" && isDefined("googleStreetViewControl")) {
        setSplitterWidth(450);
        if (googleStreetViewControl.GStreetviewPanorama)
            googleStreetViewControl.GStreetviewPanorama.checkResize();
        if (googleStreetViewControl.GMap)
            googleStreetViewControl.GMap.checkResize();
    }
    
    if (key=="ve") {
        setSplitterWidth(450);
    }
};

function dockedPanelClosed() {
    //alert("close");
    if (floatingPanelManager && floatingPanelManager.dockedPanelsCounter) {
    
        var panelCount = floatingPanelManager.dockedPanelsCounter['tabContentDockedTools'];

        if (panelCount!=null) {
            //alert("count:"+panelCount);
            var theTab = $get('tabDockedTools');
            
            if (theTab) {
                if (panelCount<1) {
                    
                    //May not want to keep this
                    //it will reset the width of the left panel back to a default value if it has
                    //deviated by more than 10 pixels from the initial setting
                    var splitter = $get("splitter");
                    var width = parseInt(splitter.style.left);
                    
                    if (Math.abs(width - defaultSplitterLeft) > 10) {
                        setSplitterWidth(defaultSplitterLeft);
                    }
                    
                    SwitchTab('toc');
                }
            }
        }
    }
};