var __AJAXImageElement = null;
var __AJAXImageLoadingPath = '';

function setLogText(text) {
	var logArea = document.getElementById('log_textarea');
	if (logArea) {
		logArea.value = text;
	}
}

function addLogText(text) {
	var logArea = document.getElementById('log_textarea');
	if (logArea) {
		logArea.value += text + "\n";
	}
}

function addLogMap(array) {
	for (var prop in array) {
		addLogText("  *" + prop + ", " + array[prop]);
	}
}

function addEvent(obj, type, func, useCapture) {
	if (obj.addEventListener) {
		obj.addEventListener(type, func, useCapture);
		return true;
	} else if (obj.attachEvent) {
		var r = obj.attachEvent('on'+type, func);
		return r;
	} else {
		obj['on'+type] = func;
	}
}

function stopPropagation(event) {
	if (window.event) {
		window.event.cancelBubble = true;
	} else if (event) {
		event.stopPropagation();
	}
}

function preventDefault(event) {
	if (window.event) {
		window.event.returnValue = false;
	} else if (event) {
		event.preventDefault();
	}
}

function hashToQueryString(hash) {
	if (hash == null) {
		return "";
	}
	var queryArray = [];
	for (var prop in hash) {
		if (hash[prop] == '#')
			queryArray.push(prop);
		else
			queryArray.push(prop + "=" + escape(hash[prop]));
	}
	return queryArray.join("&");
}

function queryStringToHash(qString) {
	//note: IE won't let you overwrite the parameters passed to functions
	var queryString = qString;
	if (queryString.charAt(0) == '#')
		queryString = queryString.substring(1,queryString.length);
	if (queryString.match(/^\s*$/))
		return {};
	var hash = {};
	var pairs = queryString.split('&');
	for (var i = 0; i < pairs.length; i++) {
		var pair = pairs[i].split('=');
		var key = pair[0];
		var value = '#';
		if (pair.length > 1)
			value = unescape(pair[1]);
		hash[key] = value;
	}
	return hash;
}

/**
ajaxSend - convenience function for sending AJAX HTTP requests
	(required parameters are method, url, hash, and callback)
	
	Requires import of Sarissa library (scripts/sarissa.js)

Parameters:
method = GET or POST (determines how contents of 'hash' are sent)
url - the URL of the page from which the response will be received
	(asynchronously)
hash - a typical JS property list mapped to key/value
	pairs in a GET/POST query string (may be null) 
callback - a function to call with the resulting XML document object
	if the response is received successfully

isAsync - 'true' if request is to be sent asynchronously; 'false'
	otherwise (defaults to 'true')
returnType - 'XML' or 'Text' (case insensitive) to determine whether
	responseXML or responseText is returned (defaults to 'text')
*/
function sendAJAXRequest(method, url, hash, callback,
				  isAsync, returnType) {
	var type = 'text';
	if (typeof returnType != 'undefined') {
		type = returnType.toLowerCase();
		if (type != 'text' && type != 'xml') {
			return;
		}
	}
	var async = true;
	if (typeof isAsync != 'undefined') {
		async = isAsync;
	}
	var xmlHttp = new XMLHttpRequest();
	var queryString = hashToQueryString(hash);
	if (method == 'POST') {
		xmlHttp.open('POST', url, async);
		xmlHttp.setRequestHeader('Content-Type', 
		 'application/x-www-form-urlencoded');
	}
	else if (method == 'GET') {
		var getURL = url;
		if (queryString != "") {
			getURL += "?" + queryString;
		}
		xmlHttp.open('GET', getURL, async);
	}
	else {
		return;
	}
	xmlHttp.onreadystatechange = function () {
		if (xmlHttp.readyState == 4) {
			if (type == 'text') {
				callback(xmlHttp.responseText, xmlHttp.status);
			}
			else {
				callback(xmlHttp.responseXML, xmlHttp.status);
			}
			if (__AJAXImageElement) {
				__AJAXImageElement.src = '';
				__AJAXImageElement.style.display = 'none';
			}
		}
	}
	//alert(url + "?" + queryString)
	var postQuery = (method == 'POST') ? queryString : null;
	xmlHttp.send(postQuery);
	if (__AJAXImageElement) {
		__AJAXImageElement.src = __AJAXImageLoadingPath;
		__AJAXImageElement.style.display = '';
	}
}

function sendTextRequest(method,url,hash,callback,async) {
	sendAJAXRequest(method,url,hash,callback,async,'text');
}

function sendXMLRequest(method,url,hash,callback,async) {
	sendAJAXRequest(method,url,hash,callback,async,'xml');
}

function setAJAXImage(imageElement, loadingPath) {
	__AJAXImageElement = imageElement;
	__AJAXImageLoadingPath = loadingPath;
	
	__AJAXImageElement.style.display = 'none';
}
	
	/**
	ajaxSend - convenience function for sending AJAX HTTP requests
		(required parameters are method, url, hash, and callback)
		
		Requires import of Sarissa library (scripts/sarissa.js)
	
	Parameters:
	method = GET or POST (determines how contents of 'hash' are sent)
	url - the URL of the page from which the response will be received
		(asynchronously)
	hash - a typical JS property list mapped to key/value
		pairs in a GET/POST query string (may be null) 
	callback - a function to call with the resulting XML document object
		if the response is received successfully
	errorCallback - a function to call with resulting HTTP error status
		if the response is not received successfully (may be null)
	
	isAsync - 'true' if request is to be sent asynchronously; 'false'
		otherwise (defaults to 'true')
	returnType - 'XML' or 'Text' (case insensitive) to determine whether
		responseXML or responseText is returned (defaults to 'text')
	*/
	function ajaxSend(method, url, hash, callback, errorCallback,
					  isAsync, returnType) {
		var type = 'text';
		if (typeof returnType != 'undefined') {
			type = returnType.toLowerCase();
			if (type != 'text' && type != 'xml') {
				return;
			}
		}
		var async = true;
		if (typeof isAsync != 'undefined') {
			async = isAsync;
		}
		var xmlHttp = new XMLHttpRequest();
		var queryString = hashToQueryString(hash);
		if (method == 'POST') {
			xmlHttp.open('POST', url, async);
			xmlHttp.setRequestHeader('Content-Type', 
		     'application/x-www-form-urlencoded');
		}
		else if (method == 'GET') {
			var getURL = url;
			if (queryString != "") {
				getURL += "?" + queryString;
			}
			xmlHttp.open('GET', getURL, async);
		}
		else {
			return;
		}
		xmlHttp.onreadystatechange = function () {
			if (xmlHttp.readyState == 4) {
				if (xmlHttp.status == 200) {
					if (type == 'text') {
						callback(xmlHttp.responseText);
					}
					else {
						callback(xmlHttp.responseXML);
					}
				}
				else {
					if (errorCallback) {
						errorCallback(xmlHttp.status);
					}
				}
			}
		}
		//alert(url + "?" + queryString)
		var postQuery = (method == 'POST') ? queryString : null;
		xmlHttp.send(postQuery);
	}

	/*function setCookie(name, value, expires, path, domain, secure) {
		 document.cookie = name + "=" + escape(value) +
			  ((expires) ? "; expires=" + expires.toUTCString() : "") +
			  ((path) ? "; path=" + path : "") +
			  ((domain) ? "; domain=" + domain : "") +
			  ((secure) ? "; secure" : "");
	}
	
	function setCookie (name, value) {
      var argv = setCookie.arguments;
      var argc = setCookie.arguments.length;
      var expires = (argc > 2) ? argv[2] : null;
      var path = (argc > 3) ? argv[3] : null;
      var domain = (argc > 4) ? argv[4] : null;
      var secure = (argc > 5) ? argv[5] : false;
      document.cookie = name + "=" + escape (value) +
        ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
        ((path == null) ? "" : ("; path=" + path)) +
        ((domain == null) ? "" : ("; domain=" + domain)) +
        ((secure == true) ? "; secure" : "");
    }
	
	function getCookie(name) {
		 var dc = document.cookie;
		 var prefix = name + "=";
		 var begin = dc.indexOf("; " + prefix);
		 if (begin == -1) {
			  begin = dc.indexOf(prefix);
			  if (begin != 0) return null;
		 } else {
			  begin += 2;
		 }
		 var end = document.cookie.indexOf(";", begin);
		 if (end == -1) {
			  end = dc.length;
		 }
		 return unescape(dc.substring(begin + prefix.length, end));
	}

	function deleteCookie(name, path, domain)	{
		 if (getCookie(name)) {
			  document.cookie = name + "=" + 
					((path) ? "; path=" + path : "") +
					((domain) ? "; domain=" + domain : "") +
					"; expires=Thu, 01-Jan-70 00:00:01 GMT";
		 }
	}*/
	
	//  Function to return the value of the cookie specified by "name".
    //    name - String object containing the cookie name.
    //    returns - String object containing the cookie value, or null if
    //      the cookie does not exist.
    //
    function getCookie (name) {
      var arg = name + "=";
      var alen = arg.length;
      var clen = document.cookie.length;
      var i = 0;
      while (i < clen) {
        var j = i + alen;
        if (document.cookie.substring(i, j) == arg)
          return getCookieVal (j);
        i = document.cookie.indexOf(" ", i) + 1;
        if (i == 0) break; 
      }
      return null;
    }

    //
    //  Function to create or update a cookie.
    //    name - String object object containing the cookie name.
    //    value - String object containing the cookie value.  May contain
    //      any valid string characters.
    //    [expires] - Date object containing the expiration data of the cookie.  If
    //      omitted or null, expires the cookie at the end of the current session.
    //    [path] - String object indicating the path for which the cookie is valid.
    //      If omitted or null, uses the path of the calling document.
    //    [domain] - String object indicating the domain for which the cookie is
    //      valid.  If omitted or null, uses the domain of the calling document.
    //    [secure] - Boolean (true/false) value indicating whether cookie transmission
    //      requires a secure channel (HTTPS).  
    //
    //  The first two parameters are required.  The others, if supplied, must
    //  be passed in the order listed above.  To omit an unused optional field,
    //  use null as a place holder.  For example, to call setCookie using name,
    //  value and path, you would code:
    //
    //      setCookie ("myCookieName", "myCookieValue", null, "/");
    //
    //  Note that trailing omitted parameters do not require a placeholder.
    //
    //  To set a secure cookie for path "/myPath", that expires after the
    //  current session, you might code:
    //
    //      setCookie (myCookieVar, cookieValueVar, null, "/myPath", null, true);
    //
	 
	 var _i = 0;
	 
    function setCookie (name, value) {
      var argv = setCookie.arguments;
      var argc = setCookie.arguments.length;
      var expires = (argc > 2) ? argv[2] : null;
      var path = (argc > 3) ? argv[3] : null;
      var domain = (argc > 4) ? argv[4] : null;
      var secure = (argc > 5) ? argv[5] : false;
		var _cname = name + "=" + value +
        ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
        ((path == null) ? "" : ("; path=" + path)) +
        ((domain == null) ? "" : ("; domain=" + domain)) +
        ((secure == true) ? "; secure" : "");
		
		if (_i < 5) {
			//alert(_cname);	
		}
		_i++;
		
      document.cookie = _cname;
    }
	 
	 function resetCookie (name) {
		setCookie(name, ''); 
	 }

    //  Function to delete a cookie. (Sets expiration date to current date/time)
    //    name - String object containing the cookie name
    //
    function deleteCookie (name) {
      var exp = new Date();
      exp.setTime (exp.getTime() - 1);  // This cookie is history
      var cval = getCookie (name);
      document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
    }
	 
	 function getCookieVal (offset) {
      var endstr = document.cookie.indexOf (";", offset);
      if (endstr == -1)
        endstr = document.cookie.length;
      return unescape(document.cookie.substring(offset, endstr));
    }
	 
	function set_cookie_array(cookie_array_name, cookie_name, cookie_value) {
		var cookie_delimiter = '@';
		var name_value_separator = '#';
		
		var cookies_string = (getCookie(cookie_array_name) != null) ? getCookie(cookie_array_name) : "";
		
		//First find if the cookie exists.
		var reCookie = new RegExp("" + cookie_delimiter + cookie_name + name_value_separator + "[^" + cookie_delimiter + ";]*");
		//alert("regexp: " + reCookie);
		var arrMatches = cookies_string.match(reCookie);
		//alert(arrMatches);
		var sMatch = (arrMatches != null) ? arrMatches[0] : "";
		
		if (sMatch != "") {//If cookie does exist, delete it, then add it to the end.
			//To "delete" part of the string, we will splice the part of
			//the string before and after the cookie.
			/*var first_part = cookies_string.substr(0, pos - 1);
			var second_part = cookies_string.substr(pos + sMatch.length);
			
			alert("first_part: " + first_part);
			alert("second_part: " + second_part);*/
			
			cookies_string = cookies_string.replace(reCookie, "");
		}
		
		cookies_string += cookie_delimiter + cookie_name + name_value_separator + cookie_value;
		
		//strip off first ';' delimiter.
		//cookies_string = cookies_string.substr(1, cookies_string.length);
		
		var expires = new Date();
		expires.setTime(expires.getTime() + (60000 * 60 * 24 * 365));
		
		setCookie(cookie_array_name, cookies_string, expires);
		
	}//end function set_cookie_array()	 
		
	function trim(sString) {
		while (sString.substring(0, 1) == ' ') {
			sString = sString.substring(1, sString.length);	
		}
		while (sString.substring(sString.length-1, sString.length) == ' ') {
			sString = sString.substring(0,sString.length-1);
		}
		return sString;
	}
	
	function addEvent(elm, evType, fn, useCapture) {
		if (elm.addEventListener) {
			elm.addEventListener(evType, fn, useCapture);
			return true;
		} else if (elm.attachEvent) {
			var r = elm.attachEvent('on' + evType, fn);
			return r;
		} else {
			elm['on' + evType] = fn;
		}
	}
	
	function isArray(object) {
		return object instanceof Array;
	}
	
	/*
	// example usage of addEvent
	function addListeners(e) {
		addEvent(document.getElementById('zip'), 'keyup', refresh_local_colleges, false);
	}
	
	addEvent(window, 'load', addListeners, false);
	*/
	
	/*function : format_number()  
	version: 1.0.0  
	This function formats a numeric value passed in to it with specified number of  
	decimal values. numeric value will not be rounded.  
	pnumber : numeric value to be formatted.  
	decimals : number of decimal points desired.  
	
	Author: Buddhike de Silva  
	Date: 21-Nov-2002 11:16 AM*/  
	
	/*  
	revision: 1.1.0  
	Author: M. Cassim Farook  
	Date: 21-Nov-2002 10:16 PM  
	Notes: No offense buddhike...but i had to rewrite the code  
	works for ADT (any dam thing)  
	usage: x = format_number(123.999, 2)  
	*/  
	
	/*  
	revision: 1.2.0  
	Authors: Buddhike de Silva  
	Date: 22-Nov-2002 12:07 PM  
	Notes: Optimized for best performence.  
	usage: x = format_number(123.999, 2)  
	*/  
	
	/* 
	 * Revision: 1.3 
	 * Author: Mike Robb (JS-X.com) 
	 * Date: May 26, 2003 
	 * Notes:  Changed to deal with negative numbers. 
	 *         Fixed length of final answer. 
	 *         Work-around for javascript internal math problem with rounding negative numbers. 
	 */ 
	
	/*
	 * Revision 1.4
	 * Author: LeAnn Roberts
	 * Date: September, 2003
	 * Note: Modified the if logic: Math.pow()
	 */
	
	/*
	 * Revision 1.5
	 * Author: Robert Heggdal
	 * Date: February, 2004
	 * Note: Modified check for negative number by replacing parseInt with parseFloat so that negative numbers between zero and minus one are recognized as such.
	 */ 
	
	/*
	 * Revision 1.6
	 * Author: Naveen
	 * Date: February, 2004
	 * Note: Rewrote format_number to correct a logic problem.
	 */
	
	/*
	 * Revision 1.7
	 * Author: JS-X.com
	 * Date: February, 2004
	 * Note: Added wrapper around format_number as negative values were dropped from
	 *       the logic.
	 */

	function format_number(p,d) 
	{
	  var r;
	  if(p<0){p=-p;r=format_number2(p,d);r="-"+r;}
	  else   {r=format_number2(p,d);}
	  return r;
	}
	function format_number2(pnumber,decimals) 
	{
	  var strNumber = new String(pnumber);
	  var arrParts = strNumber.split('.');
	  var intWholePart = parseInt(arrParts[0],10);
	  var strResult = '';
	  if (isNaN(intWholePart))
		 intWholePart = '0';
	  if(arrParts.length > 1)
	  {
		 var decDecimalPart = new String(arrParts[1]);
		 var i = 0;
		 var intZeroCount = 0;
		  while ( i < String(arrParts[1]).length )
		  {
			 if( parseInt(String(arrParts[1]).charAt(i),10) == 0 )
			 {
				intZeroCount += 1;
				i += 1;
			 }
			 else
				break;
		 }
		 decDecimalPart = parseInt(decDecimalPart,10)/Math.pow(10,parseInt(decDecimalPart.length-decimals-1)); 
		 Math.round(decDecimalPart); 
		 decDecimalPart = parseInt(decDecimalPart)/10; 
		 decDecimalPart = Math.round(decDecimalPart); 
	
		 //If the number was rounded up from 9 to 10, and it was for 1 'decimal' 
		 //then we need to add 1 to the 'intWholePart' and set the decDecimalPart to 0. 
	
		 if(decDecimalPart==Math.pow(10, parseInt(decimals)))
		 { 
			intWholePart+=1; 
			decDecimalPart="0"; 
		 } 
		 var stringOfZeros = new String('');
		 i=0;
		 if( decDecimalPart > 0 )
		 {
			while( i < intZeroCount)
			{
			  stringOfZeros += '0';
			  i += 1;
			}
		 }
		 decDecimalPart = String(intWholePart) + "." + stringOfZeros + String(decDecimalPart); 
		 var dot = decDecimalPart.indexOf('.');
		 if(dot == -1)
		 {
			decDecimalPart += '.'; 
			dot = decDecimalPart.indexOf('.'); 
		 } 
		 var l=parseInt(dot)+parseInt(decimals); 
		 while(decDecimalPart.length <= l) 
		 {
			decDecimalPart += '0'; 
		 }
		 strResult = decDecimalPart;
	  }
	  else
	  {
		 var dot; 
		 var decDecimalPart = new String(intWholePart); 
	
		 decDecimalPart += '.'; 
		 dot = decDecimalPart.indexOf('.'); 
		 var l=parseInt(dot)+parseInt(decimals); 
		 while(decDecimalPart.length <= l) 
		 {
			decDecimalPart += '0'; 
		 }
		 strResult = decDecimalPart;
	  }
	  return strResult;
	}
	
	function rand() {
		var randomNumber = Math.floor(Math.random() * 9999999);
		return randomNumber;
	}
	
	// e.g. usage: <input name="title" id="title" type="text" size="60" onKeyUp="SubmitOnEnter(event, 'frm_quick_add');">
	function EnterKeyPressed(e) { //e is event object passed from function invocation
		var characterCode; //literal character code will be stored in this variable
		
		if (e && e.which) { //if which property of event object is supported (NN4)
			e = e;
			characterCode = e.which; //character code is contained in NN4's which property
		} else {
			e = event;
			characterCode = e.keyCode; //character code is contained in IE's keyCode property
		}
		
		if (characterCode == 13) { //if generated character code is equal to ascii 13 (if enter key)
			return true;
		}

		return false;
	
	}
	
	function upload_image(path_to_textfield, upload_subfolder) {
	
		pageurl  = 'upload.php' +
				   '?path_to_textfield=' + path_to_textfield;
		//Upload to a folder within the upload folder
		
		if (arguments.length > 1) {
			pageurl += '&upload_subfolder=' + encodeURIComponent(upload_subfolder);
		}

		winname  = 'upload_image';
		w_width  = 331;
		w_height = 127;
		
		top_pos  = (screen.availHeight - w_height) / 2;
		left_pos = (screen.availWidth  - w_width)  / 2;
		
		w = window.open(pageurl, winname, 'width=' + w_width + ',height=' + w_height + ',toolbars=0,resizable=1,scrollbars=1,top=' + top_pos + ',left=' + left_pos);
		w.focus();
	}
	
	function upload_mp3(path_to_textfield, upload_subfolder) {
	
		pageurl  = 'upload_mp3.php' +
				   '?path_to_textfield=' + path_to_textfield;
		//Upload to a folder within the upload folder
		
		if (arguments.length > 1) {
			pageurl += '&upload_subfolder=' + encodeURIComponent(upload_subfolder);
		} else {
			pageurl += '&upload_subfolder=' + encodeURIComponent('mp3s');
		}

		winname  = 'upload_image';
		w_width  = 331;
		w_height = 127;
		
		top_pos  = (screen.availHeight - w_height) / 2;
		left_pos = (screen.availWidth  - w_width)  / 2;
		
		w = window.open(pageurl, winname, 'width=' + w_width + ',height=' + w_height + ',toolbars=0,resizable=1,scrollbars=1,top=' + top_pos + ',left=' + left_pos);
		w.focus();
	}
	
	function popup_window(page_url, width, height, toolbars, resizable, scrollbars) {
		var toolbars   = (arguments.length > 3) ? toolbars   : 0;
		var resizable  = (arguments.length > 4) ? resizable  : 1;
		var scrollbars = (arguments.length > 5) ? scrollbars : 1;
		
		var top_pos  = (screen.availHeight - width) / 2;
		var left_pos = (screen.availWidth  - height) / 2;
		
		var window_properties = 'width=' + width + ',height=' + height + ',toolbars='+toolbars+',resizable='+resizable+',scrollbars='+scrollbars+',top=' + top_pos + ',left=' + left_pos;
				
		w = window.open(page_url, "new_window", window_properties);
		w.focus();
	}//end function popup_window
	
	//Finds value[s] of checked inputs (could be radio buttons or checkboxes.
	function findChecked(input_name) {
		
		//Determine if object is an array.
		if (input_name[1]) { 
			var array_size = input_name.length;
			var checked_values = Array();
			
			//Loop through each array element checking to see if 
			//value is checked and if it is, add it to checked_values array.
			var j = 0;//For populating the checked_values array.
			for (var i = 0; i < array_size; i++) {
				if (input_name[i].checked) {
					checked_values[j++] = input_name[i].value;
				}
			}//end for
			
			if (settingCookie) {
				//alert(checked_values.toString());
				return checked_values.toString();
			} else {
				//Return array of checked values.
				return checked_values;
			}
			
		} else {//Object is a single checkbox, so see if it is checked.
			if (input_name.checked) return 1;
			else return 0;
		}
	}//end function findChecked
	
	
	
//-->