//http://rtfustst.rtp.epa.gov/sharedcode/pool/

//correct_loaded_pngs
function correct_loaded_pngs() 
{		
	if (old_ie() && (document.body.filters)) 
	{
		for(var i=0; i<document.images.length; i++)
		{
			var img = document.images[i]
			var imgName = img.src.toUpperCase()
			
			if(img.correct == 'false')
			{
				sizing_method='image';
			}
			else
			{
				sizing_method = 'scale';
			}
			
			if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
			{
				var imgID = (img.id) ? "id='" + img.id + "' " : ""
				var imgClass = (img.className) ? "class='" + img.className + "' " : ""
				var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='"
					+ img.alt + "' "
				var imgStyle = "display:inline-block;" + img.style.cssText 
				
				if (img.align == "left") imgStyle = "float:left;" + imgStyle
				if (img.align == "right") imgStyle = "float:right;" + imgStyle
				if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle 
				
				var strNewHTML = "<span " + imgID + imgClass + imgTitle
					+ " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;"
					+ imgStyle + ";"
					+ "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
					+ "(src=\'" + img.src + "\', sizingMethod='"+sizing_method+"');\"></span>"
				img.outerHTML = strNewHTML
				i = i-1
			}
		}
	}
}


function old_ie()
{
	arVersion = navigator.appVersion.split("MSIE");
	version = parseFloat(arVersion[1]);
	
	return (isNumeric(version) && version < 7 ? true : false);
}

if(old_ie())
{
	window.attachEvent("onload", correct_loaded_pngs);
}

//isNumeric
function isNumeric(n)
{
	return (n*1==n ? true : false);
}

//dollar format
function dollar_format(number)
{
	number = Math.round(number*100)/100;
	number = number.toString().split('.');
	
	if(number[1] == undefined)
	{
		number[1] = '00';
	}
	
	if(number[1].length == 1)
	{
		
		number[1] = number[1]+'0';
	}
	number = number.join('.');
	
	return number;
}

//find
function find(target_string,target_array)
{
	found_at = -1;
	
	for(position=0;position<target_array.length;position++)
	{
		if(target_string == target_array[position])
		{
			found_at = position;
		}
	}
	
	return found_at;
}


//announcements
announcements.prototype.open = open_announcements;
announcements.prototype.close = close_announcements;

function announcements()
{
	this.messages = [];
	this.position_check = '';
	
	document.write('<div id="announcement" style="width:100%; height:100%; overflow:auto; position:absolute; visibility:hidden; z-index:3;"><div id="blackout" style="width:100%; height:100%; overflow:auto; position:absolute; background-color:black; filter:alpha(opacity=66);-moz-opacity:.66;opacity:.66; z-index:4;"></div><div id="message_holder" style="width:100%; height:100%; overflow:auto; position:absolute; z-index:5;"><table cellpadding="0" cellspacing="0" border="0" height="100%" width="100%"><tr><td align="center" id="message_text"></td></tr></table></div></div>');
}

function open_announcements(type)
{
	this.position_check = setInterval('update_announcement_position()',1);
	
	ID('message_text').innerHTML = this.messages[type];	
	
	slide('announcement','right');
	
	if(isNumeric(version) && version < 7)
	{
		correct_loaded_pngs();
	}
}

function close_announcements()
{
	slide('announcement','left');
	clearInterval(this.position_check);
}

function update_announcement_position()
{
	ID('announcement').style.top=document.body.scrollTop;
}

//slide effect
slide_delay = 0;

function slide(id,direction)
{	
	size = browser_size();
	speed = size['width']/5;
	
	if(direction == 'right')
	{
		ID(id).style.left = 0-size['width'];	
		ID(id).style.visibility = 'visible';
		final_position=0;
	}
	else if (direction == 'left')
	{
		final_position = 0-size['width'];
	}
	
	slide_delay = setInterval('move(\''+id+'\',\''+direction+'\','+final_position+','+speed+')',0);
}


function move(id,direction,final_position,speed)
{
	clearInterval(slide_delay);		
	
	position = Number(ID(id).style.left.replace('px','').replace('pt',''));
	
	if(direction == 'right' && position+speed <= final_position)
	{
		ID(id).style.left=position+speed;
	}
	else if(direction == 'right' && position+speed > final_position)
	{
		ID(id).style.left=final_position;
	}
	else if(direction == 'left' && position-speed >= final_position)
	{
		ID(id).style.left=position-speed;
	}
	else if(direction == 'left' && position-speed < final_position)
	{
		ID(id).style.left=final_position;
		ID(id).style.visibility = 'hidden';
	}
	
	position = Number(ID(id).style.left.replace('px','').replace('pt',''));
	
	if(position != final_position)
	{
		slide_delay = setInterval('move(\''+id+'\',\''+direction+'\','+final_position+','+speed+')',0);
	}
}

//fade effect
fade_delay = 0;
function fade(id)
{
	object = ID(id).style;
	object.opacity = 0;
    object.MozOpacity = 0;
    object.KhtmlOpacity = 0;
    object.filter = "alpha(opacity=" + 0 + ")"; 
	object.visibility = 'visible';
	
	fade_delay = setInterval('fade_in(\''+id+'\')',0);
}

function fade_in(id)
{
	clearInterval(fade_delay);
	
	object = ID(id).style;
	object.opacity += 10;
    object.MozOpacity += 0.10;
    object.KhtmlOpacity += 0.10;
    object.filter = "alpha(opacity=" + object.opacity + ")"; 
	object.visibility = 'visible';
	
	if(object.opacity < 100)
	{
		fade_delay = setInterval('fade_in(\''+id+'\')',0);
	}
}

//browser_size
function browser_size()
{
	size = [];
	
	if(parseInt(navigator.appVersion)>3)
	{
		if(navigator.appName=="Netscape")
		{
			size['width'] = window.innerWidth;
			size['height'] = window.innerHeight;
		}
	
		if(navigator.appName.indexOf("Microsoft")!=-1)
		{
			size['width'] = document.body.offsetWidth;
			size['height'] = document.body.offsetHeight;
		}
	}
	
	return size;
}

function ID(obj)
{
	return document.getElementById(obj);
}

function dropdown(id)
{
	value = new Object();
	
	value.value = [];
	value.option = [];	
	value.index = [];
	
	for(x=0; x< ID(id).options.length; x++)
	{
		if(ID(id).options[x].selected == true)
		{
			value.index.push(x);
			value.value.push(ID(id).options[x].value);
			value.option.push(ID(id).options[x].text);
		}
	}
	
	if(value.index.length== 1)
	{
		value.value = value.value[0];
		value.option = value.option[0];
		value.index = value.index[0];
	}

	return value;
}

function set_dropdown(id,type,value)
{
	for(p=0; p<ID(id).options.length; p++)
	{
		if((type=='text' && ID(id).options[p].text==value) || (type=='value' && ID(id).options[p].value==value))
		{
			ID(id).selectedIndex = p;
			break;
		}
	}
}

function radio(id)
{
	for(position=0; position<ID(id).form[id].length; position++)
	{
		if(ID(id).form[id][position].checked)
		{
			return ID(id).form[id][position].value
		}
	}
	return undefined;
}

function save_response(response)
{
	ID('debug').innerHTML = response;
	status=response.split('~')[1];
	action=response.split('~')[2];
	
	if(status == 'success')
	{
		eval(action);
	}
	else
	{
		//announcements.messages['debug'] = '<a href="javascript:announcements.close();">'+response+'</a>';
		//announcements.open('debug');
	}
}

function trim(str)
{
str = str.replace(/^\s+/, '');
for (var i = str.length - 1; i >= 0; i--)
	{
		if (/\S/.test(str.charAt(i)))
		{
			str = str.substring(0, i + 1);
			break;
		}
	}
return str;
}

function go_to(url,target)
{
	if(target == undefined)
	{
		window.location.href=url;
	}
	else
	{
		window.open(url,target)
	}
}

function create_cookie(name,value,days)
{
	if (days)
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function read_cookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function erase_cookie(name)
{
	create_cookie(name,"",-1);
}

function getAbsolutePosition(element) {
    var r = { x: element.offsetLeft, y: element.offsetTop };
    if (element.offsetParent) {
      var tmp = getAbsolutePosition(element.offsetParent);
      r.x += tmp.x;
      r.y += tmp.y;
    }
    return r;
  };

function position(id)
{
	pos = new Object;
	
	function findPosX(obj)
  {
    var curleft = 0;
    if(obj.offsetParent)
        while(1) 
        {
          curleft += obj.offsetLeft;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.x)
        curleft += obj.x;
    return curleft;
  }

  function findPosY(obj)
  {
    var curtop = 0;
    if(obj.offsetParent)
        while(1)
        {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
  }

	pos.x = findPosX(id);
	pos.y = findPosY(id);
	
	return pos;	
}
dropdowns = [];

function list_dropdowns(page)
{
	dropdowns = [];
	
	forms = eval(page+'.forms');
	
	for (f = 0; f < forms.length; f++)
	{
		var elements =  forms[f].elements;
		// looping through all elements on certain form

		for (e = 0; e < elements.length; e++)
		{
		   if (elements[e].type == "select-one")
			{
				dropdowns.push(elements[e]);
			}
		}
	}
}

function hide_dropdowns()
{
	for(dropdown = 0; dropdown<dropdowns.length; dropdown++)
	{
		dropdowns[dropdown].style.visibility = 'hidden';
	}
}

function show_dropdowns()
{
	for(dropdown = 0; dropdown<dropdowns.length; dropdown++)
	{
		dropdowns[dropdown].style.visibility = 'visible';
	}
}

function url_variables()
{
	url = [];
	
	if(window.location.href.toString().indexOf('?') != -1)
	{
		query_string = window.location.href.toString().split('?')[1].split('&');
		
		for(position=0; position<query_string.length; position++)
		{
			variable=query_string[position].split('=');		
			url[variable[0]] = variable[1];
		}
	}
}

function hide(id)
{
	ID(id).style.display='none';
	//ID(id).style.position='absolute';
}

function show(id)
{
	ID(id).style.display='block';
	//ID(id).style.position='relative';
}


function uuid()
{
	now = new Date();
	return now.getFullYear().toString()+now.getMonth().toString()+now.getDate().toString()+now.getHours().toString()+now.getMinutes().toString()+now.getSeconds().toString();
}


function create_drop_down(name,default_value,values,onchange)
{
	if(onchange == undefined)
	{
		onchange = '';
	}
	
	drop_down='<select name="'+name+'" id="'+name+'" size="1" onchange="'+onchange+'">';
	
	for(position=0; position < values.length; position++)
	{
		if(values[position][0] == default_value)
		{
			drop_down += '<option value="'+values[position][0]+'" SELECTED>'+values[position][1]+'</option>';
		}
		else
		{
			drop_down += '<option value="'+values[position][0]+'">'+values[position][1]+'</option>';
		}
	}
	
	drop_down += '</select>';
	
	return drop_down;
}

form_element_styles = [];
form_element_styles_init = false;

function ajax_verify(id,success_action,failure_action)
{
	elements = ID(id).elements;
	
	if(ID('error_message') != undefined)
	{
		ID('error_message').style.display='none';
	}
	
	if(form_element_styles_init == false)
	{		
		for(element = 0; element<ID(id).elements.length; element++)
		{
			name = elements[element].name;
			
			form_element_styles[name] = [];
			//form_element_styles[name]['style'] = elements[element].style;
			form_element_styles[name]['class'] = elements[element].className;
		}
		form_element_styles_init = true;
	}
	
	for(element = 0; element<ID(id).elements.length; element++)
	{
		name = elements[element].name;
		
		if(elements[element].type != 'hidden')
		{
			//ID(name).style = form_element_styles[name]['style'];
			//ID(name).className = form_element_styles[name]['class'];
			
			if(ID(name+'_error_message') != undefined)
			{
				ID(name+'_error_message').style.display='none';
			}
		}
	}
	
	ajax.post('/lib/cf/verify.cfm?ajax=yes',ajax_verify_response,'',ajax.serialize(ID(id)));
	
	function ajax_verify_response(result)
	{
		//ID('debug').innerHTML = result;
		
		errors = result.split('~')[1];
		errors = errors.toString().split(',');
		
		if(errors != '' && errors.length > 0)
		{
			//alert('The following fields have errors:\n\n'+errors);
			for(i=0; i<errors.length; i++)
			{
				//ID(errors[i]).className = 'error';
				
				if(ID(errors[i]+'_error_message') != undefined)
				{
					ID(errors[i]+'_error_message').style.display='inline';
				}
			}
			
			if(ID('error_message') != undefined)
			{
				ID('error_message').style.display='inline';
			}
			
			if(failure_action != undefined)
			{
				//alert('success_action');
				failure_action(errors);
			}
			else
			{
				return false;
			}
			
			
		}
		else if(success_action != undefined)
		{
			//alert('success_action');
			success_action(id);
		}
		else
		{
			//alert('submit');
			ID(id).submit();
		}
	}
}

function rollover(id,new_image)
{
	ID(id).src = new_image;
}

function initcaps(original)
{
	original = original.toLowerCase();
	original = original.split(' ');
	
	new_string =[];
	
	for(s=0; s<original.length; s++)
	{
		new_string.push(original[s].substr(0, 1).toUpperCase() + original[s].substring(1, original[s].length));
	}
	return new_string.join(' ');
}

function debug(info)
{
	ID('debug').innerHTML = info;
}

//function to get random number upto m
function randrange(minVal,maxVal,floatVal)
{ 
  var randVal = minVal+(Math.random()*(maxVal-minVal));
  return typeof floatVal=='undefined'?Math.round(randVal):randVal.toFixed(floatVal);
}

function valid_email(address)
{
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   return reg.test(address);
}

url_variables();