/**This is the JavaScript portion of the Magic Web Online.
*Copyright 1999 Magic Software Enterprises Ltd. All rights reserved (c). 
*MGJavaScript.js version 8.30-5
*/

/**Global variables 
*/
  var formName = "form";
  var appletLoaded = false;
  var isNav = false;
  var isIE = false;
  var old_onkeydown;
  var old_cursor;
  var MGnewhtml = null;
  var obj2write = null;

  /**init global variables and trap events till applet is loaded
   */
  function MG_init() {
  	if (parseInt(navigator.appVersion) >= 4) {
  		if (navigator.appName == "Netscape") {
  			isNav = true
  		}
  		else	{
  			isIE = true
  		}
  	}
	if (isNav) {
		document.captureEvents(Event.KEYDOWN);
		// window.captureEvents(Event.LOAD)
	}
	// save old references for future use
	old_onkeydown = document.onkeydown
	
	   ChangeToWaitCursor(); 
	   
	// create new references
	document.onkeydown = waitForAppletToLoad;
  }
  
  
  /**events are trapped here till applet is loaded
  */
  function waitForAppletToLoad() {
  	window.status="Events are not handled till the applet is loaded !!!";
  	return false;
  }

  /**stop traping events and start running (after applet is loaded)
  */
  function start() {
  	if (isNav) {
  		document.releaseEvents(Event.KEYDOWN)
  	}
	document.onkeydown = old_onkeydown
	appletLoaded = true
	addOnChangeHandlerToElements()
	
	ChangeToOldCursor();	
	window.status="Applet is loaded";
	
	AddHandCursor(); // Adds cursor 'hand' to cotrols, on IE only
  }

  
  /**save old value of elements on the HTML during loading the applet and till it start
  */
  function saveOldValue(theObject) {
  	oldValue = theObject.valueOf()
  }
  
  
  /**return the body of a function as a string
  */
  function getFunctionBody(commandObject) {
  	var commandString
  	var indexOfCurl
  	
  	if (commandObject == null)
  		return "";
	commandString = commandObject.toString()
	// remove the perfix and suffix of the function and leave the function body
	indexOfCurl = commandString.indexOf("{")
	if (indexOfCurl != -1)
		commandString = commandString.substring(indexOfCurl+1, commandString.length-1)
	return commandString
  }
  
  /**add onchange to elements that the user might change.
   * call the event processing if the user command doesn't already include such a call
  */
  function addOnChangeHandlerToElements() {
  	var oldOnChangeCommandString;
  	var firstCommand
  	
  	for (var i = 0; i< document.form.elements.length; i++) {
  		e = document.form.elements[i]
   		switch (e.type) {
  			case "text" :
  			case "select-one" :
  			case "select-multiple" :
  			case "textarea" :
  			case "checkbox" :
  			case "radio" :
  			case "password" :
  				// add OnChange handling only if currently not handled by magic
				oldOnChangeCommandString = getFunctionBody(e.onchange)
				// first let magic do the processing, then process any user onChange commands
				firstCommand = oldOnChangeCommandString.indexOf("magicEventProcessing") == -1 ? "magicEventProcessing(event); " : ""
				e.onchange = new Function ("event", firstCommand + oldOnChangeCommandString)
   		}
  	}
  }

  
   /**private, Sends the MGWebOnLineRules to the Applet upon request from the applet(only for Netscape)
   */
   function sendRulesTOApplet()
   {
      	document.ControlClass.setRules(document.form.MGWebOnLineRules.value);
   }
   
   
   /**private, Is called by the applet to get the controls on the form
   */
	function updateAppletWithAllElementsOnHtmlPage()
	{
		for (var i = 0; i< document.form.elements.length; i++)
		{
         var fieldValue;
         fieldValue = getFieldValue(document.form.elements[i]);
			document.ControlClass.addField(document.form.elements[i].name, fieldValue);
		}
	}
	
	
	/**private, Retrieves the value of an object by its type. Is called by magicEventProcessing and magicRemoteEventProcessing only
	* @param Object field name
	* @return String the value of the field depending on its type
	*/
	function getFieldValue(field)
	{
      var returnValue;
      var updateFieldCounter = 0;
      var fieldName = field.name;
      
      if (fieldName == null)
         return "";
		
		if (fieldName.type=="radio")
		{
         while (field[updateFieldCounter].name == fieldName )
         {
            if (field[updateFieldCounter].checked)
   	         returnValue = field[updateFieldCounter].value;
   	      updateFieldCounter++;
         }
   	}
   	else
		if (field.type=="checkbox")
		{
		   if(field.checked)
		      returnValue = "true";
		   else
		      returnValue = "false";
		}
	else
		if(field.type=="select-one")
		{
			for(var i=0; i< field.length; i++)
			{
				if(field.options[i].selected)
				{
				 if(field.options[i].value!="") 
				       returnValue = field.options[i].value;
				 else  
				       returnValue = field.options[i].text;
				 break;
				}
			}
		}
	else
		if(field.type=="select-multiple")
		{
		var delimeter=",";							//default value
		 if(document.form.magicDelimeter)		//user defined value
		 {
		  if(document.form.magicDelimeter.value)
		  delimeter=""+document.form.magicDelimeter.value;
		 }
		 var firstItemFound=false;
		 for(var i=0; i< field.length; i++)
		 {
			if(field.options[i].selected)
			{
				if(!firstItemFound)		//first item found
				{
					if(field.options[i].value!="") 
						returnValue =""+ field.options[i].value;
					else  
						returnValue =""+ field.options[i].text;
				       
					firstItemFound=true;   
				}
				else					//more than one item selected
				{
					if(field.options[i].value!="") 
						returnValue +=delimeter+ field.options[i].value;
					else
						returnValue +=delimeter+ field.options[i].text;
				}
			}
		 }
		}	
		else
		   returnValue = field.value;

	   return (returnValue);
	}

  /**return 0 if the <STYLE> (IE) has user defined cursor 
  *  return 1 if cursor not defined by user or no STYLE
  *  returned value used only by AddCursor function
  */
  function getDefinedCursor(commandObject)
  {
      if (commandObject == null || commandObject.style == null)
			return 1;
    
      var styleString=commandObject.style.toString();		 
  
      if(styleString.toUpperCase().indexOf("CURSOR")>-1 )
			return 0;
	   return 1;	 
  }	
  
	/**private, this function run immediately when script is loaded and add cursor "hand"
	* to every object which get onClick handler
	*/
	function AddHandCursor()
	{
		if(isIE)
		   for(var i=0; i<document.form.elements.length; i++)
		   {
		      var e=document.form.elements[i];
		      if( e.onclick && getDefinedCursor(e)==1)
		      e.style.cursor="hand";	
		   }	
	}

	/**private, this function run immediately when script is loaded
	* or waiting for server . Change cursor to "wait".
	*/
	function ChangeToWaitCursor()
	{
	
	if(window.document.body)  // if there is no "BODY" ,yet (onLoad)
	 {
	   if(isIE)
	    {
	     old_cursor=window.document.body.style.cursor;
	     window.document.body.style.cursor="wait";    			
	    }
	   else if(isNav)
	    {
	 
	    }
	 }
	 window.status="Wait ..."; 
	}
	
	/**private, this function run after the script is loaded
	* or got answer from server . Change cursor to "old value".
	*/
	function ChangeToOldCursor()
	{
	   if (old_cursor == null) return;

	   if(isIE)
	   {
	      window.document.body.style.cursor=old_cursor;
	   }
	   else if(isNav)
	   {
         // add here whatever needed	 
	   }
	   // remove the wait message from the status
	   window.status="";
	}	
	
	/**private, Is called by the applet in order to open a new page (IE and Netscape)
	*/
	function DoWritePage(htmlPage, frame, x, y, dx, dy,wndFeatures,isPossibleWrite)
	{
      var attributes;
      if ((dy != "-1")&&(dx != "-1"))
         attributes = "width="+dx+",height="+dy+",screenX="+x+",screenY="+y+wndFeatures;
      else
      {
         var numOfComma = wndFeatures.indexOf(",");
         attributes     = wndFeatures.substring(numOfComma+1);
      }
      var done=0;
      for (var i=0; (i < parent.frames.length)&&(done!=1); i++)
      {
         if (parent.frames[i].name == frame)
         {
            //parent.frames[i].document.open();
            //parent.frames[i].document.write(htmlPage);
            //parent.frames[i].document.close();
            MGnewhtml = htmlPage;
            obj2write = parent.frames[i].document;
            done      = 1;
         }
      }
     
     //if in IE wrote window.open('...',"_top"|"_self"|"_parent",'...') -> the new window opened in OLD windows frame, new frame not opened 
      frame=frame.toLowerCase();
      if ( done==0 && isPossibleWrite == "true" &&
          ( frame=="_top" || frame=="_self" || frame=="_parent" )
         )
      {
            MGnewhtml = htmlPage;
            obj2write = window.document;
            done      = 1;
      }
      
      if (done == 0)
      {
         MGnewhtml = htmlPage;
         myMainWinVar = window.open('',"",attributes);   //frame
         myMainWinVar.document.write(htmlPage);
      }
   }
   
   
   /**************************************************************************************
    * Events
    **************************************************************************************/

   /**This function handles all events and sends a string of the event and where it originated to the Java Applet
   *@param receives the event 
   */
   function magicEventProcessing(evt)
   {
      var fieldValue;
      var elementName;
      //for Netscape
      if (isNav)
      {
		 fieldValue = getFieldValue(evt.target);
         if (fieldValue == null)
         {
			elementName = "body";
			fieldValue = "";
		 }
		 else
		 {
			elementName = evt.target.name;
		 }
      }
      //for IE
      else
      {
		 evt = event;
         if (evt.srcElement == null || evt.srcElement.tagName == "BODY")
         {
			elementName = "body";
			fieldValue = "";
		   }
		   else
		   {
			   elementName = evt.srcElement.name;
			   fieldValue = getFieldValue(evt.srcElement);
		   }
      }
      if (!appletLoaded && elementName!="body") return waitForAppletToLoad();
      document.ControlClass.eventProcessing(evt.type, elementName, fieldValue);
      if (MGnewhtml != null)
      {
         //document.write(MGnewhtml);
         //document.close();
         if(obj2write!=null)
         {
            document.ControlClass.stop();
            document.ControlClass.destroy();
            obj2write.open();         
            obj2write.write(MGnewhtml);
            obj2write.close();
            MGnewhtml=null;
            obj2write=null;
         }
      }
      return true;
   }
   
   
   /**This function is used for handling all events on all objects on the HTML page.
   *@param object: the object in which it was originated
   *@param string: the event type, such as "change", "click".....
   */
   function magicRemoteEventProcessing(objectOfEvent,eventType)
   {
      var fieldValue;
      fieldValue = getFieldValue(objectOfEvent);
      document.ControlClass.eventProcessing(eventType, objectOfEvent.name, fieldValue);
   }
	
		
	/**************************************************************************************
	 * Functions for the user:
	 **************************************************************************************/
	
	/**Returns the debug string (for debug use)
	*@return String, The value of the debug string located in the applet
	*/
	function MGGetDebugString()
	{
	   return (document.ControlClass.getDebugString());
	}
   
   /**Returns the value that the field that was sent to this function had prior to the last change (the value that is in the Java applet)
   *@param Object, The object whose value is to be restored
   */
	function MGRestoreValue(thisObject)
	{
	   return (document.ControlClass.getFieldValue(thisObject.name));
	}

	/** A user can send a string (a 'command') to be invoked directly, used to handle unhandled events
	*@param String, The command to be processed
	*/
	function MGUserCommand(commandString)
	{
	   document.ControlClass.userCommand(commandString);
	}
	
	/**run the init commands
	 * the following commands run immediately when script is loaded
	*/
	MG_init();