var newWindow;

function layerVisibility(id, status) {
	document.getElementById(id).style.visibility = status;
};

function layerDisplay(id, status) {
	document.getElementById(id).style.display = status;
};

function changeImg(obj) {
	obj.src = eval(obj.id + '_a.src');
};

function changeImgBack(obj) {
	obj.src = eval(obj.id + '_n.src');
};

function changeClass(obj, className) {
	obj.oldClassName = obj.className;
	obj.className = className;
};

function changeClassBack(obj) {
	obj.className = obj.oldClassName;
};

function popUpWindow(url, name, width) {
	var winX;
	var winY;
	var winLeftPos;
	var winTopPos;
	if (!width) {
		if (browser == "msie") {
			winX = screen.availwidth - 20;
			winY = screen.availheight - 50;
		} else {
			winX = window.innerWidth - 20;
			winY = window.innerHeight - 50;
		}
		winLeftPos = 0;
		winTopPos = 0;
	} else {
		winX = width;
		winY = (window.screen.height /3) *2;
		winLeftPos = (window.screen.width - winX)/2;
		winTopPos = (window.screen.height - winY)/2;
	}
	newWindow = eval("window.open(url, name, 'top=" + winTopPos + ", left=" + winLeftPos + ", width=" + winX + ", height=" + winY + ", resizable=yes, status=yes, scrollbars=yes')");
	newWindow.focus();
};



/*******************************
      WRAPPERS & UTILITIES
*******************************/
/**
 * Gets a value from the QueryString
 *
 * @param key The name of the variable to be retrieved
 * @param default_ Optional - a value to use if the variable is not found
 * @return String - the variable value of default value
 * @author http://www.bloggingdeveloper.com/post/JavaScript-QueryString-ParseGet-QueryString-with-Client-Side-JavaScript.aspx
*/
function getQuerystring(key, default_)
{
  if (default_==null) default_="";
  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
  var qs = regex.exec(window.location.href);
  if(qs == null)
    return default_;
  else
    return qs[1];
}

/**
 * Enables an alternate stylesheet, if boolHaveSpecialAccess is true. Otherwise disables it.
 *
 * @param strSpecialStylesheetTitle The title attribute of the special stylesheet
 * @param boolHaveSpecialAccess Boolean value defining whether access is granted to the special stylesheet
 *
 * @author BAS - based on http://www.alistapart.com/stories/alternate/
*/
function enableSpecialStyleSheet(strSpecialStylesheetTitle, boolHaveSpecialAccess) {
   var i, a, main;


   if(boolHaveSpecialAccess) {

	for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {

		if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
			a.disabled = false;
		
			if(a.getAttribute("title") == strSpecialStylesheetTitle) a.disabled = false;
		}
	}
    } else {

	for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
		if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
			a.disabled = false;
			if(a.getAttribute("title") == strSpecialStylesheetTitle) a.disabled = true;
		}
	}
    }

}


/**
 * Wrapper for getEById allowing multiple args.
 * @author Dustin Diaz (?)
*/
function $() {
	var elements = new Array();
	for (var i = 0; i < arguments.length; i++) {
		var element = arguments[i];
		if (typeof element == 'string')
			element = document.getElementById(element);
		if (arguments.length == 1)
			return element;
		elements.push(element);
	}
	return elements;
};


/**
 * Get all elements with the given class.
 * @author 3rd Party
*/
function getElementsByClass(searchClass, node, tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
};


/**
 * Get all elements of the given input tag type with the given value.
 * @author 3rd Party
*/
function getElementsByTagTypeValue(strTag, strType, strValue) {
    var arrElements = new Array();

    var inputElms = document.getElementsByTagName(strTag);
    var intCount = inputElms.length;

    for(i=0, intArrCount = 0; i<intCount; i++) {
        //-- Exclude all but elements of this type if desired
        if(strType != null && inputElms[i].type == strType) {
            //-- Exclude all but elements with this value if desired
            if(strValue != null && inputElms[i].value == strValue) {
                arrElements[intArrCount] = inputElms[i];
            }
        }
    }

    return arrElements;
};

/**
 * Toggle checkboxes of a certain class on or off.
*/
function ToggleCheckboxes(classname, node, check) {
	var checks = getElementsByClass(classname, node, 'input');
	for(var i = 0; i < checks.length; i++) {
		checks[i].checked = check;
	}
};

/*function ToggleCheckboxes(idname, check)  {
	if (document.all) { //IS IE 4 or 5 (or 6 beta)

		//alert('ie');

		if (document.all(idname).length != null) {

			var count = 0
			var el = document.all.item(idname,count);
			while (el != null) {
				el.checked = check;
				count++;
				el = document.all.item(idname, count);
			}


		} else {

			//alert("length == null");
			var el = document.all.item(idname,count);
			el.checked = check;
		}


	} else {

		//alert('not ie, number of input tags: ' + document.getElementsByTagName('input').length);


		var inputcoll = document.getElementsByTagName('input');
		for(var i = 0; i < inputcoll.length; i++) {
			if(inputcoll[i].type == 'checkbox' && inputcoll[i].id == idname) {
				inputcoll[i].checked = check;
			}
		}
	}
};*/

/**
 * Dreamweaver generated function for opening new windows.
 * V2.0
*/
function MM_openBrWindow(theURL, winName, features) {
    if(theURL.substr(theURL.length - 7, 7) == "&wname=") {
        //features = features + "&wname=" + window.name;
        theURL = theURL + window.name;
    }
    window.open(theURL, winName, features);
};

/**
 * Simply utility to check if the mouse button click that generated the event was the left one.
 * @return boolean
 * @See http://www.quirksmode.org/js/events_properties.html#button
*/
function isLeftClick(objEvent) {
    if(typeof objEvent.button == "number") {
        //-- W3C standard
        if(objEvent.button == 0)
            return true;

        //-- Most browsers
        if(objEvent.button == 1)
            return true;

    } else {
    //-- Old browsers
        if(objEvent.which == 1)
            return true;
    }
    return false;
};


/**
 * A little utility function to get mouse coordinates of the cursor *as they pertain* to the element they're over (not the page!)
 * Sets them on the global variables intMouseX & intMouseY
*/
function getMouseCoordinates(objEvent) {
    if(navigator.userAgent.indexOf('MSIE') == -1 && navigator.userAgent.indexOf('Opera') == -1) {
        intMouseX = objEvent.layerX;
        intMouseY = objEvent.layerY;
    } else {
        //-- Opera & IE
        intMouseX = objEvent.offsetX;
        intMouseY = objEvent.offsetY;
    }
};

/**
 * Calculate the distance between two sets of coordinates.
 * @return int
*/
function getDistance(intX1, intY1, intX2, intY2) {
    return Math.sqrt(Math.pow((intX1 - intX2), 2) + Math.pow((intY1 - intY2), 2))
};

/**
 * Formats the number with commas as seperators.
*/
function formatNumber(nStr) {
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
};

/**
 * Utility function for working out the position of an element on the screen based on all of its parent elements.
 * @return array [intCurLeft, intCurTop]
*/
function findPos(objElm) {
    var intCurLeft = intCurTop = 0;
    if(objElm.offsetParent) {
        intCurLeft = objElm.offsetLeft
        intCurTop = objElm.offsetTop
        while(objElm = objElm.offsetParent) {
            intCurLeft += objElm.offsetLeft
            intCurTop += objElm.offsetTop
        }
    }
    return [intCurLeft, intCurTop];
};

/**
 * Wipes the innerHTML property of the given element.
*/
function clearElement(strID) {
	var objElement = $(strID);
	if(typeof objElement != "undefined" && typeof objElement.innerHTML != "undefined")
	   objElement.innerHTML = '';
};

/**
 * Toggle the css display value of an element to show or hide it. Compatable with ancient browsers.
*/
function showhide(layer_ref) {
    var hza;
    var state;
    var elem;

    if(document.layers) { //IS NETSCAPE 4 or below
        state = document.layers[layer_ref].display;
    }

    if(document.getElementById) {
        hza = document.getElementById(layer_ref);
        state = hza.style.display;
    } else {
        if(document.all) { //IS IE 4 or 5 (or 6 beta)
            elem = document.all(layer_ref);
            if(elem != null) state = elem.style.display;
        }
    }

    if(state == 'block') {
        state = 'none';
    } else {
        state = 'block';
    }

    if(document.layers) { //IS NETSCAPE 4 or below
        document.layers[layer_ref].display = state;
    }

    if(document.getElementById) {
        hza = document.getElementById(layer_ref);
        hza.style.display = state;
    } else {
        if(document.all) { //IS IE 4 or 5 (or 6 beta)
            if(elem != null) elem.style.display = state;
        }
    }
};

/**
 * Get the size of the window in pixels.
 *
 * @author Khan
*/
function getWindowSize() {
    var intWidth = 0, intHeight = 0;

    if(typeof(window.innerWidth) == 'number') {
        //-- Non-IE
        intWidth = window.innerWidth;
        intHeight = window.innerHeight;

    } else if(document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
        //-- IE 6+ in 'standards compliant mode'
        intWidth = document.documentElement.clientWidth;
        intHeight = document.documentElement.clientHeight;

    } else if(document.body && (document.body.clientWidth || document.body.clientHeight)) {
        //-- IE 4 compatible
        intWidth = document.body.clientWidth;
        intHeight = document.body.clientHeight;
    }

		return new Array(intWidth, intHeight);
}



/******************************
    Ajax
@todo Integrate with AJAXInteraction() so it is automated?
******************************/
/**
 * Displays the "Loading..." image indicating an Ajax request is in progress.
 *
 * @todo Update mapscripts.js > changeCursor()
*/
function start_AjaxIndicator() {
  var objIndicator = document.getElementById("ajaxprogress");
  var objMapOverlay = document.getElementById("MapOverlay");

	var arrPosition = findPos(objMapOverlay);
  var intTop = arrPosition[1] + (parseInt(objMapOverlay.style.height) / 2) - 50;
  var intLeft = arrPosition[0] + (parseInt(objMapOverlay.style.width) / 2) - 50;

  objIndicator.style.top = intTop + "px";
  objIndicator.style.left = intLeft + "px";

  objIndicator.style.display = "block";
  document.body.style.cursor = "progress";
};


/**
 * Hides the "Loading..." image indicating an Ajax request is in progress.
 *
 * @todo Update mapscripts.js > processAJAXResults()
*/
function end_AjaxIndicator() {
  $("ajaxprogress").style.display = "none";
  document.body.style.cursor = 'default';
};


/**
 * Turns all the form and layer <input> elements into a query string that can be attached to Ajax requests.
 * Includes: <input> elms with a name that are either in MapForm or are a radio or checkbox and in any form.
 *
 * @return bool false or string (eg: mapwidth=500&mapwidth=400&LastCmd=Something)
*/
function mapToQueryString() {
	var strLayerParams = "";

	var colInputElms = document.getElementsByTagName("input");
	var intCount = colInputElms.length;
	var objInputElm = null;

	for(var i = 0; i<intCount; i++) {
		objInputElm = colInputElms[i];

		if(objInputElm.name != "" && objInputElm.name != "Cmd") {
			switch(objInputElm.type) {
				case "radio":
				case "checkbox":
					if(objInputElm.checked === true)
						strLayerParams += "&" + objInputElm.name + "=" + objInputElm.value;
					break;

				case "hidden":
					//-- Not aware of any that don't support it, but just in case.
					if(typeof objInputElm.form == "undefined") {
						alert("Error sending layers data. Please report this along with the details below.\n" + navigator.appName + " " + navigator.appVersion);
						return false;
					}

					if(objInputElm.form.name == "MapForm")
						strLayerParams += "&" + objInputElm.name + "=" + objInputElm.value;
					break;
			}
		}
	}

	return strLayerParams;
};