<?php
/*

ALTER TABLE `tblCourse` DROP FOREIGN KEY `tblCourse.strCourseType`;
ALTER TABLE `tblCourse` ADD CONSTRAINT `tblCourse.strCourseType` FOREIGN KEY ( `refCourseTypeID` ) REFERENCES `tblCourseType` ( `CourseTypeID` ) ON DELETE CASCADE ON UPDATE CASCADE ;


 *
 */

@include_once("includes/course.cls.php");
@include_once("course.cls.php");//either or



class Workshop extends Course
{
   private $ID = 0;

   public function __construct($DataKey)
   {
      //filters
      //inherit from course.cls

      parent::__construct($DataKey, $blnWorkshop=1);
      $this->Filters[frWorkshopType] = $this->Filters[frCourseType];
      unset($this->Filters[frCourseType]);
      //print_rr($this->Filters);
   }




   private function getListSQL($Having = "", $where ="", $blnEnableFiltering=1)
   {
      global $SystemSettings;
      $Where = "";
      if($blnEnableFiltering)
      {
         if($this->Filters[frSearch]->html->value != "")
         {
            $like = "LIKE(". $this->db->qs("%".$this->Filters[frSearch]->html->value."%") .")";
            $Where .= " AND (tblCourse.CourseID $like OR tblCourse.strCourse $like OR tblCourse.strCourseCode $like )";
         }
         //NOTE frWorkshopType = frCourseType
         if($this->Filters[frWorkshopType]->html->value != 0)
         {
            $Where .= " AND tblCourse.refCourseTypeID = ". $this->Filters[frWorkshopType]->html->value;
         }
         if($this->Filters[frStatus]->html->value != -1)
         {
            $Where .= " AND tblCourse.blnActive = ". $this->Filters[frStatus]->html->value;
         }

         if($this->blnWorkshop <> 2)
         {//20130829 - added WS indicator
            $Where .= " AND tblCourse.blnWorkshop = $this->blnWorkshop";
         }
      }




      return "
         SELECT   tblCourse.CourseID, 
                  tblCourse.strCourseHTML AS Workshop, 
                  tblVenue.strVenue as Venue, 
                  tblCourse.dtStartDate AS 'Event Date', 
                  tblCourse.strStartTime AS 'Start Time', 
                  Count(tblCourseLearners.refLearnerID) AS 'No Learners', 
                  CASE WHEN tblCourse.blnRSVPOnly=0 THEN 'No' ELSE dirRSVPs.intRSVP END AS 'RSVP',
                  tblCourse.blnActive AS Active, 
                  tblCourse.strLastUser AS 'Last User', 
                  tblCourse.dtLastEdit AS 'Last Edit'
         FROM 
         (
            tblCourseVenue RIGHT JOIN 
            (
               (
                  SELECT tblRSVP.refCourseID, Count(tblRSVP.RSVPID) AS intRSVP
                  FROM tblRSVP
                  GROUP BY tblRSVP.refCourseID
               )  
               AS dirRSVPs RIGHT JOIN 
               (
                  tblCourse LEFT JOIN 
                  (
                     SELECT tblLicence.refCourseID, tblLicence.refLearnerID
                     FROM tblLicence INNER JOIN tblLearner ON tblLicence.refLearnerID = tblLearner.LearnerID
                     WHERE tblLicence.strStatus='Active'
                     GROUP BY tblLicence.refCourseID, tblLicence.refLearnerID
                  )  
                  AS tblCourseLearners ON tblCourse.CourseID = tblCourseLearners.refCourseID
               ) 
               ON dirRSVPs.refCourseID = tblCourse.CourseID
            ) 
            ON tblCourseVenue.refCourseID = tblCourse.CourseID
         ) 
         LEFT JOIN tblVenue ON tblCourseVenue.refVenueID = tblVenue.VenueID
         WHERE 1=1 $Where $where
         GROUP BY tblCourse.CourseID, dirRSVPs.intRSVP, tblCourse.strCourseHTML, tblCourse.strCourseCode, tblCourse.dtStartDate, tblCourse.dtEndDate, tblCourse.strCourseHTML
         HAVING 1=1 $Having
         ORDER BY tblCourse.dtStartDate DESC , tblCourse.strCourse, tblCourse.strCourseCode ";
   
   }

   public function getListCurrent()
   {
      global $SystemSettings;

      $dt = date("Y-m-d");

      $this->ListSQL($this->getListSQL(" AND dtStartDate <= '$dt' AND dtEndDate >= '$dt'"),0, $this->controler);
      return $this->renderTable("Current Workshops");
   }

   public function getListPast()
   {
      global $SystemSettings;

      $dt = date("Y-m-d");

      $this->ListSQL($this->getListSQL(" AND dtEndDate < '$dt'"),0, $this->controler);
      return $this->renderTable("Past Workshops");
   }

   public function getListFuture()
   {
      global $SystemSettings;

      $dt = date("Y-m-d");

      $this->ListSQL($this->getListSQL(" AND dtStartDate > '$dt'"),0, $this->controler);
      return $this->renderTable("Future Workshops");
   }

   public static function RSVPImportForm()
   {

      $content = "<table width='100%' cellspacing='1' cellpadding='2' border='0'>
                     <caption>RSVP Import</caption>
                     <tr>
                        <td align='right'>
                           Select (.xls) file to import <i>()</i>:                        
                           <input type='file' id='fileImport' name='RSVPImport'>
                           <input id='RSVPButton' type='submit' name='Action' value='Import RSVP' class=btn>
                           <img id='rsvpLoading' style='padding: 5px 0 0 5px;display:none;' src='images/loadinfo.gif'>
                        </td>
                     </tr>
               </table>"
               .js("

                  $('#RSVPButton').click(function() {
                     file = $('#fileImport').val();

                     if(file == '')
                     {
                        alert('Please Select a file to import')
                        return false;
                     }
                     else
                     {
                        var exts = ['xls','xlsx'];
                        var get_ext = file.split('.');
                        get_ext = get_ext.reverse();

                        if ( $.inArray ( get_ext[0].toLowerCase(), exts ) > -1 )
                        {
                           loadingImg()
                        } 
                        else 
                        {
                           alert('please choose a .xls file');
                           return false;
                           alert(extension);
                           
                        }

                     }
                  });



                  function loadingImg(){
                     $('#rsvpLoading').toggle();
                  }
                  ");

      return $content;

   }
/*
   private function getListSQL($Having = "", $where ="", $blnEnableFiltering=1)
   {
      global $SystemSettings;
      $Where = "";
      if($blnEnableFiltering)
      {
         if($this->Filters[frSearch]->html->value != "")
         {
            $like = "LIKE(". $this->db->qs("%".$this->Filters[frSearch]->html->value."%") .")";
            $Where .= " AND (tblCourse.CourseID $like OR tblCourse.strCourse $like OR tblCourse.strCourseCode $like )";
         }
         if($this->Filters[frCourseType]->html->value != 0)
         {
            $Where .= " AND tblCourse.refCourseTypeID = ". $this->Filters[frCourseType]->html->value;
         }
         if($this->Filters[frStatus]->html->value != -1)
         {
            $Where .= " AND tblCourse.blnActive = ". $this->Filters[frStatus]->html->value;
         }
      }

      return "
         SELECT tblCourse.CourseID, tblCourse.strCourseHTML AS Course, tblCourse.strCourseCode AS Code, tblCourse.dtStartDate AS 'Start Date', tblCourse.dtEndDate AS 'End Date', Count(tblCourseLearners.refLearnerID) AS 'No Learners',  tblCourse.blnActive AS Active, tblCourse.strLastUser AS 'Last User', tblCourse.dtLastEdit AS 'Last Edit'
         FROM tblCourse 
         LEFT JOIN (
            SELECT tblLicence.refCourseID, tblLicence.refLearnerID
            FROM tblLicence INNER JOIN tblLearner ON tblLicence.refLearnerID = tblLearner.LearnerID
            WHERE tblLicence.strStatus='Active'
            GROUP BY tblLicence.refCourseID, tblLicence.refLearnerID
         ) AS tblCourseLearners ON tblCourse.CourseID = tblCourseLearners.refCourseID
         WHERE 1=1 $Where $where
         GROUP BY tblCourse.CourseID, tblCourse.strCourseHTML, tblCourse.strCourseCode, tblCourse.dtStartDate, tblCourse.dtEndDate, tblCourse.strCourseHTML
         HAVING 1=1 $Having
         ORDER BY tblCourse.dtStartDate DESC , tblCourse.strCourse, tblCourse.strCourseCode ";
   }
   
   public function getList($frCourseTypeID=0, $frLearnerID=0, $blnEnableFiltering=1)
   {
      global $SystemSettings, $xdb;
//vd($frCourseTypeID);
      if($frCourseTypeID != 0)
         $where = " AND refCourseTypeID = ". $xdb->qs($frCourseTypeID);

      if($frLearnerID != 0)
         $where = " AND refLearnerID = ". $xdb->qs($frLearnerID);

      $this->ListSQL($this->getListSQL(null, $where, $blnEnableFiltering) ,0,"course.php");
      return $this->renderTable("All Courses");
   }
   public function getListCurrent()
   {
      global $SystemSettings;

      $dt = date("Y-m-d");

      $this->ListSQL($this->getListSQL(" AND dtStartDate <= '$dt' AND dtEndDate >= '$dt'"),0,"course.php");
      return $this->renderTable("Current Courses");
   }
   public function getListPast()
   {
      global $SystemSettings;

      $dt = date("Y-m-d");

      $this->ListSQL($this->getListSQL(" AND dtEndDate < '$dt'"),0,"course.php");
      return $this->renderTable("Past Courses");
   }
   public function getListFuture()
   {
      global $SystemSettings;

      $dt = date("Y-m-d");

      $this->ListSQL($this->getListSQL(" AND dtStartDate > '$dt'"),0,"course.php");
      return $this->renderTable("Future Courses");
   }

   public static function getLearnerMove($LearnerID, $CurrentCourse)
   {
      global $xdb, $SystemSettings, $DT;   

      $CourseCode = explode("/",$CurrentCourse);
      $ddlCourseList = $xdb->getRowSQL("SELECT strCourse FROM tblCourse WHERE strCourseCode LIKE '$CourseCode[1]'");
              
      $rst = $xdb->doQuery("SELECT tblVenue.* FROM tblVenue Where blnActive = 1 ORDER BY strVenue");
      
      while($row = $xdb->fetch_object($rst)) 
      {   
         //ini
         $strCourseVenue = "";
         $disabled = "";
         $venueNotes ="";
         //$courseVenue ='('.$rowCourseVenue->strCourse.': '.$rowCourseVenue->dtStartDate.' --> '.$rowCourseVenue->dtEndDate.')';
         //print_rr($courseVenue);
         
         //process   
         $rowCV = $xdb->getRowSQL("SELECT tblCourse.* 
                                    FROM tblCourseVenue INNER JOIN tblCourse on tblCourseVenue.refCourseID = tblCourse.CourseID  
                                    WHERE tblCourseVenue.refVenueID = $row->VenueID AND dtStartDate <= '$rowCourse->dtStartDate' AND '$rowCourse->dtEndDate' <= dtEndDate");

         if($rowCV && $rowCV->CourseID != $CourseID)
         {//disabled!         
            $disabled = "disabled";    
            $strCourseVenue = " ($rowCV->strCourse: $rowCV->dtStartDate > $rowCV->dtEndDate)";     //strCourse or strCourseCode??    
         }       
         if($row->txtNotes != "")
         {
            $venueNotes = ' ( '.$row->txtNotes.' )';
         }       
         $ddlVenue .= "<option value='$row->VenueID' ".($row->VenueID == $rowCourseVenue->refVenueID ? "Selected" : "")." $disabled >$row->strVenue$strCourseVenue$venueNotes</option>";      
         //print_rr($rowCV->strCourse);
      }

      $strOutput = "                    
        <table width='100%' cellspacing='1' cellpadding='2' border='0'>
            <caption>Course Venue</caption> 
               <tr>
                  <td class='tdDetailsLeft' align='right'>Venue :</td>
                  <td class='tdDetailsRight' align='left'>
                     <select name='refVenueID' id='refVenueID' onChange='jsGetMaxCapacity(this.value);' class='controlText'>   
                        <option value='0'>- None -</option>                  
                           $ddlVenue
                     </select>
                  </td>
               </tr>
               <tr>
                  <td class='tdDetailsLeft' align='right'>Capacity: </td>
                  <td class='tdDetailsRight' align='left'>
                     <input type = 'text' name='intCapacity' id='intCapacity' value=\"$rowCourseVenue->intCapacity\" class='controlText controlNumeric' onBlur='removeAlpha(this);'>
                  </td>                  
               </tr>
         </table>"
         .js("
            function jsGetMaxCapacity(VID)
            {
               $('#intCapacity').hide('fast');

               $.ajax(
               {
                  type: 'POST',
                  url: 'ajaxfunctions.php',
                  data: 'header=text&type=getMaxCapacity&VenueID=' + VID,
                  success: function(data)
                  {
                     //$('#intCapacity').value = data;
                     d('intCapacity').value = data;                              
                  }
               });
               $('#intCapacity').show('fast');
            }");         

      return $strOutput;
      //return $this->renderTable("Venue");      
   }


   public static function getCourseVenue($CourseID)
   {
      global $xdb, $SystemSettings, $DT;   

      // $rowCourseVenue = $xdb->getRowSQL("SELECT tblCourseVenue.*, tblVenue.intMaxCapacity
      //                                        FROM tblCourseVenue INNER JOIN tblVenue ON tblCourseVenue.refVenueID = tblVenue.VenueID
      //                                        WHERE tblCourseVenue.refCourseID=$CourseID",0);
      $rowCourseVenue = $xdb->getRowSQL("SELECT * FROM tblCourseVenue WHERE refCourseID=$CourseID",0);
      $rowCourse = $xdb->getRowSQL("SELECT * FROM tblCourse WHERE CourseID = $CourseID");
              
      $rst = $xdb->doQuery("SELECT tblVenue.* FROM tblVenue Where blnActive = 1 ORDER BY strVenue");
      
      while($row = $xdb->fetch_object($rst)) 
      {   
         //ini
         $strCourseVenue = "";
         $disabled = "";
         $venueNotes ="";
         //$courseVenue ='('.$rowCourseVenue->strCourse.': '.$rowCourseVenue->dtStartDate.' --> '.$rowCourseVenue->dtEndDate.')';
         //print_rr($courseVenue);
         
         //process   
         $rowCV = $xdb->getRowSQL("SELECT tblCourse.* 
                                    FROM tblCourseVenue INNER JOIN tblCourse on tblCourseVenue.refCourseID = tblCourse.CourseID  
                                    WHERE tblCourseVenue.refVenueID = $row->VenueID AND dtStartDate <= '$rowCourse->dtStartDate' AND '$rowCourse->dtEndDate' <= dtEndDate");

         if($rowCV && $rowCV->CourseID != $CourseID)
         {//disabled!         
            $disabled = "disabled";    
            $strCourseVenue = " ($rowCV->strCourse: $rowCV->dtStartDate > $rowCV->dtEndDate)";     //strCourse or strCourseCode??    
         }       
         if($row->txtNotes != "")
         {
            $venueNotes = ' ( '.$row->txtNotes.' )';
         }       
         $ddlVenue .= "<option value='$row->VenueID' ".($row->VenueID == $rowCourseVenue->refVenueID ? "Selected" : "")." $disabled >$row->strVenue$strCourseVenue$venueNotes</option>";      
         //print_rr($rowCV->strCourse);
      }

      $strOutput = "                    
        <table width='100%' cellspacing='1' cellpadding='2' border='0'>
            <caption>Course Venue</caption> 
               <tr>
                  <td class='tdDetailsLeft' align='right'>Venue :</td>
                  <td class='tdDetailsRight' align='left'>
                     <select name='refVenueID' id='refVenueID' onChange='jsGetMaxCapacity(this.value);' class='controlText'>   
                        <option value='0'>- None -</option>                  
                           $ddlVenue
                     </select>
                  </td>
               </tr>
               <tr>
                  <td class='tdDetailsLeft' align='right'>Capacity: </td>
                  <td class='tdDetailsRight' align='left'>
                     <input type = 'text' name='intCapacity' id='intCapacity' value=\"$rowCourseVenue->intCapacity\" class='controlText controlNumeric' onBlur='removeAlpha(this);'>
                  </td>                  
               </tr>
         </table>"
         .js("
            function jsGetMaxCapacity(VID)
            {
               $('#intCapacity').hide('fast');

               $.ajax(
               {
                  type: 'POST',
                  url: 'ajaxfunctions.php',
                  data: 'header=text&type=getMaxCapacity&VenueID=' + VID,
                  success: function(data)
                  {
                     //$('#intCapacity').value = data;
                     d('intCapacity').value = data;                              
                  }
               });
               $('#intCapacity').show('fast');
            }");         

      return $strOutput;
      //return $this->renderTable("Venue");      
   }

   public static function Save(&$CourseID)
   {   
      //print_rr($_REQUEST);
      //die;   
      //error_reporting(E_ERROR);
      $db = new NemoDatabase("tblCourse", $CourseID, null, 0);

      $db->SetValues($_POST);

      $db->Fields[strLastUser] = $_SESSION['USER']->USERNAME;

      $result = $db->Save();

      if($CourseID == 0)
      {
         $CourseID = $db->ID[CourseID];

         //INSERT DEFAULT MODULES
         $db->doQuery("INSERT INTO modModule ( refCourseID, refCTMID, strModuleName, intModuleNumber, txtIntro, txtOutcome )
                        SELECT '$CourseID' AS refCourseID, tblCourseTypeModule.CourseTypeModuleID, tblCourseTypeModule.strModuleName, tblCourseTypeModule.intModuleNumber, tblCourseTypeModule.txtIntro, tblCourseTypeModule.txtOutcome
                        FROM tblCourseTypeModule
                        WHERE refCourseTypeID = ". $_POST[refCourseTypeID]);

         //UPDATE Release dates
         $i = 0;
         $dtRelease = $_POST[dtStartDate];
         $db->doQuery(" SELECT modModule.ModuleID, tblCourseTypeModule.strDefaultReleaseSchedule
                        FROM modModule INNER JOIN tblCourseTypeModule ON modModule.refCTMID = tblCourseTypeModule.CourseTypeModuleID
                        WHERE modModule.refCourseID = $CourseID");

         while($row = $db->fetch())
         {
            $mdb = new NemoDatabase("modModule", $row->ModuleID, null, 0);
            if($i == 0)
               $dtRelease = $_POST["dtStartDate"];
            else
               $dtRelease = date("Y-m-d", strtotime("$dtRelease $row->strDefaultReleaseSchedule"));
            //vd($dtRelease);
            $mdb->Fields[dtReleaseDate] = $dtRelease;
            $mdb->Save(0,0);
            $i++;
         }

         //replicate! copy all module child object from the previous course to the new course
         $row = $db->getRowSQL("SELECT * FROM tblCourse
                                 WHERE CourseID<>$CourseID AND refCourseTypeID=". $_POST["refCourseTypeID"] ."
                                 ORDER BY dtStartDate DESC");
         if($row)
            Course::Replicate($CourseID, $row->CourseID);
      }

      //Save Course venue details
      $intCapacity = $_POST[intCapacity];
      $refVenueID = $_POST[refVenueID];

      if($intCapacity == "")
      {
         $intCapacity = 0;
      }
      //delete cv w cid=cid
      $db->doQuery("DELETE FROM tblCourseVenue WHERE refCourseID = $CourseID");
      //insert
      if($refVenueID > 0)
      {
         $db->doQuery("INSERT INTO tblCourseVenue (refCourseID, refVenueID, intCapacity) VALUES ($CourseID, $refVenueID, $intCapacity)");
      }

      //$db->doQuery("UPDATE tblCourseVenue SET refVenueID = ".$_POST[refVenueID].", intCapacity = ".$_POST[intCapacity]." WHERE refCourseID =$CourseID");

      if($result->Error == 1)
         return $result->Message;
      else         
         return "Details Saved. ";
   }

   public static function Delete($chkSelect)
   {
      global $xdb;
      //print_rr($chkSelect);
      if(count($chkSelect) > 0){
      foreach($chkSelect as $key => $value)
      {
         $xdb->doQuery("DELETE FROM tblCourse WHERE CourseID = ". $xdb->qs($key));
      }
         return "Records Deleted.";
      }
   }

   public static function Replicate($CourseToID, $CourseFromID)
   {
      global $xdb, $DT, $SystemSettings;

   //ini

      $rowCT = $xdb->getRowSQL("SELECT * FROM tblCourseType INNER JOIN tblCourse ON refCourseTypeID = CourseTypeID WHERE CourseID = $CourseToID"); //get CT details

      $arrChildren["modAssignment"]->PK = "AssignmentID";
      $arrChildren["modAssignment"]->UID_Prefix = $rowCT->strCourseTypeCode."ASS";
      $arrChildren["modAssignment"]->Unique_Restrition = array("refModuleID","strAssignment");
      $arrChildren["modAssignment"]->DueDate = "+7 Days"; //BR: Assignment due dates = mod.startdate + 7days
      $arrChildren["modNote"]->PK = "NoteID";
      $arrChildren["modNote"]->UID_Prefix = $rowCT->strCourseTypeCode."NOT";
      $arrChildren["modNote"]->Unique_Restrition = array("refModuleID","strNote");
      $arrChildren["modPractical"]->PK = "PracticalID";
      $arrChildren["modPractical"]->UID_Prefix = $rowCT->strCourseTypeCode."PRA";
      $arrChildren["modPractical"]->Unique_Restrition = array("refModuleID","strPractical");
      $arrChildren["modVideo"]->PK = "VideoID";
      $arrChildren["modVideo"]->UID_Prefix = $rowCT->strCourseTypeCode."VID";
      $arrChildren["modVideo"]->Unique_Restrition = array("refModuleID","strVideo");

   //go
      $rstMain = $xdb->doQuery("
         SELECT modTo.ModuleID AS ModuleToID, modFrom.ModuleID as ModuleFromID, modTo.*
         FROM modModule AS modTo INNER JOIN modModule AS modFrom ON modTo.refCTMID = modFrom.refCTMID
         WHERE modTo.refCourseID=$CourseToID AND modFrom.refCourseID=$CourseFromID");
      while($rowModule = $xdb->fetch_object($rstMain))
      {//print_rr($rowModule);
         foreach($arrChildren as $table => $Child)
         {//print_rr($Child); 
            $rst = $xdb->doQuery("SELECT * FROM $table WHERE refModuleID = $rowModule->ModuleFromID AND blnActive = 1");
            while($row = $xdb->fetch_object($rst))
            {//print_rr($row);

            //ini
               $UID = $Child->PK;
               $UID = $row->$UID;

               $dbFrom = new NemoDatabase($table, $UID, null, 0);//print_rr($dbFrom->Fields);

               $dbTo = new NemoDatabase($table, "", $Child->Unique_Restrition, 0);

            //go
               $dbTo->Fields = $dbFrom->Fields; //copy

               $dbTo->Fields["$Child->PK"] = ""; //reassign
               $dbTo->Fields["refModuleID"] = $rowModule->ModuleToID;
               $dbTo->Fields["strLastUser"] = "New Course Replication";//print_rr($dbTo->Fields);
               
               if($Child->DueDate != "" && $dbTo->Fields["dtDueDate"] != "0000-00-00")
               {
                  $dbTo->Fields[dtDueDate] = date("Y-m-d", strtotime("$rowModule->dtReleaseDate $Child->DueDate"));
               }//print_rr($dbTo->Fields); die;
               
               
               $newChild = $dbTo->Save(1, 0, $Child->UID_Prefix); //save
               //print_rr($newChild);

            //post
               //add old->new child array for DC!!!
               if($newChild->Error == 0)
                  $arrDC[$UID] = $newChild->ID;

               //add to Assignment array
               if($Child->PK == "AssignmentID")
                  $arrAssignment[$UID] = $newChild->ID;

            }//eoW2
         }//eoF
      }//eoW1

   //post
      //print_rr($arrDC);

      //copy any existing DC records and files
      if(is_array($arrDC)){
      foreach($arrDC as $fromUID => $toUID)
      {
         $row = $xdb->getRowSQL("SELECT *, REPLACE(strFilename, '$fromUID', '$toUID') AS toFilename FROM modDownloadContent WHERE UniqueID = '$fromUID'");
         if($row){
            $xdb->doQuery("
               INSERT INTO modDownloadContent(UniqueID, strFilename, strLastUser)
               VALUES ('$toUID','$row->toFilename','New Course Replication')");
            if(!copy($SystemSettings[DownloadableContentDirAdmin].$row->strFilename, $SystemSettings[DownloadableContentDirAdmin].$row->toFilename))
               print_rr(error_get_last());

         }
      }}

      //copy assignment questions and options to new assignment
      //$arrAssignment["CHMASS46EEP9"] = "CHMASS93CDGE";
      if(is_array($arrAssignment)){
      foreach($arrAssignment as $fromUID => $toUID)
      {
         $rstQ = $xdb->doQuery("SELECT * FROM surQuestion WHERE refAssignmentID = '$fromUID'");
         while($rowQ = $xdb->fetch_object($rstQ))
         {
            $dbFrom = new NemoDatabase("surQuestion", $rowQ->QuestionID, null, 0);//print_rr($dbFrom->Fields);
            $dbTo = new NemoDatabase("surQuestion", 0, null, 0);
            $dbTo->Fields = $dbFrom->Fields; //copy

            $dbTo->Fields["QuestionID"] = ""; //reassign
            $dbTo->Fields["refAssignmentID"] = $toUID;
            $dbTo->Fields["strLastUser"] = "New Course Replication";

            $newQ = $dbTo->Save(1,0);
            $xdb->doQuery("
               INSERT INTO surOption ( refQuestionID, strOption, intWeighting, intOrder )
               SELECT $newQ->ID AS refQuestionID, strOption, intWeighting, intOrder
               FROM surOption
               WHERE refQuestionID=$rowQ->QuestionID");
         }
      }}

      //copy co-ordinators
      $xdb->doQuery("INSERT INTO tblCourseCoordinator ( refCourseID, refUserID )
         SELECT $CourseToID AS refCourseID, refUserID
         FROM tblCourseCoordinator
         WHERE refCourseID=$CourseFromID");
   }

   public static function ReplicateAssignments($CourseToID, $CourseFromID)
   {//20130806 - replicate PW1 assignments from IW1 cid=68
      global $xdb, $DT, $SystemSettings;

   //ini

   //go
      $rstMain = $xdb->doQuery("
         SELECT modModule.refCourseID AS CIDFrom, modModule_1.refCourseID AS CourseID, modAssignment.*, modModule_1.ModuleID AS refModuleID, 1 as blnActive, 'Replicate - PJ' as strLastUser
         FROM modModule AS modModule_1 INNER JOIN (modAssignment INNER JOIN modModule ON modAssignment.refModuleID = modModule.ModuleID) ON modModule_1.strModuleName = modModule.strModuleName
         WHERE modModule.refCourseID=$CourseFromID AND modModule_1.refCourseID IN ($CourseToID)
         ORDER BY modModule.intModuleNumber",1);
      while($rowAss = $xdb->fetch_object($rstMain))
      {//print_rr($rowAss);
         $adb = new NemoDatabase("modAssignment", null, null);
         
         $adb->SetValues($rowAss);
         $adb->Fields[blnActive] = 1;
         
         $result = $adb->Save(0,1, "PW1ASS");

         $arrAssignment[$rowAss->AssignmentID] = $result->ID; //add to arrAss[OldUID] = NewUID

      }//eoW1
      print_rr($arrAssignment);

      //copy assignment questions and options to new assignment
      //$arrAssignment["CHMASS46EEP9"] = "CHMASS93CDGE";
      if(is_array($arrAssignment)){
      foreach($arrAssignment as $fromUID => $toUID)
      {
         $rstQ = $xdb->doQuery("SELECT * FROM surQuestion WHERE refAssignmentID = '$fromUID'");
         while($rowQ = $xdb->fetch_object($rstQ))
         {
            $dbFrom = new NemoDatabase("surQuestion", $rowQ->QuestionID, null, 0);//print_rr($dbFrom->Fields);
            $dbTo = new NemoDatabase("surQuestion", 0, null, 0);
            $dbTo->Fields = $dbFrom->Fields; //copy

            $dbTo->Fields["QuestionID"] = ""; //reassign
            $dbTo->Fields["refAssignmentID"] = $toUID;
            $dbTo->Fields["strLastUser"] = "New Course Replication";

            $newQ = $dbTo->Save(1,0);
            $xdb->doQuery("
               INSERT INTO surOption ( refQuestionID, strOption, intWeighting, intOrder )
               SELECT $newQ->ID AS refQuestionID, strOption, intWeighting, intOrder
               FROM surOption
               WHERE refQuestionID=$rowQ->QuestionID",1);
         }
      }}
   }
*/

}
?>
