//LAST EDIT DATE: December 14th 2004 by Yahav (added global onkeypress method)
//first of all, announce we are included:
var _COMMON_V100_INC_=1
//assign onload event:
window.onload=rb_onload;	//RelateBase onload

//declare onload commands:
var m_onloadCmds=new Array(); //private - use only public functions to alter it!
var m_onkeypressCmds=new Array(); //private - use only public functions to alter it!
function AddOnloadCommand(strCommand){
	//---- version 1.0, by Yahav, last edit 2004-09-24
	//add to array of commands:
	m_onloadCmds[m_onloadCmds.length] = strCommand;
}
function AddOnkeypressCommand(strCommand){
	//---- version 1.0, by Yahav, last edit 2004-12-14
	//add to array of commands:
	m_onkeypressCmds[m_onkeypressCmds.length] = strCommand;
}
function rb_onload(){
	//---- version 1.0, by Yahav, last edit 2004-09-24
	//simply execute commands:
	for (var i=0; i<m_onloadCmds.length; i++){
		try{
			eval(m_onloadCmds[i]);
		}
		catch (e){
			//alert("warning: failed to initialize page. command failed: \n"+m_onloadCmds[i]+"\nerror: \n"+e.description+"\nplease report.");
			return false;
		}
	}
	if (m_onkeypressCmds.length > 0){
		document.onkeypress=function rb_keypress(){
			for (var j=0; j<m_onkeypressCmds.length; j++)
			{
				try
				{
					eval(m_onkeypressCmds[j]);
				}
				catch (e)
				{
				}
			}
		}
	}
}
//catch unload event:
window.onbeforeunload=function rb_onBeforeUnload(){

	//---- version 1.0, by Yahav, last edit 2004-10-29

	

	//store position in cookie only if we have opener window:

	if ((window.opener)&&(window.name))

	{

		//get window position:

		var H=document.body.offsetHeight;

		var W=document.body.offsetWidth;

		var L=window.screenLeft;

		var T=window.screenTop;

		var strCookie=window.name+","+H+","+W+","+L+","+T;

		AddPositionCookie(strCookie);

	}

}



function AddPositionCookie(strToAdd)

{

	//---- version 1.0, by Yahav, last edit 2004-10-29

	

	var MAX_POSITIONS=30;

	

	//verify correct input: (5 elements comma seperated)

	var arrParts=strToAdd.split(",");

	if (arrParts.length != 5)

		return;

	//get current positions:

	var arrCurPos=GetPositionsArray();

	

	//check if exceeded maximum length:

	if ((typeof  arrCurPos[arrParts[0]] == "undefined")&&(sizeof(arrCurPos) >= MAX_POSITIONS))

		return;

	

	//apply cookie and store:

	arrCurPos[arrParts[0]] = strToAdd;

	SetCookie("wPositions", Full_Join(arrCurPos, "|"));

}



function GetPositionCookie(strWindowName)

{

	//---- version 1.0, by Yahav, last edit 2004-10-29

	if (strWindowName == "")

		return "";

	

	//get current positions:

	var arrCurPos=GetPositionsArray();

	

	return arrCurPos[strWindowName];

}



/* GetPositionsArray:  get array of window positions. each element key is window name and its value is its last H,W,L,T position. */

function GetPositionsArray()

{

	//---- version 1.0, by Yahav, last edit 2004-10-29

	var arrPositions=new Array();

	var strPositions=gCookie("wPositions");

	//maybe no value?

	if ((!strPositions)||(strPositions == ""))

		return arrPositions;

	var arrTmp=strPositions.split("|");

	for (var i=0; i<arrTmp.length; i++)

	{

		if (arrTmp[i].length > 0)

		{

			var arrParts=arrTmp[i].split(",");

			//must have name,H,W,L,T parts!

			if  (arrParts.length == 5)

			{

				arrPositions[arrParts[0]] = arrTmp[i];

			}

		}

	}

	return arrPositions;

}



function Partial_Join(arr, index, seperator)

{

	//---- version 1.0, by Yahav, last edit 2004-10-29

	var strResult="";

	for (var i=index; i<arr.length; i++)

	{

		strResult += arr[i];

		if (i < (arr.length-1))

			strResult += seperator;

	}

	return strResult;

}



function Full_Join(arr, seperator)

{

	//---- version 1.0, by Yahav, last edit 2004-10-29

	var strResult="";

	

	for (var key in arr)

		strResult += arr[key]+seperator;

	

	if (strResult.length > 0)

		strResult = strResult.substr(0, strResult.length-1);

	

	return strResult;

}



function SetCookie(strCookieName, strCookieValue, strExpireDate)

{

	if((strExpireDate == "")||(typeof strExpireDate == "undefined"))

	{

		var nw = new Date();

		nw.setMonth(nw.getMonth() + 6);

		strExpireDate = nw.toGMTString();

	}

	var strPath="/";

	document.cookie = strCookieName+"="+escape(strCookieValue)+"; expires="+strExpireDate+"; path="+strPath;

}



/* PrintObj: prints all given object's properties */

function PrintObj(_ob)

{

	//---- version 1.0, by Yahav, last edit 2004-10-15

	var m="", j;

	for (j in _ob)

		m += j+": "+_ob[j]+", ";

	m = m.substr(0, m.length-2);

	alert(m);

}


/* GetSourceElement: find the source element of given event. */
function GetSourceElement(event)
{
	//---- version 1.0, by Yahav, last edit 2005-01-10
	if ((typeof event == "undefined") || (!event))
		event = window.event;
	
	if (typeof event.srcElement != "undefined")
		return event.srcElement;
	
	var node = event.target;
	while (node.nodeType != node.ELEMENT_NODE)
		node = node.parentNode;
	
	return node;
}



/**** ===================== SECTION 0 ================================



cookie and query string functions, also see the class for reading the query string at the bottom



****/



//get

function gCookie(ck){var cVal = document.cookie;var cStart = cVal.indexOf(" " + ck + "=");if(cStart==-1){ cStart = cVal.indexOf(ck + "="); }if(cStart == -1){	cVal = null;}else{cStart = cVal.indexOf("=", cStart) + 1; var cEnd = cVal.indexOf(';', cStart); if(cEnd==-1){	cEnd=cVal.length;	} cVal = unescape(cVal.substring(cStart,cEnd)); }	return cVal; }

//set -- default path works on the site root

var testmode=0;

function sCookie(cName,cVal,cPath,cExp){cVal = escape(cVal); if(cExp=='' || typeof cExp == 'undefined'){var nw = new Date();nw.setMonth(nw.getMonth() + 6);var expiry= ";expires="+nw.toGMTString();}else{var expiry='';}if(typeof cPath == 'undefined'){var path=';Path=/';}else{var path = ";Path="+cPath;}if(testmode==1){alert(cName + "="+cVal + expiry+path);}document.cookie = cName + "="+cVal + expiry+path;}



//ugh...

function gagMe(cName,cVal,cPath,cExp){ cVal = escape(cVal); if(cExp=='' || typeof cExp == 'undefined'){var nw = new Date();nw.setMonth(nw.getMonth() + 6);var expiry= ";expires="+nw.toGMTString();}else{var expiry='';}if(typeof cPath == 'undefined'){var path=';Path=/';}else{var path = ";Path="+cPath;}if(testmode==1){alert(cName + "="+cVal + expiry+path);}document.cookie = cName + "="+cVal + expiry+path;}



//must be declared .=&#046;   ^=&#136;   ==&#061;



var obsep1='.'; var valsep1='='; var decsep1='^';



function arr_enc(x){

   //encodes a string for .^=

   if(typeof x!='string')return x; x=x.replace('&','&amp;'); x=x.replace(obsep1,'&#046;'); x=x.replace(valsep1,'&#061;'); x=x.replace(decsep1,'&#136;'); return x;

} //---------- end arr_enc() -------------



function arr_dec(x){

   //decodes a string for .^=

   if(typeof x!='string')return x; x=x.replace('&#046;', obsep1); x=x.replace('&#061;', valsep1); x=x.replace('&#136;', decsep1); x=x.replace('&amp;','&'); return x;

} //---------- end arr_dec() -------------



function arr_str1(arr){

   //converts array to string for cookies

   var str='';

   for(var x in arr){ if(typeof arr[x]=='object'){ for(var y in arr[x]){            str+=arr_enc(x)+obsep1+arr_enc(y)+valsep1+arr_enc(arr[x][y])+decsep1; }}else if(typeof arr[x]=='number' || typeof arr[x]=='string'){ str+=arr_enc(x)+valsep1+arr_enc(arr[x])+decsep1; }}

   str=str.substr(0,str.length-1);   return str;

} //---------- end arr_str1() -------------



function str1_arr(str){

	//converts cookie string into array

	var obsep1='.'; var valsep1='='; var decsep1='^';

	var arr=new Array();

	var barr=str.split(decsep1);

	var buffer='';

	for(var x in barr){

		var a=barr[x].indexOf('.');

		var b=barr[x].indexOf('=');

		if(a!=-1 && a<b){

			y=barr[x].split('=');

			z=y[0].split('.');

			if(z.length>2)alert('Error: too many sub-indexes! (2 max)');

			if(z[0]!=buffer){

				buffer=z[0];

				arr[arr_dec(z[0])]=new Array();

			}

			arr[arr_dec(z[0])][arr_dec(z[1])]=arr_dec(y[1]);

		}else{

			//string

			y=barr[x].split('=');

			arr[arr_dec(y[0])]=arr_dec(y[1]);

		}

	}



	return arr;

} //---------- end str1_arr() -------------



/**** ===================== SECTION 1 ================================



navigation functions: these functions deal with adding values to the query string, modifying it, and naming windows



****/



//----------------------- get components of current window in an array



function get_win(v){

	//return.0 = level, return.1 = window group name

	if(typeof v=='undefined'){var v=self.name;}

	if(self.name==''){alert('Error: no self.name declared!');return false;}

	var s=new Array();

	s[0]=v.substr(0,v.indexOf('_'));

	s[0]=parseInt(s[0].replace('l',''));  //this is the window level

	s[1]=v.substr(v.indexOf('_')+1,v.length-1-v.indexOf('_'));

	return s;

}







function newWindow(myhref,wName,params){

	var strPosCookie=GetPositionCookie(wName);

	if ((typeof strPosCookie != "undefined")&&(strPosCookie.length > 0))

	{

		//name,H,W,L,T

		var arrPos=strPosCookie.split(",");

		if (arrPos.length == 5)

		{

			//yahav, I added these otherwise the page drifts. Unfortunately these postions aren't from the corner

			arrPos[1]-=23;

			arrPos[2]-=4;

			arrPos[3]-=4;

			arrPos[4]-=73;

			params = arrPos[2]+","+arrPos[1]+","+arrPos[3]+","+arrPos[4];

		}

	}

	if(typeof params != "undefined"){

		var reg=/^[-0-9]+,[-0-9]+$/;

		var reg2=/^[-0-9]+,[-0-9]+,[-0-9]+,[-0-9]+$/;

		if(params.match(reg)){

			var x = params.split(',');

			params='width='+x[0]+',height='+x[1]+',scrollbars,menubar,status,resizable';

		}

		else

		{

			if(params.match(reg2)){

				var x = params.split(',');

				params='width='+x[0]+',height='+x[1]+',left='+x[2]+',top='+x[3]+',scrollbars,menubar,status,resizable';

			}

		}

	}

	eval(wName+"=window.open('',wName"+(params?",params":"")+");");

	//eval(wName+"=window.open(myhref,wName"+(params?",params":"")+");");

	eval(wName+".document.write('<div style=font-family:Verdana;font-size:11px;height:100;padding:15;>Loading, please wait...</div>');");

	eval(wName+".document.location = myhref;");

	eval(wName+".window.focus();");

	return false;

}



//this is the old version



function NewWindow(mypage, myname, w, h, scroll) {

	var winl = (screen.width - w)- 200;

	var wint = (screen.height - h) - 100;

	winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+',resizable'

	win = window.open(mypage, myname, winprops)

	if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }

}



function check_component(){

	//this looks for a component for multi-process pages, to get the right page

	x=0;

	if(typeof doc.form2!='undefined'){

		if(typeof doc.form2.component!='undefined'){

			x=doc.form2.component.value;

		}else if(typeof doc.form2.componentID!='undefined'){

			x=doc.form2.componentID.value;

		}

	}

	helpWindow=newWindow('/client/help/help_v200.php?src='+escape(window.location)+(x?'&component='+x:''),'l2_helpv200','width=600,height=450,status,resizable,scrollbars');

}







function ckit(){

	alert(typeof d);

}







function sizeof(x){//this gets count of elements in an array

	var f=0;for(var g in x){f++;}return f;}



function in_array(needle,haystack){//about the same as the function in PHP

	strCase=1; //insensitive (2=sensitive)

	loc=10; //value (11=key)

	for(i=2;i<arguments.length;i++){

		arguments[i]=='sensitive' || arguments[i]==2?strCase=2:'';

		arguments[i]==11 || arguments[i]=='key'?loc=11:'';

	}

	//find the value

	for(j in haystack){

		if(strCase==1){

			if(loc==10 && haystack[j].toLowerCase()==needle.toLowerCase()){

				return true;

			}else if(loc==11 && j.toLowerCase()==needle.toLowerCase()){

				return true;

			}

		}else{

			if((loc==10 && haystack[j]==needle) || (loc==11 && j==needle)){

				return true;

			}

		}

	}

	return false;

}







function delete_element(array, n){//removes an element from an array by key value

  //delete the nth element of array

  var length = array.length;

  if (n >= length || n<0)

    return;

  for (var i=n; i<length-1; i++)

    array[i] = array[i+1];

  array.length--;

}







//--------- used only in customers.php  in rfm, probably can be merged



function winControl(href,winGroup,level,params){

	//last three values are optional

	winLevel='l'+(level!=''?level:'');

	winName=winLevel+(winLoc[winGroup][level]!=''?'_':'')+winLoc[winGroup][level];

	eval( "newWindow(href+(href.lastIndexOf('?')>0?'&':'?')+'nullWin='+winName,winName"+(params?", params":'')+");" );

}



//note: global variable!

var bugReportSubmitted=false;

var arrAppendedItems=new Array();



function sub_bugrpt(keyFormName){

	//---- version 1.0, by Yahav, last edit 2004-07-28

	//note: old function can be found in common_i1_v100_bk209.js

	//modified: 28/07/2004 by Yahav (javateam)

	//reason: fixed object allocation, fixed form losing action and target. FUNCTION IS NOW OK.

	//addition: modified so that bug report opens in custom window and after submission removes the additional fields.	

	

	//already submitted for this page?

	if (bugReportSubmitted == true)

	{

		//the form has already been appended

		alert('bug report was already submitted');

		return false;

	}



	//check if the form name given:

	switch(true){

		case (typeof keyFormName=='undefined'):

			keyFormName='form1'; break;

		case (keyFormName ==''):

			keyFormName='form1'; break;

	}

	

	//make pointer to the form object so we can append fields:

	var objForm=eval("document."+keyFormName);

	

	if (typeof objForm == 'undefined')

	{

		//need to create it...

		objForm=document.createElement("form");

		objForm.name = keyFormName;

		objForm.action = "";

		objForm.target = "";

		objForm.method = "Get";

		//append to main body:

		document.body.appendChild(objForm);

	}

	

	//store original:

	var strOldAction, strOldTarget, strOldMethod;

	strOldAction = objForm.action;

	strOldTarget = objForm.target;

	strOldMethod = objForm.method;

	

	//make the window custom:

	newWindow('/client/admin/br_0.9/index.php', 'l1_bugreports','width=540,height=350,menubar,resizable,scrollbars,status');

	

	objForm.action = "/client/admin/br_0.9/index.php";

	objForm.target = "l1_bugreports";

	objForm.method = "post";

	

	//append fields:

	/** note all get _br_ prepended. **/

	(typeof scriptID!='undefined')?

		objForm.appendChild(CreateHiddenField("br0001", "_br_scriptID", scriptID)):'';

	(typeof scriptVersion!='undefined')?

		objForm.appendChild(CreateHiddenField("br0002", "_br_scriptVersion", scriptVersion)):'';

	(typeof fileType!='undefined')?

		objForm.appendChild(CreateHiddenField("br0003", "_br_fileType", fileType)):'';

	(typeof keyFormName!='undefined')?

		objForm.appendChild(CreateHiddenField("br0004", "_br_keyFormName", keyFormName)):'';

	(typeof __FILE__!='undefined')?

		objForm.appendChild(CreateHiddenField("br0005", "_br___FILE__", __FILE__)):'';

	(typeof PHP_SELF!='undefined')?

		objForm.appendChild(CreateHiddenField("br0006", "_br_PHP_SELF", PHP_SELF)):'';

	(typeof GLOBALS!='undefined')?

		objForm.appendChild(CreateHiddenField("br0007", "_br_GLOBALS", GLOBALS)):'';

	

	//submit:

	objForm.submit();

	

	//restore old values and remove fields:

	objForm.action = strOldAction;

	objForm.target = strOldTarget;

	objForm.method = strOldMethod;

	for (i=0; i<arrAppendedItems.length; i++)

		objForm.removeChild(arrAppendedItems[i]);

	

	bugReportSubmitted = true;

	return false;

}







function CreateHiddenField(strID, strName, strValue)



{

	//---- version 1.0, by Yahav, last edit 2004-07-27

	//creates and returns new input tag object

	var objInput=document.createElement("input");

	objInput.type = "hidden";

	objInput.id = strID;

	objInput.name = strName;

	objInput.value = strValue;

	//store for later use...

	arrAppendedItems[arrAppendedItems.length] = objInput;

	return objInput;

}


function show_ctrlSection(){
	document.getElementById("ctrlSection").style.display=op[document.getElementById("ctrlSection").style.display];
}

function dataobjects_config(grp,col,hlg){

	//this passes information on the currently selected item in the group

	if(typeof hlg=='undefined'){var hlg=1;}

	var append='';

	if(typeof sel_id[hlg].id!=='undefined'){

		//controls re-select of highlight

		append='&ogrp['+grp+'][select]='+sel_id[hlg].id;

	}

	//---------- version 1.0 by Sam, 2004-09-25 ------------------

	//-- Yahav please review when you have a chance --------------

	document.selection.empty();

	if(typeof ogrp[grp]=='undefined')return;

	gotMatch=false;

	//split existing sort by ','

	ogrp[grp]['sort']=""+ogrp[grp]['sort'];

	cols=ogrp[grp]['sort'].split(',');

	if( event.shiftKey ){

		for(var x in cols){

			cols[x]=parseInt(cols[x]);

			if(Math.abs(cols[x])==col)gotMatch=true;

		}

		if(gotMatch){

			if( Math.abs(cols[0])==col ){

				//change the global var and return the new string

				//change x,y,z => -x,y,z *OR* -x,y,z => x,y,z

				cols[0]=cols[0]*-1;

				var x=cols.join(',');

				ogrp[grp]['sort']=x;

				return x+""+append;

			}else{

				//if y you'd get x,y,z => x,z

				//put it on the front, i.e.:  x,y,z => y,x,z

				var buffer=new Array();

				//remove it from the string ( y for example)

				buffer[0]=col;

				bkey=1;

				for(var x in cols){

					if(Math.abs(cols[x])!==col){buffer[bkey]=cols[x];bkey++;}

					if(bkey>2)break;

				}

				var x=buffer.join(',');

				ogrp[grp]['sort']=x;

				return x+""+append;

			}

		}else{

			//remove the last element: x,y,z => y,z

			//add the new element: w,y,z

			var x=col;

			if(typeof cols[0]!='undefined')x+=','+cols[0];

			if(typeof cols[1]!='undefined')x+=','+cols[1];

			ogrp[grp]['sort']=x;

			return x+""+append;

		}

	}

	//non-shift key

	var x=parseInt(ogrp[grp]['sort']);

	if(Math.abs(x)==col){

		ogrp[grp]['sort']=(x*-1);

		return (x*-1)+""+append;

	}

	//otherwise return col

	ogrp[grp]['sort']=col;

	return col+""+append;

}

