// A small collection of re-usable JavaScript functions

var XMLREQUEST_COMPLETE = 4;
var is_MSIE = ( document.all ) ? true : false;

// cross-platform DOM element access
function getEl(el)
{
	if ( document.getElementById )
	{
		return( document.getElementById(el) );
	}
	else if (document.all)
	{
		return( document.all[el] );
	}
	
}

function getStyleProperty(el,styleProp)
{
	//var x = document.getElementById(el);
	if (x.currentStyle)
		var y = x.currentStyle[styleProp];
	else if (window.getComputedStyle)
		var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
	return y;
}

// cross-platform external stylesheet rule grabber
function getStyle(wantedRule)
{
	var targetRule = null;
	wantedRule = wantedRule.toLowerCase();

	if ( document.styleSheets )	
	{
		// the last sheet to define the rule will prevail
		// so backwards is the way to go
		for ( i = (document.styleSheets.length - 1); i>=0; i-- )
		{
			var sheet = document.styleSheets[i];
			var ruleSet = sheet.cssRules ? sheet.cssRules : sheet.rules;
			
			for ( j=0; j<ruleSet.length; j++ )
			{
				ruleSelector = ruleSet[j].selectorText;
				if ( ruleSelector )
				{
					// Safari represents the selectorText in a *really wierd* way...
					// Example: iframe[id"workspace"]
					// Nothing a couple of regular expressions can't fix.
					ruleSelector = ruleSelector.replace(/\.(\w+)\[CLASS~="\1"\]/g,'.$1');
					ruleSelector = ruleSelector.replace(/\[ID"([^"]+)"\]/g,'#$1');
					//document.writeln("<pre>" + ruleSelector + "</pre>");
					if ( ruleSelector.toLowerCase() == wantedRule )
					{
						targetRule = ruleSet[j].style;
						break;
					}
				}
			}
			if ( targetRule != null )
				break;
		}
	}
	return( targetRule );
}

// cross-platform Event listening
function addEvent(el,evType,fn,useCapture)
{
	if ( el.addEventListener )
	{
		el.addEventListener(evType,fn,useCapture);
		return true;
	}
	else if ( el.attachEvent )
	{
		var r = el.attachEvent('on' + evType, fn);
		return r;
	}
	else
	{
		el['on' + evType] = fn;
	}
}

// cross-platform event killer
function stopEventBubble(evt)
{
	if ( !evt )
		var evt = window.event;
	evt.cancelBubble = true;
	if ( evt.stopPropagation )
		evt.stopPropagation();
}

// create an array of all elements of a given class
// credit: Dustin Diaz (www.dustindiaz.com)
function getElementsByClass(searchClass,node,tag)
{
	var classElements = new Array();
	if (node == null)
		node = document;
	if (tag == null)
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++)
	{
		// alert('element ' + i + ' classname = ' + els[i].className);
		if ( pattern.test(els[i].className) )
		{
			classElements[j] = els[i];
			j++;
		}
	}
	return( classElements );
}

// cross-platform document height determination
// Credit: alistapart.com
function getWindowHeight()
{
        var windowHeight = 0;
        if (typeof(window.innerHeight) == 'number') {
                windowHeight = window.innerHeight;
        } else {
                if (document.documentElement && document.documentElement.clientHeight) {
                        windowHeight = document.documentElement.clientHeight;
                } else {
                        if (document.body && document.body.clientHeight) {
                                windowHeight = document.body.clientHeight;
                        }
                }
        }
        return( windowHeight );
}

function getWindowWidth()
{
	return window.innerWidth ? window.innerWidth : document.body.offsetWidth;
}

// centers a popup window based on its height/width vs screen dimensions
function centerPopup(page,name,wide,tall,features)
{
	locinfo = features + ",width=" + wide + ",height=" + tall;
	if (window.screen) {
		posy = ((screen.availHeight - tall) / 2);
		posx = ((screen.availWidth - wide) / 2);
		locinfo += ",left="+posx+",top="+posy;
	}
	popper = window.open(page,name,locinfo);
	if ( popper.opener == null )
		popper.opener = self;
	popper.focus();	
	return( popper );
}

// center an element vertically and horizontally in the view
function centerElement(elementID,container)
{
	el = getEl(elementID);
//	if ( !container )
//	{
		//xpos = Math.floor((getWindowWidth() - el.offsetWidth) / 2);
		//ypos = Math.floor((getWindowHeight() - el.offsetHeight) / 2);
		xpos = Math.floor((getWindowWidth() - 610) / 2);
		ypos = Math.floor((getWindowHeight() - 500) / 2);
//	}
//	else
/*
	{
		parentEl = getEl(container);
		pTop = parentEl.offsetTop;
		pLeft = parentEl.offsetLeft;
		pWidth = parentEl.offsetWidth;
		pHeight = parentEl.offsetHeight;
		elOfsW = el.offsetWidth;
		elOfsH = el.offsetHeight;
		//xpos = Math.floor(pLeft + ((pWidth - el.offsetWidth) / 2));
//		ypos = Math.floor(pTop + ((pHeight - el.offsetHeight) / 2 ));
		xpos = Math.floor(pLeft + ((pWidth - elOfsW) / 2));
		ypos = Math.floor(pTop + ((pHeight - elOfsH) / 2 ));
	}
*/
	el.style.left = xpos + "px";
	el.style.top = ypos + "px";
}

// Correctly handle PNG transparency in Win IE 5 & 6
// Credit: http://homepage.ntlworld.com/bobosola.
function msieAlphaFix() 
{
   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
	     }
      }
}

// populate a SELECT box with an array of data
function populateSelectBox(selBox,data)
{
	selBox.options.length = 0; // clear existing list
	selBox.options.length = data.length;
	for ( i=0; i<data.length; i++ )
	{
		selBox.options[i] = new Option(data[i],data[i]);
	}
	
}

// select a specific option in a SELECT box based on value
function setSelectOption(selBox,value,fuzzy)
{
	selBox.selectedIndex = 0;
	for ( i=0; i<selBox.options.length; i++ )
	{
		if ( selBox.options[i].value == value || ( fuzzy && selBox.options[i].value.indexOf(value) >= 0) )
			selBox.selectedIndex = i;
	}
}

// abstraction for hiding an element
function hideIt(elID)
{
	if ( getEl(elID) )
		(getEl(elID)).style.display = "none";	
}

function showIt(elID)
{
	if ( getEl(elID) )
		(getEl(elID)).style.display = "block";
}

function isVisible(elID)
{
	el = getEl(elID);
	if ( el && el.style.display != "none" )
		return( true );
	else
		return( false );
}

function toggleDisplay(elID)
{
	if ( isVisible(elID) )
		hideIt(elID);
	else
		showIt(elID);	
}

// this is different than the showIt()/hideIt() combo
// since an invisible element will still occupy screen space
function setVisibility(elID,canSee)
{
	if ( getEl(elID) && canSee )
		(getEl(elID)).style.visibility = "visible";
	else
		(getEl(elID)).style.visibility = "hidden";
}

function setOpacity(elID,val)
{
	elem = getEl(elID)
	if ( elem )
	{
		if ( is_MSIE )
			elem.style.filter = "alpha(opacity=" + (Math.floor(val * 100)) + ")";
		else
			elem.style.opacity = val;
	}
}

// credit: quirksmode.org
function getPosition(elID)
{
	var curleft = curtop = 0;
	var obj = getEl(elID);
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

function setPosition(elID,x,y)
{
	elem = getEl(elID);
	if ( elem )
	{
		elem.style.position = "absolute";
		elem.style.left = x + "px";
		elem.style.top = y + "px";
	}
}

// a convenience function for AJAX work
function newXMLHTTPRequest(url,meth,callbackFunc,async)
{ 
	var xmlreq = false; 

	if (window.XMLHttpRequest)
	{ 
		// Non-MS browsers
		xmlreq = new XMLHttpRequest(); 
	}
	else if (window.ActiveXObject)
	{ 
		// MS browsers
		try { 
			xmlreq = new ActiveXObject("Msxml2.XMLHTTP"); 
		} catch (e1) { 
			try { 
				// Try for an older version
				xmlreq = new ActiveXObject("Microsoft.XMLHTTP"); 
			} catch (e2) { 
				// Complete and utter failure.
			}
		}
	} 

	if ( xmlreq )
	{
		meth = ( meth == null ) ? "GET" : meth.toUpperCase();
		async = ( async == null ) ? true : async;
		if ( callbackFunc != null )
		{
			xmlreq.onreadystatechange = function() {
				if ( xmlreq.readyState == XMLREQUEST_COMPLETE )
				{
					if ( xmlreq.status == 200 ) // HTTP status code 200 = OK
					{
						callbackFunc(xmlreq.responseXML,xmlreq.responseText);
					}
					else
					{
						alert("XMLHTTP: "+ xmlreq.status +" "+ xmlreq.statusText  +"]");
					}
				}
	
			};
		}
		
		// set up the request
		// note: this doesn't actually submit the request
		// a call to the xmlreq.send() method is needed for that.
		xmlreq.open(meth,url,async);
		
		if ( meth == "POST" )
			xmlreq.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8"); 
	}

	return( xmlreq );
}

// kinda like an indexOf() for arrays
// returns -1 if the search comes up empty
function inArray(needle,haystack)
{
	found = -1;
	for ( x=0; x<haystack.length; x++ )
	{
		if ( needle == haystack[x] )
		{
			found = x;
			break;
		}
	}
	return( found );
}

// breaks a querystring into key/value pairs
// returns an associative array
function parseQueryString(queryString)
{
	var pairs = queryString.split('&');
	var parsed = [];
	
	for ( var i=0; i<pairs.length; i++ )
	{
		var key = pairs[i].slice(0,pairs[i].indexOf('='));
		var val = pairs[i].slice(pairs[i].indexOf('=')+1,pairs[i].length);
		parsed[key] = decodeURIComponent(val);
	}
	
	return( parsed );
}

// return a random number between 0 and max with an option to force ints
function getRandom(max,forceInt)
{
	var num;

	if ( !max )
		max = 10;
	
	if ( forceInt )
		num = Math.floor( Math.random()*max );
	else
		num = Math.random() * max;

	return( num );
}

// simple debugging
function debug(message)
{
	// alert('DEBUG: ' + message);
}



function isUrl(s) 
{
return true;

//	var last = s.lastIndexOf('/');
//	s = s.substring(0, last +1 );

	var RegExp = /^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/;
//	var RegExp = /^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/;
	var RegExpIP = /^((http|https|ftp):\/\/)(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/;


	if(RegExp.test(s) || RegExpIP.test(s)){
		return true;
	}else{
		return false;
	} 

}
//function to check valid email address
function isValidEmail(email)
{
return true;
//	if ( !email.match(/[a-z0-9_\-\.\+]+@[a-z0-9][a-z0-9\.\-]{0,63}\.[a-z]{2,4}[\\?*]{1,}|([]{0})$/i) || email.match(/@{2,}/))
	var last = email.indexOf('?');
	if ( last > 0 )
		email = email.substring(0, last );


	if ( !email.match(/[a-z0-9_\-\.\+]+@[a-z0-9][a-z0-9\.\-]{0,63}\.[a-z]{2,4}$/i) || email.match(/@{2,}/))
		return false;
	else
		return true;

}
function addslashes(str) 
{
	str=str.replace(/\'/g,'\\\'');
//	str=str.replace(/\"/g,'\\"');
//	str=str.replace(/\\/g,'\\\\');
//	str=str.replace(/\0/g,'\\0');
	return str;
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
function intval( mixed_var, base ) {
	var tmp;
 
	tmp = parseInt(mixed_var);
	if ( !isNaN(tmp) )
		return tmp;
	else
		return 0;
 
 
}
function openDemo()
{
	var uLang = getEl('userLanguage').value;
	var demoLocation = "/OS4/resources/esw/demo/" + uLang + "/index.html";
//	var demoLocation = "/OS4/resources/esw/demo/en/index_en.html";

	loc = demoLocation;
	poptest = centerPopup(loc,"Demo",800,480,"resizable=no,location=no,toolbar=no,scrollbars=no,status=no");

}
function stripslashes(str) {
	str=str.replace(/\\'/g,'\'');
	str=str.replace(/\\"/g,'"');
	str=str.replace(/\\\\/g,'\\');
	str=str.replace(/\\0/g,'\0');
	return str;
}
function setPrTitle(id)
{
        getEl('tTitle').innerHTML = "ID: " + id;

}


