/*

    Copyright 2003-2007 Purdue University. 

    Developed by: Peter Turbek, Department of Mathematics, Computer Science, and Statistics, Purdue University Calumet.


    This file is part of CaluMath.

    CaluMath is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    CaluMath is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

//This file contains the commands used to when a user is done compleing or editing an object (done by clicking the Finish or Cancel or Delete button on the screen where the object is being created or edited) //

CaluMath.PM.CreateSettingsArrays=function(){ 
//Comment: This also (except for newplot) deletes the current object from lists. It also checks if the old name differs from the new name. If so it launches some sort of ChangeNameFunction.
   //Comment: This creates the settings array for the Default CaluMath.PM.PageMakerObject. It returns the options string to be used in the actual CAS command for the creation of the math object.
   var defaultobject=CM_TopWindow.CaluMath.Html.Eval("CaluMath.PM.PageMaker"+arguments[0]+"Default"); 
   var tempobject=arguments[1];
   var temprequired=tempobject.cm_tempobject; 
   var tempoptionsarray= new Array();
   var temprequiredarray= new Array();

   if(defaultobject.options.cm_inserttarget != null && defaultobject.options.cm_inserttarget.menu.options[defaultobject.options.cm_inserttarget.menu.selectedIndex].value
!= null  && defaultobject.options.cm_caswindow != null ){

      var tempinsertoptionname = defaultobject.options.cm_insertoption.menu.options[defaultobject.options.cm_insertoption.menu.selectedIndex].value;
      var tempinserttargetname = defaultobject.options.cm_inserttarget.menu.options[defaultobject.options.cm_inserttarget.menu.selectedIndex].value;
      if(tempinsertoptionname != "n/a" && tempinserttargetname != "n/a"){
         var tempcaswindowname = defaultobject.options.cm_caswindow.menu.options[defaultobject.options.cm_caswindow.menu.selectedIndex].value;
         var tempobjecttype = CaluMath.PM.PlotlistObject[tempcaswindowname].namedobjectlist[CaluMath.PM.ArrayIndex(CaluMath.PM.PlotlistObject[tempcaswindowname].namedobjectlist,tempinserttargetname,1)][2].type; 
         if(tempinsertoptionname=="cm_insertin" && (CaluMath.PM.CannotInsertInArray.cm_contains(tempobjecttype) || tempobjecttype.match(/button/))){
            return alert("You cannot insert your object inside a "+CaluMath.PM.PageMakerObjectLabelName(tempobjecttype));
         };
         if((tempinsertoptionname=="cm_insertbefore" || tempinsertoptionname=="cm_insertafter") && (CaluMath.PM.CannotInsertAfterArray.cm_contains(tempobjecttype)) ){
            return alert("You cannot insert your object before or after a "+CaluMath.PM.PageMakerObjectLabelName(tempobjecttype));
         };
      };
   };

   if(CM_TopWindow.CM_EditMode && tempobject[arguments[0]] != "newplot"){
      eval("CaluMath.PM.DeleteFromLists"+arguments[0])(tempobject);
   };

   if(CM_TopWindow.CM_EditMode==true){ 
      CaluMath.PM.AssignParents(tempobject);
      var oldname=CaluMath.PM.GetPageMakerObjectSetting(tempobject,"name");
      var oldgraph=CaluMath.PM.GetPageMakerObjectSetting(tempobject,"graph");
   };
   if(!CaluMath.PM.CheckForNormalObject(tempobject)){
      CM_TopWindow.CaluMath.PM.IgnoreMathInputChecks=true; 
   };

   var settingsnames= defaultobject.settingsnames;
   var settingsnameslength= settingsnames.length;
   for(var i=0; i<settingsnameslength; i++){ 
      if(defaultobject.options != null && defaultobject.options[settingsnames[i]] != null && defaultobject.options[settingsnames[i]].type=="input"){
         if(defaultobject.options[settingsnames[i]].input.value.replace(/\s/g,"") != "auto" && defaultobject.options[settingsnames[i]].input.value.match(/\S/g) ){
            if(defaultobject.options[settingsnames[i]].array[5] == null ||  defaultobject.options[settingsnames[i]].array[5](defaultobject.options[settingsnames[i]].input.value)){
            }
            else{
               if(defaultobject.options[settingsnames[i]].array[4].cm_constructorname=="String"){
                  var tempnamestring= defaultobject.options[settingsnames[i]].array[4];
               }
               else if(defaultobject.options[settingsnames[i]].array[4][0].cm_constructorname=="String"){
                  var tempnamestring= defaultobject.options[settingsnames[i]].array[4][0];
               }
               else{
                  var tempnamestring= defaultobject.options[settingsnames[i]].array[4][0][0];
               };

               if(defaultobject.options[settingsnames[i]].array[5] == null ||  !confirm("Your entry in "+tempnamestring+" may not be valid. It should be a "+defaultobject.options[settingsnames[i]].array[5].cm_message+". If your entry contains a mistake, click Cancel to enter a different value. If your entry refers to contants whose value cannot be determined yet (for example, if the constant depends on a point on which a user clicks) Click OK to continue.")){
                  return  ;
               };
            };
//            tempoptionsarray=tempoptionsarray.concat([[settingsnames[i],defaultobject.options[settingsnames[i]].input.value.replace(/^\s*/,'').replace(/\s*$/,'').cm_escapebackslashes().cm_escapequotes()]]);
            tempoptionsarray=tempoptionsarray.concat([[settingsnames[i],defaultobject.options[settingsnames[i]].input.value.replace(/^\s*/,'').replace(/\s*$/,'').replace(/\,/g,"/,").cm_escapebackslashes().cm_escapequotes()]]);
         };
      }
      else if(defaultobject.options != null && defaultobject.options[settingsnames[i]] != null && defaultobject.options[settingsnames[i]].type=="menu"){
         if(defaultobject.options[settingsnames[i]].menu.options[defaultobject.options[settingsnames[i]].menu.selectedIndex].value != "auto"){
            tempoptionsarray=tempoptionsarray.concat([[settingsnames[i],defaultobject.options[settingsnames[i]].menu.options[defaultobject.options[settingsnames[i]].menu.selectedIndex].value]]);
//            tempoptionsarray=tempoptionsarray.concat([[settingsnames[i],defaultobject.options[settingsnames[i]].menu.options[defaultobject.options[settingsnames[i]].menu.selectedIndex].value.cm_replacebigcharacters()]]);
         };
      }
      else if(defaultobject.required != null && defaultobject.required[settingsnames[i]] != null && defaultobject.required[settingsnames[i]].type=="input"){
         if(defaultobject.required[settingsnames[i]].input.value.replace(/\s/g,"") != "auto"){
            if(defaultobject.required[settingsnames[i]].array[5] == null || defaultobject.required[settingsnames[i]].array[5](defaultobject.required[settingsnames[i]].input.value)){
               temprequired[settingsnames[i]]=defaultobject.required[settingsnames[i]].input.value.replace(/^\s*/,'').replace(/\s*$/,''); 
            }
            else{
               if(defaultobject.required[settingsnames[i]].array[4].cm_constructorname=="String"){
                  var tempnamestring= defaultobject.required[settingsnames[i]].array[4];
               }
               else if(defaultobject.required[settingsnames[i]].array[4][0].cm_constructorname=="String"){
                  var tempnamestring= defaultobject.required[settingsnames[i]].array[4][0];
               }
               else{
                  var tempnamestring= defaultobject.required[settingsnames[i]].array[4][0][0];
               };

//               if(confirm("Your entry in "+tempnamestring+" may not be valid. It should be a "+defaultobject.required[settingsnames[i]].array[5].cm_message+". Click OK to continue anyway or click Cancel to enter a different value.")){
               if(confirm("Your entry in "+tempnamestring+" may not be valid. It should be a "+defaultobject.required[settingsnames[i]].array[5].cm_message+". If your entry contains a mistake, click Cancel to enter a different value. If your entry refers to contants whose value cannot be determined ahead of time (for example, if the constant depends on a point on which a user clicks) Click OK to continue.")){
                  temprequired[settingsnames[i]]=defaultobject.required[settingsnames[i]].input.value.replace(/^\s*/,'').replace(/\s*$/,''); 
               };
            };
            temprequiredarray=temprequiredarray.concat([[settingsnames[i],temprequired[settingsnames[i]].replace(/^\s*/,'').replace(/\s*$/,'').cm_escapebackslashes().cm_escapequotes()]]);
         };
      }
      else if(defaultobject.required != null && defaultobject.required[settingsnames[i]] != null && defaultobject.required[settingsnames[i]].type=="menu"){
         if(defaultobject.required[settingsnames[i]].menu.options[defaultobject.required[settingsnames[i]].menu.selectedIndex].value != "auto"){
            temprequired[settingsnames[i]]=defaultobject.required[settingsnames[i]].menu.options[defaultobject.required[settingsnames[i]].menu.selectedIndex].value;
//            temprequired[settingsnames[i]]=defaultobject.required[settingsnames[i]].menu.options[defaultobject.required[settingsnames[i]].menu.selectedIndex].value.cm_replacebigcharacters();
         };
         temprequiredarray=temprequiredarray.concat([[settingsnames[i],temprequired[settingsnames[i]]]]);
      }
   };

   tempobject.cm_optionsarray=tempoptionsarray;
   tempobject.cm_requiredarray=temprequiredarray;

   CM_TopWindow.CaluMath.PM.IgnoreMathInputChecks=false;
   return [tempoptionsarray, temprequiredarray];
};


   //COMMENT: THESE ALL HAVE TO DO WITH CaluMath.PM.INSERTIONOBJECTS. THE CaluMath.PM.INSERTIONOBJECTS ARE THE SOLE COMPONENTS OF CM_TopWindow.CaluMath.PM.InsertionArray. THE FUNCTIONS DETERMINE THE LAST CaluMath.PM.INSERTIONOBJECT, THE TYPE OF THE LAST CaluMath.PM.INSERTIONOBJECT ETC.

if(CM_TopWindow==window){
   CM_TopWindow.CaluMath.PM.InsertionArray= new Array();

   CaluMath.PM.InsertionObject= function(){
   //Comment: The first argument is the actual object (for example the buttonaction object or conditional object). If a second argument is present, it tells the type of the "encoding" of the object, for example if it is a NoQuote object, or a SingleQuoteObject, or DoubleQuoteObject (these have to do with whether the child, when actually written in the HTML document, will appear within single or double quotes (so certain characters will need to be escaped). 
      this.cm_object=arguments[0];
      if(arguments[1] != null){
         this.type=arguments[1];
      };
      this.firsttime=false;
   };
   
   CaluMath.PM.InsertionObject.prototype.toString= function(){
      return '('+this.cm_object+','+this.type+','+this.firsttime+')';
   };
   
   CM_TopWindow.CaluMath.PM.InsertionArray.lastobject=function(){
   //Comment: This returns the last object of CM_TopWindow.CaluMath.PM.InsertionArray.
      if(CM_TopWindow.CaluMath.PM.InsertionArray != 0){
         return CM_TopWindow.CaluMath.PM.InsertionArray[CM_TopWindow.CaluMath.PM.InsertionArray.length-1].cm_object;
      };
   };
   
   CM_TopWindow.CaluMath.PM.InsertionArray.lasttype=function(){
   //Comment: This returns the type of the last object of CM_TopWindow.CaluMath.PM.InsertionArray, for example "DoubleQuote"
      if(CM_TopWindow.CaluMath.PM.InsertionArray != 0){
         return CM_TopWindow.CaluMath.PM.InsertionArray[CM_TopWindow.CaluMath.PM.InsertionArray.length-1].type;
      };
   };
   
   //Comment: lastobjectfirsttime() looks at the last object of the CaluMath.PM.InsertionArray and examines the firsttime property. It will be either true or false. Typically, you may want differnt behavior the first time and subsequent time that you are adding children to the last object of the CaluMath.PM.InsertionArray. For example, if you create a button action, a popup cm_alert will say "Now do your button action" or something similar. After you do the item you want to add to your buttonaction (for example plotting a point or graph or adding text to the HTML page), it is no longer the first child you are adding to the buttonaction. At this point, recognizing that lastobjectfirsttime() yields false, a different popup will appear, such as "Continue with the buttonaction?" We obviously would not want this popup the first time we are adding something to a buttonaction. 

   CM_TopWindow.CaluMath.PM.InsertionArray.lastobjectfirsttime=function(){
      if(CM_TopWindow.CaluMath.PM.InsertionArray != 0){
         return CM_TopWindow.CaluMath.PM.InsertionArray[CM_TopWindow.CaluMath.PM.InsertionArray.length-1].firsttime;
      };
   };
   
   //Comment: This sets the firtime property of the last object of the CM_TopWindow.CaluMath.PM.InsertionArray. 
   CM_TopWindow.CaluMath.PM.InsertionArray.setlastobjectfirsttime=function(){
      if(CM_TopWindow.CaluMath.PM.InsertionArray != 0){
         CM_TopWindow.CaluMath.PM.InsertionArray[CM_TopWindow.CaluMath.PM.InsertionArray.length-1].firsttime= arguments[0];
      };
   };
   
   //Comment: Most created by CaluMath.PM.PageMakerObjects have two children, a text object describing what they are and a script object that contains the children of the object. This funcition gives the script object for the last object. It would be here that children would be directly inserted. 
   CM_TopWindow.CaluMath.PM.InsertionArray.lastscript=function(){
      if(CM_TopWindow.CaluMath.PM.InsertionArray != 0){
        var tempobject=CM_TopWindow.CaluMath.PM.InsertionArray.lastobject(); 
        if(tempobject.childarray != null){
           return tempobject.childarray[1];
        };
      };
   };

   //Comment: This gives the childarray of the last object of the CM_TopWindow.CaluMath.PM.InsertionArray. 
   CM_TopWindow.CaluMath.PM.InsertionArray.lastobjectchildarray=function(){
      if(CM_TopWindow.CaluMath.PM.InsertionArray != 0){
        var tempobject=CM_TopWindow.CaluMath.PM.InsertionArray.lastobject(); 
        if(tempobject.childarray != null){
           return tempobject.childarray;
        };
      };
   };

   //Comment: This gives the childarray of the script object of the last object of the CM_TopWindow.CaluMath.PM.InsertionArray. 
   CM_TopWindow.CaluMath.PM.InsertionArray.lastscriptchildarray=function(){
      if(CM_TopWindow.CaluMath.PM.InsertionArray != 0){
        var tempscript=CM_TopWindow.CaluMath.PM.InsertionArray.lastscript(); 
        if(tempscript.childarray != null){
           return tempscript.childarray;
        };
      };
   };
};  //Comment: End of insisting that InsertionArray is only for CM_TopWindow.

//Comment: If we are not in CM_EditMode and CM_TopWindow.CaluMath.PM.InsertionArray has length greater than 0, then objects should be placed as children of the last object in CM_TopWindow.CaluMath.PM.InsertionArray. So in this case, we can automatically place the object without knowing anything about the object. The function CaluMath.PM.AutomaticallyPlaceObjectAsChild does this for us. If it can place the object automatically, it does so and returns "yes". If it can't, it returns "no".  If we are in CM_EditMode then it returns "In CM_TopWindow.CM_EditMode mode." (In this case the object is someplace already and does not need to be placed again) This provides us with a test to see if the object was automatically placed or not. 

//Comment: Note that if we are not in CM_EditMode then automatically the object is given a name "htmlelement"+CM_TopWindow.HTMLElementIndex++ property and CaluMath.PM.PageMakerObjectParent is identified with this name. If we are in CM_EditMode, none of this needs to be done. Individual types of objects (such as pointplot or tangent etc) should never need to give names to the objects or assign properties to CaluMath.PM.PageMakerObjectParent if they call CaluMath.PM.AutomaticallyPlaceObjectAsChild.


   //COMMENT: END OF CaluMath.PM.INSERTIONOBJECTS AND THEIR FUNCTIONS.


//Comment: The return is "yes" if the object has been automatically placed, "no" if it is not in CM_EditMode and has not been placed as a child of the last object of CaluMath.PM.InsertionArray. 
//Comment: If in CM_EditMode, it returns "In CM_TopWindow.CM_EditMode mode." 
CaluMath.PM.AutomaticallyPlaceObjectAsChild=function(){ 
   var tempobject=arguments[0];
   if(!CM_TopWindow.CM_EditMode){
      var tempreturn = "no";
      if(CM_TopWindow.CaluMath.PM.InsertionArray.length !=0){
         if(!( tempobject.type=="iframecontainer" || tempobject.type=="iframe"  || (tempobject.type=="table" && tempobject.cm_getsetting("dynamic")=="no")) ){
            var tempchild = CM_TopWindow.CaluMath.PM.InsertionArray.lastobjectchildarray();
            if(tempchild != null){
               tempchild=tempchild.push(tempobject);
               tempobject.parent= tempchild;
               tempreturn = "yes";
            };
        };
      };
      return tempreturn; 
   }
   else{
      return "In CM_TopWindow.CM_EditMode mode.";
   };
}; 


//COMMENT: FUNCTIONS DEALING WITH STATICOBJECT AND HOW TO INSERT THEM INTO A DOCUMENT.
CaluMath.PM.InsertStaticObject= function(){ //alerttest("doing staticobjectinsert");
   var tempobject=arguments[0];
   var insertoption=CaluMath.PM.GetPageMakerObjectSetting(tempobject, "cm_insertoption");
   var inserttarget=CaluMath.PM.GetPageMakerObjectSetting(tempobject, "cm_inserttarget");
   var caswindow=CaluMath.PM.GetPageMakerObjectSetting(tempobject, "cm_caswindow");
   var oldinsertoption=arguments[1];
   var oldinserttarget=arguments[2];
   var oldcaswindow=arguments[3];

   if((oldinsertoption == null) ||  ( oldinserttarget.length >0  &&  !(oldinsertoption =="n/a" && insertoption =="n/a")  &&    !(oldinsertoption !="n/a" && oldinsertoption == insertoption && oldcaswindow == caswindow &&  oldinserttarget == inserttarget)) ){
      //Comment: Basically we must insert the object as a child somewhere if it is not already inserted (in other words, oldinsertoption is null) or if it was originally inserted somewhere but is now to be inserted in a different place. This part explains the remainder of the above Boolean. 
      //Comment: Note that math formulas and text that contain cm_eval don't have inserttargets. So we make sure the oldinserttarget length is greater than 0. If not, it means the object should stay where it is. 
      if(oldinsertoption != null){
         //Comment: In this case they changed where the object is inserted. So we remove the old placement of the object. 
         CaluMath.PM.AssignParents();
         var tempindex= CaluMath.PM.AssignChildIndex(tempobject);
         tempobject.parent.childarray.splice(tempindex,1);
      };
      if(insertoption =="n/a"){
         if(caswindow=="CM_MainWindow"){
            CaluMath.PM.PageMakerObjectArray=CaluMath.PM.PageMakerObjectArray.concat(tempobject); 
         }
         else{
            var tempindex = CaluMath.PM.ArrayIndex(CaluMath.PM.PlotlistObject.newwindowlist,caswindow,0);
            var tempparent = CaluMath.PM.PlotlistObject.newwindowlist[tempindex][2];
            tempparent.childarray.push(tempobject);
         };
      }
      else{
         //Comment: Note that "n/a" is the first option. Therefore we subtract 1 from the index to get the correct index in relation to the staticobjectlist. 
         if(insertoption =="cm_insertin" && inserttarget != "n/a"){
            var tempindex = CaluMath.PM.ArrayIndex(CaluMath.PM.PlotlistObject[caswindow].staticobjectlist,inserttarget,1); 
            var tempparent = CaluMath.PM.PlotlistObject[caswindow].staticobjectlist[tempindex][2];
            tempparent.childarray.push(tempobject);
         }
         else{
            CaluMath.PM.PageMakerObjectArray.push(tempobject);
         };
      };
   };
};


CaluMath.PM.StaticTextAddToStaticLists=function(){
   var tempobject= arguments[0];
   var tempcaswindow= arguments[1];
   var tempname =CaluMath.PM.GetPageMakerObjectSetting(tempobject,"name"); 
   if( tempname.length >0){
      CM_TopWindow.CaluMath.PM.PlotlistObject[tempcaswindow].staticobjectlist.push([tempname, tempname, tempobject]);
      if(CaluMath.PM.GetPageMakerObjectSetting(tempobject,"cm_caswindow").length ==0){
         CaluMath.PM.SetPageMakerObjectSetting(tempobject,"cm_caswindow", tempcaswindow)
      };
   };
   if(tempobject.childarray != null && tempobject.childarray.length>0){
      var childarray= tempobject.childarray; 
      var childarraylength= childarray.length; 
      for(var i=0; i< childarraylength; i++){
         CaluMath.PM.StaticTextAddToStaticLists(childarray[i], tempcaswindow);
      };
   };
};

CaluMath.PM.StaticTextDeleteFromStaticLists=function(){ //alerttest(tempobject);   //alerttest(CaluMath.PM.PlotlistObject[tempcaswindow].staticobjectlist.length);
   var tempobject= arguments[0];
   var tempname =CaluMath.PM.GetPageMakerObjectSetting(tempobject,"name"); 
   var tempcaswindow =CaluMath.PM.GetPageMakerObjectSetting(tempobject,"cm_caswindow"); 

   if( tempname.length >0){
      var tempindex = CaluMath.PM.ArrayIndex(CaluMath.PM.PlotlistObject[tempcaswindow].staticobjectlist,tempobject,2); 
      CM_TopWindow.CaluMath.PM.PlotlistObject[tempcaswindow].staticobjectlist.splice(tempindex, 1);
   };
   if(tempobject.childarray != null && tempobject.childarray.length>0){
      var childarray= tempobject.childarray; 
      var childarraylength= childarray.length; 
      for(var i=0; i< childarraylength; i++){
         CaluMath.PM.StaticTextDeleteFromStaticLists(childarray[i]);
      };
   };
};


CaluMath.PM.IsEntirelyInStaticObjects=function(){
   tempobject=arguments[0];
   CaluMath.PM.AssignParents();
   var tempparent=tempobject.parent;
   var allstaticobjectparents= "yes";
   var continuechecking = "yes";
   while(tempparent != null && tempparent != CaluMath.PM.PageMakerObjectArray && continuechecking == "yes"){
      if(tempparent.type=="table" && tempparent.cm_getsetting("dynamic")=="yes"){
         continuechecking = "no";
         allstaticobjectparents= "no";
      }
      else if(tempparent != null && tempparent.type == "newwindow"){
         continuechecking = "no";
         allstaticobjectparents= "yes";
      }
      else if( !(["iframecontainer", "iframe", "newwindow", "table", "tablecell", "tablerow"].cm_contains(tempparent.type))){
         continuechecking = "no";
         allstaticobjectparents= "no";
      }
      else{
         tempparent=tempparent.parent;
      };
   };
   return allstaticobjectparents;
};

CaluMath.PM.IsContainedInANewWindow=function(){
   tempobject=arguments[0];
   CaluMath.PM.AssignParents();
   var tempparent=tempobject.parent;
   var isinnewwindow= "no";
   var continuechecking = "yes";
   while(tempparent != null && tempparent != CaluMath.PM.PageMakerObjectArray && continuechecking == "yes"){
      if(tempparent.type=="newwindow"){
         continuechecking = "no";
         isinnewwindow= "yes";
      }
      else{
         tempparent=tempparent.parent;
      };
   };
   return isinnewwindow;
};


//COMMENT: ABOVE ENDS STATICOBJECT SECTION.

//COMMENT: SECTION DEALING WITH CaluMath.PM.CHECKFORNORMALOBJECT AND ASSOCIATED THINGS SUCH AS INSERTING STATIC OBJECTS
