
//Pops up a safe window in any browser
function popWindow(url, title, width, height, WindowOptions) {
	if (!WindowOptions) {
	 var win = window.open(url, title, 'width='+width+',height='+height+',directories=no,location=no,menubar=no,status=yes,toolbar=no,resizable=yes,scrollbars=yes');
	 win.focus();
	 return win;
	}else{
	 var win = window.open(url, title, 'width='+width+',height='+height+','+WindowOptions);
	 win.focus();
	 return win;
	}
}


window._alert = window.alert;
window.alert = function(text) {
	if(!window.alert.halt) {
	  var result = confirm(text);

		if(!result) {
			window.alert.halt = true;
	  }
  }
}
/**Returns -1 if value is in javascript array
 *
 */
Array.prototype.in_array = function(value) {
	for(var i = 0; i < this.length; i++ ) {
		if(this[i] == value) {
			return i;
		} else if(this[i] instanceof Array) {
			return this[i].in_array(value);
	  }
	}
	return -1;
}

/**Search array for value and return corresponding index
 * @param   array   arr    Array to search
 * @param   string  value  Value to search for
 * @return  int   Array index corresponding to value
 */
function arrayFind(arr, value) {
	for (var i=0; i < arr.length; i++) {
		if (value == arr[i]) {
			return i;
		}
	}
	return -1;
}

function buildSelectOptions(values, texts) {
	html = "";
	for(var i=0; i < values.length; i++) {
		html += '<option value="' + values[i] + '">' + texts[i] + '</option>';
	}
	return html;
}

/**Set form to "not modified"
 *
 * Sets the "modified" attribute on the form object
 * @param  string  formName   Name of form
 */
function cacheForm(formName) {
	document.forms[formName].setAttribute("modified", "false");
}

/**Set form to "not modified"
 *
 * Creates a "modified" attribute on the form object
 * and sets the onchange element of all the form's elements
 * to change the flag when one of the form's elements is
 * modified.
 *
 * @param  string  formName   Name of form
 */
function cacheFormInit(formName) {
	var form = document.forms[formName];
	form.setAttribute("modified", "false");

	var setModified = function() {
		var form;
		if(window.event) {
			form = window.event.srcElement.form;
		} else {
			form = this.form;
		}
		form.setAttribute('modified', 'true');
	}

	for(var i=0; i < form.elements.length; i++) {
		el = form.elements[i];
		//el.onchange = setModified;

		if(el.addEventListener) {
			el.addEventListener("keypress", setModified, false);
			el.addEventListener("change", setModified, false);
		} else if(el.attachEvent) {
			el.attachEvent("onkeypress", setModified);
			el.attachEvent("onchange", setModified);
		}
	}
}





/**Enable or disable control
 * @param  mixed              ctrl      Object OR (String) ID of the control object
 * @param  mixed  (optional)  toState   "enabled" or "disabled"  OR  undefined --
 *                                       Toggle control (to opposite of its current state)
 */
function enDisableControl(ctrl,toState){

	//**** TODO:  ID is NOT DEFINED ANYWHERE  ***/
	if(typeof(id) != 'object') {
	  ctrl = document.getElementById(ctrl);
		if(!ctrl) {
			alert(ctrl + "not defined in enDisableControl");
		}
	}

	if(!toState){
    if(ctrl.className.match(/disabled/i)){toState = 'enabled';}
    else{toState = 'disabled';}
  }
  if(toState == 'enabled'){
    ctrl.className = ctrl.className.replace(/disabled/i,'');
    ctrl.disabled = false;
    return true;
  }
  else{
    if(!ctrl.className.match(/disabled/i)){
      ctrl.className += 'Disabled';
      ctrl.disabled = true;
    }
    return false;
  }
}

/**Fills form with data from a JSON object
 *
 * Loops through the form elements array and uses
 * the name of each form element as an index into the
 * JSON data object (to get the value for insertion)
 *
 * @param  object  json    JSON object with key-value pairs
 * @param  object  form    Form object
 */
function fillFormValues(json, form) {
	if(!json) {
		return;
	}
	for(var i=0; i < form.elements.length; i++) {
		var el = form.elements[i];

		if(el.name && typeof(json[el.name]) != 'undefined') {
			if(el.tagName == "INPUT" || el.tagName == "TEXTAREA") {
				el.value = unescape_quotes(json[el.name] + "", 0x3);
			} else {
				el.value = json[el.name];
			}
	  }
	}
}

/**Finds the X (absolute) position of an object on the screen
 *
 * This function was added because elementPosition of
 * MochiKit doesn't work in Internet Explorer
 *
 */
function findPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}

/**Finds the Y (absolute) position of an object on the screen
 *
 * This function was added because elementPosition of
 * MochiKit doesn't work in Internet Explorer
 *
 */
function findPosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}

/**Finds the X (absolute) position of the cursor on the screen*/
function mouseX(evt) {
	if (evt.pageX) {
		return evt.pageX;
	}else if (evt.clientX) {
		 return evt.clientX + (document.documentElement.scrollLeft ?
		 document.documentElement.scrollLeft :
		 document.body.scrollLeft);
	}else{
		return null;
	}
}

/**Finds the Y (absolute) position of the cursor on the screen*/
function mouseY(evt) {
	if (evt.pageY) {
		return evt.pageY;
	}else if (evt.clientY) {
		 return evt.clientY + (document.documentElement.scrollTop ?
		 document.documentElement.scrollTop :
		 document.body.scrollTop);
	}else{
		return null;
	}
}

/**Hide and show elements
 * @param  array   hide   array containing id's of elements to hide
 * @param  array   show   array containing id's of elements to show
 */
function hide_show(hide, show) {
	for(var i=0; i<hide.length; i++) {
		var el = document.getElementById(hide[i]);
		if(el) {
			el.style.display = "none";
		}
	}
	for(var i=0; i<show.length; i++) {
		var el = document.getElementById(show[i]);
		if(el) {
			el.style.display = "block";
		}
	}
}

/**Check if a form has been modified
 *
 * Checks the form's "modified" attribute (set by cacheForm)
 * to see if the form has been modified.
 *
 * @param   string   formName   Name of form
 * @return  boolean  True if form has been modified, false otherwise
 */
function isFormModified(formName) {
	var form = document.forms[formName];
	if(form.getAttribute("modified") == "true") {
		return true;
	}else{
		return false;
	}
}

/**Test to see if <enter> key pressed
 *
 * Usually used on a form element's "onkeypress" attribute
 * to see if the user wants to submit the form
 *
 * @return  boolean  True if <enter> pressed, false otherwise
 */
function isKeyEnter(e) {
	e = e || window.event;
	k = document.all?e.keyCode:e.which;
	return k==13;
}

function liniarSearch(a, findKey, value) {
	for (var i=0; i<a.length; i++) {
		if (a[i][findKey] == value) {
			return i;
		}
	}
	return -1;
}


/**Show notification (eg AJAX 'Save') in browser upper-right corner
 * @param  string   text   Text to show in notification
 * @param  int      show   0 = hide notify div, 1 = show
 * @param  hex-int  color  Color of notify div
 * @param  OPTIONAL  int  Milliseconds to wait before shutting
 *                        off notification
 *
 * Example:
 * notifyBar(1, "Loading...", "#FF9933");
 */
function notifyBar(show, text, color, timeout) {
	var el = document.getElementById("notifyBar");

	if(!el) {
		var html = '<div class="notifyBar" id="notifyBar"></div>'
         + '<style>'
				 + '.notifyBar {'
				 + '  position: absolute;'
				 + '  top: 0;'
				 + '  right: 0;'
				 + '  padding: 2px;'
				 + '  padding-left: 5px;'
				 + '  padding-right: 5px;'
				 + '  font-size: 10px;'
				 + '  font-family:Verdana, Arial, Helvetica, sans-serif;'
				 + '  visibility: hidden;'
				 + '}'
         + '</style>';

		document.body.innerHTML += html;
	  el = document.getElementById("notifyBar");
	}

	if(show) {
		el.style.visibility = 'visible';

		if(timeout) {
			func = "notifyBar(0,'',0)";
			setTimeout(func, timeout);
		}
		el.style.backgroundColor = color;
		el.innerHTML = text;
  } else {
		el.style.visibility = 'hidden';
	}
}

/**Set the value of a hidden form element
 * @param  string  id      Id or name of the hidden input element
 * @param  string  value   Value to set
 */
function setHiddenInput(formName, name, value) {
	var el = document.getElementById(name);
	if(!el) {
		var form = document.forms[formName];
		if(form) {
			var el = form[name];
		  if(!el) {
				el = document.createElement('INPUT');
				el.setAttribute('style', 'display: none');
				el.setAttribute('name', name);
				el.setAttribute('value', value);
				form.appendChild(el);
				return;
			}
		}
	}
  el.value = value;
}

/**Private method for sorting JSON objects by number values
 * (used by sortArrayOfJSON function)
 */
function _sortArrayOfJSON_number(a, b) {
	var field = document.sortArrayOfJSON_field;
  var arr = document.sortArrayOfJSON_arr;
	//alert(_a);
	var a = a[field];
	var b = b[field];

	return a - b;
}

/**Private method for sorting JSON objects by string values
 * (used by sortArrayOfJSON function)
 */
function _sortArrayOfJSON_string(a, b) {
	var field = document.sortArrayOfJSON_field;
  var arr = document.sortArrayOfJSON_arr;
	//alert(_a);
	var a = a[field] + "";
	var b = b[field] + "";

	if(a > b) {
		return 1;
	} else if(a < b) {
		return -1;
	}
	return 0;
}

/**Sort array of JSON objects
 * @param  array   arr    Array of JSON objects
 * @param  string  field  Array key in JSON object (eg. "id", "subject", "name", etc)
 * @param  int     flag   0 = sort a string field
 *                        1 = sort a number field
 */
function sortArrayOfJSON(arr, field, flag, ascending) {
	document.sortArrayOfJSON_field = field;
	document.sortArrayOfJSON_arr = arr;
	document.sortArrayOfJSON_flag = flag;

	if(!flag) {
		arr.sort(_sortArrayOfJSON_string);
	} else if(flag == 1) {
		arr.sort(_sortArrayOfJSON_number);
	}
	if(!ascending) {
		arr = arr.reverse();
	}
}


function typeSelectInit() {
	var sel = document.getElementsByTagName("select");

  for(var i=0; i < sel.length; i++) {
		if(sel[i].tagName == "SELECT") {
			//alert(sel[i].name);
			var el = sel[i];
			if(el.addEventListener) {
				el.addEventListener("keypress", typeSelect, true);
      } else if (el.attachEvent) {
				el.attachEvent("onkeypress", typeSelect);
			}
		}
	}
}

/* allows IE users to type in a select box and jump to the best match
 * instead of just jumping to the first word for each letter typed
 * param: event object
 * return: false to cancel key pressed; true to let key bubble
 * implementation: <select onkeypress="return typeSelect(event);">
*/
function typeSelect(){
	//document.getElementById("clientemail").style.backgroundColor = 'green';
	evt = window.event;
	//alert("here, in typeSelect");
	//alert("hey");
	//alert(this.form.name + " hey!!!");
	//this.form.setAttribute("modified", "true");

	if(typeof(snipTimer) != "undefined"){clearTimeout(snipTimer);}
  // get the key pressed
  if (window.event) {keycd=window.event.keyCode; var srcElm = evt.srcElement;}//IE
  else {return true;}//MOZ type select functionality is native to browser
  if(keycd < 32){return true;}//abort if a special key pressed (i.e. tab)
  var key = String.fromCharCode(keycd);
  // add the key pressed onto the snip (search term)
  if(typeof(snip) == "undefined"){snip = key;}
  else{snip += key}
  snip = snip.toLowerCase();
  // loop through looking for the first option substring that matches the snip
  for(var i=0; i<srcElm.options.length; i++){
    var optSnip = srcElm.options[i].text.substr(0,snip.length).toLowerCase();
    if(snip == optSnip){srcElm.selectedIndex = i; break;}
  }
  // reset the snip if no key is pressed for more than 1 second
  snipTimer = setTimeout("snip = '';",1000);
  return false;
}
// alert('util loaded');
