/*****************************************
 * This JS file is for any miscellaneous,
 * useful methods to be shared within the
 * entire website.
 */

// This function provides a trim function for JavaScript
String.prototype.trim = function() {
  return this.replace(/^\s+|\s+$/g, "");
}

//This function escapes a string so it can be used as a regular expression
RegExp.escape = function(text) {
  if (!arguments.callee.sRE) {
    var specials = [
      '/', '.', '*', '+', '?', '|',
      '(', ')', '[', ']', '{', '}', '\\'
    ];
    arguments.callee.sRE = new RegExp(
      '(\\' + specials.join('|\\') + ')', 'g'
    );
  }
  return text.replace(arguments.callee.sRE, '\\$1');
}


function doClick(buttonName,e)
    {
//the purpose of this function is to allow the enter key to point to the correct button to click.
//your call to this function should include the event arg (which is defined by default), and should look like:
//On a text input, for example, onKeyPress="return doClick('theInputButtonsID', event)"

        var key;
         if(window.event)
              key = window.event.keyCode;     //IE
         else
              key = e.which;     //firefox
        if (key == 13)
        {
            //Get the button the user wants to have clicked

            var btn = document.getElementById(buttonName);
            //check if onclick is defined. This allows buttons to be images or anchors. Otherwise use the click method to 
            //simulate the click of a button. Note the img, a cannot have an onClick, it must be onclick (CASE SENSITIVE)
            if(btn.onclick!=undefined && btn.onclick!=null)
            	 btn.onclick();
            else{
	            if (btn != null)
	            { //If we find the button click it
					
	                btn.click();
	            }
            }
        //don't submit the form
        return false;
        }
   }

/*TODO: Figure out how to use a dynamic submitTargetName to assign inputs to a specific target that is not hard coded. */
function addEnterSubmitListenerToInputs(inputIDsArray, submitTargetName){
	for(var i=0;i<inputIDsArray.length;i++){
		document.getElementById(inputIDsArray[i]).onkeypress=handleClick;
	}		
}

function handleClick(e)
{
	//you must have the submit image/button/anchor have an id of 'submitTarget'
	doClick('submitTarget', e);
}

function disableEnterKey(e)
{
	//If you don't want an input to submit the form when the enter key is pressed
	//your call to this function should include the event arg (which is defined by default), and should look like:
	//onkeypress="return disableEnterKey(event)"
     var key;
     if(window.event)
          key = window.event.keyCode;     //IE
     else
          key = e.which;     //firefox
     if(key == 13)
          return false;
     else
          return true;
}

//########################################
// Util URL Encode/Decode functions, for decodeing encoded contents of xml response
//########################################
// ====================================================================
//       URLEncode and URLDecode functions
//
// Copyright Albion Research Ltd. 2002
// http://www.albionresearch.com/
//
// You may copy these functions providing that 
// (a) you leave this copyright notice intact, and 
// (b) if you use these functions on a publicly accessible
//     web site you include a credit somewhere on the web site 
//
// If you find or fix any bugs, please let us know at albionresearch.com
//
// SpecialThanks to Neelesh Thakur for being the first to
// report a bug in URLDecode() - now fixed 2003-02-19.
// And thanks to everyone else who has provided comments and suggestions.
//
// Tweaked by Nate
// ====================================================================
function URLEncode(thestring)
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var plaintext = thestring;
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	return encoded;
};

function URLDecode(thestring)
{
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
   var HEXCHARS = "0123456789ABCDEFabcdef"; 
   var encoded = thestring;
   var plaintext = "";
   var i = 0;
   while (i < encoded.length) {
       var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2) 
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while
   return plaintext;
}

//Functions to preload images for popIns and hover overs, etc.
function preloadImages(imagePaths)
{
	var myimages = new Array();
	function preloading(){
		for (x=0; x<preloading.arguments.length; x++){
			myimages[x] = new Image();
			myimages[x].src = preloading.arguments[x];
		}
	}
	preloading(imagePaths);
}

