﻿// General functions used in the application.
var baGoHomeCallback = "";

//***********************
//Get elementById
//***********************
function getEl(id)
{
    var el = document.getElementById(id);
    return el;
}
//***********************
//Show an element
//***********************
function showEl(id)
{
	var el = returnEl(id);
	if (el) el.style.display = "";
}
//***********************
// Hide an element
//***********************
function hideEl(id)
{
	var el = returnEl(id);
	if (el) el.style.display = "none";
}
//***********************
// Disable form elements
//***********************
function disableEl(id)
{
	var el = returnEl(id);
	if (el) el.disabled = "disabled";
}
//***********************
// Enable form elements
//***********************
function enableEl(id)
{
	var el = returnEl(id);
	if (el) el.disabled = "";
}

//***********************
// Helper fuinction  to determine IF
// the param is an el or id.
//***********************
function returnEl(id)
{
	var paramType = typeof(id);
	if (paramType == 'string')
	{
	    var el = getEl(id);
		return el;
	}
	else
	{
		var el = id;
		return el;
	}
}
//***********************
//Toggle an element
//***********************
function toggleEl(el)
{
    if (el)
    {
        if (el.style.display == "none")
        {
            showEl(el)
        }
        else
        {
            hideEl(el)
        }
    }
}

//*************************************************************
// Remove Special Characters from string. //Returns new sting
//*************************************************************
function cleanString(string) 
{
    var invalidChar = /\$|,|@|#|~|`|\%|\*|\^|\&|\(|\)|\+|\=|\[|\-|\_|\]|\[|\}|\{|\;|\:|\'|\"|\<|\>|\?|\||\\|\!|\$|\./g;
    // remove special characters like "$" and "," etc...
    return string.replace(invalidChar, "");
}

//*************************************************************
// Creates and shows a busy indicator along with a description
// You must create a placeholder first to tell the function where
// the indicator should go.
// The placeholder ID is passed to the function (contentElementId)
//*************************************************************
function showBusyIndicator(contentElementId, description)
{
    //get the element assigned to hold the indicator
    el = getEl(contentElementId);

    var elID = contentElementId+'_busyIndicator';
    var descriptionID = elID + "_description";
    
    //Build HTML contents if it does not exists
    if(getEl(elID) == undefined)
    {
        var html ='<span id="'+elID+'" style="display:none;"> <img src="../images/callbackActivityIndicator.gif"> <span id="'+descriptionID+'">&nbsp;&nbsp;'+description+'</span></span>';
        el.innerHTML = html;
    }

    //get the busy indicator element (created above if it did not already exists)
    var busyIndicator = getEl(elID);
    
    //set a new description
    getEl(descriptionID).innerHTML = description;
    
    //show it!
    showEl(busyIndicator);  
}

//*************************************************************
//This will hide a created busy indicator
// Pass in the placeholders id (id)
//*************************************************************
function hideBusyIndicator(id)
{
    var busyId = id + "_busyIndicator";
    hideEl(getEl(busyId));
}

//*************************************************************
//Create a Div on the page dynamically
//*************************************************************
function createComplexDiv(id,top,left,width,height) {

    //fill in blank spaces in id
    id =  id.replace(/ /g, "");

    if (width != "") { width += "px"; }
    if (height != "") { height += "px"; }
    if (top != "") { top += "px"; }
    if (left != "") { left += "px"; }
   
	var newDiv = document.createElement(id);
	newDiv.id = id;
	newDiv.style.position = "absolute";
	newDiv.style.visibility = "visible";
	newDiv.style.width = width; 
	newDiv.style.height =  height;
	newDiv.style.top = top;
	newDiv.style.left = left;
	newDiv.style.zIndex = 1000;
	
	document.body.appendChild(newDiv);
	
	return newDiv;
}

//*************************************************************
// Display a message from JavaScript in a standard way
//   ** This function intended to be called from JavaScipt only
//   ** From C# code, use the library method:
//        Bergmann.ArcGISServer.CallbackUtil.AddMessageToMapCallback
//*************************************************************
function displayMessageJS(title, text)
{
    displayMessage(title, text, -1);
}

//*************************************************************
// Display a message to the user in a standard way
//*************************************************************
function displayMessage(title, text, minWidth)
{
    if (minWidth > 0)
    {
        // Note: width and MaxWidth do not work as expected (bug?) - only way to get
        // a dialog wider than about 600 pixels is to set minWidth.
//        Ext.Msg.show({
//            title: title,
//            msg: text,
//            buttons: Ext.MessageBox.OK,
//            minWidth: minWidth
//        });
        alert(text);
    }
    else
    {
        // let dialog size itself
//        Ext.Msg.show({
//            title: title,
//            msg: text,
//            buttons: Ext.MessageBox.OK
//        });
    alert(text);
    }
}

//*************************************************************
// Callback handlers for user clicking "Home" link on WebApp page
//   ** mimicks CloseOut() and CloseOutResponse() functions in WebMapApp.js
//*************************************************************
function goHome() {
	var argument = "ControlID=Map1&ControlType=Map&EventArg=GoToHomePage";
	var	map = $find('Map1');
	var context = map.get_id();  // map.controlName;	<- property not valid at 9.3
	eval(baGoHomeCallback);
}

function goHomeResponse(response, context) {
    // transfer to home page
    document.location = response; 
}

//*************************************************************
// Programatically set the active tool on a toolbar
//*************************************************************
function setToolBarTool_92(toolbarName, toolbarItemName)
{
// from 92
    // based on function ToolbarMouseDown in display_toolbar.js (in /aspnet_client/ESRI/WebADF/JavaScript)
	if ((toolbarName == "") || (toolbarItemName == "")) return;
	var f = document.forms[docFormID];
	var imageTag = toolbarName + toolbarItemName + "Image";
	var cell = toolbarName + toolbarItemName;
	var toolbar = Toolbars[toolbarName];
	if (toolbar == null) return;
	if (toolbar.items[toolbarItemName].disabled)
        return;

    //change toolbar's selected tool
    f.elements[toolbar.currentToolField].value = toolbarItemName;
    //clientAction for each buddy control
    var clientAction =  toolbar.items[toolbarItemName].clientAction;
    if (clientAction != null)
    {
	    var clientActions = "";
      if (!toolbar.items[toolbarItemName].isClientActionCustom)
      {
		    var buddies = toolbar.buddyControls;
		    if (buddies != null)
		    {
			    for (var i = 0; i < buddies.length; i++)
			    {
				    var modeField = f.elements[buddies[i] + "_mode"];
				    if (modeField != null)
				      modeField.value = toolbarItemName;
				    var cursor = toolbar.items[toolbarItemName].cursor;
				    if (cursor != null)
				      clientActions = clientActions + clientAction + " ( '" + buddies[i] + "' , '" + toolbarItemName + "', " + toolbar.items[toolbarItemName].showLoading + ",'" + cursor + "'); ";
				    else
				      clientActions = clientActions + clientAction + " ( '" + buddies[i] + "' , '" + toolbarItemName + "', " + toolbar.items[toolbarItemName].showLoading + "); ";
			    }
		    }
	    }
	    else
	    {
		    clientActions = clientAction;
	    }
        if (toolbar.items[toolbarItemName].preExecFunction != null)
            clientActions += toolbar.items[toolbarItemName].preExecFunction;
            
	    var clientActionFunction = new Function(clientActions);
	    clientActionFunction.call(null);
	    //select this tool and unselect others
	    Toolbars[toolbarName].selectTool();
	    Toolbars[toolbarName].refreshGroup();
    }	
}
function setToolBarTool(toolbarName, toolbarItemName)
{
// From ags93dpm
  if ((toolbarName == "") || (toolbarItemName == "")) return;
  var f = document.forms[docFormID];
  var imageTag = toolbarName + toolbarItemName + "Image";
  var cell = toolbarName + toolbarItemName;
  var toolbar = Toolbars[toolbarName];
  if (toolbar == null) return;
//alert('toolbar.items[toolbarItemName].disabled: ' + toolbar.items[toolbarItemName].disabled);
  if (toolbar.items[toolbarItemName].disabled) { return; }
        	
        		
    //change toolbar's selected tool
    f.elements[toolbar.currentToolField].value = toolbarItemName;
    //clientAction for each buddy control
    var clientAction =  toolbar.items[toolbarItemName].clientAction;
    if (clientAction != null) {
      var clientActions = "";
        if (!toolbar.items[toolbarItemName].isClientActionCustom) {
        var buddies = toolbar.buddyControls;
        if (buddies != null) {
	        for (var i = 0; i < buddies.length; i++)
	        {
		        var modeField = f.elements[buddies[i] + "_mode"];
		        if (modeField != null)
			        modeField.value = toolbarItemName;
		        var cursor = toolbar.items[toolbarItemName].cursor;
		        if (cursor != null)
			        clientActions = clientActions + clientAction + " ( '" + buddies[i] + "' , '" + toolbarItemName + "', " + toolbar.items[toolbarItemName].showLoading + ",'" + cursor + "'); ";
		        else
			        clientActions = clientActions + clientAction + " ( '" + buddies[i] + "' , '" + toolbarItemName + "', " + toolbar.items[toolbarItemName].showLoading + "); ";
	        }
        }
      }
      else
      {
        clientActions = clientAction;
      }
      //fire onSelect handler if set... fires before clientActions
      var tbObject = $find(toolbarName);
      if (tbObject!=null) {
                var handler = tbObject.get_events().getHandler('onToolSelected');
                if(handler) 
                    handler(tbObject,{"name": toolbarItemName, "tool": toolbar.items[toolbarItemName]});
      }
      if (toolbar.items[toolbarItemName].preExecFunction != null)
        clientActions += toolbar.items[toolbarItemName].preExecFunction;
    
      var clientActionFunction = new Function(clientActions);
      clientActionFunction.call(null);
      //select this tool and unselect others
      Toolbars[toolbarName].selectTool();
      Toolbars[toolbarName].refreshGroup();
    }
}

//*************************************************************
// Change the cursor to the type indicated
//*************************************************************
function changeCursorTo(newCursor) 
{
   map = $find('Map1');
   map.divObject.style.cursor = newCursor;
}

//*************************************************************
// Functions (15) to change cursor explicitly to standard types
//*************************************************************
function changeCursorToDefault() 
{
   changeCursorTo("default");
}

function changeCursorToPointer() 
{
   changeCursorTo("pointer");
}

function changeCursorToCrosshair() 
{
   changeCursorTo("crosshair");
}

function changeCursorToTextInsert() 
{
   changeCursorTo("text");
}

function changeCursorToWait() 
{
   changeCursorTo("wait");
}

function changeCursorToHelp() 
{
   changeCursorTo("help");
}

function changeCursorToMove() 
{
   changeCursorTo("move");
}

function changeCursorToEastResize() 
{
   changeCursorTo("e-resize");
}

function changeCursorToNortheastResize() 
{
   changeCursorTo("ne-resize");
}

function changeCursorToNorthwestResize() 
{
   changeCursorTo("nw-resize");
}

function changeCursorToNorthResize() 
{
   changeCursorTo("n-resize");
}

function changeCursorToSoutheastResize() 
{
   changeCursorTo("se-resize");
}

function changeCursorToSouthwestResize() 
{
   changeCursorTo("sw-resize");
}

function changeCursorToSouthResize() 
{
   changeCursorTo("s-resize");
}

function changeCursorToWestResize() 
{
  changeCursorTo("w-resize");
}

//*************************************
// Opens a new window for the given url
//*************************************
function openUrlInNewWindow(url)
{
    window.open(url);
}

//*************************************************************
// truncates the string to the length passed and adds ellipses
//*************************************************************
function truncateString(description,length)
{
	if (description.length > length)
	{
		description = description.substr(0,length) + "...";
	}
	return description;
}

//****************************************************
// Check for an Enter key press
//****************************************************
function checkEnter(e, buttonId)
{ 
    if (!e) var e = window.event;
    var unicode = e.charCode ? e.charCode : e.keyCode;
    if (unicode == 13) getEl(buttonId).click();
}

//****************************************************
// Checks that browser is internet explorer before 
// opening the given URL in a new window.
//****************************************************
function openUrlInNewWindowIEOnly(url)
{
    if (document.all)
    {
        openUrlInNewWindow(url);
    }
    else
    {
        displayMessageJS("Alert", "This functionality is only available in Internet Explorer");
    }
}
//---------------------------------------------------------
// Opens URL in new window allowing use of title - not
// on title bar -- as name of window -- supports Pictometry
//---------------------------------------------------------
function openUrlInNewWindowTitle(url, title)
{
    var popUpWindow = window.open(url, title);
    return isPopupBlockedAndAlert(popUpWindow);
}
//---------------------------------------------------------
// Opens URL in new Internet Explorer window only, 
// allowing use of title - not on title bar -- as name 
// of window -- supports Pictometry
//---------------------------------------------------------
function openUrlInNewWindowIEOnlyTitle(url, title)
{
    if (document.all)
    {
        openUrlInNewWindowTitle(url, title);
    }
    else
    {
        displayMessageJS("Alert", "This functionality is only available in Internet Explorer");
    }
}
/****************************************************************************
* The following functions extend the string functionality to allow for trim,
* left trim, and right trim.  Usage is myString.trim()
*****************************************************************************/
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}

    //*****************************************************
    // Debug Log
    //*****************************************************
    function log(message) 
    {
        if (!log.window_ || log.window_.closed) 
        {
            var win = window.open("", null, "width=400, height=200," +
                              "scrollbars=yes, resizable=yes, status=no," +
                              "location=no, menubar=no, toolbar=no");
            if (!win) return;
            var doc = win.document;
            doc.write("<html><head><title>Debug Log</title></head>" +
                      "<body></body></html>");
            doc.close();
            log.window_ = win;
        }
        var logLine = log.window_.document.createElement("div");
        logLine.appendChild(log.window_.document.createTextNode(message));
        log.window_.document.body.appendChild(logLine);
    }

