/*
	Copyright (C) 2004-2007 BITPlan GmbH
                                          
	Pater-Delp-Str. 1                       
	D-47877 Willich-Schiefbahn              
                                          
	Fon. +49 1805 BITPlan                   
	   = +49 1805 2487526                   
  Fax. +49 2154 811 481                   

	$Header: /usr/cvsroot/Source/PHP/com/bitplan/phpbobase/Common.js,v 1.16 2008/12/13 07:11:39 wf Exp $
	$Id: Common.js,v 1.16 2008/12/13 07:11:39 wf Exp $
	$Log: Common.js,v $
	Revision 1.16  2008/12/13 07:11:39  wf
	editing improved

	Revision 1.15  2008/07/20 14:22:35  msf
	search with enter

	Revision 1.14  2008/06/13 12:50:04  msf
	changed

	Revision 1.13  2007/12/10 15:17:41  msf
	changed

	Revision 1.12  2007/12/02 18:26:09  wf
	linkme

	Revision 1.11  2007/11/12 15:29:11  msf
	r e a d o n l y

	Revision 1.10  2007/05/05 14:56:20  msf
	n u l l v a l u e d i s p l a y

	Revision 1.9  2006/08/21 17:17:00  wf
	improved for HTMLEditOption

	Revision 1.8  2006/08/20 15:09:21  wf
	improved

	Revision 1.7  2006/08/17 18:31:44  wf
	HTMLTablePrinter support

	Revision 1.6  2006/02/04 17:50:43  wf
	for multi selection

	Revision 1.5  2005/09/04 17:33:59  wf
	regenerated

	Revision 1.4  2005/06/28 11:42:29  wf
	remember old option value
	
	Revision 1.3  2005/05/03 13:35:09  wf
	fix editize handling
	
	Revision 1.2  2005/03/13 08:58:31  wf
	for editize
	
	Revision 1.1  2005/03/07 14:17:18  wf
	Javascript for fireaction
	

*/
// global variable for default button
var phpbobase_defaultButtonId;
// shall the enter event handler be overriden?
var phpbobase_handleEnterEvent	= true;

// get the navigator type
function getnavigator() {
  if (navigator.appName == "Netscape") return "ns";
  if (navigator.appName == "Microsoft Internet Explorer") return "ie";
  return "other";
} // getnavigator

// print the Window
function printWindow(){
  browserVersion = parseInt(navigator.appVersion)
  if (browserVersion >= 4) window.print()
} // printWindow

// find the main uml2php Form
function getuml2phpForm(doc) {
  return doc.forms["uml2php_trigger_form"];
} // getuml2phpForm 

// body loaded event 
function body_loaded(win) {
  if (win!=null) {
    form=getuml2phpForm(win.document);
    if (form) {
    	init_form(form);
    }	
  }
} // body_loaded

// fire the action fo the default button if enter is pressed
function fireActionOnEnter(fieldId,e)
{
	if (phpbobase_handleEnterEvent) {
		var keycode;
		var myEvent;
		if (window.event) myEvent = window.event; //IE
		else if (e) myEvent = e; //firefox
		else return true;
		
		keycode = myEvent.keyCode;
		if (keycode == 13) {
			var myfield	= document.getElementById(fieldId);
			// only eval onclick action if field is given
			if (myfield) {
				myfield.onclick(e);
			} // if
			// myfield.form.submit();
			return false;
		} else {
			return true;
		} // if
	} else {
		return true;
	} // if
} // fireActionOnEnter

// fireaction - central handler for all events
function fireaction(form,functionid,bokey,callMethod,parameter,framemode) { 
  try {
  	var theform=document.forms[form];
    theform.__form.value       = form;
    theform.__functionid.value = functionid;
    theform.__bokey.value      = bokey;
    theform.__callMethod.value = callMethod;
    theform.__parameter.value  = parameter;
    theform.__framemode.value  = framemode;
    // editize handling ...
    try {
	    for (var i = 0; i < __editizeArray.length; i++)
	 	  {
				document.applets[__editizeArray[i][0]].writeToField();
			}	
	  } catch(e1) {
	  	// ignore invalid access to __editizeArray
	  	if (!e1.name=="ReferenceError")
	  		// rethrow if necessary
	  		throw (e1);
		}	
    theform.submit();
  } catch(e) {
    alert(e+" "+form+":"+functionid+":"+bokey+":"+callMethod);
  } // try/catch
} // fireaction

//--------------------------------------------------------------------------------------------------------
function toggleVisibility(keyID, cID,tag) {
//--------------------------------------------------------------------------------------------------------
	/*
	Display Style 'none' => invisible
	Display Style '' => visible 
	*/
	var tTR = document.getElementById(cID+tag+keyID);
	for (i=0;; i++) {
		if (keyID == i) continue;
		var tTRTemp = document.getElementById(cID+tag+i);
		if (tTRTemp != null) {
			if (tTRTemp.style.display != 'none') {
				tTRTemp.style.display = 'none';
			} // 
		} else break;
	} // for 
	
	if (tTR != null) {
		if (tTR.style.display == 'none') {
			tTR.style.display='';
		} else {
			tTR.style.display = 'none';
		} //
	} // if
} // toggleVisibility
//--------------------------------------------------------------------------------------------------------

//--------------------------------------------------------------------------------------------------------
function toggleMenuVisibility(keyID, cID) {
//--------------------------------------------------------------------------------------------------------
	toggleVisibility(keyID,cID,'menu');
} // toggleMenuVisibility
/*
Script by RoBorg
RoBorg@geniusbug.com
http://javascript.geniusbug.com
Please do not remove or edit this message
*/
var dynselect = new dynamicSelect();
function dynamicSelect() {
  this.selects = new Array();
  //addSelect
  this.addSelect = function(name)	{
    this.selects[name] = new selectObj();
  } //addSelect
  //updateOptions
  this.updateOptions = function(selectionname,source, target) {
    var form = getuml2phpForm(document);
    if (!form) {
    	alert("form not found for updateOptions:"+selectionname);
    	return;
    }
    var target = form.elements[target];
    oldvalue = getSelectedValue(target);
    value = getSelectedValue(source);
    while(target.options.length) target.options[0]=null;
    if(!this.selects[selectionname].options[value]) {
      //alert("Invalid selection:"+value); //For debugging while you set it up
      return;
    } // if
    var data = this.selects[selectionname].options[value].options;
    var newIndex=0;
    for(var x=0; x<data.length; x++) {
    	if (data[x].value==oldvalue) {
    		newIndex=x;
    	}	
      try {
        target.options[x]=data[x];
      } catch(e) {
        target.add(data[x], null);
      }
    } // for
    target.selectedIndex = newIndex;
  } // updateOptions
} // dynamic select			
//This object is used to store available options in a non-dynamic menu.

function selectObj() {
  this.options = new Array();
  
  this.addOption = function(value)
  {
    this.options[value] = new optionObj();
  }
} // selectObj

//This object stores a list of Option objects to be added to a dynamic select box.

function optionObj() {
  this.options = new Array();
  
  this.createOption = function(name, value)
  {
    this.options[this.options.length] = new Option(name, value);
  }
}	// optionObj

// hide or show a control
function show_control(id,show) {
  var object;
  try {
    object = document.getElementById(id);
    if (object ==null) {
       var objectlist= document.getElementsByName(id);
       if (objectlist.length==1) object=objectlist[0];
    }
    if (object!=null) {
		// enabling by hide and show      
    	if (show) 
    		object.style.display = '';
    	else
    		object.style.display = 'none';
    } // if object
  } catch(e) {
      alert(e+" "+id);  
  } // try/catch      
}

// generic enabler for controls			
var defaultEnableColor="#FFFFFF";			
var defaultDisableColor="#B0B0B0";			
function enable_control(id, enable,enableColor,disableColor) {			
  var object;
  try {
    object = document.getElementById(id);
    if (object ==null) {
       var objectlist= document.getElementsByName(id);
       if (objectlist.length==1) object=objectlist[0];
    }
    if (object!=null) {
		// enabling with browser features
      if (getnavigator()=="ns") {
        if (enable) {
          object.style.backgroundColor = enableColor;
        } else {
          object.style.backgroundColor = disableColor;
        }
      }
      object.disabled = !enable;
    } // if object
  } catch(e) {
      alert(e+" "+id);  
  } // try/catch      
} // enable_control

// get whether a control is disabled
function isDisabledControl(control) {
  try {
		if (control!=null) {
			// get control state
			return control.disabled;
		} // if control
  } catch(e) {
      alert(e+" "+control.id);  
  } // try/catch      
} // isDisabledControl
  
// get the index for a selected radio button
function getSelectedRadio(buttonGroup) {
  // returns the array number of the selected radio button or -1 if no button is selected
  if (buttonGroup[0]) { // if the button group is an array (one button is not an array)
    for (var i=buttonGroup.length-1; i>=0;i--) {
      if (buttonGroup[i].checked) {
        return i
      }
    }
  } else {
    if (buttonGroup.checked) { return 0; } // if the one button is checked, return zero
  }
  // if we get to this point, no radio button is selected
  return -1;
} // getSelectedRadio
// set the index for a selected radio button
function setSelectedRadio(buttonGroup,value) {
  // set the selected radio button 
  if (buttonGroup[0]) { // if the button group is an array (one button is not an array)
    for (var i=buttonGroup.length-1; i>=0;i--) {
      if (buttonGroup[i].value==value) {
        buttonGroup[i].checked=true;
      }
    }
  }
} // Ends the "setSelectedRadio" function

// find out the selected value no matter
// what type of control (radiobutton, selection list or other)
// returns -1 if no selection
function getSelectedValue(control)
{
  var s_value=-1; 
  // radiobutton first
  if (control.length && !control.type) {
    var radio = getSelectedRadio(control);
    if (radio>=0)
      s_value=control[radio].value;      
  } else {
    try { // any normal control
      s_value = control.value; 
    } catch(e1) { // last try - selection list			
      try {
        s_value = control.options[control.selectedIndex].value;
      } catch(e1) {
        alert("wrong control for getSelectedValue:");
      }
    }
  }
  return s_value;
} // getSelectedValue
/*
Yet another hack. It is derived from http://www.tek-tips.com/userinfo.cfm?member=Kendel
*/
function ChangeComboSelected(myCombo,textval)
{
    for(var i=0; i<myCombo.length; i++)
    {
        if(myCombo.options[i].value==textval)
        {
            myCombo.options[i].selected=true;
        }
    }
}
/*
by BITPlan, RB
*/
function ChangeSelected(myElem,textval)
{
  try {
  	if (myElem[0]){
  		if (myElem[0].type=="radio"){
  			setSelectedRadio (myElem,textval);
  		}
  		else{
  			ChangeComboSelected (myElem,textval);
  		}
  	}
  } catch(e1) {			
  	alert("wrong elementtype for ChangeSelected:");			
  }
} // ChangeSelected

/**
 * Checks/unchecks all Business Objects
 *
 * @param   string   the form name
 * @param   boolean  whether to check or to uncheck the element
 *
 * @return  boolean  always true
 */
function setCheckboxes(the_form, do_check)
{
		if (document != null) {
			var dom = document;
			var forms = document.forms;
			var form = forms[the_form];
			var els = form.elements;
			var elts = els['selected_row'];
			var elts2 = els['selected_row[]'];
			var len = elts.length;
			var type = typeof(elts.length);
			var elts_cnt  = (type != 'undefined')
										? elts.length
										: 0;
	
			if (elts_cnt) {
					for (var i = 0; i < elts_cnt; i++) {
							elts[i].checked = do_check;
					} // end for
			} else {
					elts.checked        = do_check;
			} // end if... else
		}

    return false;
} // end of the 'setCheckboxes()' function

function setCheckboxesRange(the_form, do_check, basename, min, max)
{
    for (var i = min; i < max; i++) {
        if (typeof(document.forms[the_form].elements[basename + i]) != 'undefined') {
            document.forms[the_form].elements[basename + i].checked = do_check;
        }
        if (typeof(document.forms[the_form].elements[basename + i + 'r']) != 'undefined') {
            document.forms[the_form].elements[basename + i + 'r'].checked = do_check;
        }
    }

    return true;
} // end of the 'setCheckboxesRange()' function

// cross-browser object reference fetcher
function __getObj(id) {
	if (document.getElementById) { // DOM-compliant browsers (MSIE5+, NSN6+, O5+)
		return document.getElementById(id);
	} else if (document.all) { // MSIE4
		return document.all[id];
	} else { // NSN4
		for (var i = 0; i < document.forms.length; i++)
		{
			if (document.forms[i].elements[id])
				return document.forms[i].elements[id];
		}
		return eval("document."+id); // If all else fails...
	}
}

// encode for html
function htmlEncode(s) {
  return s
  .replace(/&/g, "&amp;")
  .replace(/\</g, "&lt;")
  .replace(/\>/g, "&gt;")
  .replace(/\"/g, "&quot;");
}

// decode for html
function htmlDecode(s) {
  return s.replace(/&lt;/g, "<")
    .replace(/&gt;/g, ">")
    .replace(/&quot;/g, '"')
    .replace(/&amp;/g, "&");
}

/**
 * show the editor controls for the given usermode
 */
function __showControlsForUserMode(id,usermode,mode) {
  //alert("showC"+id+"-"+usermode+"-"+mode);
	modes = new Array("view","edit","viewsource","editsource","upload","download");
	for (var i = 0; i < modes.length; i++) {
		if (mode==modes[i]) {
			toggleVisibility(id+modes[i]+"div","","");
		} else {
			//if (usermode!="multi") {
			show_control(id+modes[i]+"div",false);
			//}	// if
		} // if	
	} // for	
}	// showControlsForUserMode

/**
 * activate an InnovaEditor for a given Textarea
 */
function __editWithInnovaEditor(id,usermode) {
	__showControlsForUserMode(id,usermode,"edit");
	show_control(id,true);
	eval(id+"= new InnovaEditor(id);");
	eval(id+".useTab=false;");
	eval(id+".REPLACE(id);");
}

	
/**
 * copy html code to the text are for editing
 * if asked to do so ... (this way we do not need to
 * transfer it twice ..)  
 */
function __editWithTextArea(id,encoded,usermode) {
	var viewId=id+'viewdiv';
	var editId=id+'editsourcediv';
	var tareaId=id+'tarea';
	var viewDiv=__getObj(viewId);
	var editDiv=__getObj(editId);
	var tarea=__getObj(tareaId);
	//alert(id);
	//alert(tareaId);
	if (tarea) {
		//alert(tarea.value);
		if (tarea.value==tareaId) {
			var content=viewDiv.innerHTML;
			//alert(content);
			// var parent=editDiv.parentNode;
			// insertAfter(parent,tarea,editDiv);
			// parent.insertBefore(tarea,viewDiv);
		  // parent.removeChild(viewDiv);
		  if (encoded)
		  	tarea.value = htmlDecode(content)
		  else	
		  	tarea.value = content;
		}  
	}	
	__showControlsForUserMode(id,usermode,"editsource");
  tarea.focus();
}

// if a field is clicked and has a null value in it select it in order to let the 
// user override it 
function nullValueSelect(myField,NULL_VALUE_DISPLAY) { 
  if (myField.value==NULL_VALUE_DISPLAY) { // check whether the field contains a null value 
        myField.select(); // select the field 
    } // if 
} // nullValueSelect

// 
// return the number of clicks that ask for a
// new request within the current request
// that is: menu clicks as well as any 
// standard or user defined function (e.g. via button)
// this is called by FireAction and by linkMe
function requestClickCount() {
	if (!requestClickCount.counter) 
		requestClickCount.counter=1; 
	else 
		requestClickCount.counter++;
	return requestClickCount.counter;
}		

// return the number of clicks that ask for a
// new request within the current request
// that is: menu clicks as well as any 
// standard or user defined function (e.g. via button)
// this is called by FireAction and by linkMe
function getRequestClickCount() {
	if (!requestClickCount.counter) 
		requestClickCount.counter=0;
	return requestClickCount.counter
}		
		
// linkme
function linkme(thelink) {
	var clickCount=requestClickCount();
	if (clickCount==1) {
		window.location.href=thelink;
	} else {
		// alert('you clicked  '+clickCount+' times');
	}		
}	

/**
 * show progress indicator
 * @param anId the Id of the Image Object to turn into a progress indicator
 */
function showProgressIndicator(anId) {
	var clickCount=getRequestClickCount();
	if (clickCount==0) {
		anImage=__getObj(anId);
		anImage.src='/com/bitplan/phpbobase/images/style/throbber16x16.gif';
	} // if
}	// showProgressIndicator
