var IE;
var didPngFix = false;
var on_account_details;
var user_chem;

//must be same in start.php
var separation_char1 = "~^sep1^~";
var separation_char2 = "~^sep2^~";

try
{
	if(readCookie("isviewer") == "true") hideEdits();
}catch(e){}

//$(document).ready(mainInit); 

function mainInit()
{
	IE = document.all?true:false
	
	try
	{
		document.onclick = hideList;
	}catch(e){}
	
	fixPngs();
	fixBodyHeight();
	setFlickrMouseOvers();
	
	//$("#list table").tablesorter({sortList: [[0,0]], headers: {6: {sorter: false},7: {sorter: false},8: {sorter: false},9: {sorter: false}}});
}

function flickrOver()
{
	alert(window.event.fromElement);
}

function el(id)
{
	return document.getElementById(id);
}

//would just use :hover in CSS but does not work in IE
function setFlickrMouseOvers()
{
	all_body_elem = getAllChildNodes(el("body"));
	
	for(i=0; i<all_body_elem.length; i++)
	{
		if(all_body_elem[i].className == "click_edit")
		{
			if(!(onDetails2 && (all_body_elem[i].id=="formula_t" || all_body_elem[i].id=="cas_t") && !user_chem))
			{
				all_body_elem[i].onmouseover = function () {this.style.backgroundColor="#FF0"; this.style.cursor="pointer"}
				all_body_elem[i].onmouseout = function () {this.style.backgroundColor="#FFF"; this.style.cursor="auto"}
			}
		}
	}
}

function removeNode(node)
{
	node.parentNode.removeChild(node);
}

function fixBodyHeight()
{
	/* not working right?  was using because Opera bug

	_body = el("body");
	_body.style.height = "0px";
	
	//for quick add page
	try
	{
		fixContainerHeight(_body,el("add_input"));
	}catch(e){}
	
	//for inventory page
	try
	{
		if(el("inventory") != null)
		{
			fixContainerHeight(_body,el("inventory"));
			fixContainerHeight(_body,el("errors"));
			fixContainerHeight(_body,el("list"));
		}
	}catch(e){}
	
	//for myaccountdetails page
	try
	{
		if(el("account_details") != null)
		{
			fixContainerHeight(_body,el("myaccount_top"));
			fixContainerHeight(_body,el("errors"));
			fixContainerHeight(_body,el("account_details"));
		}
	}catch(e){}
	
	//for myaccountlocations page
	try
	{
		if(el("stuff") != null)
		{
			fixContainerHeight(_body,el("myaccount_top"));
			fixContainerHeight(_body,el("errors"));
			fixContainerHeight(_body,el("stuff"));
			fixContainerHeight(_body,el("locations"));
		}
	}catch(e){}
	
	//_body.style.border = "2px solid green";
	
	*/
}

function hideEdits()
{
	theRules = getRules();
	
	for(i=0; i<theRules.length; i++)
	{
		if(theRules[i].selectorText.toLowerCase() == ".edit")
		{
			theRules[i].style.visibility = "hidden";
			theRules[i].style.display = "none";
		}
	}
}

function getRules()
{
	if (document.styleSheets[0].cssRules) return document.styleSheets[0].cssRules;
	else if (document.styleSheets[0].rules)	return document.styleSheets[0].rules;
	return false;
}

function readCookie(name)
{
	cook = readCookie2(name);
	if(cook) cook = cook.replace("+"," ","g");
	return cook;
}

function readCookie2(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 setCookie(c_name,value,expiredays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function GetXmlHttpObject()
{
	var xmlHttp=null;
	try
	{
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
	}
	catch (e)
	{
		// Internet Explorer
		try
		{
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e)
		{
			xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	return xmlHttp;
}

function checkStrings(_form)
{
	_sgood = false;
	
	if((!checkSpaces(_form.login_id, "Login id")) && (!checkSpaces(_form.password, "Password"))) _sgood = true;
	
	return _sgood;
}

function checkSpaces(_field, _name)
{
	if(_field.value.search(" ") != -1)
	{
		alert("" + _name + " cannot have spaces");
		_field.focus();
		_field.select();
		return true;
	}
	return false;
}

function validateInfo(_form)
{
	_igood = true;
	if(checkStrings(_form))
	{
		_message = blanks(_form);
		if(_message != "none")
		{
			alert("Please enter "+_message);
			_igood = false;
		}
		else if(!validEmail(_form.email.value))	_igood = false;
	}
	else _igood = false;
	if(!on_account_details && !passwordsMatch(_form))
	{
		_igood = false;
		alert("passwords do not match");
	}
	if(!on_account_details && _form.password.value == _form.viewer_password.value)
	{
		_igood = false;
		alert("Admin password and Viewer password cannot match");
	}
	
	return _igood;
}

function passwordsMatch(_form)
{
	if(_form.password2 && (_form.password.value != _form.password2.value)) return false;
	else return true;
}

function validEmail(_email)
{
	_vgood = true;
	
	if((_email.indexOf("@") == -1) || (_email.indexOf("@") != _email.lastIndexOf("@"))) _vgood = false;		// only one @
	else if(!(_email.indexOf(".") != -1)) _vgood = false;													// at least one .
	else if(_email.indexOf(".", _email.indexOf("@")) == -1) _vgood = false;									// a . after @
	
	if(!_vgood) alert("Not a valid email address");
	
	return _vgood;
}

function blanks(_form)
{
	if(_form.login_id.value=="") return "a login id";
	else if(_form.password.value=="") return "a password";
	else if(_form.viewer_password.value=="") return "a viewer password";
	else if(_form.organization.value=="") return "an organization";
	else if(_form.street.value=="") return "a street";
	else if(_form.city.value=="") return "a city";
	else if(_form.state.value=="") return "a state";
	else if(_form.zip.value=="") return "a zip";
	else if(_form.contact_name.value=="") return "a contact name";
	else if(_form.phone.value=="") return "a phone number";
	else if(_form.email.value=="") return "an email address";
	else return "none";
}

function setError(error)
{
	if(error != "")
	{
		el("errors").innerHTML = error;
		el("errors").style.display = "inline";
	}
	else el("errors").style.display = "none";
}

function getMouseXY(e)
{
	if (IE)
	{
	    tempX = event.clientX + document.body.scrollLeft;
	    tempY = event.clientY + document.body.scrollTop;
	}
	else
	{
		tempX = e.pageX;
		tempY = e.pageY;
	}
	
	return [tempX,tempY];
}

function getKeyCode(e)
{
	var _keycode;

	if(window.event) _keycode = e.keyCode;			// IE
	else if(e.which) _keycode = e.which;			// Netscape/Firefox/Opera
	return _keycode;
}

function fixPngs()
{
	/* 
	Correctly handle PNG transparency in Win IE 5.5 & 6.
	http://homepage.ntlworld.com/bobosola. Updated 18-Jan-2006.
	*/

	var arVersion = navigator.appVersion.split("MSIE");
	var version = parseFloat(arVersion[1]);

	if ((version >= 5.5) && (document.body.filters)) 
	{
		for(var i=0; i<document.images.length; i++)
		{
			var img = document.images[i];
			var imgName = img.src.toUpperCase();
			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='scale');\"></span>";
				img.outerHTML = strNewHTML;
				i = i-1;
			}
		}
		didPngFix = true;
	}
}

function fixContainerHeight(_container, _content)
{
	_current_height = _container.offsetHeight;
	_height = _content.offsetHeight;
	
	_container.style.height = _current_height + _height + "px";
}

function getStyle(oElm, strCssRule)
{
	var strValue = "";
	if(document.defaultView && document.defaultView.getComputedStyle)
	{
		strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
	}
	else if(oElm.currentStyle)
	{
		strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1)
													{
														return p1.toUpperCase();
													});
		strValue = oElm.currentStyle[strCssRule];
	}
	return strValue;
}

function debug(str)
{
	el("span").innerHTML += str;
}

function debugl(str)
{
	str += "<br>";
	el("span").innerHTML += str;
}

function dean_addEvent(element, type, handler) {
	if (element.addEventListener) element.addEventListener(type, handler, false);
	else
	{
		// assign each event handler a unique ID
		if (!handler.$$guid) handler.$$guid = dean_addEvent.guid++;
		// create a hash table of event types for the element
		if (!element.events) element.events = {};
		// create a hash table of event handlers for each element/event pair
		var handlers = element.events[type];
		if (!handlers) {
			handlers = element.events[type] = {};
			// store the existing event handler (if there is one)
			if (element["on" + type]) {
				handlers[0] = element["on" + type];
			}
		}
		// store the event handler in the hash table
		handlers[handler.$$guid] = handler;
		// assign a global event handler to do all the work
		element["on" + type] = handleEvent;
	}
}

function getAllChildNodes(node)
{
	var node_list = new Array();
	
	if(node.childNodes.length>0)
	{
		for(var i=0; i<node.childNodes.length; i++)
		{
			node_list.push(node.childNodes[i]);
			var temp_node = getAllChildNodes(node.childNodes[i]);
			if(temp_node instanceof Array) node_list = node_list.concat(temp_node);
		}
		return node_list;
	}
}

function addEvent( obj, type, fn )
{
	if (obj.addEventListener)
		obj.addEventListener( type, fn, false );
	else if (obj.attachEvent)
	{
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
	}
}

function removeEvent( obj, type, fn )
{
	if (obj.removeEventListener)
		obj.removeEventListener( type, fn, false );
	else if (obj.detachEvent)
	{
		obj.detachEvent( "on"+type, obj[type+fn] );
		obj[type+fn] = null;
		obj["e"+type+fn] = null;
	}
}

function findPos(obj)
{
	var curleft = curtop = 0;
	if (obj.offsetParent)
	{
		do
		{
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	}
	return [curleft,curtop];
}

/* doesnt work?
function stackTrace(startingPoint)
{
	var stackTraceMessage = "Stack trace: <br>\n";
	var nextCaller = startingPoint;
	while(nextCaller)
	{
		stackTraceMessage += getSignature(nextCaller) + "<br>\n";
		nextCaller = nextCaller.caller;
	}
	stackTraceMessage += "<br>\n\n";
	// display message
	//document.getElementById("output").innerHTML = stackTraceMessage + document.getElementById("output").innerHTML;
	alert(stackTraceMessage);
	
	function getSignature(theFunction)
	{
		var signature = getFunctionName(theFunction);
		signature += "(";
		for(var x=0; x<theFunction.arguments.length; x++)
		{
			// trim long arguments
			var nextArgument = theFunction.arguments[x];
			if(nextArgument.length > 30) nextArgument = nextArgument.substring(0, 30) + "...";
			// apend the next argument to the signature
			signature += "'" + nextArgument + "'";
			// comma separator
			if(x < theFunction.arguments.length - 1) signature += ", ";
		}
		signature += ")";
		return signature;
		
		function getFunctionName(theFunction)
		{
			// mozilla makes it easy. I love mozilla.
			if(theFunction.name)
			{
				return theFunction.name;
			}
			// try to parse the function name from the defintion
			var definition = theFunction.toString();
			var name = definition.substring(definition.indexOf('function') + 8,definition.indexOf('('));
			if(name) return name;
			// sometimes there won't be a function name
			// like for dynamic functions
			return "anonymous";
		} 
	} 
}*/
