<!DOCTYPE html>
<html>
   <head>
      <?php  
         define('USER', 'inese.andersone@gatewaybaltic.com');
         define('TOKEN', 'F274va12MeWcTdUfPfB9r7X3=3b0naF9I7=003r0'); 
         require 'Solve360Service.php';
         $caller=$_GET["c"];
         $solve360Service = new Solve360Service(USER, TOKEN);
         $data=array();
         
         switch ($caller) {
            case 'Sales LV':
            case 'Sales LT':
            case 'Sales EE':
            case 'Sales International':
               $projects = $solve360Service->searchProjectblogs(array('layout' => '1','searchmode' => 'S4471832','searchvalue' => "$caller",'special' => 'OR'));
               foreach ($projects->children() as $ch) {
                  $title=$ch->title;
                  if (strlen($title)>0) {
                     $id=$ch->id;
                     $clientEmail='';
                     $coord=$ch->custom9401708;
                     $coord='Jesse Turner';
                     $data[]=array("$id","$title",2,'Inese Andersone',"$coord","$clientEmail",false);
                  }
               }
               break;
            case 'Sandra Gudrite':
               $projects = $solve360Service->searchProjectblogs(array('layout' => '1','searchmode' => 'S9401709','searchvalue' => 'Preparation','special' => 'OR'));
               foreach ($projects->children() as $ch) {
                  $title=$ch->title;
                  if (strlen($title)>0) {
                     $id=$ch->id;
                     $clientEmail=$ch->custom9484073;
                     $coord=$ch->custom9401708;
                     $data[]=array("$id","$title",1,"$coord","$caller","$clientEmail",false);
                  }
               }
               // intentional run-through!!
            default:
               $projects = $solve360Service->searchProjectblogs(array('layout' => '1','searchmode' => 'S4471833','searchvalue' => "$caller",'special' => 'OR'));      
               foreach ($projects->children() as $ch) {
                  $title=$ch->title;
                  $statusStr=$ch->custom9401709;
                  switch ($statusStr) {
                     case 'Unstarted':
                        $status=0;
                        break;
                     case 'Selection':
                     case 'Preparation':
                        $status=1;
                        break;
                     case 'Attraction':
                        $status=2;
                        break;
                     case 'Finalisation':
                     case 'Reports':
                        $status=3;
                        break;
                     case 'Completed':
                        $status=4;
                        break;
                     default:
                        $status=-1;
                  }
                  if (strlen($title)>0 && ($status!=1 || $caller!='Sandra Gudrite')) {
                  //if (strlen($title)>0) {
                     $id=$ch->id;
                     $clientEmail=$ch->custom9484073;
                     $coord=$ch->custom9401708;
                     //$coord='Jesse Turner';
                     //$caller='Jesse Turner';
                     $data[]=array("$id","$title",$status,"$coord","$caller","$clientEmail",false);
                  }
               }
         }
      ?>
      <script type="text/javascript">
         // -------------------------- constants -------------------------------
         var SHIFT=1000;
         var NOSUBPROJECT="*NOSUBPROJECT*";
         //
         var WAITING=0;
         var SENT=-1;			// solve loading statuses
         var SENTplusCheckErrors =-2;
         var RECEIVED=-3;
         var ALLLOADING=-1;		// return value for _continueLoading function
         var ALLLOADED=-2;       // return value for _continueLoading function
         //
         var STATUS=0;
         var COMPANYID=1;		// solveCompanies indices
         var COMPANYNAME=2;
         var ACTIVITIES=3;		// (contains call logs and simple notes only - from under company + under relevant related contacts)
         var RELATED=4;			// (this will contain project blog relations only; for parsing [<project name>] tags)
         var WEBSITE=5;
         var PHONE=6;
         var ADDRESS=7;
         var TURNOVER=8;
         var EMPLOYEES=9;
         var PROFILE=10;			// for now use existing Solve profile field!
         var INDUSTRY=11;
         var BACKGROUND=12;
         var COUNTRY=13;
         var CREATED=14;
         var SUBPROJ=15;
         var DATE1=16;
         var COMMENT1=17;
         var DATE2=18;
         var COMMENT2=19;
         var DECISION=20;
         var HIDEON=21;    // true or false
         var oDATE1=22;
         var oCOMMENT1=23;
         var oDATE2=24;
         var oCOMMENT2=25;
         var oDECISION=26;
         var CONTACTS=27;
         //
         var CONTACTNAME=0;
         var CONTACTTITLE=1;
         var CONTACTLANDPHONE=2;
         var CONTACTMOBILE=3;
         var CONTACTEMAIL=4;
         var CONTACTWEBSITE=5;
         var CONTACTCOUNTRY=6;
         var CONTACTASSIGNEDTO=7;
         var CONTACTRELATEDTO=8;
         var CONTACTISRELATED=9;
         var CONTACTPROJECTS=10;
         var CONTACTID=11;
         //
         var DATE=0;
         var COMMENT=1;
         var COMTYPE=2;
         var ACTIVITYCONTACTNAME=3;
         var ISCALL=0;     // for COMTYPE (notes/other = 1)
         
         var TOTALCALLS=0;
         var NO1CALLS=1;
         var NO2CALLS=2;
         var oTOTALCALLS=3;
         var oNO1CALLS=4;
         var oNO2CALLS=5;
         //
         var NOTFOUND=-1;
         var FIRSTCONTACT=0;
         var RED=1;
         var YELLOW=2;
         var GREEN=3;
         var START=4;
         var END=5;
         var PRIVATE=6;
         var CONFIRMED=7;
         var INVALID=8;
         var UNCONTACTABLE=9;
         var NOTCONTACTED=10;		
         var NODECISION=0;
         var ONFIRSTCALL=-2;
         //
         // ***********************************
         var UNSTARTED=0;
         var PREPARATION=1;
         var ATTRACTION=2;
         var FINALISATION=3;
         var COMPLETED=4;
         // ***********************************
         //
         var MENU=0;
         var RADIO=1;
         var CHECK=2;
         var HIDE=3;
         //
         var DONOTHING=-1;
         var ACTIONS=0;
         var REPORTS=1;
         var FULL=2;
         var SHORT=3;
         var SUMMARY=4;
         var ACTIONVIEW=5;
         var PROJECTVIEW=6;
         var TOGGLEPROJECTSPLIT=7;
         var HIDECOLOURED=8;
         var HIDEWHITE=9;
         //
         // ***********************************
         //
         var HEADERSMALL="#fffffd";			// th, small font (centred)
         var HEADER="#ffffff";			// th, bottom border (centred)
         var HEADERLEFT="#fffffe";			// th, bottom border (left)
         var BLANK="-1";
         var DATA="0";				// default
         var DATA_BOLD="1";			// th, left align
         var DATA_RIGHT="2";			// right align
         var UPDATA="0";			// default,top
         var UPDATA_BOLD="1";			// th, left align,top
         var UPDATA_RIGHT="2";			// right align,top
         var UPDATA_CENTRED="3";			// centre align
         
         // -------------------------- globals -------------------------------         
         var projects;
         var mainDisplay=REPORTS;
         var reportsDisplay=SUMMARY;
         var actionsDisplay=ACTIONVIEW;
         var splitProjects=true;
         var hideColoured=false;
         var hideWhite=false;
         var showStats=false;
         var dateFrom;            // date for OLD stats, status, etc.
         //
         var loadingBlog=0;
         var solveCompanies=new Array();
         var solveStats=new Array();         // =[ #activities(excl.notes,private) , #no1 , #no2 ]
         var updatingProj=-1;
         //
         var no12patch=new Array();
         var missing1tags=new Array();
         
         var loadError="";
         
         // -------------------------- update functions -------------------------------
         function _update(id,checkErrorsAfter) {
            var comp=parseInt(id.slice(5),10);
            comp=comp%SHIFT;
            var proj=_getProjectFromRadio();
            //if (comp==3) alert(solveCompanies[proj][comp][CONTACTS].toSource());
            //alert(solveCompanies[proj][comp][COMPANYNAME]);
            solveCompanies[proj][comp][STATUS]=WAITING;
            _reloadCompany(proj,comp,checkErrorsAfter);
            _display(MENU,DONOTHING);
         }
         
         function _reloadProject() {
            var proj=_getProjectFromRadio();
            //alert("Not yet functional");
            document.location.reload(true);
         }
         
         function _correctErrors(corrections,proj,thisComp,subProj,cont) {
            if (proj==-1) proj=_getProjectFromRadio();
            comp=thisComp%SHIFT;
            if (subProj==-1) subProj=(thisComp-comp)/SHIFT;

            if (corrections==0) {
               //if (missing1tags[proj][comp][subProj]) _correctMissing1Tag(proj,comp,subProj);
               
               for (var j=0;j<solveCompanies[proj][comp][CONTACTS].length;j++) {
                  var toCorrect="";
                  var notinsolve=false;
                  var noactivity=true;
                  var isrelated=solveCompanies[proj][comp][CONTACTS][j][CONTACTISRELATED];
                  if (solveCompanies[proj][comp][CONTACTS][j][CONTACTTITLE]=="NOTINSOLVE") notinsolve=true;
                  var startLoop=(solveCompanies[proj][comp][SUBPROJ].length==0) ?0 :1;
                  for (var k=startLoop;k<=solveCompanies[proj][comp][SUBPROJ].length;k++) {
                     if (solveCompanies[proj][comp][CONTACTS][j][CONTACTPROJECTS][k]!=-1) noactivity=false;
                  }

                  if (!notinsolve) {
                     if (isrelated && noactivity) {
                        var projTag=projects[proj][1];
                        if (subProj!=0) projTag+=":"+solveCompanies[proj][comp][SUBPROJ][subProj-1];
                        toCorrect+="con==[*]["+projTag+"]con='"+solveCompanies[proj][comp][CONTACTS][j][CONTACTNAME]+"';;";
                     }
                     if (!isrelated && !noactivity) toCorrect+="related=="+projects[proj][0]+";;";
                     if (isrelated && solveCompanies[proj][comp][CONTACTS][j][CONTACTLANDPHONE]=="" && solveCompanies[proj][comp][PHONE]!="") toCorrect+="phone=="+solveCompanies[proj][comp][PHONE]+";;";
                     if (isrelated && solveCompanies[proj][comp][CONTACTS][j][CONTACTWEBSITE]=="" && solveCompanies[proj][comp][WEBSITE]!="") toCorrect+="website=="+solveCompanies[proj][comp][WEBSITE]+";;";
                     if (isrelated && solveCompanies[proj][comp][CONTACTS][j][CONTACTCOUNTRY]=="" && solveCompanies[proj][comp][COUNTRY]!="") toCorrect+="country=="+solveCompanies[proj][comp][COUNTRY]+";;";
                     if (isrelated && solveCompanies[proj][comp][CONTACTS][j][CONTACTASSIGNEDTO]=="") toCorrect+="assigned=="+_getAssignedToCode(projects[proj][4])+";;";
                  }
                  if (toCorrect.length>0) _correctContact(proj,comp,subProj,j,toCorrect.slice(0,toCorrect.length-2));
               }
            }
         }
         
         function _getAssignedToCode(callerName) {
            var GBstaff = [   ["42368419","Baiba Auzane"],["24202362","Didzis Melbiksis"],["23392014","Inese Manguse"],
                              ["34988889","Jesse Turner"],["25687818","Liga Vanaga"],["47351311","Mara Labunska"],
                              ["35555333","Zanda Vipule"],["47664778","Baiba Dance"], ];
            var found=NOTFOUND;
            for (var i=0;i<GBstaff.length && found==NOTFOUND;i++) {
               if (GBstaff[i][1]==callerName) found=i;
            }
            if (found==NOTFOUND) alert("Error - couldn't find caller reference code!");
            else return GBstaff[found][0];
         }
         
         function _correctContact(proj,comp,subProj,cont,toCorrect) {
            //alert(solveCompanies[proj][comp][CONTACTS][cont][CONTACTID]);
            //alert(toCorrect.toSource());
            while (toCorrect.indexOf("+")>=0) {
               var pos=toCorrect.indexOf("+");
               toCorrect=toCorrect.slice(0,pos)+"*plus*"+toCorrect.slice(pos+1);
            }
            var xmlhttp;
            if (window.XMLHttpRequest) xmlhttp=new XMLHttpRequest();
            else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            xmlhttp.onreadystatechange=function() {
               if (xmlhttp.readyState==4 && xmlhttp.status==200) {
                  var retData=JSON.parse(xmlhttp.responseText);
                  // =["OK",proj,comp,subProj,cont,toCorrect]
                  if (retData[0]!="OK") alert("Error correcting contact");
                  //else alert(retData[5]);
                  var proj=parseInt(retData[1],10);
                  var comp=parseInt(retData[2],10);
                  var subProj=parseInt(retData[3],10);
                  var cont=parseInt(retData[4],10);
                  var toCorrect=retData[5].split(";;");
                  //
                  var needUpdate=false;
                  var needReload=false;
                  for (var i=0;i<toCorrect.length;i++) {
                     var corr=toCorrect[i].split("==");
                     switch (corr[0]) {
                        case "phone":
                           solveCompanies[proj][comp][CONTACTS][cont][CONTACTLANDPHONE]=corr[1];
                           break;
                        case "website":
                           solveCompanies[proj][comp][CONTACTS][cont][CONTACTWEBSITE]=corr[1];
                           break;
                        case "country":
                           solveCompanies[proj][comp][CONTACTS][cont][CONTACTCOUNTRY]=corr[1];
                           break;
                        case "assigned":
                           solveCompanies[proj][comp][CONTACTS][cont][CONTACTASSIGNEDTO]=projects[proj][4];
                           break;
                        case "related":
                           solveCompanies[proj][comp][CONTACTS][cont][CONTACTISRELATED]=true;
                           // intentional follow through(!)
                        case "con":
                           needReload=true;
                           break;
                     }
                  }
                  //
                  solveCompanies[proj][comp][STATUS]=RECEIVED;
                  if (needUpdate) {
                     _processActivities(proj,comp,false);
                     _calculateCallStats(proj);
                     solveCompanies[proj][comp][HIDEON][0]=false;
                     if (solveCompanies[proj][comp][SUBPROJ].length>0) {
                        for (var k=1;k<=solveCompanies[proj][comp][SUBPROJ].length;k++) solveCompanies[proj][comp][HIDEON][k]=false;
                     }
                  } else if (needReload) _reloadCompany(proj,comp);
                  _display(MENU,DONOTHING);
               }
            }
            solveCompanies[proj][comp][STATUS]=SENT;
            xmlhttp.open("GET","correctcontact.php?proj="+proj+"&comp="+comp+"&subProj="+subProj+"&cont="+cont+"&contId="+solveCompanies[proj][comp][CONTACTS][cont][CONTACTID] +"&toCorrect="+toCorrect,true);
            //alert("correctcontact.php?proj="+proj+"&comp="+comp+"&subProj="+subProj+"&cont="+cont+"&contId="+solveCompanies[proj][comp][CONTACTS][cont][CONTACTID] +"&toCorrect="+toCorrect);
            xmlhttp.send();
            _display(MENU,DONOTHING); 
         }
         
         // ----------------------------- selector date functions --------------------------------
         
         function _setDates() {
            var d=new Date();
            var dy=d.getDay();
            if (dy<2) document.getElementById("yesterday").innerHTML="Show status on Friday";
            else document.getElementById("yesterday").innerHTML="Show status yesterday";
            if (dy==1) document.getElementById("weekstart").style.display="none";
            else document.getElementById("weekstart").style.display="";
            var sel=document.getElementById("OLDselector");
            switch (parseInt(sel[sel.selectedIndex].value)) {
               case 0:
               case 7:
               case 14:
               case 28:
                  d.setDate(d.getDate()-parseInt(sel[sel.selectedIndex].value));
                  break;
               case 1:
                  if (dy>1) d.setDate(d.getDate()-1);
                  else d.setDate(d.getDate()-2-dy);
                  break;
               case 2:
                  if (dy==0) dy=7;
                  d.setDate(d.getDate()-dy+1);
                  break;
            }
            var yr=d.getFullYear();
            var mn="0"+(d.getMonth()+1);
            var dy="0"+d.getDate();
            var dateFromStr=yr+mn.slice(-2)+dy.slice(-2)+"000000";
            dateFrom=parseInt(dateFromStr.slice(2),10);
         }
         
         function _changeDate() {
            _setDates();
            var proj=_getProjectFromRadio();
            if (proj==NOTFOUND) alert("Unexpected error!");
            for (var i=0;i<solveCompanies[proj].length;i++) _processActivities(proj,i,true);
            _calculateCallStats(proj);
            _displayProgressSummary(proj);
         }
         
         // -------------------------- display functions -------------------------------
         function _display(type,option) {
            if (type==MENU) {
               switch (option) {
                  case ACTIONS:
                     mainDisplay=ACTIONS;
                     document.getElementById("actionOpts").style.display="inline";
                     document.getElementById("reportOpts").style.display="none";
                     _setProjectSelectDisplay(CHECK);
                     _highlighting("ACTIONS","REPORTS","");
                     break;
                  case REPORTS:
                     mainDisplay=REPORTS;
                     document.getElementById("actionOpts").style.display="none";
                     document.getElementById("reportOpts").style.display="inline";
                     _setProjectSelectDisplay(RADIO);
                     _highlighting("REPORTS","ACTIONS","");
                     break;
                  case FULL:
                     reportsDisplay=FULL;
                     _highlighting("FULL","SHORT","SUMMARY");
                     break;
                  case SHORT:
                     reportsDisplay=SHORT;
                     _highlighting("SHORT","FULL","SUMMARY");
                     break;
                  case SUMMARY:
                     reportsDisplay=SUMMARY;
                     _highlighting("SUMMARY","FULL","SHORT");
                     break;
                  case ACTIONVIEW:
                     actionsDisplay=ACTIONVIEW;
                     _highlighting("ACTIONVIEW","PROJECTVIEW","");
                     break;
                  case PROJECTVIEW:
                     actionsDisplay=PROJECTVIEW;
                     _highlighting("PROJECTVIEW","ACTIONVIEW","");
                     break;
                  case TOGGLEPROJECTSPLIT:
                     splitProjects=!splitProjects;
                     if (splitProjects) document.getElementById("TOGGLEPROJECTSPLIT").innerHTML="Split projects on";
                     else document.getElementById("TOGGLEPROJECTSPLIT").innerHTML="Split projects off";
                     break;
                  case HIDECOLOURED:
                     hideColoured=!hideColoured;
                     if (hideColoured) document.getElementById("HIDECOLOURED").innerHTML="Hide on";
                     else document.getElementById("HIDECOLOURED").innerHTML="Hide off";
                     break;
                  case HIDEWHITE:
                     hideWhite=!hideWhite;
                     if (hideWhite) document.getElementById("HIDEWHITE").innerHTML="Hide on";
                     else document.getElementById("HIDEWHITE").innerHTML="Hide off";
                     break;
                  case SHOWSTATS:
                     showStats=!showStats;
                     if (showStats) document.getElementById("SHOWSTATS").innerHTML="Statistics on";
                     else document.getElementById("SHOWSTATS").innerHTML="Statistics off";
                     break;
               }
            }
            if (type==HIDE) {
               _setHide(option);
            } else {
               if (mainDisplay==REPORTS) _displayReports();
               else _displayActions();
            }
         }
         
         function _setHide(id) {
            // need to check that not in action mode!!!!!!!!!!!!!!!
            // in fact, in action mode, will need project number to be passed by function!!
            // ... or IDs in action mode will need to include project index!
            var proj=_getProjectFromRadio();
            if (proj==NOTFOUND) alert("Unexpected error!");
            var comp=parseInt(id.slice(5),10);
            var thisSubProj=Math.floor(comp/SHIFT);
            comp=comp%SHIFT;
            var colr=(solveCompanies[proj][comp][DECISION][thisSubProj]==NODECISION || solveCompanies[proj][comp][DECISION][thisSubProj]==ONFIRSTCALL) ?false :true;
            if (document.getElementById(id).checked=="checked" || document.getElementById(id).checked==true) {
               solveCompanies[proj][comp][HIDEON][thisSubProj]=true;
               if ((colr && hideColoured) || (!colr && hideWhite)) {
                  document.getElementById("progressRow"+parseInt(id.slice(5),10)).style.display="none";
                  _checkDisplayNonEmpty(proj);
               }
            } else {
               solveCompanies[proj][comp][HIDEON][thisSubProj]=false;
               //if ((colr && hideColoured) || (!colr && hideWhite)) alert("show company");
            }
         }
         
         function _highlighting(selected,desel1,desel2) {
            document.getElementById(selected).setAttribute("class","menuSelected");
            document.getElementById(desel1).setAttribute("class","menu");
            if (desel2!="") document.getElementById(desel2).setAttribute("class","menu");
         }
         
         function _showOnly(id) {
            var divs=["progresssummary","OLDprogresssummary","progressreport","actionlist","loadstatus","OLDselector","emptyreport"];
            for (var i=0;i<divs.length;i++) {
               if (divs[i]==id) document.getElementById(id).style.display="block";
               else document.getElementById(divs[i]).style.display="none";
            }
            if (id=="progresssummary") {
               var sel=document.getElementById("OLDselector");
               sel.style.display="block";
               if (sel.selectedIndex==0) document.getElementById("OLDprogresssummary").style.display="none";
               else document.getElementById("OLDprogresssummary").style.display="block";
               document.getElementById("SHOWSTATS").style.display="inline";
               if (showStats) {
                  document.getElementById("stats").style.display="block";
                  document.getElementById("OLDstats").style.display="block";
                  document.getElementById("summaryseparator").style.display="block";
               } else {
                  document.getElementById("stats").style.display="none";
                  document.getElementById("OLDstats").style.display="none";
                  document.getElementById("summaryseparator").style.display="none";
               }
            } else {
               document.getElementById("SHOWSTATS").style.display="none";
               document.getElementById("summaryseparator").style.display="none";
               document.getElementById("OLDselector").style.display="none";
            }
            if (id=="progressreport" || id=="emptyreport") {
               document.getElementById("HIDECOLOURED").style.display="inline";
               document.getElementById("HIDEseparator").style.display="inline";
               document.getElementById("HIDEWHITE").style.display="inline";
            } else {
               document.getElementById("HIDECOLOURED").style.display="none";
               document.getElementById("HIDEseparator").style.display="none";
               document.getElementById("HIDEWHITE").style.display="none";
            }
            if (id=="") {
            } else {
            }
         }
         
         function _setProjectSelectDisplay(type) {
            if (projects.length>1) {
               if (type==RADIO) {
                  var rad="inline";
                  var chk="none";
               } else {
                  var rad="none";
                  var chk="inline";
               }
               for (var i=0;i<projects.length;i++) {
                  document.getElementById("check"+i).style.display=chk;
                  document.getElementById("checkLabel"+i).style.display=chk;
                  document.getElementById("radio"+i).style.display=rad;
                  document.getElementById("radioLabel"+i).style.display=rad;
               }
            } else {
               document.getElementById("check0").style.display="none";
               document.getElementById("checkLabel0").style.display="none";
               document.getElementById("radio0").style.display="inline";
               document.getElementById("radioLabel0").style.display="inline";
            }
         }
         
         function _tickAndHide(proj,row) {
            if (row==-1) {
               for (i=0;i<solveCompanies[proj].length;i++) {
                  var startLoop=(solveCompanies[proj][i][SUBPROJ].length==0) ?0 :1;
                  for (var k=startLoop;k<=solveCompanies[proj][i][SUBPROJ].length;k++) {
                     var toID=k*SHIFT+i;
                     //alert(solveCompanies[proj][i][COMPANYNAME]+" / "+k+" ... "+solveCompanies[proj][i][HIDEON][k]);
                     if (solveCompanies[proj][i][HIDEON][k]==true) {
                        document.getElementById("HIDE_"+toID).checked="checked";
                        var colr=(solveCompanies[proj][i][DECISION][k]==NODECISION || solveCompanies[proj][i][DECISION][k]==ONFIRSTCALL) ?false :true;
                        if ((colr && hideColoured) || (!colr && hideWhite)) document.getElementById("progressRow"+toID).style.display="none";
                     } else {
                        document.getElementById("HIDE_"+toID).checked="";
                        document.getElementById("progressRow"+toID).style.display="";
                     }
                  }
               }
            }
         }
         
         // *************** reports *****************
         function _displayReports() {
            var proj=_getProjectFromRadio();
            if (proj==NOTFOUND) alert("Unexpected error!");
            if (updatingProj==proj) {
               
            } else {
               switch (reportsDisplay) {
                  case FULL:
                  case SHORT:
                     _displayProgressReport(proj);
                     break;
                  case SUMMARY:
                     _displayProgressSummary(proj);
                     break;
               }
            }
         }
         
         function _getProjectFromRadio() {
            var proj=NOTFOUND;
            for (var i=0;i<projects.length && proj==NOTFOUND;i++) {
               var chkd=document.getElementById("radio"+i).checked;
               if (chkd=="checked" || chkd==true) proj=i;
            }
            return proj;
         }
         
         // ******** summary ********
         function _displayProgressSummary(proj) {
            document.getElementById("errorcontainer").style.display="none";
            //
            _displayErrors(_searchForMissingTags(proj),"missing1tag");           
            _displayErrors(_checkForContactRelationErrors("unentered",proj),"contactnotinsolve");
            _displayErrors(_checkForContactRelationErrors("nocon",proj),"missingcontag");
            _displayErrors(_checkForContactRelationErrors("norelation",proj),"missingrelatedto");
            _displayErrors(_checkForContactRelationErrors("unrelated",proj),"unrelatedcontacts");
            _displayErrors(_checkForMissingContactInformation(proj),"missinginfo");
         
            _setText("greenNum",_countDecisions(proj,GREEN));
            _setText("yellowNum",_countDecisions(proj,YELLOW));
            _setText("redNum",_countDecisions(proj,RED));
            _setText("firstNum",_countDecisions(proj,ONFIRSTCALL));
            _setText("followNum",_countDecisions(proj,NODECISION));
            _setText("callsT",solveStats[proj][TOTALCALLS]);
            _setText("calls1",solveStats[proj][NO1CALLS]);
            _setText("calls2",solveStats[proj][NO2CALLS]);
            _setText("callsC",solveStats[proj][TOTALCALLS]-solveStats[proj][NO1CALLS]-solveStats[proj][NO2CALLS]);
            _setText("totalNum",solveCompanies[proj].length+" =");
            //
            _setText("OLDgreenNum",_countOldDecisions(proj,GREEN));
            _setText("OLDyellowNum",_countOldDecisions(proj,YELLOW));
            _setText("OLDredNum",_countOldDecisions(proj,RED));
            _setText("OLDfirstNum",_countOldDecisions(proj,ONFIRSTCALL));
            _setText("OLDfollowNum",_countOldDecisions(proj,NODECISION));
            _setText("OLDcallsT",solveStats[proj][oTOTALCALLS]);
            _setText("OLDcalls1",solveStats[proj][oNO1CALLS]);
            _setText("OLDcalls2",solveStats[proj][oNO2CALLS]);
            _setText("OLDcallsC",solveStats[proj][oTOTALCALLS]-solveStats[proj][oNO1CALLS]-solveStats[proj][oNO2CALLS]);
            _setText("OLDtotalNum",_countOLDcompanies(proj)+" =");
            //
            document.getElementById("statusselector").selectedIndex=projects[proj][2];
            _showOnly("progresssummary");
         }
         
         function _displayErrors(text,id) {
            var el=document.getElementById(id);
            if (text=="") el.style.display="none";
            else {
               el.style.display="block";
               el.innerHTML+=text;
               document.getElementById("errorcontainer").style.display="block";
            }
         }
         
         function _errorHeaderClick(el) {
            switch (el.innerHTML) {
               case "Mark as correct":
                  el.innerHTML="Correct errors";
                  el.style.color="green";
                  var colr="grey";
                  break;
               case "Correct errors":
                  el.innerHTML="Mark as correct";
                  el.style.color="blue";
                  var colr="black";
                  break;
            }
            document.getElementById("contactnotinsolve").style.color=colr;
            document.getElementById("allunentered").style.color=colr;
            for (var i=0;i<solveCompanies[proj].length;i++) {
               for (var j=0;j<solveCompanies[proj][i][CONTACTS].length;j++) {
                  var compId="00"+i;
                  var conId="00"+j;
                  var existing=document.getElementById("unentered"+compId.slice(-3)+conId.slice(-3));
                  if (existing!=null) existing.style.color=colr;
               }
            }
         }
         
         function _mouseError(mouseAction,el) {
            var id=el.id;
            var colr="black";
            var textDec="none";
            if (mouseAction==2) {
               alert("click");
            } else {
               if (mouseAction==1) {
                  switch (document.getElementById("errorheader").innerHTML) {
                     case "Mark as correct":
                        colr="blue";
                        textDec="underline";
                        break;
                     case "Correct errors":
                        colr="green";
                        textDec="underline";
                        break;
                  }
               }
               if ((id=="allunentered" || id.slice(0,9)=="unentered") && document.getElementById("errorheader").innerHTML!="Mark as correct") {
                  colr="grey";
                  textDec="none";
               }
               el.style.color=colr;
               el.style.textDecoration=colr;
            }
      
            var setAll=[];
            if (id=="allunentered") {
               setAll.push("unentered");
               el.style.color="black";
               if (colr=="grey") el.style.color="grey";
               el.style.textDecoration="none";
            }
            if (id=="allnocon") {
               setAll.push("nocon");
               el.style.color="black";
               el.style.textDecoration="none";
            }
            if (id=="allunrelated") {
               setAll.push("unrelated");
               el.style.color="black";
               el.style.textDecoration="none";
            }
            if (id=="allnorelation") {
               setAll.push("norelation");
               el.style.color="black";
               el.style.textDecoration="none";
            }
            if (id=="allmissing" || id.slice(0,14)=="contactmissing") {
               setAll.push("nophone");
               setAll.push("nowebsite");
               setAll.push("noassigned");
               setAll.push("nocountry");
               el.style.color="black";
               el.style.textDecoration="none";
            }
            if (setAll.length>0) {
               if (id.slice(0,14)=="contactmissing") {
                  var compId=id.slice(14,17);
                  var conId=id.slice(17,20);
                  for (var setType=0;setType<setAll.length;setType++) {
                     var existing=document.getElementById(setAll[setType]+compId+conId);
                     if (existing!=null) {
                        if (mouseAction==2) {
                           alert("click-there");
                        } else {
                           existing.style.color=colr;
                           existing.style.textDecoration=colr;
                        }
                     }
                  }
               } else {
                  var proj=_getProjectFromRadio();
                  for (var setType=0;setType<setAll.length;setType++) {
                     for (var i=0;i<solveCompanies[proj].length;i++) {
                        for (var j=0;j<solveCompanies[proj][i][CONTACTS].length;j++) {
                           var compId="00"+i;
                           var conId="00"+j;
                           //alert(setAll[setType]+compId.slice(-3)+conId.slice(-3));
                           var existing=document.getElementById(setAll[setType]+compId.slice(-3)+conId.slice(-3));
                           if (existing!=null) {
                              if (mouseAction==2) {
                                 alert("clickhere");
                              } else {
                                 //alert("there");
                                 existing.style.color=colr;
                                 existing.style.textDecoration=colr;
                              }
                           }
                        }
                     }
                  }
               }
            }
         }
         
         // onclick='_mouseError(2,this)'
         
         // unrelated contacts:  contacts who are con= (related to company but not project), contacts who aren't con= [probably not an error]
         // + related contacts who aren't con= (those who have -1??)
         //                                                                                                                                                    TITLE          ISRELATED   ACTIVITY==-1
         // unentered contact: => contact ==NOTINSOLVE                                                                                                         notinsolve         -           -
         // missing con=   => isrelated==true, ==-1                                                                                                           !notinsolve        true        true
         // missing relation: actually, these are included in contact list but comments aren't!, => contacts !=-1, !=NOTINSOLVE but isrelated==false          !notinsolve        false       false
         // unrelated contacts: => !=NOTINSOLVE, isrelated==false (add == -1)                                                                                 !notinsolve        false       true
         
         function _checkForContactRelationErrors(errType,proj) {
            // errType="unentered","nocon","norelation","unrelated" -- id bases for elements too!
            switch (errType) {
               case "unentered":
                  _setText("contactnotinsolve","<span class='bold' id='allunentered' onclick='_mouseError(2,this)' onmouseover='_mouseError(1,this)' onmouseout='_mouseError(0,this)'>Unentered contacts: </span>");
                  break;
               case "nocon":
                  _setText("missingcontag","<span class='bold' id='allnocon' onclick='_mouseError(2,this)' onmouseover='_mouseError(1,this)' onmouseout='_mouseError(0,this)'>Missing <span class='italic'>con=</span> code: </span>");
                  break;
               case "norelation":
                  _setText("missingrelatedto","<span class='bold' id='allnorelation' onclick='_mouseError(2,this)' onmouseover='_mouseError(1,this)' onmouseout='_mouseError(0,this)'>Missing related to: </span>");
                  break;
               case "unrelated":
                   _setText("unrelatedcontacts","<span class='bold' onclick='_mouseError(2,this)' onmouseover='_mouseError(1,this)' onmouseout='_mouseError(0,this)' id='allunrelated'>Unrelated contacts: </span>");
                  break;
            }
            
            var errorText="";
            for (var i=0;i<solveCompanies[proj].length;i++) {
               for (var j=0;j<solveCompanies[proj][i][CONTACTS].length;j++) {
                  var notinsolve=false;
                  var noactivity=true;
                  var isrelated=solveCompanies[proj][i][CONTACTS][j][CONTACTISRELATED];
                  if (solveCompanies[proj][i][CONTACTS][j][CONTACTTITLE]=="NOTINSOLVE") notinsolve=true;
                  
                  var startLoop=(solveCompanies[proj][i][SUBPROJ].length==0) ?0 :1;
                  for (var k=startLoop;k<=solveCompanies[proj][i][SUBPROJ].length;k++) {
                     if (solveCompanies[proj][i][CONTACTS][j][CONTACTPROJECTS][k]!=-1) noactivity=false;
                  }
                  
                  var addToList=false;
                  if (errType=="unentered" && notinsolve) addToList=true;
                  if (errType=="nocon" && !notinsolve && isrelated && noactivity) addToList=true;
                  if (errType=="norelation" && !notinsolve && !isrelated && !noactivity) addToList=true;
                  if (errType=="unrelated" && !notinsolve && !isrelated && noactivity) addToList=true;
                  
                  if (addToList) {
                     if (errorText!="") errorText+=", ";
                     var compId="00"+i;
                     var conId="00"+j;
                     errorText+="<span onclick='_mouseError(2,this)' onmouseover='_mouseError(1,this)' onmouseout='_mouseError(0,this)' id='"+errType+compId.slice(-3)+conId.slice(-3)+"'>"+solveCompanies[proj][i][CONTACTS][j][CONTACTNAME]+"</span>";
                  }
               }
            }
            return errorText;
         }
         
         function _searchForMissingTags(proj) {
            var errorText="";
            _setText("missing1tag","<span class='bold'>Missing [1] tag: </span>");
            for (var i=0;i<missing1tags[proj].length;i++) {
               var startLoop=(solveCompanies[proj][i][SUBPROJ].length==0) ?0 :1;
               for (var k=startLoop;k<=solveCompanies[proj][i][SUBPROJ].length;k++) {
                  if (missing1tags[proj][i][k]) {
                     if (errorText!="") errorText+=", ";
                     errorText+=solveCompanies[proj][i][COMPANYNAME];
                     if (k>0) errorText+=" ("+solveCompanies[proj][i][SUBPROJ][k-1]+")";
                  }
               }
            }
            return errorText; 
         }
                  
         function _checkForMissingContactInformation(proj) {
            _setText("missinginfo","<p class='errorsub bold' onclick='_mouseError(2,this)' onmouseover='_mouseError(1,this)' onmouseout='_mouseError(0,this)' id='allmissing'>Missing information: </p>");
            var errorText="";
            for (var i=0;i<solveCompanies[proj].length;i++) {
               for (var j=0;j<solveCompanies[proj][i][CONTACTS].length;j++) {
                  var tmpErrTxt="";
                  var compId="00"+i;
                  var conId="00"+j;
                  if (solveCompanies[proj][i][CONTACTS][j][CONTACTLANDPHONE]=="" && solveCompanies[proj][i][PHONE]!="") tmpErrTxt+="<span onclick='_mouseError(2,this)' onmouseover='_mouseError(1,this)' onmouseout='_mouseError(0,this)' class='italic' id='nophone"+compId.slice(-3)+conId.slice(-3)+"'>phone number</span>, ";
                  if (solveCompanies[proj][i][CONTACTS][j][CONTACTWEBSITE]=="" && solveCompanies[proj][i][WEBSITE]!="") tmpErrTxt+="<span onclick='_mouseError(2,this)' onmouseover='_mouseError(1,this)' onmouseout='_mouseError(0,this)' class='italic' id='nowebsite"+compId.slice(-3)+conId.slice(-3)+"'>website</span>, ";
                  if (solveCompanies[proj][i][CONTACTS][j][CONTACTCOUNTRY]=="" && solveCompanies[proj][i][COUNTRY]!="") tmpErrTxt+="<span onclick='_mouseError(2,this)' onmouseover='_mouseError(1,this)' onmouseout='_mouseError(0,this)' class='italic' id='nocountry"+compId.slice(-3)+conId.slice(-3)+"'>country</span>, ";
                  if (solveCompanies[proj][i][CONTACTS][j][CONTACTASSIGNEDTO]=="") tmpErrTxt+="<span onclick='_mouseError(2,this)' onmouseover='_mouseError(1,this)' onmouseout='_mouseError(0,this)' class='italic' id='noassigned"+compId.slice(-3)+conId.slice(-3)+"'>assigned to</span>, ";
                  if (tmpErrTxt!="" && solveCompanies[proj][i][CONTACTS][j][CONTACTTITLE]!="NOTINSOLVE") {
                     tmpErrTxt="<p class='errorsub'><span onclick='_mouseError(2,this)' onmouseover='_mouseError(1,this)' onmouseout='_mouseError(0,this)' class='italic' id='contactmissing"+compId.slice(-3)+conId.slice(-3)+"'>"+solveCompanies[proj][i][CONTACTS][j][CONTACTNAME]+"</span>: "+tmpErrTxt;
                     tmpErrTxt=tmpErrTxt.slice(0,tmpErrTxt.length-2)+"</p>";
                     errorText+=tmpErrTxt;
                  }
               }
            }
            return errorText;
         }
         
         function _setText(id,text) {
            var el=document.getElementById(id);
            el.innerHTML=text;
         }
         
         function _countDecisions(proj,dec) {
            var count=0;
            for (var i=0;i<solveCompanies[proj].length;i++) {
               if (solveCompanies[proj][i][SUBPROJ].length==0) {
                  if (solveCompanies[proj][i][DECISION][0]==dec) count++;
               } else {
                  var tmpDec=ONFIRSTCALL;
                  var isFirst=false;
                  var isFollow=false;
                  for (k=1;k<=solveCompanies[proj][i][SUBPROJ].length;k++) {
                     if (solveCompanies[proj][i][DECISION][k]==ONFIRSTCALL) isFirst=true;
                     if (solveCompanies[proj][i][DECISION][k]==NODECISION) isFollow=true;
                     if (solveCompanies[proj][i][DECISION][k]>tmpDec) tmpDec=solveCompanies[proj][i][DECISION][k];
                  }
                  if (tmpDec==RED && isFollow) tmpDec=NODECISION;
                  else if (tmpDec==RED && isFirst) tmpDec=ONFIRSTCALL;
                  if (tmpDec==dec) count++;
               }
            }
            return count;
         }
         
         function _countOldDecisions(proj,dec) {
            var count=0;
            for (var i=0;i<solveCompanies[proj].length;i++) {
               if (solveCompanies[proj][i][oDECISION][0]==dec && solveCompanies[proj][i][CREATED]<=dateFrom) count++;
            }
            return count;
         }
         
         // ******** progress reports ********
         function _displayProgressReport(proj) {
            var existing=document.getElementById("progressTable");
            if (existing!=null) document.getElementById("progressreport").removeChild(existing);
            document.getElementById("HIDECOLOURED").style.display="inline";
            document.getElementById("HIDEseparator").style.display="inline";
            document.getElementById("HIDEWHITE").style.display="inline";
            
            var table=document.createElement("table");
            table.setAttribute("id","progressTable");
            if (reportsDisplay==FULL) var columnWidths=[25,77,30,155,30,155];
            else var columnWidths=[25,113,45,315]; 
            		
            var tableWidth=_calculateTableWidth(columnWidths)+"px";             
            table.style.width=tableWidth;
            _setTableColumnWidths(table,columnWidths);
            
            var header=_makeProgressReportHeader();	
            table.appendChild(header);
            
            var body=_makeProgressReportBody(proj);		
            table.appendChild(body);
            
            document.getElementById("progressreport").appendChild(table);
            _tickAndHide(proj,-1);
            _checkDisplayNonEmpty(proj);
         }

         // *************** actions *****************
         function _displayActions() {
            _showOnly("actionlist");
         }

         function _checkDisplayNonEmpty(proj) {
            var visComp=0;
            var subDivided=0;
            var numSubProj=0;
            for (i=0;i<solveCompanies[proj].length;i++) {
               var startLoop=(solveCompanies[proj][i][SUBPROJ].length==0) ?0 :1;
               subDivided+=startLoop;
               numSubProj+=(solveCompanies[proj][i][SUBPROJ].length==0) ?0 :solveCompanies[proj][i][SUBPROJ].length-1;
               for (var k=startLoop;k<=solveCompanies[proj][i][SUBPROJ].length;k++) {  
                  if (solveCompanies[proj][i][HIDEON][k]==true) {
                     var colr=(solveCompanies[proj][i][DECISION][k]==NODECISION || solveCompanies[proj][i][DECISION][k]==ONFIRSTCALL) ?false :true;
                     if (colr && !hideColoured) visComp++;
                     else if (!colr && !hideWhite) visComp++;
                  } else visComp++;
               }
            }
            
            switch (solveCompanies[proj].length) {
               case 0:
                  var text="No companies.";
                  break;
               case 1:
                  var text="1 company";
                  break;
               default:
                  var text=solveCompanies[proj].length+" companies";
                  if (subDivided>0) text+=" ("+subDivided+" subdivided)";
            }
            
            if (solveCompanies[proj].length>0) {
               if (visComp==solveCompanies[proj].length+numSubProj) text+=".";
               else {
                  if (visComp==0) text+=", all rows hidden.";
                  else {
                     if (solveCompanies[proj].length+numSubProj-visComp==1) text+=", "+(solveCompanies[proj].length+numSubProj-visComp)+" row hidden.";
                     else text+=", "+(solveCompanies[proj].length+numSubProj-visComp)+" rows hidden.";
                  }
               }
            }
            
            document.getElementById("tabletextEmpty").innerHTML=text;
            document.getElementById("tabletext").innerHTML=text;
            
            if (visComp==0) _showOnly("emptyreport");
            else _showOnly("progressreport");
         }

         // -------------------------- table creation functions -------------------------------                  
         
         function _makeProgressReportHeader() {
	         var header=document.createElement("thead");
            var row=document.createElement("tr");
            _makeCell("Hide",row,HEADERSMALL,1,1,"");
            _makeCell("Company",row,HEADERLEFT,1,1,"");
            if (reportsDisplay==FULL) {
               _makeCell("1st call",row,HEADER,2,1,"");			
               _makeCell("Follow-up",row,HEADER,2,1,"");
            } else {
               _makeCell("Date",row,HEADER,1,1,"");			
               _makeCell("Comment",row,HEADER,1,1,"");
            }		
            header.appendChild(row);
            row=document.createElement("tr");
            return header; 
         }
         
         function _makeProgressReportBody(proj) {
            var body=document.createElement("tbody");
            for (var i=0;i<solveCompanies[proj].length;i++) {
               var startLoop=(solveCompanies[proj][i][SUBPROJ].length==0) ?0 :1;
               for (var k=startLoop;k<=solveCompanies[proj][i][SUBPROJ].length;k++) {
                  var toID=k*SHIFT+i;
                  var row=document.createElement("tr");
                  row.setAttribute("id","progressRow"+toID);
                  var nameText=solveCompanies[proj][i][COMPANYNAME];
                  if (k>0) nameText+=" ("+solveCompanies[proj][i][SUBPROJ][k-1]+")";
                  
                  var nameParts=nameText.split(" ");
                  nameText="";
                  if (reportsDisplay==FULL) var maxWide=12;
                  else var maxWide=16;
                  for (var np=0;np<nameParts.length;np++) nameText+=_shortened(nameParts[np],maxWide)+" ";
                  nameText=nameText.slice(0,nameText.length-1);
                  
                  var conList=_getContactFieldList(proj,i,k,false);
                  
                  if (solveCompanies[proj][i][STATUS]==RECEIVED) {
                     var infoMessage=_getFullActivityList((+proj)+SHIFT*k,i);
                     if (infoMessage!="") row.setAttribute("title",infoMessage);

                     // colour row based on solveCompanies[proj][i][DECISION][k]
                     switch (solveCompanies[proj][i][DECISION][k]) {
                        case GREEN:
                           row.style.backgroundColor="#92D050";
                           break;
                        case YELLOW:
                           row.style.backgroundColor="yellow";
                           break;
                        case RED:
                           row.style.backgroundColor="red";
                           break;
                        case NODECISION:
                        case ONFIRSTCALL:
                           row.style.backgroundColor="white";
                           break;
                     }

                     _makeCell("HIDE_"+toID,row,BLANK,1,1,"");
                     _makeCompanyNameCell(nameText,conList,row,proj,i,k);
                                          
                     if (reportsDisplay==FULL || solveCompanies[proj][i][DATE2][k]=="") {
                        if (reportsDisplay==FULL || (solveCompanies[proj][i][DECISION][k]!=NODECISION && solveCompanies[proj][i][DECISION][k]!=ONFIRSTCALL) || solveCompanies[proj][i][DATE1][k]=="") _makeCell(solveCompanies[proj][i][DATE1][k],row,UPDATA_CENTRED,1,1,"t1dat"+(i+SHIFT*k));
                        else {
                           if (solveCompanies[proj][i][DECISION][k]==ONFIRSTCALL) _makeCell(solveCompanies[proj][i][DATE1][k]+" [1st]",row,UPDATA_CENTRED,1,1,"t1dat"+(i+SHIFT*k));
                           else _makeCell(solveCompanies[proj][i][DATE1][k]+" [F-up]",row,UPDATA_CENTRED,1,1,"t1dat"+(i+SHIFT*k));
                        }
                        _makeCell(_expanded(solveCompanies[proj][i][COMMENT1][k]),row,UPDATA,1,1,"t1com"+(i+SHIFT*k));
                     }
                     if (reportsDisplay==FULL || solveCompanies[proj][i][DATE2][k]!="") {
                        if (reportsDisplay==FULL || (solveCompanies[proj][i][DECISION][k]!=NODECISION && solveCompanies[proj][i][DECISION][k]!=ONFIRSTCALL)) _makeCell(solveCompanies[proj][i][DATE2][k],row,UPDATA_CENTRED,1,1,"t2dat"+(i+SHIFT*k));
                        else _makeCell(solveCompanies[proj][i][DATE2][k]+" [F-up]",row,UPDATA_CENTRED,1,1,"t2dat"+(i+SHIFT*k));
                        _makeCell(_expanded(solveCompanies[proj][i][COMMENT2][k]),row,UPDATA,1,1,"t2com"+(i+SHIFT*k));
                     }
                  } else {
                     _makeCell("HIDE_"+toID,row,BLANK,1,1,"");
                     _makeCell(nameText,row,UPDATA_BOLD,1,1,"");
                     _makeCell("",row,UPDATA_CENTRED,1,1,"");
                     _makeCell("Updating...",row,UPDATA,1,1,"");
                     if (reportsDisplay==FULL) {
                        _makeCell("",row,UPDATA_CENTRED,1,1,"");
                        _makeCell("Updating...",row,UPDATA,1,1,"");
                     }
                  }
                  
                  body.appendChild(row);
               }
            }
            return body;
         }
         
         function _makeCompanyNameCell(text,addText,row,proj,comp,subProj) {
            // check for errors
            var errorText="";
            if (missing1tags[proj][comp][subProj]) errorText="Missing [1] tag.\n";
            
            for (var j=0;j<solveCompanies[proj][comp][CONTACTS].length;j++) {
               var notinsolve=false;
               var noactivity=true;
               var isrelated=solveCompanies[proj][comp][CONTACTS][j][CONTACTISRELATED];
               if (solveCompanies[proj][comp][CONTACTS][j][CONTACTTITLE]=="NOTINSOLVE") notinsolve=true;
               
               var startLoop=(solveCompanies[proj][comp][SUBPROJ].length==0) ?0 :1;
               for (var k=startLoop;k<=solveCompanies[proj][comp][SUBPROJ].length;k++) {
                  if (solveCompanies[proj][comp][CONTACTS][j][CONTACTPROJECTS][k]!=-1) noactivity=false;
               }
               
               var missingText="missing ";               
               var addToList="";
               if (notinsolve) addToList="not in Solve.\n";
               else {
                  if (isrelated && noactivity) {
                     addToList=missingText+"con=, ";
                     missingText="";
                  }
                  if (!isrelated && !noactivity) {
                     addToList+=missingText+"related to, ";
                     missingText="";
                  }
                  if (isrelated && solveCompanies[proj][comp][CONTACTS][j][CONTACTLANDPHONE]=="" && solveCompanies[proj][comp][PHONE]!="") {
                     addToList+=missingText+"phone, ";
                     missingText="";
                  }
                  if (isrelated && solveCompanies[proj][comp][CONTACTS][j][CONTACTWEBSITE]=="" && solveCompanies[proj][comp][WEBSITE]!="") {
                     addToList+=missingText+"website, ";
                     missingText="";
                  }
                  if (isrelated && solveCompanies[proj][comp][CONTACTS][j][CONTACTCOUNTRY]=="" && solveCompanies[proj][comp][COUNTRY]!="") {
                     addToList+=missingText+"country, ";
                     missingText="";
                  }
                  if (isrelated && solveCompanies[proj][comp][CONTACTS][j][CONTACTASSIGNEDTO]=="") {
                     addToList+=missingText+"assigned to, ";
                  }
                  
                  if (addToList.length>0) addToList=addToList.slice(0,addToList.length-2)+".\n";
               }
               
               if (addToList.length>0) {
                  errorText+=solveCompanies[proj][comp][CONTACTS][j][CONTACTNAME]+": "+addToList;
               }
            }
            
            if (errorText=="") errorText="No errors."
            else text="*"+text;
            
            // make cell
            var cell=document.createElement("th");
            cell.style.textAlign="left";
            cell.style.verticalAlign="top";
            cell.appendChild(document.createTextNode(text));
            cell.appendChild(document.createElement("br"));
            var spanner=document.createElement("span");
            spanner.style.fontStyle="italic";
            spanner.style.fontWeight="normal";
            spanner.appendChild(document.createTextNode(addText));
            cell.appendChild(spanner);
            cell.style.cursor="pointer";
            cell.setAttribute("id","tname"+(subProj*SHIFT+comp));
            cell.setAttribute("title",errorText);
            cell.onclick=function(e) { var evt = e ? e:window.event; var id=this.id; if (evt.ctrlKey || evt.which==2) _correctErrors(0,-1,parseInt(id.slice(5),10),-1,-1); else _update(this.id,evt.altKey); };
            row.appendChild(cell);
         }
         
         function _calculateTableWidth(columnWidths) {
            var tableWidth=0;
            for (var i=0;i<columnWidths.length;i++) tableWidth+=columnWidths[i]+13;
            return tableWidth;
         }
         
         function _setTableColumnWidths(table,columnWidths) {
            var colgroup=document.createElement("colgroup");
            var col;
            for (var i=0;i<columnWidths.length;i++) {
               col=document.createElement("col");
               col.setAttribute("span","1");
               col.setAttribute("style","width:"+columnWidths[i]+"px;");
               colgroup.appendChild(col);
            }
            table.appendChild(colgroup);
         }
         
         function _makeCell(text,row,type,numCols,numRows,id) {
            var cell;
            switch (type) {
               case BLANK:
               case HEADERSMALL:
               case HEADER:
               case HEADERLEFT:
                  cell=document.createElement("th");
                  cell.style.border="none";
                  //cell.style.backgroundColor=type;
                  break;
               case DATA_BOLD:
               case UPDATA_BOLD:
                  cell=document.createElement("th");
                  cell.style.textAlign="left";
                  break;         
               case DATA_RIGHT:
               case UPDATA_RIGHT:
                  cell=document.createElement("td");
                  cell.style.textAlign="right";
                  break;
               case UPDATA_CENTRED:
                  cell=document.createElement("td");
                  cell.style.textAlign="center";
                  break;
               case DATA:
               case UPDATA:
                  cell=document.createElement("td");
                  break;
            }
            if (type==HEADER || type==HEADERLEFT) cell.style.borderBottom="1px solid black";
            if (type==UPDATA || type==UPDATA_RIGHT || type==UPDATA_BOLD || type==UPDATA_CENTRED) cell.style.verticalAlign="top";
            if (type==HEADERLEFT) cell.style.textAlign="left";
            if (type==HEADERSMALL) {
               cell.style.fontSize="0.8em";
               cell.style.verticalAlign="middle";
            }
            if (type==BLANK) cell.style.backgroundColor="white";

            cell.colSpan=numCols;
            cell.rowSpan=numRows;
         
            if (text.slice(0,5)=="HIDE_") {
               var chkbx=document.createElement("input");
               chkbx.setAttribute("type","checkbox");
               chkbx.setAttribute("id",text);
               chkbx.setAttribute("value",0);
               chkbx.onclick=function() { _display(HIDE,this.id);};
               cell.appendChild(chkbx);
            } else {
               cell.appendChild(document.createTextNode(text));
               cell.style.cursor="pointer";
               if (id!="") {
                  cell.setAttribute("id",id);
                  cell.onclick=function(e) { var evt = e ? e:window.event; var id=this.id; if (evt.ctrlKey || evt.which==2) _correctErrors(0,-1,parseInt(id.slice(5),10),-1,-1); else _update(this.id,evt.altKey); };
               }
            }
            row.appendChild(cell);
         }

         // -------------------------- activity processing functions -------------------------------   
         function _returnSubProjects(proj,comp) {
            var retSubProjs=[];
            for (var i=0;i<solveCompanies[proj][comp][ACTIVITIES].length;i++) {
               var subProjs=_getProjectTags(_returnTagList(solveCompanies[proj][comp][ACTIVITIES][i][COMMENT]));
               for (var j=0;j<subProjs.length;j++) {
                  if (_findString(projects[proj][1].toLowerCase(),subProjs[j][0].toLowerCase(),true)!=NOTFOUND && subProjs[j][1]!=NOSUBPROJECT) {
                     found=false;
                     for (var k=0;k<retSubProjs.length && !found;k++) {
                        if (subProjs[j][1]==retSubProjs[k]) found=true;
                     }
                     if (!found) retSubProjs.push(subProjs[j][1]);
                  }
               }
            }
            return retSubProjs;
         }
         
         function _getProjectTags(tagList) {
            var otherTags=["1","c","e","green","g","red","r","yellow","y","+","!","*"];
            var retData=[];
            for (var i=0;i<tagList.length;i++) {
               var found=false;
               for (var j=0;j<otherTags.length && !found;j++) {
                  if (tagList[i]==otherTags[j]) found=true;
               }
               if (!found) {
                  // is a project tag
                  // remove start/end if found
                  var boundLoc=_findString(tagList[i],"=",true);
                  if (boundLoc!=NOTFOUND) {
                     if (_findString(tagList[i],"=start",true)!=NOTFOUND || _findString(tagList[i],"=end",true)!=NOTFOUND) tagList[i]=tagList[i].slice(0,boundLoc);
                     else {
                        if (_findString(tagList[i],"start=",true)!=NOTFOUND) tagList[i]=tagList[i].slice(boundLoc+1);
                        else tagList[i]=tagList[i].slice(boundLoc+1);
                     }
                  }
                  // check if subproject
                  var colon=_findString(tagList[i],":",true);
                  if (colon==NOTFOUND) retData.push([tagList[i],NOSUBPROJECT]);
                  else retData.push([tagList[i].slice(0,colon),tagList[i].slice(colon+1)]);
               }
            }
            return retData;
         }
                        
         function _processActivities(proj,comp,useDate) {
            var i,dec;
            var data;
            //
            if (useDate) {
               var D1=oDATE1;
               var D2=oDATE2;
               var C1=oCOMMENT1;
               var C2=oCOMMENT2;
               var DEC=oDECISION;
            } else {
               var D1=DATE1;
               var D2=DATE2;
               var C1=COMMENT1;
               var C2=COMMENT2;
               var DEC=DECISION;
               solveCompanies[proj][comp][SUBPROJ]=_returnSubProjects(proj,comp);
               for (j=0;j<solveCompanies[proj][comp][CONTACTS].length;j++) {
                  solveCompanies[proj][comp][CONTACTS][j][CONTACTPROJECTS]=new Array();
                  for (var k=0;k<=solveCompanies[proj][comp][SUBPROJ].length;k++) {
                     solveCompanies[proj][comp][CONTACTS][j][CONTACTPROJECTS].push(-1);
                  }
               }
               no12patch[proj][comp]=new Array();
               missing1tags[proj][comp]=new Array();
               for (var k=0;k<=solveCompanies[proj][comp][SUBPROJ].length;k++) {
                  no12patch[proj][comp].push(-1);
                  missing1tags[proj][comp].push(false);
               }
               _processActivities(proj,comp,true);
            }
            solveCompanies[proj][comp][D1]=[""];
            solveCompanies[proj][comp][C1]=[""];
            solveCompanies[proj][comp][D2]=[""];
            solveCompanies[proj][comp][C2]=[""];
            solveCompanies[proj][comp][DEC]=[ONFIRSTCALL];
            if (!useDate) solveCompanies[proj][comp][HIDEON]=[false];
            
            var startLoop=(solveCompanies[proj][comp][SUBPROJ].length==0) ?0 :1;
            for (var k=1;k<=solveCompanies[proj][comp][SUBPROJ].length;k++) {
               solveCompanies[proj][comp][D1].push("");
               solveCompanies[proj][comp][C1].push("");
               solveCompanies[proj][comp][D2].push("");
               solveCompanies[proj][comp][C2].push("");
               solveCompanies[proj][comp][DEC].push(ONFIRSTCALL);
               if (!useDate) solveCompanies[proj][comp][HIDEON].push(false);
            }
            if (solveCompanies[proj][comp][ACTIVITIES].length>0) {
               // first order activities by date!
               if (solveCompanies[proj][comp][ACTIVITIES].length>1) _orderByDate(proj,comp);                              

               for (var subpr=startLoop;subpr<=solveCompanies[proj][comp][SUBPROJ].length;subpr++) {
               
                  // check for start and end; modify variables accordingly
                  var start=_getActivityBoundary("start",(+proj)+(SHIFT*subpr),comp);
                  if (start==NOTFOUND) start=solveCompanies[proj][comp][ACTIVITIES].length-1;
                  var end=_getActivityBoundary("end",(+proj)+(SHIFT*subpr),comp);
                  if (end==NOTFOUND) end=0;
                  
                  if (useDate) {
                     var newend=end;
                     for (i=start;i>=end;i--) {
                        if (_getDateNum(solveCompanies[proj][comp][ACTIVITIES][i][DATE])<=dateFrom) newend=i;
                     }
                     end=newend;
                  } 
                  _buildContactList((+proj)+(SHIFT*subpr),comp,start,end);
                  //if (comp==2) alert(solveCompanies[proj][comp].toSource());

                  var stop=false;
                  for (i=end;i<=start && stop==false;i++) {
                     // not interested patch
                     var tempStr=solveCompanies[proj][comp][ACTIVITIES][i][COMMENT];
                     if (tempStr.indexOf("[fool]")>=0) {
                        var tempPos=tempStr.indexOf("[fool]");
                        tempStr=tempStr.slice(0,tempPos)+"[r]The company indicated that they were not interested in cooperation with overseas suppliers and did not wish to receive the company profile.  They were unwilling to discuss the matter any further."+tempStr.slice(tempPos+6);
                        solveCompanies[proj][comp][ACTIVITIES][i][COMMENT]=tempStr;
                     }
                     // language patch
                     var tempStr=solveCompanies[proj][comp][ACTIVITIES][i][COMMENT];
                     if (tempStr.indexOf("[norsk]")>=0) {
                        var tempPos=tempStr.indexOf("[norsk]");
                        tempStr=tempStr.slice(0,tempPos)+"[1][r]The company indicated that they were unwilling to discuss business matters in any language other than Norwegian.  It would therefore be impractical for them to cooperate with foreign suppliers."+tempStr.slice(tempPos+7);
                        solveCompanies[proj][comp][ACTIVITIES][i][COMMENT]=tempStr;
                     }
                     // 2nd language patch
                     var tempStr=solveCompanies[proj][comp][ACTIVITIES][i][COMMENT];
                     if (tempStr.indexOf("[finished]")>=0) {
                        var tempPos=tempStr.indexOf("[finished]");
                        tempStr=tempStr.slice(0,tempPos)+"[1][r]The company indicated that they were unwilling to discuss business matters in any language other than Finnish.  It would therefore be impractical for them to cooperate with foreign suppliers."+tempStr.slice(tempPos+10);
                        solveCompanies[proj][comp][ACTIVITIES][i][COMMENT]=tempStr;
                     }
                     //
                     data=_parseTags(solveCompanies[proj][comp][ACTIVITIES][i][COMMENT],false,(+proj)+(SHIFT*subpr),comp,i);
                     if (data[1]==FIRSTCONTACT) {
                        solveCompanies[proj][comp][D1][subpr]=_processDate(solveCompanies[proj][comp][ACTIVITIES][i][DATE]);
                        solveCompanies[proj][comp][C1][subpr]=_correctText(data[0]);
                        solveCompanies[proj][comp][DEC][subpr]=NODECISION;
                        var start=i;
                        for (i=end;i<=start && stop==false;i++) {
                           data=_parseTags(solveCompanies[proj][comp][ACTIVITIES][i][COMMENT],false,(+proj)+(SHIFT*subpr),comp,i);
                           if (data[2]==RED || data[2]==GREEN || data[2]==YELLOW) {
                              if (i<start) solveCompanies[proj][comp][D2][subpr]=_processDate(solveCompanies[proj][comp][ACTIVITIES][i][DATE]);
                              if (i<start) solveCompanies[proj][comp][C2][subpr]=_correctText(data[0]);
                              solveCompanies[proj][comp][DEC][subpr]=data[2];
                              if (!useDate) solveCompanies[proj][comp][HIDEON][subpr]=true;
                              stop=true;
                              if (!useDate) _checkForPluses((+proj)+(SHIFT*subpr),comp,start,end,i);
                           }
                        }
                        if (stop==false) {
                           for (i=end;i<start && stop==false;i++) {
                              data=_parseTags(solveCompanies[proj][comp][ACTIVITIES][i][COMMENT],false,(+proj)+(SHIFT*subpr),comp,i);
                              if (data[1]!=PRIVATE) {
                                 solveCompanies[proj][comp][D2][subpr]=_processDate(solveCompanies[proj][comp][ACTIVITIES][i][DATE]);
                                 solveCompanies[proj][comp][C2][subpr]=_correctText(data[0]);
                                 stop=true;
                                 if (!useDate) _checkForPluses((+proj)+(SHIFT*subpr),comp,start,end,-1);
                              }
                           }
                           if (!useDate && _stripSpaces(solveCompanies[proj][comp][C2][subpr])!=_expanded(solveCompanies[proj][comp][C2][subpr])) {
                              stop=false;
                              no12patch[proj][comp][subpr]=-2;
                              for (i=end;i<start && stop==false;i++) {
                                 data=_parseTags(solveCompanies[proj][comp][ACTIVITIES][i][COMMENT],false,(+proj)+(SHIFT*subpr),comp,i);
                                 if (data[1]!=PRIVATE && _stripSpaces(data[0])==_expanded(data[0])) {
                                    no12patch[proj][comp][subpr]=i;
                                    stop=true;
                                 }
                              }
                           }
                        }
                        stop=true;
                     }
                  }
                  if (stop==false) {
                     for (i=end;i<=start && stop==false;i++) {
                        data=_parseTags(solveCompanies[proj][comp][ACTIVITIES][i][COMMENT],false,(+proj)+(SHIFT*subpr),comp,i);
                        if (data[1]!=PRIVATE) {
                           solveCompanies[proj][comp][D1][subpr]=_processDate(solveCompanies[proj][comp][ACTIVITIES][i][DATE]);
                           solveCompanies[proj][comp][C1][subpr]=_correctText(data[0]);
                           stop=true;
                        }
                     }
                     if (!useDate && _stripSpaces(solveCompanies[proj][comp][C1][subpr])!=_expanded(solveCompanies[proj][comp][C1][subpr])) {
                        stop=false;
                        no12patch[proj][comp][subpr]=-2;
                        for (i=end;i<start && stop==false;i++) {
                           data=_parseTags(solveCompanies[proj][comp][ACTIVITIES][i][COMMENT],false,(+proj)+(SHIFT*subpr),comp,i);
                           if (data[1]!=PRIVATE && _stripSpaces(data[0])==_expanded(data[0])) {
                              no12patch[proj][comp][subpr]=i;
                              stop=true;
                           }
                        }
                     }
                     if (!useDate) {
                        // look for decision without [1] tag, for error tracking
                        stop=false;
                        for (i=end;i<=start && stop==false;i++) {
                           data=_parseTags(solveCompanies[proj][comp][ACTIVITIES][i][COMMENT],false,(+proj)+(SHIFT*subpr),comp,i);
                           if (data[2]==RED || data[2]==GREEN || data[2]==YELLOW) {
                              stop=true;
                              missing1tags[proj][comp][subpr]=true;
                           }
                        }
                     }
                  }
               }
            }
         }
         
         function _buildContactList(proj,comp,start,end) {
            var thisProj=proj%SHIFT;
            var thisSubProj=(proj-thisProj)/SHIFT;
            var data;
            
            for (var i=start;i>=end;i--) {
               data=_parseTags(solveCompanies[thisProj][comp][ACTIVITIES][i][COMMENT],true,proj,comp,-1);
               if (data[0]!="" && data[1]!=PRIVATE) {
                  text=_stripSpaces(_deTag(solveCompanies[thisProj][comp][ACTIVITIES][i][COMMENT]));
                  if (text.slice(0,4)=="con=" || text.slice(0,5)=="cont=") {
                     text=text.slice(4);
                     if (text.charAt(0)=="=") text=text.slice(1);
                     text=_getNameFromConCode(text);
                     var found=NOTFOUND;
                     for (j=0;j<solveCompanies[thisProj][comp][CONTACTS].length && found==NOTFOUND;j++) {
                        if (_findString(solveCompanies[thisProj][comp][CONTACTS][j][CONTACTNAME].toLowerCase(),text.toLowerCase(),true)!=NOTFOUND) found=j;
                     }
                     if (found==NOTFOUND) {
                        //if (comp==2) alert("Adding new contact: "+text);
                        found=solveCompanies[thisProj][comp][CONTACTS].length;
                        // array("$contactName","$contactTitle","$contactPhone","$contactMobile","$contactEmail", "$contactWebsite","$contactCountry", "$contactAssigned", "$contactRelated", $isRelated);
                        solveCompanies[thisProj][comp][CONTACTS].push([text,"NOTINSOLVE","","","","","","","",false,new Array()]);
                        for (var k=0;k<=solveCompanies[thisProj][comp][SUBPROJ].length;k++) solveCompanies[thisProj][comp][CONTACTS][j][CONTACTPROJECTS].push(-1);
                        //if (comp==2) alert("Added new contact: "+text);
                     }
                     
                     if (solveCompanies[thisProj][comp][CONTACTS][found][CONTACTPROJECTS][thisSubProj]==-1) solveCompanies[thisProj][comp][CONTACTS][found][CONTACTPROJECTS][thisSubProj]=i;
                  }
               }
            }
         }
         
         function _getNameFromConCode(text) {
            if (text.charAt(0)=="\"" || text.charAt(0)=="'") {
               var endMarker=text.charAt(0);
               text=text.slice(1);
            } else var endMarker=" ";
            var endPos=_findString(text,endMarker,true);
            if (endPos!=NOTFOUND) {
               text=text.slice(0,endPos);
               if (text.slice(-1)=="." || text.slice(-1)=="," || text.slice(-1)==";") text=text.slice(0,text.length-1);
            }
            return text;
         }
         
         function _getTextFromConCode(text) {
            if (text.charAt(0)=="\"" || text.charAt(0)=="'") {
               var endMarker=text.charAt(0);
               text=text.slice(1);
            } else var endMarker=" ";
            var endPos=_findString(text,endMarker,true);
            if (endPos==NOTFOUND) return "";
            else {
               if (endMarker!=" ") return text.slice(endPos+1);
               else {
                  if (text.slice(endPos-1,endPos)=="." || text.slice(endPos-1,endPos)=="," || text.slice(endPos-1,endPos)==";") return text.slice(endPos-1);
                  else return text.slice(endPos);
               }
            }
         }
         
         function _checkForPluses(proj,comp,loc1,end,locDec) {
            var thisProj=proj%SHIFT;
            var thisSubProj=(proj-thisProj)/SHIFT;
            var data;
            for (var i=loc1;i>locDec;i--) {
               var text=solveCompanies[thisProj][comp][ACTIVITIES][i][COMMENT];
               if (text.indexOf("[+]")>=0) {
                  data=_parseTags(text,false,proj,comp,i);
                  if (data[0]!="" && data[1]!=PRIVATE) solveCompanies[thisProj][comp][COMMENT1][thisSubProj]+="\n"+_processDate(solveCompanies[thisProj][comp][ACTIVITIES][i][DATE])+": "+_deTag(_correctText(text));
               }
            }
            if (locDec!=-1) {
               for (var i=locDec;i>=end;i--) {
                  var text=solveCompanies[thisProj][comp][ACTIVITIES][i][COMMENT];
                  if (text.indexOf("[+]")>=0) {
                     data=_parseTags(text,false,proj,comp,i);
                     if (data[0]!="" && data[1]!=PRIVATE) solveCompanies[thisProj][comp][COMMENT2][thisSubProj]+="\n"+_processDate(solveCompanies[thisProj][comp][ACTIVITIES][i][DATE])+": "+_deTag(_correctText(text));
                  }
               }
            }
         }
         
         function _getFullActivityList(proj,comp) {
            var data;
            var thisProj=proj%SHIFT;
            var thisSubProj=(proj-thisProj)/SHIFT;
            //var conList=_getContactFieldList(thisProj,comp,thisSubProj,true);
            //if (conList=="") conList="none";
            //var text="IDENTIFIED CONTACTS: "+conList+".";
            var text="";
                        
            if (solveCompanies[thisProj][comp][ACTIVITIES].length>0) {
               // check for start and end; modify variables accordingly
               var start=_getActivityBoundary("start",proj,comp);
               if (start==NOTFOUND) start=solveCompanies[thisProj][comp][ACTIVITIES].length-1;
               var end=_getActivityBoundary("end",proj,comp);
               if (end==NOTFOUND) end=0;
               //
               for (i=end;i<=start;i++) {
                  data=_parseTags(solveCompanies[thisProj][comp][ACTIVITIES][i][COMMENT],true,proj,comp,i);
                  if (data[0]!="" && data[1]!=PRIVATE) {
                     text+=_processShortDate(solveCompanies[thisProj][comp][ACTIVITIES][i][DATE])+" "+_correctText(data[0])+"\n";
                  } 
               }
            }
            return text;
         }
         
         function _getFinalReportFeedback(proj,comp,subProj) {
            var thisProj=(+proj)+SHIFT*subProj;
            var text="";
            var data;
            //alert(proj+"/"+comp);
            if (solveCompanies[proj][comp][ACTIVITIES].length>0) {
               // check for start and end; modify variables accordingly
               var start=_getActivityBoundary("start",thisProj,comp);
               if (start==NOTFOUND) start=solveCompanies[proj][comp][ACTIVITIES].length-1;
               var end=_getActivityBoundary("end",thisProj,comp);
               if (end==NOTFOUND) end=0;
               //
               for (i=start;i>=end;i--) {
                  data=_parseTags(solveCompanies[proj][comp][ACTIVITIES][i][COMMENT],false,thisProj,comp,i);
                  if (data[0]!="" && data[1]!=PRIVATE) {
                     text+=_processFinalReportDate(solveCompanies[proj][comp][ACTIVITIES][i][DATE])+".  __*"+_expanded(_correctText(data[0]))+"__*";
                  }
               }
            }
            //alert("out");
            if (text=="") return "";
            else return _replaceManyForPHP(text.slice(0,text.length-3));
         }
         
         function _stripBraces(text) {
            do {
               start=_findString(text,"{",true);
               if (start!=NOTFOUND) {
                  end=_findString(text,"}",true);
                  if (end==NOTFOUND) {
                     text=text.slice(0,start)+text.slice(start+1);
                     loadError+="Missing } in activities\n";
                  } else {
                     if (end>start) text=text.slice(0,start)+text.slice(end+1);
                     else {
                        text=text.slice(0,end)+text.slice(end+1);
                        loadError+="Missing { in activities\n";
                     }
                  }
               }
            } while (start!=NOTFOUND);
            return text;
         }
         
         function _returnTagList(text) {
            var tagList=[];
            do {
               start=_findString(text,"[",true);
               if (start!=NOTFOUND) {
                  end=_findString(text,"]",true);
                  
                  if (end==NOTFOUND) {
                     text=text.slice(0,start)+text.slice(start+1);
                     loadError+="Missing ] in activities\n";
                  } else {
                     if (end>start) {
                        tagList.push(text.slice(start+1,end));
                        text=text.slice(0,start)+text.slice(end+1);
                     } else {
                        text=text.slice(0,end)+text.slice(end+1);
                        loadError+="Missing [ in activities\n";
                     }
                  }
               }
            } while (start!=NOTFOUND);
            return tagList;
         }
         
         function _deTag(text) {
            do {
               var start=_findString(text,"[",true);
               if (start!=NOTFOUND) {
                  var end=_findString(text,"]",true);
                  if (end==NOTFOUND) {
                     text=text.slice(0,start)+text.slice(start+1);
                     loadError+="Missing ] in activities\n";
                  } else {
                     if (end>start) text=text.slice(0,start)+text.slice(end+1);
                     else {
                        text=text.slice(0,end)+text.slice(end+1);
                        loadError+="Missing [ in activities\n";
                     }
                  }
               }
            } while (start!=NOTFOUND);
            return text;
         }
         
         function _parseTags(text,showPrivate,proj,comp,actv) {
            var start,end,tagText;
            var foundLimiter=false;
            var foundThisProj=false;
            var markedAsPrivate=false;
            //
            var currCon=999999;
            //
            var sourceOkay=true;
            var thisProj=proj%SHIFT;
            var thisSubProj=(proj-thisProj)/SHIFT;
            //
            if (actv!=-1) {
               if (solveCompanies[thisProj][comp][ACTIVITIES][actv][ACTIVITYCONTACTNAME]!="COMPANYROOTPAGE") {
                  sourceOkay=false;
                  for (var j=0;j<solveCompanies[thisProj][comp][CONTACTS].length && !sourceOkay;j++) {
                     if (solveCompanies[thisProj][comp][CONTACTS][j][CONTACTNAME]==solveCompanies[thisProj][comp][ACTIVITIES][actv][ACTIVITYCONTACTNAME] && solveCompanies[thisProj][comp][CONTACTS][j][CONTACTPROJECTS][thisSubProj]!=-1) {
                        sourceOkay=true;
                        currCon=j;
                     }
                  }
               }
            }
            if (!sourceOkay) {
               var returnData=["",PRIVATE,NODECISION];
            } else { 
               var returnData=["",NOTFOUND,NODECISION]; 
               if (!showPrivate) text=_stripBraces(text);
               //
               var tagList=_returnTagList(text);
               for (var i=0;i<tagList.length;i++) {
                  switch (tagList[i]) {
                     case "1":
                     case "c":
                     case "e":
                        if (returnData[1]!=PRIVATE) returnData[1]=FIRSTCONTACT;
                        break;
                     case "red":
                     case "r":
                        if (returnData[1]!=PRIVATE) returnData[2]=RED;
                        break;
                     case "yellow":
                     case "y":
                        if (returnData[1]!=PRIVATE) returnData[2]=YELLOW;
                        break;
                     case "green":
                     case "g":
                        if (returnData[1]!=PRIVATE) returnData[2]=GREEN;
                        break;
                     case "!":
                     case "*":
                        if (!showPrivate) {
                           returnData[1]=PRIVATE;
                           returnData[2]=NODECISION;
                        }
                        markedAsPrivate=true;
                        break;
                     case "+":
                        // do nothing (except remove tag)
                        // dealt with in a separate function!
                        break;
                     default:
                        foundLimiter=true;
                        if (_checkTagProject(tagList[i],proj,comp)) foundThisProj=true;
                  }
               }
               text=_deTag(text);
               if (text.length>0) {
                  while (text.charAt(0)==" ") text=text.slice(1);
               }
               if (text.slice(0,3)=="con") {
                  if (text.slice(0,4)=="con=" || text.slice(0,5)=="cont=") {
                     if (!markedAsPrivate) {
                        text=text.slice(4);
                        if (text.charAt(0)=="=") text=text.slice(1);
                        var contactName=_getNameFromConCode(text);
                        contactName=_getContactNameAndTitle(contactName,thisProj,comp);
                        text=_getTextFromConCode(text);
                        var firstChar=0;
                        while (text.charAt(firstChar)==" ") firstChar++;
                        if (text.charAt(firstChar)=="." || text.charAt(firstChar)=="," || text.charAt(firstChar)==";") text="Conversation with "+contactName+text;
                        else {
                           if (text.charCodeAt(firstChar)>=65 && text.charCodeAt(firstChar)<=90) text="Conversation with "+contactName+"."+text;
                           else text="Conversation with "+contactName+","+text;
                        }
                     }
                  } else {
                     var currentContact="";
                     if (currCon==999999) {
                        for (var cc=0;cc<solveCompanies[thisProj][comp][CONTACTS].length;cc++) {
                           if (solveCompanies[thisProj][comp][CONTACTS][cc][CONTACTPROJECTS][thisSubProj]>actv && solveCompanies[thisProj][comp][CONTACTS][cc][CONTACTPROJECTS][thisSubProj]<currCon) currCon=cc;
                        }
                     }
                     if (currCon==999999) {
                        // alert("Unexpected error - cannot find contact reference for "+solveCompanies[thisProj][comp][COMPANYNAME]);
                     } else {
                        currentContact=solveCompanies[thisProj][comp][CONTACTS][currCon][CONTACTNAME];
                     
                        if (text.slice(0,4)=="cont") text=text.slice(4);
                        else text=text.slice(3);
                        var firstChar=0;
                        while (text.charAt(firstChar)==" ") firstChar++;
                        if (text.charAt(firstChar)=="." || text.charAt(firstChar)==",") text="Conversation with "+currentContact+text;
                        else {
                           if (text.charCodeAt(firstChar)>=65 && text.charCodeAt(firstChar)<=90) text="Conversation with "+currentContact+"."+text;
                           else text="Conversation with "+currentContact+","+text;
                        }
                     }
                  }
               }
               
               returnData[0]=text;
               if ((foundLimiter && !foundThisProj) || text=="") {
                  returnData[1]=PRIVATE;
                  returnData[2]=NODECISION;
               }
            }
            return returnData;
         }
         
         function _getContactNameAndTitle(contactName,proj,comp) {
            var found=NOTFOUND;
            for (var i=0;i<solveCompanies[proj][comp][CONTACTS].length && found==NOTFOUND;i++) {
               if (_findString(solveCompanies[proj][comp][CONTACTS][i][CONTACTNAME].toLowerCase(),contactName.toLowerCase(),true)!=NOTFOUND) found=i;
            }
            if (found==NOTFOUND) return contactName;
            else {
               //alert(solveCompanies[proj][comp][CONTACTS][found][CONTACTNAME]+" ... "+solveCompanies[proj][comp][CONTACTS][found][CONTACTTITLE]);
               var conTitle=solveCompanies[proj][comp][CONTACTS][found][CONTACTTITLE];
               contactName=solveCompanies[proj][comp][CONTACTS][found][CONTACTNAME];
               if (conTitle=="" || conTitle=="NOTINSOLVE") return contactName;
               else return contactName+" ("+conTitle+")";
            }
         }
         
         function _getActivityBoundary(searchStr,proj,comp) {
            var thisProj=proj%SHIFT;
            var end=0;
            var start=solveCompanies[thisProj][comp][ACTIVITIES].length-1;
            var found=NOTFOUND;
            for (i=end;i<=start && found==NOTFOUND;i++) {
               var tagList=_returnTagList(solveCompanies[thisProj][comp][ACTIVITIES][i][COMMENT]);
               for (var j=0;j<tagList.length && found==NOTFOUND;j++) {
                  if (_findString(tagList[j],searchStr+"=",true)!=NOTFOUND || _findString(tagList[j],"="+searchStr,true)!=NOTFOUND) {
                     //alert(searchStr+" in "+tagList[j]);
                     if (_checkTagProject(tagList[j],proj,comp)) found=i;
                  }
               }
            }
            //if (found!=NOTFOUND) alert("("+comp+") "+searchStr+" => "+found);
            return found;
         }
         
         function _checkTagProject(tagProj,proj,comp) {
            //if (comp==24 && tagProj=="start=adazu kukulitis") alert("Found A.K.");
            var thisProj=proj%SHIFT;
            var thisSubProj=(proj-thisProj)/SHIFT;
            if (tagProj.indexOf("=")>=0) {
               var equals=tagProj.indexOf("=");
               if (tagProj.slice(0,equals)=="start" || tagProj.slice(0,equals)=="end") tagProj=tagProj.slice(equals+1);
               else tagProj=tagProj.slice(0,equals);
            }
            var colon=tagProj.indexOf(":");
            if (colon!=NOTFOUND) {
               var tagSubProj=tagProj.slice(colon+1);
               tagProj=tagProj.slice(0,colon);
            } else var tagSubProj="";
            tagProj=tagProj.toLowerCase();
            thisProjName=projects[thisProj][1].toLowerCase();
            if (thisProjName.indexOf(tagProj)>=0) {
               if (tagSubProj=="") return true;
               else {
                  if (thisSubProj==0) return false;
                  else {
                     if (solveCompanies[thisProj][comp][SUBPROJ][thisSubProj-1]==tagSubProj) return true;
                     else return false;
                  }
               }
            }
            else return false;
         }
         
         function _processShortDate(dateStr) {
            var day=parseInt(dateStr.slice(8,10),10);
            var month=parseInt(dateStr.slice(5,7),10);
            return day+"."+month+".";
         }
         
         function _processDate(dateStr) {
            var months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
            var day=parseInt(dateStr.slice(8,10),10);
            var month=parseInt(dateStr.slice(5,7),10);
            return day+" "+months[month-1];
         }
         
         function _processFinalReportDate(dateStr) {
            var months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
            var day=parseInt(dateStr.slice(8,10),10);
            var month=parseInt(dateStr.slice(5,7),10);
            var callStr=dateStr.slice(11,13);
            var callTime=parseInt(callStr,10)+2;   // time correction
            var callStr=callTime+dateStr.slice(13,16);
            return day+" "+months[month-1]+", "+callStr;
         }
         
         function _getDateNum(dateStr) {
            var year=parseInt(dateStr.slice(2,4),10);
            var day=parseInt(dateStr.slice(8,10),10);
            var month=parseInt(dateStr.slice(5,7),10);
            var callStr=dateStr.slice(11,13)+dateStr.slice(14,16)+dateStr.slice(17,19);
            var callTime=parseInt(callStr,10);
            return 10000000000*year+100000000*month+1000000*day+callTime;
         }

         function _orderByDate(proj,comp) {
            var swapped;
            var swapTemp;
            do {
               swapped=false;
               for (i=0;i<solveCompanies[proj][comp][ACTIVITIES].length-1;i++) {
                  var date1=_getDateNum(solveCompanies[proj][comp][ACTIVITIES][i][DATE]);
                  var date2=_getDateNum(solveCompanies[proj][comp][ACTIVITIES][i+1][DATE]);
                  if (date2>date1) {
                     swapTemp=solveCompanies[proj][comp][ACTIVITIES][i];
                     solveCompanies[proj][comp][ACTIVITIES][i]=solveCompanies[proj][comp][ACTIVITIES][i+1];
                     solveCompanies[proj][comp][ACTIVITIES][i+1]=swapTemp;
                     swapped=true;
                  }
               }
            } while (swapped);
         }
            
         // ------------------------------------------- text correction functions -----------------------------------------------         
         function _expanded(text) {
            var expText=["","No answer/line busy","The contact person was unavailable"];
            while (text.charAt(0)==" ") text=text.slice(1);
            //
            var st=text.slice(0,2);
            if (st.toLowerCase()=="no") {
               st=text.slice(2,4);
               var found=0;
               if (st.charAt(0)=="1" || st.charAt(1)=="1") found=1;
               if (st.charAt(0)=="2" || st.charAt(1)=="2") found=2;
               if (found>0) {
                  if (st.charAt(0)=="1" || st.charAt(0)=="2") st=text.slice(3);
                  else st=text.slice(4);
                  if (_stripSpaces(st).length==0) text=expText[found]+".";
                  else {
                     var tmp=_stripSpaces(st).charAt(0);
                     if (tmp.charCodeAt(0)>=65 && tmp.charCodeAt(0)<=90) text=expText[found]+"."+st;
                     else text=expText[found]+st;
                  }
               }  
            }
            //alert(text);
            return text;
         }
         
         function _stripSpaces(text) {
            var isSpaced=true;
            while (text.length>0 && isSpaced) {
               if (text.charCodeAt(0)==32) text=text.slice(1);
               else isSpaced=false;
            }
            return text;
         }
         
         function _removeBackgroundBraces(text) {
            do {
               start=_findString(text,"{",false);
               if (start!=NOTFOUND) {
                  end=_findString(text,"}",false);
                  if (end==NOTFOUND) {
                     text=text.slice(0,start)+text.slice(start+1);
                     loadError+="Missing } in background\n";
                  } else {
                     if (end>start) text=text.slice(0,start)+text.slice(end+1);
                     else {
                        text=text.slice(0,end)+text.slice(end+1);
                        loadError+="Missing { in background\n";
                     }
                  }
               }
            } while (start!=NOTFOUND);
            
            // remove initial space, end space
            if (text.slice(0,1)==" ") text=text.slice(1);
            if (text.slice(-1)==" ") text=text.slice(0,text.length);
            
            return text;
         }
                
         function _correctText(text) {
            var start,end;
            // change ASCII-10 to space
            for (var i=0;i<text.length;i++) {
               if (text.charCodeAt(i)==10) {
                  text=text.slice(0,i)+" "+text.slice(i+1);
               }
            }
            
            // remove formatting
            do {
               start=_findString(text,"<",false);
               if (start!=NOTFOUND) {
                  end=_findString(text,">",false);
                  text=text.slice(0,start)+" "+text.slice(end+1);
               }
            } while (start!=NOTFOUND);
            //
            // change nbsp to normal space
            do {
               start=_findString(text,"&nbsp;",true);
               if (start!=NOTFOUND) text=text.slice(0,start)+" "+text.slice(start+6);
            } while (start!=NOTFOUND);
            //
            // correct &amp;
            do {
               start=_findString(text,"&amp;",true);
               if (start!=NOTFOUND) text=text.slice(0,start)+"&"+text.slice(start+5);
            } while (start!=NOTFOUND);
            //
            // remove \n
            do {
               start=_findString(text,"\n",true);
               if (start!=NOTFOUND) text=text.slice(0,start)+text.slice(start+1);
            } while (start!=NOTFOUND);
            //
            // correct << and >> ------------ do later!
            //
            // remove double space
            do {
               start=_findString(text,"  ",true);
               if (start!=NOTFOUND) text=text.slice(0,start)+text.slice(start+1);
            } while (start!=NOTFOUND);
            
            // remove initial space, end space
            if (text.slice(0,1)==" ") text=text.slice(1);
            if (text.slice(-1)==" ") text=text.slice(0,text.length);
            
            return text;
         }
         
         function _findString(text,searchString,canRepeat) {
            var endSearch=false;
            var pos=0;
            while (endSearch==false) {
               pos=text.indexOf(searchString,pos);
               if (pos==NOTFOUND) endSearch=true;
               else if (canRepeat==true || text.slice(pos+1,pos+2)!=searchString) endSearch=true;
            }
            return pos;
            //return NOTFOUND;
         }
         
         function _shortened(name,maxLen) {
            if (name.length>maxLen) name=name.slice(0,maxLen-1)+"...";
            return name;
         }
         // -------------------------- Statistic functions ---------------------------------
         function _calculateCallStats(proj) {
            // doesn't take into account start/end boundaries, or proj tags!!!!!!!!!!!
            // NEED TO FIX THIS!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            solveStats[proj][TOTALCALLS]=0;
            solveStats[proj][NO1CALLS]=0;
            solveStats[proj][NO2CALLS]=0;
            solveStats[proj][oTOTALCALLS]=0;
            solveStats[proj][oNO1CALLS]=0;
            solveStats[proj][oNO2CALLS]=0;
            if (solveCompanies[proj].length>0) {
               for (var comp=0;comp<solveCompanies[proj].length;comp++) {
                  if (solveCompanies[proj][comp][ACTIVITIES].length>0) {
                     for (var ac=0;ac<solveCompanies[proj][comp][ACTIVITIES].length;ac++) {
                        if (solveCompanies[proj][comp][ACTIVITIES][ac][COMTYPE]==ISCALL) {
                           var st=solveCompanies[proj][comp][ACTIVITIES][ac][COMMENT];
                           if (st.indexOf("[!]")==NOTFOUND) {
                              solveStats[proj][TOTALCALLS]++;
                              if (_getDateNum(solveCompanies[proj][comp][ACTIVITIES][ac][DATE])<=dateFrom) solveStats[proj][oTOTALCALLS]++;
                              st=st.toLowerCase();
                              if (st.slice(0,2)=="no") {
                                 if (st.charAt(2)=="1" || st.charAt(3)=="1") {
                                    solveStats[proj][NO1CALLS]++;
                                    if (_getDateNum(solveCompanies[proj][comp][ACTIVITIES][ac][DATE])<=dateFrom) solveStats[proj][oNO1CALLS]++;
                                 }
                                 if (st.charAt(2)=="2" || st.charAt(3)=="2") {
                                    solveStats[proj][NO2CALLS]++;
                                    if (_getDateNum(solveCompanies[proj][comp][ACTIVITIES][ac][DATE])<=dateFrom) solveStats[proj][oNO2CALLS]++;
                                 }
                              }
                           }
                        }
                     }
                  }
               }
            }
         }
         
         function _countOLDcompanies(proj) {
            var count=0;
            for (var comp=0;comp<solveCompanies[proj].length;comp++) {
               if (solveCompanies[proj][comp][CREATED]<=dateFrom) count++;
            }
            return count;
         }
         
         // -------------------------- Solve loading functions -------------------------------
         function _loadSolveData(proj) {
            var xmlhttp;
	         if (window.XMLHttpRequest) xmlhttp=new XMLHttpRequest();
	         else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	      
	         xmlhttp.onreadystatechange=function() {
	            if (xmlhttp.readyState==4 && xmlhttp.status==200) {
		            var companyList=JSON.parse(xmlhttp.responseText);
                  // [projId,id0,id1,...]
                  var proj=_getProjectNumber(companyList[0]);
                  var ind=solveStats.push(new Array())-1;
                  for (var k=0;k<6;k++) solveStats[ind].push(0);
                  if (companyList.length>1) {
                     //for (var i=1;i<companyList.length;i++) {
                     // DEBUGGER1
                     for (var i=1;i<14;i++) {
                        solveCompanies[proj].push(new Array(WAITING,companyList[i]));
                        no12patch[proj].push([-1]);
                        missing1tags[proj].push([false]);
                     }
                     if (proj<projects.length-1) _loadSolveData(proj+1);
                     if (proj==0) {
                        document.getElementById("loading"+proj).innerHTML="Loading "+projects[proj][1]+" ... 0%";
                        for (var i=0;i<7 && i<solveCompanies[proj].length;i++) {
                           _loadCompany(proj,i); 
                        }
                     } else _continueLoading();
                  } else {
                     document.getElementById("loading"+proj).innerHTML="Loading "+projects[proj][1]+" ... 100% (no companies)";
                  }
               }
            }
            document.getElementById("loading"+proj).innerHTML="Loading "+projects[proj][1]+" ...";
            xmlhttp.open("GET","getcompanylist.php?p="+projects[proj][0],true);
            xmlhttp.send();
         }
         
         function _reloadSolveData(proj) {
            var xmlhttp;
	         if (window.XMLHttpRequest) xmlhttp=new XMLHttpRequest();
	         else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	      
	         xmlhttp.onreadystatechange=function() {
	            if (xmlhttp.readyState==4 && xmlhttp.status==200) {
		            var companyList=JSON.parse(xmlhttp.responseText);
                  // [projId,id0,id1,...]
                  var proj=updatingProj;
                  for (var k=0;k<6;k++) solveStats[proj].push(0);
                  solveCompanies[proj]=new Array();
                  if (companyList.length>1) {
                     for (var i=1;i<companyList.length;i++) {
                        solveCompanies[proj].push(new Array(WAITING,companyList[i]));
                     }
                     document.getElementById("loading"+proj).innerHTML="Loading "+projects[proj][1]+" ... 0%";
                     for (var i=0;i<7 && i<solveCompanies[proj].length;i++) {
                        _loadCompany(proj,i);
                     }
                  } 
               }
            }
            document.getElementById("reloadButton").disabled=true;
            updatingProj=proj;
            document.getElementById("loading"+proj).innerHTML="Loading "+projects[proj][1]+" ...";
            xmlhttp.open("GET","getcompanylist.php?p="+projects[proj][0],true);
            xmlhttp.send();
         }
         
         function _getProjectNumber(projId) {
            var proj=0;
            while (projId!=projects[proj][0]) proj++;
            return proj;
         }
         
         function _loadPercentage(proj) {
            var count=0;
            for (var i=0;i<solveCompanies[proj].length;i++) {
               if (solveCompanies[proj][i][STATUS]==RECEIVED) count++;
            }
            var progr=Math.round(count*100/solveCompanies[proj].length);
            if (progr==100 && count<solveCompanies[proj].length) progr=99;
            return progr;
         }
         
         function _loadCompany(proj,comp) {
            var xmlhttp;
            if (window.XMLHttpRequest) xmlhttp=new XMLHttpRequest();
            else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            xmlhttp.onreadystatechange=function() {
               if (xmlhttp.readyState==4 && xmlhttp.status==200) {
                  var companyData=JSON.parse(xmlhttp.responseText);
                  // =[projNumber,companyID,name,[activities],background]
                  var proj=companyData[0];
                  var comp=_getCompanyNumber(proj,companyData[1]);
                  solveCompanies[proj][comp][STATUS]=RECEIVED;
                  // solveCompanies[proj][comp][STATUS,id,name,[activities],...]
                  for (var i=COMPANYNAME;i<companyData.length;i++) solveCompanies[proj][comp].push(companyData[i]);
                  if (solveCompanies[proj][comp][COMPANYNAME]!="CLIENTDETAILS-NOTCOMPANY") {
                     solveCompanies[proj][comp][BACKGROUND]=_removeBackgroundBraces(_correctText(solveCompanies[proj][comp][BACKGROUND]));
                     solveCompanies[proj][comp][CREATED]=_getDateNum(solveCompanies[proj][comp][CREATED]);
                     _processActivities(proj,comp,false);
                  }
                  document.getElementById("loading"+proj).innerHTML="Loading "+projects[proj][1]+" ... "+_loadPercentage(proj)+"%";
                  _continueLoading();
               }
            }
            solveCompanies[proj][comp][STATUS]=SENT;
            xmlhttp.open("GET","loadcompany.php?p="+proj+"&c="+solveCompanies[proj][comp][COMPANYID]+"&n="+_getPHPBlogName(proj),true);
            xmlhttp.send();
         }
         
         function _reloadCompany(proj,comp,checkErrors) {
            var xmlhttp;
            if (window.XMLHttpRequest) xmlhttp=new XMLHttpRequest();
            else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            xmlhttp.onreadystatechange=function() {
               if (xmlhttp.readyState==4 && xmlhttp.status==200) {
                  var companyData=JSON.parse(xmlhttp.responseText);
                  // =[projNumber,companyID,name,[activities],background]
                  var proj=companyData[0];
                  var comp=_getCompanyNumber(proj,companyData[1]);
                  var checkErrors=(solveCompanies[proj][comp][STATUS]==SENTplusCheckErrors) ?true :false;
                  solveCompanies[proj][comp][STATUS]=RECEIVED;
                  // solveCompanies[proj][comp][STATUS,id,name,[activities],...]
                  for (var i=COMPANYNAME;i<companyData.length;i++) solveCompanies[proj][comp][i]=companyData[i];
                  solveCompanies[proj][comp][BACKGROUND]=_correctText(solveCompanies[proj][comp][BACKGROUND]);
                  solveCompanies[proj][comp][CREATED]=_getDateNum(solveCompanies[proj][comp][CREATED]);
                  _processActivities(proj,comp,false);
                  _calculateCallStats(proj);
                  solveCompanies[proj][comp][HIDEON][0]=false;
                  if (solveCompanies[proj][comp][SUBPROJ].length>0) {
                     for (var k=1;k<=solveCompanies[proj][comp][SUBPROJ].length;k++) solveCompanies[proj][comp][HIDEON][k]=false;
                  }
                  if (checkErrors) _correctErrors(-1,proj,comp,0,-1);
                  _display(MENU,DONOTHING);
               }
            }
            if (checkErrors) solveCompanies[proj][comp][STATUS]=SENTplusCheckErrors;
            else solveCompanies[proj][comp][STATUS]=SENT;
            xmlhttp.open("GET","loadcompany.php?p="+proj+"&c="+solveCompanies[proj][comp][COMPANYID]+"&n="+_getPHPBlogName(proj),true);
            xmlhttp.send();
         }
         
         function _getPHPBlogName(proj) {
            var name=projects[proj][1];
            for (var i=0;i<name.length;i++) {
               if (name.charCodeAt(i)==32) name=name.slice(0,i)+"+"+name.slice(i+1);
            }
            return name;
         }
         
         function _getCompanyNumber(proj,companyId) {
            var comp=0;
            while (companyId!=solveCompanies[proj][comp][COMPANYID]) comp++;
            return comp;
         }
         
         function _continueLoading() {
            var proj;
            var comp=ALLLOADING;
            for (var i=0;i<projects.length && (comp==ALLLOADING || comp==ALLLOADED);i++) {
               proj=i;
               comp=_getNextCompanyToLoad(proj);
            }
            if (comp==ALLLOADED) _finishedLoading();
            else if (comp!=ALLLOADING) _loadCompany(proj,comp);
         }
         
         function _getNextCompanyToLoad(proj) {
            var comp=ALLLOADED;
            for (var i=0;i<solveCompanies[proj].length && (comp==ALLLOADING || comp==ALLLOADED);i++) {
               if (solveCompanies[proj][i][STATUS]==WAITING) comp=i;
               else if (solveCompanies[proj][i][STATUS]==SENT) comp=ALLLOADING;
            } 
            return comp;
         }
         
         function _finishedLoading() {
            for (var i=0;i<projects.length;i++) {
               for (var j=0;j<solveCompanies[i].length;j++) {
                  if (solveCompanies[i][j][COMPANYNAME]=="CLIENTDETAILS-NOTCOMPANY") {
                     solveCompanies[i].splice(j,1);
                     missing1tags[i].splice(j,1);
                     no12patch[i].splice(j,1);
                     j--;
                  }
               }
            }
            
            //if (loadError!="") alert(loadError);
            
            for (var i=0;i<projects.length;i++) _calculateCallStats(i);
            document.getElementById("menubar").style.display="block";
             _display(MENU,REPORTS);
             document.getElementById("reloadButton").disabled=false;
             updatingProj=-1;
         }
         
         // -------------------------------------------- excel progress report generation ------------------------------------------------------
         function _excelReport2() {
            var xmlhttp;
            if (window.XMLHttpRequest) xmlhttp=new XMLHttpRequest();
            else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            xmlhttp.onreadystatechange=function() {
               if (xmlhttp.readyState==4 && xmlhttp.status==200) {
                  var proj=_getProjectFromRadio();
                  document.getElementById("loading0").innerHTML="Generating Excel progress report for "+projects[proj][1]+".<br/>Finished building report part 1.";
                  var okay=xmlhttp.responseText;
                  if (okay=="OK") {
                     var mons=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
                     var d=new Date();
                     var mn=d.getMonth();
                     var dy=d.getDate();
                     var dateStr=mons[mn]+dy;
                     _emailReport2(proj,dateStr);
                  } else {
                     alert("Unexpected error when building report!");
                     document.getElementById("menubar").style.display="";
                     _display(MENU,DONOTHING);
                  }
               }
            }
            _showOnly("loadstatus");
            document.getElementById("menubar").style.display="none";
            var div=document.getElementById("loadstatus");
            for (var i=1;i<projects.length;i++) document.getElementById("loading"+i).style.display="none";
            var proj=_getProjectFromRadio();
            document.getElementById("loading0").innerHTML="Generating Excel progress report for "+projects[proj][1]+".<br/>Compiling data...";
            var PHPdata="";
            // name,subproj,decision,[contactlist,subName,date1,com1,date2,com2],...
            for (var i=0;i<100;i++) {
               PHPdata+=_replaceAmp(solveCompanies[proj][i][COMPANYNAME])+"__#";
               PHPdata+=solveCompanies[proj][i][SUBPROJ].length+"__#";
               var startLoop=(solveCompanies[proj][i][SUBPROJ].length==0) ?0 :1;
               PHPdata+=_getCombinedDecision(proj,i)+"__#";
               //alert(_getCombinedDecision(proj,i));
               for (var k=startLoop;k<=solveCompanies[proj][i][SUBPROJ].length;k++) {
                  PHPdata+=_getContactFieldList(proj,i,k,false)+"__#";
                  if (startLoop==0) PHPdata+=NOSUBPROJECT+"__#";
                  else PHPdata+=solveCompanies[proj][i][SUBPROJ][k-1]+"__#";
                  var tmpDat1=solveCompanies[proj][i][DATE1][k];
                  var tmpDat2=solveCompanies[proj][i][DATE2][k];
                  var tmpCom1=_replaceAmp(solveCompanies[proj][i][COMMENT1][k]);
                  var tmpCom2=_replaceAmp(solveCompanies[proj][i][COMMENT2][k]);
                  if (no12patch[proj][i][k]!=-1) {
                     if (solveCompanies[proj][i][DECISION][k]==ONFIRSTCALL) {
                        if (no12patch[proj][i][k]==-2) {
                           tmpDat1="";
                           tmpCom1="";
                        } else {
                           tmpDat1=_processDate(solveCompanies[proj][i][ACTIVITIES][no12patch[proj][i][k]][DATE]);
                           tmpCom1=_replaceAmp(solveCompanies[proj][i][ACTIVITIES][no12patch[proj][i][k]][COMMENT]);
                        }
                     } else {
                        if (no12patch[proj][i][k]==-2) {
                           tmpDat2="";
                           tmpCom2="";
                        } else {
                           tmpDat2=_processDate(solveCompanies[proj][i][ACTIVITIES][no12patch[proj][i][k]][DATE]);
                           tmpCom2=_replaceAmp(solveCompanies[proj][i][ACTIVITIES][no12patch[proj][i][k]][COMMENT]);
                        }
                     }
                  }
                  PHPdata+=tmpDat1+"__#";
                  PHPdata+=tmpCom1+"__#";
                  PHPdata+=tmpDat2+"__#";
                  PHPdata+=tmpCom2+"__#";
               }
            }
            PHPdata=PHPdata.slice(0,PHPdata.length-3);
            //alert(PHPdata);
            //document.getElementById("loading0").innerHTML=PHPdata;
            //
            var mons=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
            var d=new Date();
            var mn=d.getMonth();
            var dy=d.getDate();
            var dateStr=mons[mn]+dy;
            //
            xmlhttp.open("POST","excelprogressreport.php?p="+_getPHPBlogName(proj)+"&d="+dateStr,true);
            xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            xmlhttp.send("data="+PHPdata);
            document.getElementById("loading0").innerHTML="Generating Excel progress report for "+projects[proj][1]+".<br/>Building report";
            _animateDots();
         }
         
         function _excelReport3() {
            var xmlhttp;
            if (window.XMLHttpRequest) xmlhttp=new XMLHttpRequest();
            else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            xmlhttp.onreadystatechange=function() {
               if (xmlhttp.readyState==4 && xmlhttp.status==200) {
                  var proj=_getProjectFromRadio();
                  document.getElementById("loading0").innerHTML="Generating Excel progress report for "+projects[proj][1]+".<br/>Finished building report.";
                  var okay=xmlhttp.responseText;
                  if (okay=="OK") {
                     var mons=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
                     var d=new Date();
                     var mn=d.getMonth();
                     var dy=d.getDate();
                     var dateStr=mons[mn]+dy;
                     _emailReport(proj,dateStr);
                  } else {
                     alert("Unexpected error when building report!");
                     document.getElementById("menubar").style.display="";
                     _display(MENU,DONOTHING);
                  }
               }
            }
            _showOnly("loadstatus");
            document.getElementById("menubar").style.display="none";
            var div=document.getElementById("loadstatus");
            for (var i=1;i<projects.length;i++) document.getElementById("loading"+i).style.display="none";
            var proj=_getProjectFromRadio();
            document.getElementById("loading0").innerHTML="Generating Excel progress report for "+projects[proj][1]+".<br/>Compiling data...";
            var PHPdata="";
            // name,subproj,decision,[contactlist,subName,date1,com1,date2,com2],...
            for (var i=100;i<solveCompanies[proj].length;i++) {
               PHPdata+=_replaceAmp(solveCompanies[proj][i][COMPANYNAME])+"__#";
               PHPdata+=solveCompanies[proj][i][SUBPROJ].length+"__#";
               var startLoop=(solveCompanies[proj][i][SUBPROJ].length==0) ?0 :1;
               PHPdata+=_getCombinedDecision(proj,i)+"__#";
               //alert(_getCombinedDecision(proj,i));
               for (var k=startLoop;k<=solveCompanies[proj][i][SUBPROJ].length;k++) {
                  PHPdata+=_getContactFieldList(proj,i,k,false)+"__#";
                  if (startLoop==0) PHPdata+=NOSUBPROJECT+"__#";
                  else PHPdata+=solveCompanies[proj][i][SUBPROJ][k-1]+"__#";
                  var tmpDat1=solveCompanies[proj][i][DATE1][k];
                  var tmpDat2=solveCompanies[proj][i][DATE2][k];
                  var tmpCom1=_replaceAmp(solveCompanies[proj][i][COMMENT1][k]);
                  var tmpCom2=_replaceAmp(solveCompanies[proj][i][COMMENT2][k]);
                  if (no12patch[proj][i][k]!=-1) {
                     if (solveCompanies[proj][i][DECISION][k]==ONFIRSTCALL) {
                        if (no12patch[proj][i][k]==-2) {
                           tmpDat1="";
                           tmpCom1="";
                        } else {
                           tmpDat1=_processDate(solveCompanies[proj][i][ACTIVITIES][no12patch[proj][i][k]][DATE]);
                           tmpCom1=_replaceAmp(solveCompanies[proj][i][ACTIVITIES][no12patch[proj][i][k]][COMMENT]);
                        }
                     } else {
                        if (no12patch[proj][i][k]==-2) {
                           tmpDat2="";
                           tmpCom2="";
                        } else {
                           tmpDat2=_processDate(solveCompanies[proj][i][ACTIVITIES][no12patch[proj][i][k]][DATE]);
                           tmpCom2=_replaceAmp(solveCompanies[proj][i][ACTIVITIES][no12patch[proj][i][k]][COMMENT]);
                        }
                     }
                  }
                  PHPdata+=tmpDat1+"__#";
                  PHPdata+=tmpCom1+"__#";
                  PHPdata+=tmpDat2+"__#";
                  PHPdata+=tmpCom2+"__#";
               }
            }
            PHPdata=PHPdata.slice(0,PHPdata.length-3);
            //alert(PHPdata);
            //document.getElementById("loading0").innerHTML=PHPdata;
            //
            var mons=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
            var d=new Date();
            var mn=d.getMonth();
            var dy=d.getDate();
            var dateStr=mons[mn]+dy;
            //
            xmlhttp.open("POST","excelprogressreport2.php?p="+_getPHPBlogName(proj)+"&d="+dateStr,true);
            xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            xmlhttp.send("data="+PHPdata);
            document.getElementById("loading0").innerHTML="Generating Excel progress report for "+projects[proj][1]+".<br/>Building report";
            _animateDots();
         }
         
         function _selectionReport() {
            var xmlhttp;
            if (window.XMLHttpRequest) xmlhttp=new XMLHttpRequest();
            else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            xmlhttp.onreadystatechange=function() {
               if (xmlhttp.readyState==4 && xmlhttp.status==200) {
                  var proj=_getProjectFromRadio();
                  document.getElementById("loading0").innerHTML="Generating Excel partner selection for "+projects[proj][1]+".<br/>Finished building selection.";
                  var okay=xmlhttp.responseText;
                  if (okay=="OK") {
                     var mons=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
                     var d=new Date();
                     var mn=d.getMonth();
                     var dy=d.getDate();
                     var dateStr=mons[mn]+dy;
                     _emailSelection(proj,dateStr); 
                  } else {
                     alert("Unexpected error when building selection!");
                     document.getElementById("menubar").style.display="";
                     _display(MENU,DONOTHING);
                  }
               }
            }
            _showOnly("loadstatus");
            document.getElementById("menubar").style.display="none";
            var div=document.getElementById("loadstatus");
            for (var i=1;i<projects.length;i++) document.getElementById("loading"+i).style.display="none";
            var proj=_getProjectFromRadio();
            document.getElementById("loading0").innerHTML="Generating Excel partner selection for "+projects[proj][1]+".<br/>Compiling data...";
            var PHPdata="";
            // COMPANYNAME,WEBSITE,PHONE,ADDRESS,TURNOVER,EMPLOYEES,PROFILE,INDUSTRY,BACKGROUND,COUNTRY,CREATED
            // company, address, country, phone, website, turnover, employees, industry, profile, background, <<location
            // https://maps.google.com/?saddr=Pulkveza+Brieza+8+Riga+LV-1010+Latvia
            var compNum=solveCompanies[proj].length;
            for (var i=0;i<compNum;i++) {
            //var cStart=0;
            //var cEnd=10;
            //do {
            //for (var i=cStart;i<cEnd;i++) {
               PHPdata+=_replaceAmp(solveCompanies[proj][i][COMPANYNAME])+"__#";
               PHPdata+=_replaceAmp(solveCompanies[proj][i][ADDRESS])+"__#";
               PHPdata+=_replaceAmp(solveCompanies[proj][i][COUNTRY])+"__#";
               PHPdata+=_replaceForPHP("+","*plus*",solveCompanies[proj][i][PHONE])+"__#";
               PHPdata+=_replaceAmp(solveCompanies[proj][i][WEBSITE])+"__#";
               PHPdata+=_replaceAmp(solveCompanies[proj][i][TURNOVER])+"__#";
               PHPdata+=_replaceAmp(solveCompanies[proj][i][EMPLOYEES])+"__#";
               PHPdata+=_replaceAmp(solveCompanies[proj][i][INDUSTRY])+"__#";
               PHPdata+=_replaceAmp(solveCompanies[proj][i][PROFILE])+"__#";
               PHPdata+=_replaceAmp(solveCompanies[proj][i][BACKGROUND])+"__#";
               PHPdata+=_getLocation(solveCompanies[proj][i][ADDRESS])+"__#";
            }           
            //cStart=cEnd;
            //cEnd+=10;
            //if (cEnd>compNum) cEnd=compNum;
            //if (cStart==cEnd) {
            //   var letsGoAgain=0;
            //} else {
            //   var letsGoAgain=prompt("Do "+cStart+"-"+cEnd+" ?(1/0)");
            //}
            //} while (letsGoAgain==1);
            
            PHPdata=PHPdata.slice(0,PHPdata.length-3);
            //if (whichComp==2) alert(PHPdata);
            
            //document.getElementById("loading0").innerHTML=PHPdata;
            //
            var mons=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
            var d=new Date();
            var mn=d.getMonth();
            var dy=d.getDate();
            var dateStr=mons[mn]+dy;
            //
            xmlhttp.open("POST","selection.php?p="+_getPHPBlogName(proj)+"&d="+dateStr,true);
            xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            xmlhttp.send("data="+PHPdata);
            document.getElementById("loading0").innerHTML="Generating Excel partner selection for "+projects[proj][1]+".<br/>Building selection";
            _animateDots();
         }
         
         function _getLocation(addr) {
            for (var i=0;i<addr.length;i++) {
               if (addr.charCodeAt(i)<=13) addr=addr.slice(0,i)+" "+addr.slice(i+1);
            }
            var addrs=addr.split(" ");
            var mapAddress="";
            for (var i=0;i<addrs.length;i++) {
               var tmp="";
               for (var j=0;j<addrs[i].length;j++) {
                  var ch=addrs[i].charCodeAt(j);
                  if (ch>32 && ch!=38 && ch!=44 && ch!=46 ) tmp+=addrs[i].charAt(j);
               }
               if (tmp.length>0) {
                  if (mapAddress.length>0) mapAddress+="+";
                  mapAddress+=tmp;
               }
            }
            return mapAddress;
         }
         
         function _excelReport() {
            var xmlhttp;
            if (window.XMLHttpRequest) xmlhttp=new XMLHttpRequest();
            else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            xmlhttp.onreadystatechange=function() {
               if (xmlhttp.readyState==4 && xmlhttp.status==200) {
                  var proj=_getProjectFromRadio();
                  document.getElementById("loading0").innerHTML="Generating Excel progress report for "+projects[proj][1]+".<br/>Finished building report.";
                  var okay=xmlhttp.responseText;
                  if (okay=="OK") {
                     var mons=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
                     var d=new Date();
                     var mn=d.getMonth();
                     var dy=d.getDate();
                     var dateStr=mons[mn]+dy;
                     _emailReport(proj,dateStr);
                     /*
                     alert("All okay?");
                     document.getElementById("menubar").style.display="";
                     _display(MENU,DONOTHING);
                     */
                  } else {
                     alert("Unexpected error when building report!");
                     document.getElementById("menubar").style.display="";
                     _display(MENU,DONOTHING);
                  }
               }
            }
            _showOnly("loadstatus");
            document.getElementById("menubar").style.display="none";
            var div=document.getElementById("loadstatus");
            for (var i=1;i<projects.length;i++) document.getElementById("loading"+i).style.display="none";
            var proj=_getProjectFromRadio();
            document.getElementById("loading0").innerHTML="Generating Excel progress report for "+projects[proj][1]+".<br/>Compiling data...";
            var PHPdata="";
            // name,subproj,decision,[contactlist,subName,date1,com1,date2,com2],...
            for (var i=0;i<solveCompanies[proj].length;i++) {
               PHPdata+=_replaceAmp(solveCompanies[proj][i][COMPANYNAME])+"__#";
               PHPdata+=solveCompanies[proj][i][SUBPROJ].length+"__#";
               var startLoop=(solveCompanies[proj][i][SUBPROJ].length==0) ?0 :1;
               PHPdata+=_getCombinedDecision(proj,i)+"__#";
               //alert(_getCombinedDecision(proj,i));
               for (var k=startLoop;k<=solveCompanies[proj][i][SUBPROJ].length;k++) {
                  // PHPdata+=_getContactFieldList(proj,i,k,false)+"__#";
                  /* no longer using contact names */
                  PHPdata+=_replaceAmp(solveCompanies[proj][i][WEBSITE])+"__#";
                  if (startLoop==0) PHPdata+=NOSUBPROJECT+"__#";
                  else PHPdata+=solveCompanies[proj][i][SUBPROJ][k-1]+"__#";
                  var tmpDat1=solveCompanies[proj][i][DATE1][k];
                  var tmpDat2=solveCompanies[proj][i][DATE2][k];
                  var tmpCom1=_replaceAmp(solveCompanies[proj][i][COMMENT1][k]);
                  var tmpCom2=_replaceAmp(solveCompanies[proj][i][COMMENT2][k]);
                  
                  /* no longer using
                  if (no12patch[proj][i][k]!=-1) {
                     if (solveCompanies[proj][i][DECISION][k]==ONFIRSTCALL) {
                        if (no12patch[proj][i][k]==-2) {
                           tmpDat1="";
                           tmpCom1="";
                        } else {
                           tmpDat1=_processDate(solveCompanies[proj][i][ACTIVITIES][no12patch[proj][i][k]][DATE]);
                           tmpCom1=_replaceAmp(solveCompanies[proj][i][ACTIVITIES][no12patch[proj][i][k]][COMMENT]);
                        }
                     } else {
                        if (no12patch[proj][i][k]==-2) {
                           tmpDat2="";
                           tmpCom2="";
                        } else {
                           tmpDat2=_processDate(solveCompanies[proj][i][ACTIVITIES][no12patch[proj][i][k]][DATE]);
                           tmpCom2=_replaceAmp(solveCompanies[proj][i][ACTIVITIES][no12patch[proj][i][k]][COMMENT]);
                        }
                     }
                  }
                  */
                  
                  PHPdata+=tmpDat1+"__#";
                  PHPdata+=_expanded(tmpCom1)+"__#";
                  PHPdata+=tmpDat2+"__#";
                  PHPdata+=_expanded(tmpCom2)+"__#";
               }
            }
            PHPdata=PHPdata.slice(0,PHPdata.length-3);
            //alert(PHPdata);
            //document.getElementById("loading0").innerHTML=PHPdata;
            //
            var mons=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
            var d=new Date();
            var mn=d.getMonth();
            var dy=d.getDate();
            var dateStr=mons[mn]+dy;
            //
            xmlhttp.open("POST","excelprogressreport.php?p="+_getPHPBlogName(proj)+"&d="+dateStr,true);
            xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            xmlhttp.send("data="+PHPdata);
            document.getElementById("loading0").innerHTML="Generating Excel progress report for "+projects[proj][1]+".<br/>Building report";
            _animateDots();
         }
         
         function _getContactFieldList(proj,comp,subProj,markNonSolve) {
            var fieldText="";
            var lastFound=999999;
            for (var j=0;j<solveCompanies[proj][comp][CONTACTS].length;j++) {
               var found=NOTFOUND;
               var foundName="";
               var foundTitle="";
               for (var k=0;k<solveCompanies[proj][comp][CONTACTS].length;k++) {
                  if (solveCompanies[proj][comp][CONTACTS][k][CONTACTPROJECTS][subProj]>found && solveCompanies[proj][comp][CONTACTS][k][CONTACTPROJECTS][subProj]<lastFound) {
                     found=solveCompanies[proj][comp][CONTACTS][k][CONTACTPROJECTS][subProj];
                     foundName=solveCompanies[proj][comp][CONTACTS][k][CONTACTNAME];
                     foundTitle=solveCompanies[proj][comp][CONTACTS][k][CONTACTTITLE];
                  }
               }
               if (found!=NOTFOUND) {
                  lastFound=found;
                  if (fieldText!="") fieldText+=", ";
                  fieldText+=foundName;
                  if (markNonSolve && foundTitle=="NOTINSOLVE") fieldText+="(NOT IN SOLVE!)";
               }
            }
            return fieldText;
         }
         
         function _getCombinedDecision(proj,comp) {
            if (solveCompanies[proj][comp][SUBPROJ].length==0) {
               var tmpDec=solveCompanies[proj][comp][DECISION][0];
               if (tmpDec==ONFIRSTCALL) tmpDec=NODECISION;
            } else {
               var tmpDec=NODECISION;
               var isWhite=false;
               for (var k=1;k<=solveCompanies[proj][comp][SUBPROJ].length;k++) {
                  if (solveCompanies[proj][comp][DECISION][k]<RED) isWhite=true;
                  if (solveCompanies[proj][comp][DECISION][k]>tmpDec) tmpDec=solveCompanies[proj][comp][DECISION][k];
               }
               if (isWhite && tmpDec==RED) tmpDec=NODECISION;
            }
            return tmpDec;
         }
         
         function _getCombinedDate(proj,comp,dateField) {
            if (solveCompanies[proj][comp][SUBPROJ].length==0) return solveCompanies[proj][comp][dateField][0];
            else {
               var dateLow=999999;
               var dateHigh=0;
               for (var k=1;k<=solveCompanies[proj][comp][SUBPROJ].length;k++) {
                  var dateNum=_getDateNumberFromText(proj,comp,solveCompanies[proj][comp][dateField][k]);
                  if (dateNum<dateLow) dateLow=dateNum;
                  if (dateNum>dateHigh) dateHigh=dateNum;
               }
               if (dateLow==dateHigh) return _processDateFromDateNumber(dateLow);
               else return _processDateFromDateNumber(dateLow)+" - "+_processDateFromDateNumber(dateHigh);
            }
         }
         
         function _processDateFromDateNumber(dateNum) {
            var months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
            var day=dateNum%100;
            var month=(dateNum%10000-day)/100;
            return day+" "+months[month-1];
         }
         
         function _getDateNumberFromText(proj,comp,dateStr) {
            var found=-1;
            for (var i=0;i<solveCompanies[proj][comp][ACTIVITIES].length && found==-1;i++) {
               if (_processDate(solveCompanies[proj][comp][ACTIVITIES][i][DATE])==dateStr) found=_getDateNum(solveCompanies[proj][comp][ACTIVITIES][i][DATE]);
            }
            return found;
         }
         
         function _animateDots() {
            var text=document.getElementById("loading0").innerHTML;
            if (text.indexOf("mailed")<0) {
               var count=0;
               while (text.slice(-1)==".") {
                  count++;
                  text=text.slice(0,text.length-1);
               }
               if (++count>5) count=1;
               for (var i=0;i<count;i++) text+=".";
               document.getElementById("loading0").innerHTML=text;
               var t=setTimeout("_animateDots()",500);
            }
         }
         
         function _replaceAmp(text) {
            while (text.indexOf("&")>=0) {
               text=text.slice(0,text.indexOf("&"))+"*amp*"+text.slice(1+text.indexOf("&"));
            }
            return text;
         }
         
         function _emailSelection(proj,dateStr) {
            var xmlhttp;
            if (window.XMLHttpRequest) xmlhttp=new XMLHttpRequest();
            else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            xmlhttp.onreadystatechange=function() {
               if (xmlhttp.readyState==4 && xmlhttp.status==200) {
                  var proj=_getProjectFromRadio();
                  document.getElementById("loading0").innerHTML="Generating Excel partner selection for "+projects[proj][1]+".<br/>Selection emailed.";
                  var okay=xmlhttp.responseText;
                  if (okay!="OK") alert("Unexpected error when emailing selection!");
                  document.getElementById("menubar").style.display="";
                  _display(MENU,DONOTHING);
               }
            }
            document.getElementById("loading0").innerHTML="Generating Excel partner selection for "+projects[proj][1]+".<br/>Composing email";
            xmlhttp.open("GET","emailSelection.php?d="+dateStr+"&proj="+_getPHPBlogName(proj)+"&to="+_getEmailAddress(projects[proj][4]),true);
            //xmlhttp.open("GET","emailSelection.php?d="+dateStr+"&proj="+_getPHPBlogName(proj)+"&to=jesse.turner@gatewaybaltic.com",true);
            xmlhttp.send();
            document.getElementById("loading0").innerHTML="Generating Excel partner selection for "+projects[proj][1]+".<br/>Emailing selection";
            //alert("emailfile.php?proj="+_getPHPBlogName(proj)+"&to="+_getEmailAddress(projects[proj][3])+"&exec="+projects[proj][4]+"&from="+_getEmailAddress(projects[proj][4])+"&client="+projects[proj][5]);
         }
         
         function _emailReport(proj,dateStr) {
            var xmlhttp;
            if (window.XMLHttpRequest) xmlhttp=new XMLHttpRequest();
            else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            xmlhttp.onreadystatechange=function() {
               if (xmlhttp.readyState==4 && xmlhttp.status==200) {
                  var proj=_getProjectFromRadio();
                  document.getElementById("loading0").innerHTML="Generating Excel progress report for "+projects[proj][1]+".<br/>Report emailed.";
                  var okay=xmlhttp.responseText;
                  if (okay!="OK") alert("Unexpected error when emailing report!");
                  document.getElementById("menubar").style.display="";
                  _display(MENU,DONOTHING);
               }
            }
            document.getElementById("loading0").innerHTML="Generating Excel progress report for "+projects[proj][1]+".<br/>Composing email";
            xmlhttp.open("GET","emailfile.php?d="+dateStr+"&proj="+_getPHPBlogName(proj)+"&to="+_getEmailAddress(projects[proj][3])+"&exec="+projects[proj][4]+"&from=" +_getEmailAddress(projects[proj][4])+"&client="+projects[proj][5],true);
            xmlhttp.send();
            document.getElementById("loading0").innerHTML="Generating Excel progress report for "+projects[proj][1]+".<br/>Emailing report";
            //alert("emailfile.php?proj="+_getPHPBlogName(proj)+"&to="+_getEmailAddress(projects[proj][3])+"&exec="+projects[proj][4]+"&from="+_getEmailAddress(projects[proj][4])+"&client="+projects[proj][5]);
         }

         function _emailReport2(proj,dateStr) {
            var xmlhttp;
            if (window.XMLHttpRequest) xmlhttp=new XMLHttpRequest();
            else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            xmlhttp.onreadystatechange=function() {
               if (xmlhttp.readyState==4 && xmlhttp.status==200) {
                  var proj=_getProjectFromRadio();
                  document.getElementById("loading0").innerHTML="Generating Excel progress report for "+projects[proj][1]+".<br/>Report part 1 emailed.";
                  var okay=xmlhttp.responseText;
                  if (okay!="OK") {
                     alert("Unexpected error when emailing report!");
                     document.getElementById("menubar").style.display="";
                     _display(MENU,DONOTHING);
                  } else _excelReport3();
               }
            }
            document.getElementById("loading0").innerHTML="Generating Excel progress report for "+projects[proj][1]+".<br/>Composing email";
            xmlhttp.open("GET","emailfile.php?d="+dateStr+"&proj="+_getPHPBlogName(proj)+"&to="+_getEmailAddress(projects[proj][3])+"&exec="+projects[proj][4]+"&from=" +_getEmailAddress(projects[proj][4])+"&client="+projects[proj][5],true);
            xmlhttp.send();
            document.getElementById("loading0").innerHTML="Generating Excel progress report for "+projects[proj][1]+".<br/>Emailing report part 1";
            //alert("emailfile.php?proj="+_getPHPBlogName(proj)+"&to="+_getEmailAddress(projects[proj][3])+"&exec="+projects[proj][4]+"&from="+_getEmailAddress(projects[proj][4])+"&client="+projects[proj][5]);
         }
         
         function _getEmailAddress(empl) {
            var names=empl.split(" ");
            if (names.length==2) empl=names[0]+"."+names[1]+"@gatewaybaltic.com";
            else empl=names[0]+"@gatewaybaltic.com";
            return empl.toLowerCase();
         }
         
         function _emailFinalReport(proj) {
            var xmlhttp;
            if (window.XMLHttpRequest) xmlhttp=new XMLHttpRequest();
            else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            xmlhttp.onreadystatechange=function() {
               if (xmlhttp.readyState==4 && xmlhttp.status==200) {
                  var proj=_getProjectFromRadio();
                  document.getElementById("loading0").innerHTML="Generating partial final report for "+projects[proj][1]+".<br/>Report emailed.";
                  var okay=xmlhttp.responseText;
                  if (okay!="OK") alert("Unexpected error when emailing report!");
                  document.getElementById("menubar").style.display="";
                  _display(MENU,DONOTHING);
               }
            }
            document.getElementById("loading0").innerHTML="Generating partial final report for "+projects[proj][1]+".<br/>Composing email";
            xmlhttp.open("GET","emailReport.php?proj="+_getPHPBlogName(proj)+"&to="+_getEmailAddress(projects[proj][4]),true);
            xmlhttp.send();
            document.getElementById("loading0").innerHTML="Generating partial final report for "+projects[proj][1]+".<br/>Emailing report";
            //alert("emailReport.php?proj="+_getPHPBlogName(proj)+"&to="+_getEmailAddress(projects[proj][4]));
         }
         
         // -------------------------------------------- final report generation ------------------------------------------------------
         function _wordReport() {
            var xmlhttp;
            if (window.XMLHttpRequest) xmlhttp=new XMLHttpRequest();
            else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            xmlhttp.onreadystatechange=function() {
               if (xmlhttp.readyState==4 && xmlhttp.status==200) {
                  var proj=_getProjectFromRadio();
                  document.getElementById("loading0").innerHTML="Generating Final report for "+projects[proj][1]+".<br/>Finished building report. Emailed.";
                  var okay=xmlhttp.responseText;
                  if (okay=="OK") {
                     //alert("OK");
                     _emailFinalReport(proj);
                     //document.getElementById("menubar").style.display="";
                     //_display(MENU,DONOTHING);
                  } else {
                     alert("Unexpected error!");
                     document.getElementById("menubar").style.display="";
                     _display(MENU,DONOTHING);
                  }
               }
            }
            _showOnly("loadstatus");
            document.getElementById("menubar").style.display="none";
            var div=document.getElementById("loadstatus");
            for (var i=1;i<projects.length;i++) document.getElementById("loading"+i).style.display="none";
            var proj=_getProjectFromRadio();
            document.getElementById("loading0").innerHTML="Generating Final report for "+projects[proj][1]+".<br/>Compiling data...";
            var PHPdata="";
            
            var successContact=0;
            var notContact=0;
            var unContactable=0;
            for (var i=0;i<solveCompanies[proj].length;i++) {
               var stats=_calculateFinalReportStats(proj,i,0);
               switch (stats[4]) {
                  case GREEN:
                     successContact++;
                     break;
                  case YELLOW:
                     successContact++;
                     break;
                  case RED:
                     successContact++;
                     break;
                  case NODECISION:
                     successContact++;
                     break;
                  case UNCONTACTABLE:
                     unContactable++;
                     break;
                  case NOTCONTACTED:
                     notContact++;
                     break;
               }
               var addr=solveCompanies[proj][i][ADDRESS];
               var subst;
               for (var j=0;j<addr.length;j++) {
                  if (addr.charCodeAt(j)>122) {
                     subst=addr.charAt(j);
                     switch (addr.charCodeAt(j)) {
                        case 216:
                        case 214:
                           subst="O";
                           break;
                        case 8211:
                           subst="-";
                           break;
                        case 197:
                           subst="A";
                           break;
                        case 229:
                           subst="a";
                           break;
                        case 248:
                        case 246:
                           subst="o";
                           break;
                        default:
                           //alert(subst+" = "+addr.charCodeAt(j));
                     }
                     addr=addr.slice(0,j)+subst+addr.slice(j+1);
                  }
               }
               solveCompanies[proj][i][ADDRESS]=addr;
            }
            /*var PHPdata="In total "+solveCompanies[proj].length+" were selected in the Finnish market.  "+successContact+" were sucessfully contacted and the information about ";
            PHPdata+=projects[proj][1]+" was delivered to the persons responsible for selecting suppliers.  ";
            PHPdata+=notContact+" of the companies originally selected was not contacted at all, since ......  ";
            PHPdata+="A further "+unContactable+" companies were not contacted successfully, ..........__#"; */
            
            var thisDec=[GREEN,NODECISION,YELLOW,RED,UNCONTACTABLE,NOTCONTACTED];
            for (var decn=0;decn<thisDec.length;decn++) {
               for (var i=0;i<solveCompanies[proj].length;i++) {
                  var startLoop=(solveCompanies[proj][i][SUBPROJ].length==0) ?0 :1;
                  for (var k=startLoop;k<=solveCompanies[proj][i][SUBPROJ].length;k++) {
                     var stats=_calculateFinalReportStats(proj,i,k);
                     var compDec=stats[4];
                     if (compDec==ONFIRSTCALL) compDec=NODECISION;
                     if (compDec==thisDec[decn]) {
                        PHPdata+=compDec+"__#";
                        PHPdata+=_replaceManyForPHP(solveCompanies[proj][i][COMPANYNAME])+"__#";
                        PHPdata+=_replaceManyForPHP(solveCompanies[proj][i][ADDRESS])+"__#";
                        PHPdata+=_replaceForPHP("+","*plus*",solveCompanies[proj][i][PHONE])+"__#";
                        PHPdata+=_replaceManyForPHP(solveCompanies[proj][i][WEBSITE])+"__#";
                        var tempdatt=_replaceManyForPHP(solveCompanies[proj][i][TURNOVER]);
                        if (tempdatt=="n/a" || tempdatt=="N/A") tempdatt="";
                        PHPdata+=tempdatt+"__#";
                        var tempdatt=_replaceManyForPHP(solveCompanies[proj][i][EMPLOYEES]);
                        if (tempdatt=="n/a" || tempdatt=="N/A") tempdatt="";
                        PHPdata+=tempdatt+"__#";
                        PHPdata+=_replaceManyForPHP(solveCompanies[proj][i][BACKGROUND])+"__#";
                        PHPdata+=_getFinalReportFeedback(proj,i,k)+"__#";
                        PHPdata+=_getSummaryAndContacts(proj,i,k)+"__#";
                     }
                  }
               }
            }
            PHPdata=PHPdata.slice(0,PHPdata.length-3);
            //
            // separate fields split with __#, with activities as one field, to be subdivided splitting by __*
            
            xmlhttp.open("POST","finalreport.php?p="+_getPHPBlogName(proj),true);
            xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            xmlhttp.send("data="+PHPdata);
            document.getElementById("loading0").innerHTML="Generating Final report for "+projects[proj][1]+".<br/>Building report";
            _animateDots();
            //document.getElementById("loading0").innerHTML=PHPdata;
         }
                 
         function _getSummaryAndContacts(proj,comp,subProj) {
            var lastFound=999999;
            var conList=new Array();
            var found;
            var foundName="";
            var foundTitle="";
            var contactNumber=-1;
            for (var j=0;j<solveCompanies[proj][comp][CONTACTS].length;j++) {
               found=NOTFOUND;
               for (var k=0;k<solveCompanies[proj][comp][CONTACTS].length;k++) {
                  if (solveCompanies[proj][comp][CONTACTS][k][CONTACTPROJECTS][subProj]>found && solveCompanies[proj][comp][CONTACTS][k][CONTACTPROJECTS][subProj]<lastFound) {
                     found=solveCompanies[proj][comp][CONTACTS][k][CONTACTPROJECTS][subProj];
                     foundName=solveCompanies[proj][comp][CONTACTS][k][CONTACTNAME];
                     foundTitle=solveCompanies[proj][comp][CONTACTS][k][CONTACTTITLE];
                     contactNumber=k;
                  }
               }
               //alert(found);
               if (found!=NOTFOUND) {
                  lastFound=found;
                  conList.push(foundName);
               }
            }

            var cStr="";                       
            switch (conList.length) {
               case 0:
                  var cListStr="";
                  break;
               case 1:
                  var cListStr=conList[0];
                  break;
               default:
                  var cListStr="";
                  for (var i=0;i<conList.length-1;i++) cListStr+=conList[i]+", ";
                  cListStr=cListStr.slice(0,cListStr.length-2)+" and "+conList[conList.length-1];
            }
            
            var stats=_calculateFinalReportStats(proj,comp,subProj);
            
            switch (stats[0]) {
               case 0:
                  var summStr="No attempts were made to contact the company.";
                  break;
               case 1:
                  var summStr="";
                  break;
               default:
                  var summStr=stats[0]+" attempts were made to contact the company during the period "+_getDateRange(stats[5],stats[6])+".";
                  if (stats[3]<stats[0] && stats[3]>0) {
                     summStr+="  "+stats[3]+" of these resulted in ";
                     if (stats[3]==1) summStr+="a conversation about "+projects[proj][1];
                     else summStr+="conversations about "+projects[proj][1];
                     if (conList.length<2) summStr+=".";
                     else summStr+=", with the following people: "+cListStr+".";
                  }
            }
            
            //summStr+="*Status="+stats[4]+"*";
            
            if (conList.length==0) return "0__#"+summStr+"__#";
            else {
               cStr+=_replaceManyForPHP(foundName)+"__*";
               if (foundTitle=="NOTINSOLVE") cStr+="__*";
               else cStr+=_replaceManyForPHP(foundTitle)+"__*";
               cStr+=_replaceForPHP("+","*plus*",solveCompanies[proj][comp][CONTACTS][contactNumber][CONTACTMOBILE])+"__*";
               cStr+=_replaceManyForPHP(solveCompanies[proj][comp][CONTACTS][contactNumber][CONTACTEMAIL])+"__*";
               return conList.length+"__#"+summStr+"__#"+cStr.slice(0,cStr.length-3);
            }
         }
         
         function _getDateRange(start,end) {
            var months=["January","February","March","April","May","June","July","August","September","October","November","December"];
            var sDay=parseInt(start.slice(8,10),10);
            var eDay=parseInt(end.slice(8,10),10);
            var sMonth=parseInt(start.slice(5,7),10);
            var eMonth=parseInt(end.slice(5,7),10);
            if (sMonth==eMonth) return sDay+"-"+eDay+" "+months[sMonth-1];
            else return sDay+" "+months[sMonth-1]+"-"+eDay+" "+months[eMonth-1];
         }
         
         function _calculateFinalReportStats(proj,comp,subProj) {
            var stats=[0,0,0,0,0,"",""];
            stats[4]=solveCompanies[proj][comp][DECISION][subProj];
            if (solveCompanies[proj][comp][ACTIVITIES].length>0) {
               // check for start and end; modify variables accordingly
               var thisProj=(+proj)+SHIFT*subProj;
               // check for start and end; modify variables accordingly
               var start=_getActivityBoundary("start",thisProj,comp);
               if (start==NOTFOUND) start=solveCompanies[proj][comp][ACTIVITIES].length-1;
               var end=_getActivityBoundary("end",thisProj,comp);
               if (end==NOTFOUND) end=0;               
               //
               for (i=end;i<=start;i++) {
                  if (solveCompanies[proj][comp][ACTIVITIES][i][COMTYPE]==ISCALL) {
                     var data=_parseTags(solveCompanies[proj][comp][ACTIVITIES][i][COMMENT],false,(+proj)+(SHIFT*subProj),comp,i);
                     if (data[0]!="" && data[1]!=PRIVATE) {
                        stats[0]++;
                        var st=solveCompanies[proj][comp][ACTIVITIES][i][COMMENT];
                        if (st.indexOf("[invalid]")!=NOTFOUND) stats[4]=INVALID;
                        st=st.toLowerCase();
                        if (st.slice(0,2)=="no") {
                           if (st.charAt(2)=="1" || st.charAt(3)=="1") stats[1]++;
                           if (st.charAt(2)=="2" || st.charAt(3)=="2") stats[2]++;
                        }
                     }
                  } 
               }
               stats[5]=solveCompanies[proj][comp][ACTIVITIES][start][DATE];
               stats[6]=solveCompanies[proj][comp][ACTIVITIES][end][DATE];
            }
            stats[3]=stats[0]-stats[1]-stats[2];
            if (stats[4]==GREEN) {
               var found=false;
               for (i=0;i<solveCompanies[proj][comp][ACTIVITIES].length && !found;i++) {
                  // look for confirmed tag
               }
            } else {
               if (stats[4]==ONFIRSTCALL) {
                  if (stats[3]==0) {
                     if (stats[2]==0) {
                        if (stats[1]==0) stats[4]=NOTCONTACTED;   // no calls at all
                        else stats[4]=UNCONTACTABLE;              // only no1's
                     } else {
                        stats[4]=UNCONTACTABLE;    // only no1s and no2s -> follow-up???
                     }
                  } else {
                     // conversations, but no [1] ?!
                     // -> follow-up???
                     stats[4]=NODECISION;
                  }
               }
            }
            //alert(solveCompanies[proj][comp][COMPANYNAME]+" = "+stats[0]+","+stats[1]+","+stats[2]+","+stats[3]+","+stats[4]);
            return stats;
         }
         
         function _replaceForPHP(searchTxt,replTxt,text) {
            while (text.indexOf(searchTxt)>=0) {
               var pos=text.indexOf(searchTxt);
               text=text.slice(0,pos)+replTxt+text.slice(pos+1);
            }
            return text;
         }
         
         function _replaceManyForPHP(text) {
            text=_replaceAmp(text);
            //text=_replaceForPHP("\"","*quote*",text);
            return text;
         }
         
         // -------------------------------------------- initialisation functions -----------------------------------------------------------
         function _startUp() {
            var areProjects=false;
            for (var i=0;i<projects.length && !areProjects;i++) {
               if (projects[i][6]==true) areProjects=true;
            }
            if (areProjects) {
               var div=document.getElementById("loadstatus");
               while (div.hasChildNodes()) div.removeChild(div.lastChild);
               //
               for (var i=0;i<projects.length;i++) {
                  if (projects[i][6]==false) {
                     projects.splice(i,1);
                     i--;
                  }
               }
               //
               var sel=document.getElementById("projSelect");
               var el;
               for (var i=0;i<projects.length;i++) {
                  el=document.createElement("input");
                  el.setAttribute("type","checkbox");
                  el.setAttribute("id","check"+i);
                  el.setAttribute("value",i);
                  el.onclick=function() { _display(CHECK,this.value);};
                  sel.appendChild(el);
                  el=document.createElement("label");
                  el.htmlFor="check"+i;
                  el.setAttribute("id","checkLabel"+i);
                  el.appendChild(document.createTextNode(_shortened(projects[i][1],19)));
                  sel.appendChild(el);
                  //
                  el=document.createElement("input");
                  el.setAttribute("type","radio");
                  el.setAttribute("id","radio"+i);
                  el.setAttribute("value",i);
                  el.setAttribute("name","projectGroup");
                  if (i==0) el.setAttribute("checked","checked");
                  el.onclick=function() { _display(RADIO,this.value);};
                  sel.appendChild(el);
                  el=document.createElement("label");
                  el.htmlFor="radio"+i;
                  el.setAttribute("id","radioLabel"+i);
                  el.appendChild(document.createTextNode(_shortened(projects[i][1],19)));
                  sel.appendChild(el);
                  //
                  el=document.createElement("br");
                  sel.appendChild(el);
                  //
                  solveCompanies.push(new Array());
                  no12patch.push(new Array());
                  missing1tags.push(new Array());
                  //
                  el=document.createElement("p");
                  el.setAttribute("id","loading"+i);
                  div.appendChild(el);
               }
               var proj=0;
               document.getElementById("loading"+proj).innerHTML="Loading "+projects[proj][1];
               document.getElementById("OLDselector").selectedIndex=0;
               document.getElementById("statusselector").disabled=true;
               _setDates();
               _loadSolveData(proj);       
            } else {
               alert("You have not selected any projects!");
            }  
         }
         
         function _refreshProjectList(tickAllProj) {
            var div=document.getElementById("projectlistcontainer");
            var el;
            var miniDiv;
            while (div.hasChildNodes()) div.removeChild(div.lastChild);
            for (var i=0;i<projects.length;i++) {
               var isShow=false;
               switch (projects[i][2]) {
                  case 0:
                     if (document.getElementById("unstartedcheck").checked==true) isShow=true;
                     break;
                  case 1:
                     if (document.getElementById("preparationcheck").checked==true) isShow=true;
                     break;
                  case 2:
                     if (document.getElementById("attractioncheck").checked==true) isShow=true;
                     break;
                  case 3:
                     if (document.getElementById("finalisationcheck").checked==true) isShow=true;
                     break;
                  case 4:
                     if (document.getElementById("completedcheck").checked==true) isShow=true;
                     break;
               }
               if (isShow) {
                  miniDiv=document.createElement("div");
                  miniDiv.setAttribute("id","checkprojectdiv"+i);
                  miniDiv.setAttribute("class","projectlistdiv");
                  el=document.createElement("input");
                  el.setAttribute("type","checkbox");
                  el.setAttribute("id","checkproject"+i);
                  el.onclick=function() { var projNumStr=this.id; var proj=parseInt(projNumStr.slice(12)); if (this.checked==true) projects[proj][6]=true; else projects[proj][6]=false; };
                  if (tickAllProj) projects[i][6]=true;
                  if (projects[i][6]) el.checked=true;
                  miniDiv.appendChild(el);
                  el=document.createElement("label");
                  el.setAttribute("class","projectlistchecklabel");
                  el.htmlFor="checkproject"+i;
                  el.appendChild(document.createTextNode(projects[i][1]));
                  miniDiv.appendChild(el);
                  div.appendChild(miniDiv);
               } else projects[i][6]=false;
            }
         }
         
         // -------------------------------------------- end of javascript functions -----------------------------------------------------------
      </script>
      <style type="text/css">
         body { margin:0; padding:5px; font-family:arial,sans-serif; font-size:100%;  }
         h1 { font-size:2.5em; }
         h2 { font-size:1.25em; }
         h3 { font-size:1.0em; }
         h4 { font-size:0.875em; }
         p { font-size:0.75em; }
         p.close { margin:0 0 5px 0; padding:0; }
         .bold { font-weight:bold; }
         .italic { font-style:italic; }
         #menubar { border-bottom:1px solid black; width:560px; height:50px; top:0; left:0; position:fixed; z-index:99999; background:white; margin:0; padding:0 5px; }
         #dummy { border-bottom:1px solid white; width:560px; height:50px; position:relative; margin:0; padding:0; visibility:hidden; }
         span.menu { font-size:0.75em; }
         span.menuSelected { font-size:0.75em; color:blue; cursor:default; }
         span.menu:hover { cursor:pointer; text-decoration:underline; }
         span.toggle { font-size:0.75em; }
         span.toggle:hover { cursor:pointer; text-decoration:underline; }
         
         #TOGGLEPROJECTSPLIT { margin:0 0 0 20px; }
         #HIDECOLOURED { margin:0 0 0 20px; background:url("colouredband.png") no-repeat center top; background-clip:border-box;}
         #SHOWSTATS { margin:0 0 0 20px; }
         
         #projSelect { font-size:0.75em; margin:0; padding:0; position:absolute; top:0; left:110px; width:150px; height:40px; overflow-y:auto; overflow-x:hidden; white-space:nowrap; }
         /* #projSelect:hover { height:80px; z-index:999; background:white; } */

         #reportOpts { margin:0 0 0 175px; }
         #actionOpts { margin:0 0 0 175px; }
         #loadstatus { position:fixed; top:10px; left:20px; }
         #reloadButton { display:block; position:absolute; top:23px; left:26px; font-size:0.6875em; width:50px; height:20px; padding:0; margin:0; }
         
         p.whiteNumclass { margin:0 0 5px 0; padding:0; }
         
         #progresssummary { position:relative; width:355px; height:115px; margin:0; padding:0; }
         #summaryseparator { position:relative; width:300; height:44px; }
         #OLDprogresssummary { position:relative; width:240px; height:100px; margin:0; }
         
         #tabletextEmpty { margin:0 0 10px 10px; font-style:italic; }
         #tabletext { margin:0 0 10px 10px; font-style:italic; }
         
         #emptyreport { position:relative; padding:10px 10px 10px 0; }
         #progressreport { position:relative; padding:10px 10px 10px 0; }
         div.colouredDivs { position:absolute; width:36px; height:34px; font-size:1.75em; font-weight:bold; text-align:center; margin:0; padding:0; border:1px solid black; }
         #greenNum { background:#92D050; top:10px; left:75px; }
         #yellowNum { background:yellow; top:10px; left:120px; }
         #redNum { background:red; top:10px; left:165px; }
         #whiteNum { top:10px; left:225px; width:200px; height:76px; border:none; }
         #firstNum { margin:0; padding:0; font-size:1em; }
         #followNum { margin:0; padding:0; position:relative; top:42px; font-size:1em; }
         #firstNumLabel { margin:0; padding:0; position:absolute; top:12px; left:44px; width:100px; font-size:0.5em; text-align:left; }
         #followNumLabel { margin:0; padding:0; position:absolute; top:54px; left:44px; width:100px; font-size:0.5em; text-align:left; }
         #stats { position:absolute; top:96px; left:16px; background:url("statsicons.jpg") no-repeat; background-size:contain; width:400px; height:34px; margin:0; padding:0; }
         #callsT { position:absolute; top:16px; left:18px; font-size:0.8em; margin:0; padding:0; }
         #calls1 { position:absolute; top:16px; left:89px; font-size:0.8em; margin:0; padding:0; }
         #calls2 { position:absolute; top:16px; left:166px; font-size:0.8em; margin:0; padding:0; }
         #callsC { position:absolute; top:16px; left:239px; font-size:0.8em; margin:0; padding:0; }
         #totalNum { position:absolute; top:10px; left:0px; width:65px; height:34px; font-size:1.5em; font-weight:bold; text-align:right; margin:0; padding:4px 0 0 0; }

         div.OLDcolouredDivs { position:absolute; width:22px; height:21px; font-size:1em; font-weight:bold; text-align:center; margin:0; padding:0; border:1px solid black; }
         #OLDgreenNum { background:#92D050; top:10px; left:54px; }
         #OLDyellowNum { background:yellow; top:10px; left:83px; }
         #OLDredNum { background:red; top:10px; left:112px; }
         #OLDwhiteNum { top:10px; left:146px; width:200px; height:76px; border:none; }
         #OLDfirstNum { margin:0; padding:0; font-size:1em; }
         #OLDfollowNum { margin:0; padding:0; position:relative; top:28px; font-size:1em; }
         #OLDfirstNumLabel { margin:0; padding:0; position:absolute; top:7px; left:28px; width:100px; font-size:0.65em; text-align:left; }
         #OLDfollowNumLabel { margin:0; padding:0; position:absolute; top:34px; left:28px; width:100px; font-size:0.65em; text-align:left; }
         #OLDstats { position:absolute; top:70px; left:20px; background:url("statsicons.jpg") no-repeat; background-size:contain; width:250px; height:23px; margin:0; padding:0; }
         #OLDcallsT { position:absolute; top:10px; left:11px; font-size:0.6em; margin:0; padding:0; }
         #OLDcalls1 { position:absolute; top:10px; left:59px; font-size:0.6em; margin:0; padding:0; }
         #OLDcalls2 { position:absolute; top:10px; left:111px; font-size:0.6em; margin:0; padding:0; }
         #OLDcallsC { position:absolute; top:10px; left:162px; font-size:0.6em; margin:0; padding:0; }
         #OLDtotalNum { position:absolute; top:10px; left:0px; width:47px; height:21px; font-size:0.8em; font-weight:bold; text-align:right; margin:0; padding:4px 0 0 0; }
         
         #OLDselector { margin:0 0 5px 16px; }
               
         table { border-collapse:collapse; font-size:0.6875em; table-layout:fixed; padding:0; margin:0; }
         td { text-align:left; vertical-align:top; border:1px solid black; padding:5px; cursor:default; }
         th { text-align:center; vertical-align:top; border:1px solid black; padding:5px; cursor:default; }
         
         /* --------------- new ---------------------- */
         #statuscontainer { position:absolute; top:10px; left:415px; margin:0; padding:10px; border:1px solid black; width:95px; height:124px; }
         #statuslabel { font-size:0.75em; font-weight:bold; width:100px; display:block; margin:0; }
         #statusselector { display:block; margin:5px 0; padding:0; }

         #catchbox { position:absolute; top:162px; left:270px; width:250px; height:170px; margin:0; padding:10px 5px 10px 10px; background:white; } 
         #errorcontainer { position:absolute; top:170px; left:280px; width:230px; height:150px; margin:0; padding:10px 5px 10px 10px; border:1px solid black; cursor:default; background:white; }
         #errorsubcontainer { width:100%; height:127px; overflow-x:hidden; overflow-y:auto; margin:0; padding:0; }
         .errornote { margin:0 0 8px 0; padding:0; font-size:0.6875em; }
         .errorsub { margin:0 0 4px 0; padding:0; font-size:1em; }
         #errorheader { color:green; cursor:pointer; }
         #errorheader:hover { text-decoration:underline; }

         #excelreport { margin:10px 0 3px 14px; color:green; font-size:0.6875em; padding:0; }
         #wordreport { margin:0 0 0 16px; color:blue; font-size:0.6875em; padding:0; }
         #selectionreport { margin:5px 0 0 20px; color:black; font-size:0.6875em; padding:0; }
         
         .projectchecklabel { font-size:0.75em; padding:0; margin:0 10px 0 0; position:relative; top:-2px; left:-2px; }
         #projectlistcontainer { margin:20px; padding:0; width:505px; height:210px; overflow-x:hidden; overflow-y:auto; }
         .projectlistchecklabel { font-size:0.75em; padding:0; position:relative; top:-2px; left:2px; }
         .projectlistdiv { padding:0; margin:0 20px 5px 0; float:left; width:230px; height:20px; }
      </style>
   </head>
   <body>
      <div id="dummy"></div>
      <div id="menubar">
         <span id="ACTIONS" class="menu" onclick="_display(MENU,ACTIONS)">Actions</span>
         <span>|</span>
         <span id="REPORTS" class="menuSelected" onclick="_display(MENU,REPORTS)">Reports</span>
         
         <span id="reportOpts">
            <span id="FULL" class="menu" onclick="_display(MENU,FULL)">Full</span>
            <span>|</span>
            <span id="SHORT" class="menu" onclick="_display(MENU,SHORT)">Short</span>
            <span>|</span>
            <span id="SUMMARY" class="menuSelected" onclick="_display(MENU,SUMMARY)">Summary</span>
            <span id="HIDECOLOURED" class="toggle" onclick="_display(MENU,HIDECOLOURED)">Hide off</span>
            <span id="HIDEseparator">|</span>
            <span id="HIDEWHITE" class="toggle" onclick="_display(MENU,HIDEWHITE)">Hide off</span>          
            <span id="SHOWSTATS" class="toggle" onclick="_display(MENU,SHOWSTATS)">Statistics off</span>
         </span>
         
         <span id="actionOpts">
            <span id="ACTIONVIEW" class="menuSelected" onclick="_display(MENU,ACTIONVIEW)">Action sort</span>
            <span>|</span>
            <span id="PROJECTVIEW" class="menu" onclick="_display(MENU,PROJECTVIEW)">Project sort</span>
            <span id="TOGGLEPROJECTSPLIT" class="toggle" onclick="_display(MENU,TOGGLEPROJECTSPLIT)">Split projects on</span>
         </span>
         <button id="reloadButton" onclick="_reloadProject();">Restart</button>
         
         <div id="projSelect"></div>
      </div>
      <div id="emptyreport"><p id="tabletextEmpty">text</p></div>
      <div id="progressreport"><p id="tabletext">text</p></div>
      <div id="progresssummary">
         <p id="totalNum"></p>
         <div id="greenNum" class="colouredDivs"></div>
         <div id="yellowNum" class="colouredDivs"></div>
         <div id="redNum" class="colouredDivs"></div>
         <div id="whiteNum" class="colouredDivs">
            <div id="firstNum" class="colouredDivs"></div>
            <div id="followNum" class="colouredDivs"></div>
            <p id="firstNumLabel">1st calls</p>
            <p id="followNumLabel">follow-ups</p>
         </div>
         <div id="stats">
            <p id="callsT"></p>
            <p id="calls1"></p>
            <p id="calls2"></p>
            <p id="callsC"></p>
         </div>
         <div id="statuscontainer">
            <label for="statusselector" id="statuslabel">Project status:</label>
            <select id="statusselector">
               <option value="0">Unstarted</option>
               <option value="1">Preparation</option>
               <option value="2">Attraction</option>
               <option value="3">Finalisation</option>
               <option value="4">Completed</option>
            </select>
            <button id="excelreport" onclick="_excelReport()">Excel report</button>
            <button id="wordreport" onclick="_wordReport()">Final report</button>
            <button id="selectionreport" onclick="_selectionReport()">Selection</button>
         </div>
         <div id="catchbox"></div>
         <div id="errorcontainer">
            <h4 id="errorheader" class="errornote" onclick="_errorHeaderClick(this)">Correct errors</h4>
            <div id="errorsubcontainer">
               <p id="missing1tag" class="errornote" style="color:grey;"></p>
               <p id="contactnotinsolve" class="errornote" style="color:grey;"></p>
               <p id="missingcontag" class="errornote"></p>
               <p id="missingrelatedto" class="errornote"></p>
               <p id="unrelatedcontacts" class="errornote"></p>
               <p id="missinginfo" class="errornote"></p>
            </div>
         </div>
      </div>
      <div id="summaryseparator"></div>
      <select id="OLDselector" onchange="_changeDate()">
         <option value="0">Show current situation only</option>
         <option value="1" id="yesterday">Show situation yesterday</option>
         <option value="2" id="weekstart">Show situation at start of week</option>
         <option value="7">Show situation 1 week ago</option>
         <option value="14">Show situation 2 weeks ago</option>
         <option value="28">Show situation 4 weeks ago</option>
      </select>
      <div id="OLDprogresssummary">
         <p id="OLDtotalNum"></p>
         <div id="OLDgreenNum" class="OLDcolouredDivs"></div>
         <div id="OLDyellowNum" class="OLDcolouredDivs"></div>
         <div id="OLDredNum" class="OLDcolouredDivs"></div>
         <div id="OLDwhiteNum" class="OLDcolouredDivs">
            <div id="OLDfirstNum" class="OLDcolouredDivs"></div>
            <div id="OLDfollowNum" class="OLDcolouredDivs"></div>
            <p id="OLDfirstNumLabel">1st calls</p>
            <p id="OLDfollowNumLabel">follow-ups</p>
         </div>
         <div id="OLDstats">
            <p id="OLDcallsT"></p>
            <p id="OLDcalls1"></p>
            <p id="OLDcalls2"></p>
            <p id="OLDcallsC"></p>
         </div>
      </div>
      <div id="actionlist"><br/>This feature is not operational yet.</div>
      <div id="loadstatus">
         <h4 id="welcomenote">You have no projects assigned to you. This is because (i) you have no &nbsp;&nbsp;&nbsp; projects; or (ii) your projects' statuses have not been correctly set in Solve.</h4>
         <div id="projectoptionbox" style="border:1px solid black; width:485px; height:24px; margin:0; padding:5px 0 0 5px;">
            <input type="checkbox" id="unstartedcheck" onclick="_refreshProjectList(false)"/>
            <label for="unstartedcheck" class="projectchecklabel" style="color:grey;">Unstarted</label>
            <input type="checkbox" id="preparationcheck" onclick="_refreshProjectList(false)"/>
            <label for="preparationcheck" class="projectchecklabel" id="preparationchecklabel" style="color:grey;">Preparation</label>
            <input type="checkbox" id="attractioncheck" onclick="_refreshProjectList(false)"/>
            <label for="attractioncheck" class="projectchecklabel" id="attractionchecklabel">Attraction</label>
            <input type="checkbox" id="finalisationcheck" onclick="_refreshProjectList(false)"/>
            <label for="finalisationcheck" class="projectchecklabel" id="finalisationchecklabel">Finalisation</label>
            <input type="checkbox" id="completedcheck" onclick="_refreshProjectList(false)"/>
            <label for="completedcheck" class="projectchecklabel" id="completedchecklabel">Completed</label>
         </div>
         <div id="projectlistcontainer">
         </div>
         <button id="projectlistokaybutton" onclick="_startUp()">OK</button>
      </div>
      <script type="text/javascript">
         //var el=document.getElementById("errorcontainer");
         //el.onmouseout=function(e) { var relTarg = e.relatedTarget; if (relTarg.id=="catchbox") { document.getElementById("errorheader").innerHTML="Possible Solve errors"; document.getElementById("errorheader").style.color="red"; } };
         projects = <?php echo json_encode($data); ?>;
         //alert(projects.toSource());
         //
         document.getElementById("menubar").style.display="none";
         document.getElementById("unstartedcheck").disabled=true;
         document.getElementById("preparationcheck").disabled=true;
         document.getElementById("attractioncheck").checked=true;
         document.getElementById("finalisationcheck").checked=false;
         document.getElementById("completedcheck").checked=false;
         var areProjects=false;
         for (var i=0;i<projects.length && !areProjects;i++) {
            if (projects[i][2]>1 || projects[i][4]=="Sandra Gudrite") areProjects=true;
         }
         if (areProjects) {
            switch (projects[0][4]) {
               case "Darta Dzerve":
                  var nickname="Dz"+String.fromCharCode(234)+"rv"+String.fromCharCode(238)+"te";
                  break;
               case "Urte Kaselyte":
                  var nickname="Urte";
                  break;
               case "Armands Liseks":
                  var nickname="Armands";
                  break;
               case "Laima Bilinska":
                  var nickname="Laima Pulkstenis";
                  break;
               case "Baiba Soika":
                  var nickname="Baibul"+String.fromCharCode(238)+"te";
                  break;
               case "Sandra Gudrite":
                  var nickname="Sandrina";
                  document.getElementById("preparationcheck").disabled=false;
                  document.getElementById("preparationcheck").checked=true;
                  document.getElementById("preparationchecklabel").style.color="black";
                  break;
               case "Jesse Turner":
                  var nickname="Jesse";
                  break;
               case "Nana Rostobaia":
                  var nickname="Nanny";
                  break;
               case "Inese Manguse":
                  var nickname="Inese D"+String.fromCharCode(238)+"v"+String.fromCharCode(226)+"ns";
                  break;
               case "Liga Vanaga":
                  var nickname="Hawk Lady";
                  break;
               case "Zanda Vipule":
                  var nickname="Zanda Panda";
                  break;
               case "Krista Petersone":
                  var nickname="Kristap";
                  break;
               case "Kaspar Ilves":
                  var nickname="Kaspar";
                  break;
               case "Vija Krievina":
                  var nickname="Crazy Chick";
                  break;
               default:
                  nickname="Whoever-you-are";
            }
            document.getElementById("welcomenote").innerHTML="Hello "+nickname+"! Select the projects you will be working on today...";
            _refreshProjectList(true);
         } else {
            document.getElementById("projectoptionbox").style.display="none";
            document.getElementById("projectlistokaybutton").style.display="none";
         }
         _showOnly("loadstatus");
         if (projects.length==1 && projects[0][1].slice(0,5)=="Sales") _startUp();
         
         //    NEED TO CHANGE NO2 TO INCLUDE CONTACT NAME ON PROGRESS REPORT!!!!
         /*
               future tags:   [1r] or [r1] -> expanded to [1][r] before tag parsing (at the same time as {} removal?)
                              [1=],[1r=],[r1=]  combines tag with con= code.
                              [r.][y.][g.] combines decision tag with con code.
                              - - - - - -
                              no2=<contact>  no2 + con= ... expands to "The contact person, who is <contact> (<title>), was unavailable."
                              [invalid]
                              [proj=dd/mm/yyyy@tt.tt]
                              [setdate=dd/mm/yyyy] - for setting notes!
         */
      </script>
   </body>
</html> 