var StudentChart = new Array();
var SwitchOnChartQuarter = 3;

function format2(number){
  return Math.round(number*Math.pow(10,2))/Math.pow(10,2)
}
function EJGetValue(Variable,Quarter){
if (typeof(TheField[Variable])=='undefined')return parseFloat(TheFieldValues[Variable].QuarterValues[Quarter]);
if (Variable=='CurrentRank')alert(TheFieldValues[Variable]);
  if (Quarter!=CurrentQuarter) return parseFloat(TheField[Variable].QuarterValues[Quarter]);
  if (document.getElementById(Variable).innerHTML) return GetSpanValue(Variable);
  return GetValue(Variable);
}

function inspect(obj, maxLevels, level)
{
  var str = '', type, msg;

    // Start Input Validations
    // Don't touch, we start iterating at level zero
    if(level == null)  level = 0;

    // At least you want to show the first level
    if(maxLevels == null) maxLevels = 1;
    if(maxLevels < 1)     
        return '<font color="red">Error: Levels number must be > 0</font>';

    // We start with a non null object
    if(obj == null)
    return '<font color="red">Error: Object <b>NULL</b></font>';
    // End Input Validations

    // Each Iteration must be indented
    str += '<ul>';

    // Start iterations for all objects in obj
    for(property in obj)
    {
      try
      {
          // Show "property" and "type property"
          type =  typeof(obj[property]);
          str += '<li>(' + type + ') ' + property + 
                 ( (obj[property]==null)?(': <b>null</b>'):('='+obj[property])) + '</li>';

          // We keep iterating if this property is an Object, non null
          // and we are inside the required number of levels
          if((type == 'object') && (obj[property] != null) && (level+1 < maxLevels))
          str += inspect(obj[property], maxLevels, level+1);
      }
      catch(err)
      {
        // Is there some properties in obj we can't access? Print it red.
        if(typeof(err) == 'string') msg = err;
        else if(err.message)        msg = err.message;
        else if(err.description)    msg = err.description;
        else                        msg = 'Unknown';

        str += '<li><font color="red">(Error) ' + property + ': ' + msg +'</font></li>';
      }
    }

      // Close indent
      str += '</ul>';

    return str;
}


function doShowHint(point, series, chart, hint, hover_select) {
     var hint;
     if (hover_select == "hover") {
       hint = 'Hovering over: [x],[y]';
     } else {
       hint = '[series_title]<br />' + 'Selected Point: [x],[y]';
       
     }
     return hint;
}
function doShowHintQuarter(point, series, chart, hint, hover_select) {
     var hint;
     if (hover_select == "hover") {
       hint = '[series_title]<br />Quarter [x]: [y]';
     } else {
     //alert('chart is '+inspect(chart));
     //alert('chart __el_hint_canvas is '+inspect(chart['__el_hint_canvas']['style']));
     //alert('chart __el_hint_labels  is '+inspect(chart['__el_hint_labels']['style']));
     //alert('chart __el_hint is '+inspect(chart['__el_hint']['style']));
     
     
//     alert('point label value is '+point['label']);
     }
     return hint;
}




function BuildBIChartDIV(panel,Count,TheClass){
  var ChartID = panel + "EJDiv" + Count;
  return "<div id="+ChartID+" class="+TheClass+"></div><div id="+ChartID+"Warning class=ChartWarning></div>";

}


function CreateChartDiv(panel,TheDivs){
  if (getCookie(panel+"ChartContainer")==1) setTimeout("MinMaxChartDiv('"+panel+"ChartContainer')",700);
  return "<div class=MinChartLink><a href=javascript:void(null); onclick=MinMaxChartDiv('"+panel+"ChartContainer')><img src=images/ChartIconBG.gif border=0></a></div><div id="+panel+"ChartContainer class=ChartContainer>"+TheDivs+"</div><div style='clear: both;'></div>";
}
function MinMaxChartDiv(TheDiv){
  if (!document.getElementById(TheDiv) || 
      !document.getElementById(TheDiv).style ||
      !document.getElementById(TheDiv).style.display || 
       document.getElementById(TheDiv).style.display=='block'){
    document.getElementById(TheDiv).style.display='none';
            setCookie(TheDiv,1);

  } else {
    document.getElementById(TheDiv).style.display='block';
            deleteCookie(TheDiv);

  }
}


function BuildDataStringByQuarter(TheVar,StartQuarter){
   var TheString='';
   if (!StartQuarter || StartQuarter=='') StartQuarter=0
   for (var i=StartQuarter;i<=MaxQuarter-1;i++){       
        if (TheString !='') TheString+=","
        TheString+=i.toString() + "|" + EJGetValue(TheVar,i).toString();
     }
   return TheString;
}

function WarningChart(TheDiv,Level){
  document.getElementById(TheDiv+'Warning').style.display='none';
  document.getElementById(TheDiv).style.color='black';
  if (Level==0) return;
  if (Level>3) Level=3
  var Pos = findPos(TheDiv);
  if (Level>=2) document.getElementById(TheDiv).style.paddingRight = "25px";
  if (Level==2) document.getElementById(TheDiv).style.border='2px solid #f47a17';
  if (Level==3) document.getElementById(TheDiv).style.border='2px solid #ff0000';
  if (Level>=2) document.getElementById(TheDiv).style.backgroundImage = "url(images/WarningBG"+Level+".gif)";
  document.getElementById(TheDiv+'Warning').style.display='block';
  //document.getElementById(TheDiv+'Warning').style.backgroundColor='#eee';
  document.getElementById(TheDiv+'Warning').style.height=150;
  document.getElementById(TheDiv+'Warning').style.width=40;
  var AltText='Mild Warning'
  if (Level==2)AltText='Moderate Warning -- Some Attention Recommended';
  if (Level==3)AltText='Severe Warning -- Immediate Attention Strongly Recommended.  This is a warning that your performance in this area is poor and needs immediate corrective action.';
  document.getElementById(TheDiv+'Warning').innerHTML='<img title="'+AltText+'" alt="'+AltText+'" src=images/Warning'+Level+'.png width=50% border=0>';
}

function drillpanel(destPanel,offset){
  showpanel(destPanel);
//  xpos = parseInt(document.getElementById(srcPanel).style.left) +  20
//  ypos = parseInt(document.getElementById(srcPanel).style.top) + 120
   if (offset==null || offset=='') offset=0;
  
   //xpos=MouseX+20+offset;
   xpos=10;
   //ypos=MouseY+20+offset;
   ypos = ScreenTop+offset;
  document.getElementById(destPanel).style.left=xpos+'px';
  document.getElementById(destPanel).style.top=ypos+'px';    
}
function SetLegendOff(TheDiv,TheChart){
   var currentTime = new Date()
   StudentChart[TheDiv]=TheChart
   StudentChart[TheDiv].TurnOff = true;
   StudentChart[TheDiv].TurnOffTime = currentTime.getTime() + 2000;
}
function ClearLegend(){
   var currentTime = new Date()
   for (var word in StudentChart){
      if (StudentChart[word].TurnOff && StudentChart[word].TurnOffTime<currentTime.getTime()){
         StudentChart[word].TurnOff=false;
         StudentChart[word].legendMinimize();
        //    StudentChart1.setShowLegend(false);
      }
   }
}

function CheckEnoughQuarter(TheDiv){
  el = document.getElementById(TheDiv);
  if (!el || el=='undefined' || el==null) return false;
  if (MaxQuarter<SwitchOnChartQuarter){
    el.innerHTML='<i>Not enough data to chart. <br>Check back to this area in subsequent quarters.</i>';
  if (TheDiv.indexOf('Promote')>-1 ||  TheDiv.indexOf('ChartPopup')>-1 ||  TheDiv.indexOf('panelMain')>-1 ) return false;
    document.getElementById(TheDiv).style.display='none';
    document.getElementById(TheDiv).style.visibility='hidden';
    var panel = TheDiv.replace(/EJDiv\d/,'');
    if (document.getElementById(panel+"ChartContainer")) document.getElementById(panel+"ChartContainer").style.display='none';
    return false;
  }
  return true;
}

function DrawPanelCharts(panel){
    var chart1Div = panel + "EJDiv1";
    var chart2Div = panel + "EJDiv2";
    var chart3Div = panel + "EJDiv3";
    var chart4Div = panel + "EJDiv4";
    if (!CheckEnoughQuarter(chart1Div)) return false;
    setTimeout('ClearLegend()',4000);
    switch (panel) {

     // /////////////////////////////////////////////////////////////////////////
  
       case "panelRatio":

 

       var chart1 = new EJSC.Chart(chart1Div, {
          title: "Financial Ratios",
          legend_title:'Ratios',

          allow_mouse_wheel_zoom: false,
          show_legend: true ,


          axis_bottom: { caption: "Quarter" , 
              formatter: new EJSC.NumberFormatter({ forced_decimals: 0 }),
              grid:{show:false},
              crosshair: { show: true } 
          } ,
          axis_left: { caption: "" , grid:{show:false}, crosshair: { show: true } } ,
          axis_right: { caption: "" , grid:{show:false}, crosshair: { show: true } } ,


          onShowHint: function(point, series, chart, hint, hover_select) {
                        var hint = '[series_title]<br />Quarter [x]: [y]';

                        if (hover_select == "hover") {
                        } else {    
                            var label = series['title'];
                            if (
                                label.indexOf('Current')>-1 ||
                                label.indexOf('Debt')>-1 ||
                                label.indexOf('Quick')>-1 
                                ) drillpanel('panelBalSheet');
                            if (
                                label.indexOf('Return on Sale')>-1 ||
                                label.indexOf('Times Interest')>-1 
                                ) drillpanel('panelIncome');
                        
                            if (
                                label.indexOf('Inventory')>-1 
                                ){ drillpanel('panelCOGS'); drillpanel('panelIncome'); }
                        
                            if (
                                label.indexOf('Fixed Asset')>-1 ||
                                label.indexOf('Equity')>-1 ||
                                label.indexOf('Total Asset')>-1 
                                ){ drillpanel('panelBalSheet'); drillpanel('panelIncome'); }
                        }

                     return hint;
                     }
         });
         SetLegendOff(chart1Div,chart1)
       
         
         chart1.addSeries(new EJSC.LineSeries(
           new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('RatCurrent')),
           { title: 'Current'
           }
         ));
         chart1.addSeries(new EJSC.LineSeries(
           new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('RatQuick')),
           { title: 'Quick'
           }
         ));
         chart1.addSeries(new EJSC.LineSeries(
           new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('RatDebitAsset')),
           { title: 'Debt to Tot Assets'
           }
         ));

         //chart1.addSeries(new EJSC.LineSeries(
         //  new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('RatTimesInt')),
         //  { title: 'Times Interest Earned'
         //  }
         //));

         //chart1.addSeries(new EJSC.LineSeries(
         //  new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('RatInvTurn')),
         //  { title: 'Inventory Turnover'
         //  }
         //));
         //chart1.addSeries(new EJSC.LineSeries(
         //  new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('RatFixAssetTurn')),
         //  { title: 'Fixed Assets Turnover'
         //  }
         //));
         //chart1.addSeries(new EJSC.LineSeries(
         //  new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('RatTotAssetTurn')),
         //  { title: 'Total Asset Turnover'
         //  }
         //));
         chart1.addSeries(new EJSC.LineSeries(
           new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('RatRetSale')),
           { 
           y_axis: "right",
           title: 'Ret On Sales'
           }
         ));
         chart1.addSeries(new EJSC.LineSeries(
           new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('RatRetTotAsset')),
           {
           y_axis: "right",
           title: 'Ret On Tot Assets'
           }
         ));
         chart1.addSeries(new EJSC.LineSeries(
           new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('RatRetEquity')),
           {
           y_axis: "right",
            title: 'Ret On Equity'
           }
         ));
  
         return;


     // /////////////////////////////////////////////////////////////////////////
  
       case "panelRM":

         var Level=0
         var Use = EJGetValue('RMUseUnitA1',CurrentQuarter)+ EJGetValue('RMUseUnitA2',CurrentQuarter) + EJGetValue('RMUseUnitA3',CurrentQuarter);
         var EndInv = EJGetValue('RMFinInvUnitA1',CurrentQuarter)+ EJGetValue('RMFinInvUnitA2',CurrentQuarter) + EJGetValue('RMFinInvUnitA3',CurrentQuarter);
         if (EndInv>1.5*Use) Level=1
         if (EndInv>2*Use) Level=2
         if (EndInv>2.5*Use) Level=3
         WarningChart(chart1Div,Level);
         
         
 

       var chart1 = new EJSC.Chart(chart1Div, {
          title: "Raw Material Q"+CurrentQuarter ,
          show_legend: true ,
          allow_mouse_wheel_zoom: false,


          axis_bottom: { caption: "Quarter" , 
              formatter: new EJSC.NumberFormatter({ forced_decimals: 0 }),
              grid:{show:false},
              crosshair: { show: true } 
          } ,
          axis_left: { caption: "" , grid:{show:false}, crosshair: { show: true } } ,


          onShowHint: function(point, series, chart, hint, hover_select) {
                        var hint = '<nobr>[series_title] = [x]</nobr>';
                        if (hover_select == "hover") {
                        } else {    
                            var label = point['label'];
                            if (label.indexOf('Use')>-1) drillpanel('panelWHOp');
                            if (label.indexOf('Remain')>-1) drillpanel('panelOPERDec');
                        }

                     return hint;
                     }
         });
         SetLegendOff(chart1Div,chart1)

         chart1.addSeries(new EJSC.PieSeries(
           new EJSC.ArrayDataHandler([
           [ EJGetValue('RMUseUnitA1',CurrentQuarter)+EJGetValue('RMUseUnitA2',CurrentQuarter)+EJGetValue('RMUseUnitA3',CurrentQuarter),'Total Use'],
           [ EJGetValue('RMFinInvUnitA1',CurrentQuarter)+EJGetValue('RMFinInvUnitA2',CurrentQuarter)+EJGetValue('RMFinInvUnitA3',CurrentQuarter),'Remaining Inv']           
           ]),
           { title: 'RM' }
         ));

             
         chart1.addSeries(new EJSC.LineSeries(
           new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('RMFinInvUnitA1')),
           { title: 'Inventory - R1 '
           
           }
         ));
         chart1.addSeries(new EJSC.LineSeries(
           new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('RMFinInvUnitA2')),
           { title: 'Inventory - R2 '
           
           }
         ));
         chart1.addSeries(new EJSC.LineSeries(
           new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('RMFinInvUnitA3')),
           { title: 'Inventory - R3 '
           
           }
         ));



         return;


     // /////////////////////////////////////////////////////////////////////////
  
       case "panelCOGS":

         var Level=0
         var CG = EJGetValue('CGTotCOGSPerUnit',CurrentQuarter);
         var Subcon = EJGetValue('MICFinGoodA1',CurrentQuarter);
         if (CG>.8*Subcon) Level=1
         if (CG>.9*Subcon) Level=2
         if (CG>Subcon) Level=3
         WarningChart(chart2Div,Level);
         
         
 

       var chart1 = new EJSC.Chart(chart1Div, {
          title: "COGS Breakdown Q"+CurrentQuarter ,
          show_legend: true ,
                    allow_mouse_wheel_zoom: false,

          onShowHint: function(point, series, chart, hint, hover_select) {
                        var hint = '<nobr>[series_title]: [label] = [x]</nobr><br>Click on graph to get more info.';
                        if (hover_select == "hover") {
                        } else {    
                            var label = point['label'];
                            if (
                               label.indexOf('Worker')>-1 || 
                               label.indexOf('Overtime')>-1 || 
                               label.indexOf('Hire')>-1 || 
                               label.indexOf('Lease')>-1
                               ) drillpanel('panelPlant');
                            if (label.indexOf('Maintenance')>-1) drillpanel('panelPlantDec');
                            if (label.indexOf('Training')>-1) drillpanel('panelOPERDec');
                            if (label.indexOf('Subcontract')>-1) drillpanel('panelOPERDec');
                            if (label.indexOf('Raw')>-1) drillpanel('panelRM');
                            if (label.indexOf('Deprec')>-1) drillpanel('panelBalSheet');
                            if (label.indexOf('Overtime')>-1) drillpanel('panelPlant');
                                                        
                        }
                      return hint;

                     }
         });
         var Units = EJGetValue('CGManufTotUnit',CurrentQuarter);
         chart1.addSeries(new EJSC.PieSeries(
           new EJSC.ArrayDataHandler([
           [ format2(EJGetValue('CGMaterialTot',CurrentQuarter)/Units),'Raw Material'],
           [ format2(EJGetValue('CGRegPayTot',CurrentQuarter)/Units),'Worker Pay'],
           [ format2(EJGetValue('CGOvertimeTot',CurrentQuarter)/Units),'Overtime'],
           [ format2(EJGetValue('CGOverheadTot',CurrentQuarter)/Units),'Overhead'],
           [ format2((EJGetValue('CGHireCostTot',CurrentQuarter)+EJGetValue('CGLayoffCostTot',CurrentQuarter))/Units),'Hire+Layoff'],
           [ format2(EJGetValue('CGLeaseTot',CurrentQuarter)/Units),'Lease'],
           [ format2(EJGetValue('CGDepTot',CurrentQuarter)/Units),'Depreciation'],
           [ format2(EJGetValue('CGQualityTot',CurrentQuarter)/Units),'Quality'],
           [ format2(EJGetValue('CGPlantMainTot',CurrentQuarter)/Units),'Maintenance'],
           [ format2(EJGetValue('CGTrainDevCostTot',CurrentQuarter)/Units),'Training'],          
           [ format2(EJGetValue('CGFinGoodTot',CurrentQuarter)/Units),'Subcontract']
           ]),
           { 

           title: 'COGS' }
         ));

       var chart2 = new EJSC.Chart(chart2Div, {
          title: "Mfg COGS and Subcontract" ,
                    allow_mouse_wheel_zoom: false,
          axis_bottom: { caption: "Quarter" , 

              formatter: new EJSC.NumberFormatter({ forced_decimals: 0 }),
              crosshair: { show: true } 
          } ,
          axis_left: { caption: "" , grid:{show:false}, crosshair: { show: true } } ,
          axis_right: { caption: "" , grid:{show:false}, crosshair: { show: true } } ,
          show_legend: true, 
          legend_title:'COGS & Subcon',
          auto_zoom: 'y' ,
          grid:{show:false},
          auto_find_point_by_x: true,
          onShowHint: doShowHintQuarter
         });
         SetLegendOff(chart2Div,chart2)
         SetLegendOff(chart1Div,chart1)

         chart2.addSeries(new EJSC.LineSeries(
           new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('CGTotCOGSPerUnit')),
           { title: 'COGS', lineWidth:2
           
           }
         ));
         chart2.addSeries(new EJSC.LineSeries(
           new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('MICFinGoodA1')),
           { opacity:20,
             title: 'Subcon R1'
           }
         ));
         chart2.addSeries(new EJSC.LineSeries(
           new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('MICFinGoodA2')),
           { opacity:20,
           visible: false,
             title: 'Subcon R2'
           }
         ));
         chart2.addSeries(new EJSC.LineSeries(
           new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('MICFinGoodA3')),
           { opacity:20,
            y_axis: 'right',
           visible: false,
             title: 'Subcon R3'
           }
         ));



         return;


     // /////////////////////////////////////////////////////////////////////////
  
       case "panelSAReport":

              
 
       var chart1 = new EJSC.Chart(chart1Div, {
          title: "S&A Breakdown Q"+CurrentQuarter ,
          show_legend: true ,
                    allow_mouse_wheel_zoom: false,

          onShowHint: function(point, series, chart, hint, hover_select) {
                        var hint = '<nobr>[series_title]: [label] = [x]</nobr><br>Click on graph to get more info.';
                        if (hover_select == "hover") {
                        } else {    
                        drillpanel('panelMRKT');
                        }
                      return hint;

                     }
         });
         var Units = EJGetValue('CGTotCOGSUnit',CurrentQuarter);
         if (!CheckFieldEnable('SalesReps')){
           chart1.addSeries(new EJSC.PieSeries(
           new EJSC.ArrayDataHandler([
           [ format2(EJGetValue('SARHireTot',CurrentQuarter)/Units),'Hire'],
           [ format2(EJGetValue('SARTrainTot',CurrentQuarter)/Units),'Training'],
           [ format2(EJGetValue('SARRegTot',CurrentQuarter)/Units),'Salary'],
           [ format2(EJGetValue('SARCommisTot',CurrentQuarter)/Units),'Commission'],
           [ format2(EJGetValue('SARTranTotal',CurrentQuarter)/Units),'Transfers'],
           [ format2(EJGetValue('SARLAdTot',CurrentQuarter)/Units),'Local Newpaper'],
           [ format2(EJGetValue('SARNAdExpTot',CurrentQuarter)/Units),'Trade Pub'],
           [ format2(EJGetValue('SARPI',CurrentQuarter)/Units),'Feature Dev'],
           [ format2(EJGetValue('SARCompInfoExp',CurrentQuarter)/Units),'Competitive Info'],
           [ format2(EJGetValue('SARAdminExp',CurrentQuarter)/Units),'Admin Expense'],          
           [ format2(EJGetValue('SARFineRefExp',CurrentQuarter)/Units),'Fines/Refunds']
           ]),
           { 

           title: 'S & A' }
         ));
         } else {


         chart1.addSeries(new EJSC.PieSeries(
           new EJSC.ArrayDataHandler([
           [ format2(EJGetValue('SARLAdTot',CurrentQuarter)/Units),'Local Newpaper'],
           [ format2(EJGetValue('SARNAdExpTot',CurrentQuarter)/Units),'Trade Pub'],
           [ format2(EJGetValue('SARPI',CurrentQuarter)/Units),'Feature Dev'],
           [ format2(EJGetValue('SARCompInfoExp',CurrentQuarter)/Units),'Competitive Info'],
           [ format2(EJGetValue('SARAdminExp',CurrentQuarter)/Units),'Admin Expense'],          
           [ format2(EJGetValue('SARFineRefExp',CurrentQuarter)/Units),'Fines/Refunds']
           ]),
           { 

           title: 'S & A' }
         ));
         }

       var chart2 = new EJSC.Chart(chart2Div, {
          title: "S&A Expense" ,
                    allow_mouse_wheel_zoom: false,

          axis_bottom: { caption: "Quarter" , 
              formatter: new EJSC.NumberFormatter({ forced_decimals: 0 }),
              crosshair: { show: true } 
          } ,
          axis_left: { caption: "" , grid:{show:false}, crosshair: { show: true } } ,
          show_legend: true, 
          legend_title:'S&A Expense',
          auto_zoom: 'y' ,
          grid:{show:false},
          auto_find_point_by_x: true,
          onShowHint: doShowHintQuarter
         });
             
         SetLegendOff(chart1Div,chart1)
         SetLegendOff(chart2Div,chart2)

         if (!CheckFieldEnable('SalesReps')) chart2.addSeries(new EJSC.LineSeries(
           new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('SARSalesTotal')),
           { title: 'Sales Person Cost', lineWidth:2  }    ));
           
         chart2.addSeries(new EJSC.AreaSeries(
           new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('SARTotExp')),
           { opacity:20,
             title: 'Total S A'
           }
         ));



         return;


// /////////////////////////////////////////////////////////////////////////

       case "panelPlant":



       var chart = new Array();
       var MaxRegion = (CheckFieldEnable('Region3'))? 2 : 3;

       for (var Area=1;Area<=MaxRegion;Area++){       
         var TheDiv = chart1Div;
         if (Area==2) TheDiv = chart2Div;
         if (Area==3) TheDiv = chart3Div;
          var Level=0;
          var Prod = EJGetValue('ODProductA'+Area,CurrentQuarter );
          var Plant = EJGetValue('PltTotCapA'+Area,CurrentQuarter );
          var Workers = EJGetValue('WFCrewsA'+Area,CurrentQuarter )*EJGetValue('WFProductivityA'+Area,CurrentQuarter );
          if (Level<1 && (Plant>1.05 * Prod || Plant<0.95 * Prod || Workers>1.05 * Prod || Workers<0.95 * Prod)) Level = 1
          if (Level<2 && (Plant>1.1 * Prod || Plant<0.9 * Prod || Workers>1.1 * Prod || Workers<0.9 * Prod)) Level = 2
          if (Level<3 && (Plant>1.15 * Prod || Plant<0.85 * Prod || Workers>1.15 * Prod || Workers<0.85 * Prod)) Level = 3

         
         WarningChart(TheDiv,Level);
         var showlegend=(Area>=1)? true: false;         


          chart[Area] = new EJSC.Chart(TheDiv, {
          title: "Region "+Area ,
                    allow_mouse_wheel_zoom: false,

          axis_bottom: { caption: "Quarter" , 
              formatter: new EJSC.NumberFormatter({ forced_decimals: 0 }),
              crosshair: { show: true } 
          } ,
          axis_left: { caption: "%" , grid:{show:false}, crosshair: { show: true } } ,
          legend_title:'Efficiency',
          show_legend: showlegend,          
          auto_zoom: 'y' ,
          auto_find_point_by_x: true,
          onShowHint: doShowHintQuarter
         });
             
             
         if (Area==1) SetLegendOff(chart1Div,chart[Area])
         if (Area==2) SetLegendOff(chart2Div,chart[Area])
         if (Area==3) SetLegendOff(chart3Div,chart[Area])

             
         var TheStringW = ''
         var TheStringP = ''
         for (var i=0;i<=MaxQuarter-1;i++){       
	    if (TheStringW !='') TheStringW+=","
	    if (TheStringP !='') TheStringP+=","
	    var Prod = EJGetValue('ODProductA'+Area,i );
	    var Plant = EJGetValue('PltTotCapA'+Area,i );
	    var Workers = EJGetValue('WFCrewsA'+Area,i )*EJGetValue('WFProductivityA'+Area,i);
	    if (Prod==0){
	      TheValueW=100;
	      TheValueP=100;
	    } else {
	      TheValueW = format2(100*Prod/Workers);
	      TheValueP = format2(100*Prod/Plant);
	    }

	    TheValue = EJGetValue('WHOEndInvA'+Area,i) - EJGetValue('WHOLostSalesA'+Area,i);

            TheStringW+=i.toString() + "|" + TheValueW.toString();
            TheStringP+=i.toString() + "|" + TheValueP.toString();
         }


         chart[Area].addSeries(new EJSC.LineSeries(
           new EJSC.CSVStringDataHandler(TheStringW),
           { title: 'Workforce Eff - R'+Area
           
           }
         ));
         chart[Area].addSeries(new EJSC.LineSeries(
           new EJSC.CSVStringDataHandler(TheStringP),
           { 
             title: 'Plant Efficiency - R'+Area
           }
         ));

      }
         return;


     // /////////////////////////////////////////////////////////////////////////

       case "panelCashFlow":

         var Level=0;
         var CG;
         if (CurrentQuarter<MaxQuarter){
           CG = EJGetValue('CFCompLoan',CurrentQuarter );
           if (CG>50000) Level=1
           if (CG>100000) Level=2
           if (CG>250000) Level=3
         } else {
           CG = EJGetValue('CFEndCash',CurrentQuarter );
           if (CG<-50000) Level=1
           if (CG<-100000) Level=2
           if (CG<-250000) Level=3
         }
         
         WarningChart(chart1Div,Level);
         
         
 


       var chart1 = new EJSC.Chart(chart1Div, {
          title: "Net Cash Flow & Short Term Loans" ,
                    allow_mouse_wheel_zoom: false,
          axis_bottom: { caption: "Quarter" , 

              formatter: new EJSC.NumberFormatter({ forced_decimals: 0 }),
              crosshair: { show: true } 
          } ,
          axis_left: { caption: "" , grid:{show:false}, crosshair: { show: true } } ,
          legend_title:'Cash',
          show_legend: true,          
          auto_zoom: 'y' ,
          auto_find_point_by_x: true,
          onShowHint: doShowHintQuarter
         });
             
             
         SetLegendOff(chart1Div,chart1)
    
         chart1.addSeries(new EJSC.LineSeries(
           new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('CFNetCash')),
           { title: 'Net Cash Flow', lineWidth:2
           
           }
         ));
         chart1.addSeries(new EJSC.LineSeries(
           new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('CFLoan')),
           { 
             title: 'ST Loan'
           }
         ));
         chart1.addSeries(new EJSC.AreaSeries(
           new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('CFCompLoan')),
           { 
             title: 'Emergency Loan', color:'rgb(255,0,0)'
             
           }
         ));



         return;




     // /////////////////////////////////////////////////////////////////////////

       case "panelIncome":

         var Level=0;
         var NetIncome= EJGetValue('ISNIncomeCurrent',CurrentQuarter );
         var NetIncome1= EJGetValue('ISNIncomeCurrent',CurrentQuarter-1 );
         
         if (NetIncome<0 && NetIncome1<-25000) Level=1
         if (NetIncome<-50000 && NetIncome1<-50000) Level=2
         if (NetIncome<-75000 && NetIncome1<-75000) Level=3
         
         WarningChart(chart1Div,Level);


       var chart1 = new EJSC.Chart(chart1Div, {
          title: "Income Statement Breakdown" ,
                    allow_mouse_wheel_zoom: false,

          axis_bottom: { caption: "Quarter" , 
              formatter: new EJSC.NumberFormatter({ forced_decimals: 0 }),
              crosshair: { show: true } 
          } ,
          axis_left: { caption: "" , grid:{show:false}, crosshair: { show: true } } ,
          legend_title:'Cash',
          show_legend: true,          
          auto_zoom: 'y' ,
          auto_find_point_by_x: true,
          onShowHint: function(point, series, chart, hint, hover_select) {
                        var hint = '<nobr>[series_title]: Quarter [x] = [y]</nobr><br>Click on graph to get more info.';
                        if (hover_select == "hover") {
                        } else {    
                        var label = series['title'];
                        if (label.indexOf('Cost of Goods')>-1) drillpanel('panelCOGS');
                        if (label.indexOf('S & A')>-1) drillpanel('panelSAReport');
                        if (label.indexOf('Warehouse')>-1) drillpanel('panelWHOp');
                        if (label.indexOf('Interest')>-1) drillpanel('panelCashFlow');

                        }
                      return hint;

                     }
         });
             
             
         SetLegendOff(chart1Div,chart1)


       var stack = chart1.addSeries(new EJSC.StackedBarSeries({title:'Breakdown'}));
         
         stack.addSeries(new EJSC.BarSeries(
           new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('ISCOGSCurrent')),
           { title: "Cost of Goods Sold" }
         ));
         stack.addSeries(new EJSC.BarSeries(
           new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('ISSAExpenseCurrent')),
           { title: "S & A Expense"
           }
         ));
         stack.addSeries(new EJSC.BarSeries(
           new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('ISWarehouseCurrent')),
           { title: "Warehouse Ops"
           }
         ));
         stack.addSeries(new EJSC.BarSeries(
           new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('ISNetIntCurrent')),
           { title: "Net Interest"
           }
         ));
         stack.addSeries(new EJSC.BarSeries(
           new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('ISIncTaxProvCurrent')),
           { title: "Tax"
           }
         ));
         stack.addSeries(new EJSC.BarSeries(
           new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('ISNIncomeCurrent')),
           { title: "Net Income"
           }
         ));
             

         return;


     // /////////////////////////////////////////////////////////////////////////

       case "panelBalSheet":


       var chart1 = new EJSC.Chart(chart1Div, {
          title: "Assets" ,
                    allow_mouse_wheel_zoom: false,

          axis_bottom: { caption: "Quarter" , 
              formatter: new EJSC.NumberFormatter({ forced_decimals: 0 }),
              crosshair: { show: true } 
          } ,
          axis_left: { caption: "" , grid:{show:false}, crosshair: { show: true } } ,
          legend_title:'Assets',
          show_legend: true,          
          auto_zoom: 'y' ,
          auto_find_point_by_x: true,
          onShowHint: doShowHintQuarter
         });
             
       var chart2 = new EJSC.Chart(chart2Div, {
          title: "Liabilities & Equity" ,
                    allow_mouse_wheel_zoom: false,

          axis_bottom: { caption: "Quarter" , 
              formatter: new EJSC.NumberFormatter({ forced_decimals: 0 }),
              crosshair: { show: true } 
          } ,
          axis_left: { caption: "" , grid:{show:false}, crosshair: { show: true } } ,
          legend_title:'Liabilities',
          show_legend: true,          
          auto_zoom: 'y' ,
          auto_find_point_by_x: true,
          onShowHint: doShowHintQuarter
         });
             
         SetLegendOff(chart1Div,chart1)
         SetLegendOff(chart2Div,chart2)


       var stack1 = chart1.addSeries(new EJSC.StackedBarSeries({title:'Breakdown'}));
         
         stack1.addSeries(new EJSC.BarSeries(
           new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('BSCash')),
           { title: "Cash"
           }
         ));
         stack1.addSeries(new EJSC.BarSeries(
           new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('BSAR')),
           { title: "Accounts Rec"
           }
         ));

         var TheString = ''
         var TheBonds = ''
         for (var i=0;i<=MaxQuarter-1;i++){       
	    if (TheString !='') TheString+=","
	    if (TheBonds !='') TheBonds+=","
	    TheValue = EJGetValue('BSSTInvest',i) + EJGetValue('BSMaterial',i) + EJGetValue('BSFinGoods',i);
	    TheValue1 = EJGetValue('BSBond1',i) + EJGetValue('BSBond2',i);
            TheString+=i.toString() + "|" + TheValue.toString();
            TheBonds+=i.toString() + "|" + TheValue1.toString();
         }
         stack1.addSeries(new EJSC.BarSeries(
           new EJSC.CSVStringDataHandler(TheString),
           { title: "Other"
           }
         ));
         stack1.addSeries(new EJSC.BarSeries(
           new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('BSPlant')),
           { title: "Plant"
           }
         ));
         stack1.addSeries(new EJSC.BarSeries(
           new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('BSAccDep')),
           { title: "Accum Deprec"
           }
         ));



       var stack2 = chart2.addSeries(new EJSC.StackedBarSeries({title:'Liabilities & Equity'}));
         
         stack2.addSeries(new EJSC.BarSeries(
           new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('BSNotes')),
           { title: "Notes" }
         ));
         stack2.addSeries(new EJSC.BarSeries(
           new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('BSTax')),
           { title: "Tax" }
         ));

         stack2.addSeries(new EJSC.BarSeries(
           new EJSC.CSVStringDataHandler(TheBonds),
           { title: "Bonds" }
         ));
         stack2.addSeries(new EJSC.BarSeries(
           new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('BSStock')),
           { title: "Stock" }
         ));
         stack2.addSeries(new EJSC.BarSeries(
           new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('BSRetEarn')),
           { title: "Retained Earn" }
         ));



         return;






     // /////////////////////////////////////////////////////////////////////////

       case "panelWHOp":
       var chart = new Array();
       var MaxRegion = (CheckFieldEnable('Region3'))? 2 : 3;
       for (var Area=1;Area<=MaxRegion;Area++){       
         var TheDiv = chart1Div;
         if (Area==2) TheDiv = chart2Div;
         if (Area==3) TheDiv = chart3Div;
         var Level=0;
           CG = EJGetValue('WHOLostSalesA'+Area,CurrentQuarter );
           EndInv = EJGetValue('WHOEndInvA'+Area,CurrentQuarter );
           if (CG>0 || EndInv> 2000) Level=1;
           if (CG>1000 || EndInv> 4000) Level=2;
           if (CG>2000|| EndInv> 6000) Level=3;
         
         WarningChart(TheDiv,Level);
         
          var showlegend=(Area>=1)? true: false;         
 
         chart[Area] = new EJSC.Chart(TheDiv, {
       	      title: "Region "+Area ,
       	                allow_mouse_wheel_zoom: false,

              axis_bottom: { caption: "Quarter" , 
              formatter: new EJSC.NumberFormatter({ forced_decimals: 0 }),
              crosshair: { show: true } 
          } ,
          axis_left: { caption: "" , grid:{show:false}, crosshair: { show: true } } ,
          legend_title:'Units',
          show_legend: showlegend,          
          auto_zoom: 'y' ,
          auto_find_point_by_x: true,
          onShowHint: doShowHintQuarter
         });
             
         if (Area==1) SetLegendOff(chart1Div,chart[Area])
         if (Area==2) SetLegendOff(chart2Div,chart[Area])
         if (Area==3) SetLegendOff(chart3Div,chart[Area])

             
         chart[Area].addSeries(new EJSC.LineSeries(
           new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('WHOSoldA'+Area)),
           { title: 'Units Sold', lineWidth:2
           
           }
         ));
         chart[Area].addSeries(new EJSC.LineSeries(
           new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('MDForecastA'+Area)),
           { title: 'Forecast', lineWidth:2
           
           }
         ));
         
         var TheString = ''
         for (var i=0;i<=MaxQuarter-1;i++){       
	    if (TheString !='') TheString+=","
	    TheValue = EJGetValue('WHOEndInvA'+Area,i) - EJGetValue('WHOLostSalesA'+Area,i);
            TheString+=i.toString() + "|" + TheValue.toString();
         }
                
         chart[Area].addSeries(new EJSC.AreaSeries(
           new EJSC.CSVStringDataHandler(TheString),
           { 
             title: 'End Inventory'
             
           }
         ));

        }
        

         return;




 

    }
}

function BuildChartMarker(MyField,TheLabel){
  if (
     TheLabel ==' ' ||
     TheLabel =='' ||
     HideDisplay[MyField] ||
     !TheLabel 
     ) return " ";
  if (
     MyField.indexOf('MDTrans')>-1 ||
     MyField.indexOf('CID')>-1 ||
     MyField.indexOf('MDNoSale')>-1 ||
     MyField.indexOf('PDTech')>-1 ||
     MyField.indexOf('PDSellTech')>-1 ||
     MyField.indexOf('PDCrew')>-1 ||
     MyField.indexOf('PDProduct')>-1 ||
     MyField.indexOf('MDLAMess')>-1 
     ) return "&nbsp;";
  TheLabel=TheLabel.replace("'",'');
  TheLabel=TheLabel.replace('"','');
  return "<a href='javascript:void(null);' onclick=\"AddToChartPopup('"+
          MyField+
          "','"+
          TheLabel+
          "');\"  style='width:15px; margin-left:10px; padding:0px;text-align:left;'><img src=images/ChartIconBG.gif border=0></a>";
 
}
function SurfaceChart(){
  RemoveMinPanel('ChartPopupContainer');
  SurfacePanel('ChartPopupContainer');
  MaxPromote('ChartPopupContainer');
}
function AddToChartPopup(MyField,TheLabel){
  if (MaxQuarter < SwitchOnChartQuarter){
    alert('There is not enough quarterly data to chart yet.  This chart will be available in Quarter '+SwitchOnChartQuarter+'.');
    return false;
  }
  RecordObjectAction('ChartPopupContainer','Open',MyField)
  div = document.getElementById('ChartPopupContainer');
  CleanChartPopup()
  div.style.visibility="visible";
  SetOpacity(div, 100);

  setTimeout('SurfaceChart()',200);
  if (!CheckEnoughQuarter('ChartPopup')) return false;
  var MaxRegion = (CheckFieldEnable('Region3'))? 2 : 3;
  
  for (var Area=1;Area<=MaxRegion;Area++){       
     var FieldArea=MyField+'A'+Area;
     if (TheField[FieldArea]){
     var YAXIS = (Area==3 && TheField[FieldArea].Format.indexOf('Currency')>-1)? "right" : "left";
     PopupChart.addSeries(new EJSC.LineSeries(
           new EJSC.CSVStringDataHandler(BuildDataStringByQuarter(FieldArea)),
           { 
            y_axis: YAXIS,
           title: TheLabel + ' R'+Area           }

         ));
     }
  }
     if (TheField[MyField]){
     PopupChart.addSeries(new EJSC.LineSeries(
           new EJSC.CSVStringDataHandler(BuildDataStringByQuarter(MyField)),
           { title: TheLabel            }
         ));
     }
  SetLegendOff(div,PopupChart)
  setTimeout('ClearLegend()',4000);
    
}

function BuildPopupChart(){
  if (!CheckEnoughQuarter('ChartPopup')) return false;

PopupChart = new EJSC.Chart('ChartPopup', {
       	      title: 'Micromatic Quick Chart' ,
       	                allow_mouse_wheel_zoom: false,

              axis_bottom: { caption: "Quarter" , 
              formatter: new EJSC.NumberFormatter({ forced_decimals: 0 }),
              crosshair: { show: true } 
          } ,
          axis_left: { caption: "" , grid:{show:true}, crosshair: { show: true } } ,
          axis_right: { caption: "" , grid:{show:true}, crosshair: { show: true } } ,
          show_legend: true,          
          auto_zoom: 'y' ,
          auto_find_point_by_x: true,
          onShowHint: doShowHintQuarter
         });

}

function CleanChartPopup(){
     if (PopupChart) PopupChart.remove();
     BuildPopupChart();
 }
 
function TurnOnChartPopup(){
currentpanel="ChartPopupContainer";
TurnOnOver();
}

function HideChartPopup(){
  document.getElementById('ChartPopupContainer').style.visibility="hidden";
}

function HidePromotePopup(idNumber){
  document.getElementById('PromoteContainer'+idNumber).style.visibility="hidden";
}
function RaisePopup(idNumber){
  SurfacePanel('PromoteContainer'+idNumber);
}
function DisplayPromotePopup(idNumber,NoMove){
  div = document.getElementById('PromoteContainer'+idNumber);
  div.style.visibility='visible';
  SetOpacity(div, 100)
  if (NoMove != true){
  xpos=(20*idNumber);
  ypos=80+(30*idNumber);
  div.style.left=xpos+'px';
  div.style.top=ypos+'px';    
  }
  DrawPromoteCharts(idNumber);
  setTimeout('RaisePopup('+idNumber+')',200);
  }

function TurnOnPromotePopup(idNumber){
currentpanel="PromoteContainer"+idNumber;
SurfacePanel(currentpanel);
TurnOnOver();
}

function BuildPromoteChartObj(TheDiv,TheTitle,DrillPanel){
   var TheChart = new EJSC.Chart(TheDiv, {
       	      title: TheTitle ,

              axis_bottom: { caption: "Quarter" , 
              formatter: new EJSC.NumberFormatter({ forced_decimals: 0 }),
              crosshair: { show: true } 
          } ,          
         axis_right: {  visible: false,   grid:{show:false}    },  	            
	 axis_left: {  visible: false,    grid:{show:false}    },	
         show_legend: false,          
         auto_zoom: 'y' ,
         auto_find_point_by_x: true,
         
         onShowHint: function(point, series, chart, hint, hover_select) {
	                 if (hover_select != "hover" && DrillPanel !=''){
	                    document.getElementById('PromoteContainer0').style.zIndex=299;
	                    document.getElementById('PromoteContainer1').style.zIndex=299;
	                    document.getElementById('PromoteContainer2').style.zIndex=299;
	                    document.getElementById('PromoteContainer3').style.zIndex=299;

	                    drillpanel(DrillPanel);
	                 }
   	                 return '[series_title]<br />Quarter [x]: [y]<br>Click on graph to get more info.';
	             }

         
        });
    return TheChart;
}
function DrawPromoteCharts(idNumber){
  var div1 = 'Promote'+idNumber+'1'
  var div2 = 'Promote'+idNumber+'2'
  var div3 = 'Promote'+idNumber+'3'
  var div4 = 'Promote'+idNumber+'4'
  if (!CheckEnoughQuarter(div1)) return false;

  var MaxRegion = (CheckFieldEnable('Region3'))? 2 : 3;

  if (idNumber==0){


      Chart1 = BuildPromoteChartObj(div1,'Headcount By Region','panelPlant');
      Chart2 = BuildPromoteChartObj(div2,'Expense Factors','panelIncome');
      Chart3 = BuildPromoteChartObj(div3,'Sales vs Net Income','panelIncome');
      Chart4 = BuildPromoteChartObj(div4,'Return on Sales & Assets','panelRatio');
      for (Area=1;Area<=MaxRegion;Area++){
           TheString=''
           TheCOGS='';
           TheSA ='';
           TheWarehouse = '';
           TheInterest = '';
           for (var i=0;i<=MaxQuarter-1;i++){       
	     if (TheString !='') TheString+=","
	     if (TheCOGS !='') TheCOGS+=","
	     if (TheSA !='') TheSA+=","
	     if (TheWarehouse !='') TheWarehouse+=","
	     if (TheInterest !='') TheInterest+=","
             TheValue = EJGetValue('SARAvailA'+Area,i)+ EJGetValue('WFAvailA'+Area,i) 
             TheString+=i.toString() + "|" + TheValue.toString();

             var Num  =EJGetValue('CGTotCOGSUnit',i) 
             TheValue = format2(EJGetValue('ISCOGSCurrent',i)/Num);
             TheCOGS+=i.toString() + "|" + TheValue.toString();

             TheValue = format2(EJGetValue('ISSAExpenseCurrent',i)/Num);
             TheSA+=i.toString() + "|" + TheValue.toString();

             TheValue = format2(EJGetValue('ISWarehouseCurrent',i)/Num);
             TheWarehouse+=i.toString() + "|" + TheValue.toString();

             TheValue = format2(EJGetValue('ISNetIntCurrent',i)/Num);
             TheInterest+=i.toString() + "|" + TheValue.toString();

           }


       Chart1.addSeries(new EJSC.LineSeries(new EJSC.CSVStringDataHandler(TheString),
	  	            { title: "Region "+Area
	  	            }));

      }
      
       Chart2.addSeries(new EJSC.LineSeries(new EJSC.CSVStringDataHandler(TheCOGS),
	  	            { title: "COGS/Unit"
	  	            }));
       Chart2.addSeries(new EJSC.LineSeries(new EJSC.CSVStringDataHandler(TheSA),
	  	            { title: "S & A/Unit"
	  	            }));
       Chart2.addSeries(new EJSC.LineSeries(new EJSC.CSVStringDataHandler(TheWarehouse),
	  	            { title: "Warehouse/Unit"
	  	            }));
       Chart2.addSeries(new EJSC.LineSeries(new EJSC.CSVStringDataHandler(TheInterest),
	  	            { title: "Net Interest/Unit"
	  	            }));
	  	            
	  	            
	  	            
       Chart3.addSeries(new EJSC.LineSeries(new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('ISNetSalesCurrent')),
	  	            { title: "Sales",
	  	            y_axis_formatter: new EJSC.NumberFormatter( { thousand_separator:',', forced_decimals: 0 } )
	  	            }));
       Chart3.addSeries(new EJSC.LineSeries(new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('ISNIncomeCurrent')),
	  	            { title: "Net Income",
	  	            y_axis_formatter: new EJSC.NumberFormatter( { thousand_separator:',', forced_decimals: 0 } )
	  	            }));

       Chart4.addSeries(new EJSC.LineSeries(new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('RatRetSale')),
	  	            { title: "Return on Sales"
	  	            }));
       Chart4.addSeries(new EJSC.LineSeries(new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('RatRetTotAsset')),
	  	            { title: "Return on Assets "
	  	            }));


  
  }  else if (idNumber==1){
      Chart1 = BuildPromoteChartObj(div1,'Revenue By Region','panelMRKT');
      Chart2 = BuildPromoteChartObj(div2,'Forecast vs Act Sales','panelMRKT');
      Chart3 = BuildPromoteChartObj(div3,'Sales Staff By Region','panelSAReport');
      Chart4 = BuildPromoteChartObj(div4,'Features vs Spending','panelSAReport');

         for (Area=1;Area<=MaxRegion;Area++){
           TheString=''
           for (var i=0;i<=MaxQuarter-1;i++){       
	     if (TheString !='') TheString+=","
             TheValue = EJGetValue('WHOSoldA'+Area,i)* EJGetValue('MDPriceA'+Area,i) 
             TheString+=i.toString() + "|" + TheValue.toString();
           }
         YAXIS=(Area<3)? 'left':'right';
       Chart1.addSeries(new EJSC.LineSeries(new EJSC.CSVStringDataHandler(TheString),
	  	            { title: "Region "+Area, 
	  	              y_axis_formatter: new EJSC.NumberFormatter( { thousand_separator:',', forced_decimals: 0 } ),
	  	              y_axis:YAXIS
	  	            }  ));
       if (Area==1) Chart2.addSeries(new EJSC.LineSeries(new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('MDForecastA'+Area)),
	  	            { title: "Forecast R"+Area,
	  	              y_axis_formatter: new EJSC.NumberFormatter( { thousand_separator:',', forced_decimals: 0 } )

	  	            }));
       if (Area==1) Chart2.addSeries(new EJSC.LineSeries(new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('MDActSalesA'+Area)),
	  	            { title: "Act Sales R"+Area,
	  	            y_axis_formatter: new EJSC.NumberFormatter( { thousand_separator:',', forced_decimals: 0 } )
	  	            } ));
       Chart3.addSeries(new EJSC.BarSeries(new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('SARAvailA'+Area)),
	  	            { title: "Region "+Area,
	  	            y_axis_formatter: new EJSC.NumberFormatter( { thousand_separator:',', forced_decimals: 0 } )
	  	            }));
         }



      Chart4.addSeries(new EJSC.LineSeries(new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('SARPICount')),
	  	            { title: "Features"}   ));
      Chart4.addSeries(new EJSC.LineSeries(new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('SARPI')),
	  	            { title: "Features Spending", 
	  	            	  	            y_axis_formatter: new EJSC.NumberFormatter( { thousand_separator:',', forced_decimals: 0 } ),
	  	              y_axis: 'right' }   ));
  
  }  else if (idNumber==2){


      Chart1 = BuildPromoteChartObj(div1,'Workforce By Region','panelPlant');
      Chart2 = BuildPromoteChartObj(div2,'Productivity By Region','panelPlant');
      Chart3 = BuildPromoteChartObj(div3,'Plant Capacity','panelPlant');
      Chart4 = BuildPromoteChartObj(div4,'Transport & Inven Cost','panelWHOp');

      for (Area=1;Area<=MaxRegion;Area++){
       Chart1.addSeries(new EJSC.LineSeries(new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('WFAvailA'+Area)),
	  	            { title: "Region "+Area,
	  	              y_axis_formatter: new EJSC.NumberFormatter( { thousand_separator:',', forced_decimals: 0 } )

	  	            }));
       Chart2.addSeries(new EJSC.LineSeries(new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('WFProductivityA'+Area)),
	  	            { title: "Region "+Area,
	  	              y_axis_formatter: new EJSC.NumberFormatter( { thousand_separator:',', forced_decimals: 0 } )

	  	            }));
       Chart3.addSeries(new EJSC.LineSeries(new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('PltTotCapA'+Area)),
	  	            { title: "Region "+Area,
	  	            y_axis_formatter: new EJSC.NumberFormatter( { thousand_separator:',', forced_decimals: 0 } )
	  	            }));
      }



      Chart4.addSeries(new EJSC.LineSeries(new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('WHOTransTotal')),
	  	            { title: "Transportation Cost",
	  	            	  	            y_axis_formatter: new EJSC.NumberFormatter( { thousand_separator:',', forced_decimals: 0 } )
	  	            }   ));
      Chart4.addSeries(new EJSC.LineSeries(new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('WHOInvCarryCost')),
	  	            { title: "Inventory Cost", 
	  	            	  	            y_axis_formatter: new EJSC.NumberFormatter( { thousand_separator:',', forced_decimals: 0 } ),
	  	              y_axis: 'right' }   ));
  



  }  else if (idNumber==3){
  
  
  
      Chart1 = BuildPromoteChartObj(div1,'Gross Profit','panelIncome');
      Chart1.addSeries(new EJSC.LineSeries(new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('ISGProfitCurrent')),
	  	            { title: "Gross Profit",
	  	            	       y_axis_formatter: new EJSC.NumberFormatter( { thousand_separator:',', forced_decimals: 0 } )
                            }   ));

      Chart2 = BuildPromoteChartObj(div2,'Net Income After Tax','panelIncome');
      Chart2.addSeries(new EJSC.LineSeries(new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('ISNIncomeCurrent')),
	  	            { title: "Net Income",
	  	            y_axis_formatter: new EJSC.NumberFormatter( { thousand_separator:',', forced_decimals: 0 } )
	  	            }   ));

      Chart3 = BuildPromoteChartObj(div3,'Accum Ret Earning','panelBalSheet');
      Chart3.addSeries(new EJSC.LineSeries(new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('BSRetEarn')),
	  	            { title: "Accum Retain Earn",
	  	              y_axis_formatter: new EJSC.NumberFormatter( { thousand_separator:',', forced_decimals: 0 } )
}   ));

      Chart4 = BuildPromoteChartObj(div4,'Cash Reserve','panelBalSheet');
      Chart4.addSeries(new EJSC.LineSeries(new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('BSCash')),
	  	            { title: "Cash Reserve",
	  	            y_axis_formatter: new EJSC.NumberFormatter( { thousand_separator:',', forced_decimals: 0 } )
	  	            }   ));
	  	            
  }  
  
  
}


// -------------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------------
// Main Dashboard setup below.......
// -------------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------------





function SetupMain(){
  BuildPanel("panelMain");
  document.getElementById("panelMain").innerHTML += SetupMainNav() + SetupMainDashboard()  
  if (MaxQuarter<SwitchOnChartQuarter){
    showMap();
  } else {
    setTimeout("BuildDashCharts()",500);
    showpanel("panelMain",true);
    document.getElementById('panelMain').style.top='125px';
    
  }
  setTimeout("CheckExpireLease()",3000)
  setTimeout("CheckSubcontract()",5000)

}
function CheckExpireLease(){
  var PltExpireNext = EJGetValue('PltExpireNextA1',MaxQuarter)+EJGetValue('PltExpireNextA2',MaxQuarter)+EJGetValue('PltExpireNextA3',MaxQuarter);
  var LeasePurchase = EJGetValue('PltLeaseCapOrderA1',MaxQuarter)+EJGetValue('PltLeaseCapOrderA2',MaxQuarter)+EJGetValue('PltLeaseCapOrderA3',MaxQuarter);
  if (PltExpireNext>0 && LeasePurchase==0){
    var LeaseWarningDiv = document.getElementById('LeaseWarning');
    LeaseWarningDiv.innerHTML="<h3>Lease Expiring</h3>You have been notified by your leasing company that your lease for <b>"+
       PltExpireNext+"</b> units of plant capacity terminates at the end of this quarter. If you do not "+
       " initiate action to extend this lease, your production capacity will decrease by this amount "+
       " at the beginning of next quarter.<p><a href=javascript:void(null) onclick=ShowLeaseInfo()>Show Me More</a>&nbsp;&nbsp;&nbsp;&nbsp;<a href=javascript:void(null) onclick=HideLeaseWarning()>Ignore for now</a>"
    LeaseWarningDiv.style.display='block';
  }
}
function CheckSubcontract(){
  var ODFinGood = EJGetValue('ODFinGoodA1',MaxQuarter-1)+EJGetValue('ODFinGoodA2',MaxQuarter-1)+EJGetValue('ODFinGoodA3',MaxQuarter-1);
  var WHOSubcon = EJGetValue('WHOSubconA1',MaxQuarter-1)+EJGetValue('WHOSubconA2',MaxQuarter-1)+EJGetValue('WHOSubconA3',MaxQuarter-1);
  if (ODFinGood>0  && ODFinGood > WHOSubcon){
    var SubcontractWarningDiv = document.getElementById('SubcontractWarning');
    SubcontractWarningDiv.innerHTML="<h3>Incomplete Subcontracted Order</h3>You have been notified by your subcontracting company that they were unable to fill your entire order due to supply chain difficulties. Only a total <b>"+
       WHOSubcon+"</b> units have been provided by the end of last quarter.   "+
       "<p><a href=javascript:void(null) onclick=ShowSubcontractInfo()>Show Me More</a>&nbsp;&nbsp;&nbsp;&nbsp;<a href=javascript:void(null) onclick=HideSubcontractWarning()>Ignore for now</a>"
    SubcontractWarningDiv.style.display='block';
  }
}

function HideSubcontractWarning(){
    document.getElementById('SubcontractWarning').style.display='none';
}
function HideLeaseWarning(){
    document.getElementById('LeaseWarning').style.display='none';
}
function ShowLeaseInfo(){
  HideLeaseWarning();
  CheckItOut2('panelPlantDec','panelPlant');
}
function ShowSubcontractInfo(){
  HideSubcontractWarning();
  SwitchQuarter(MaxQuarter-1);
  CheckItOut2('panelOPERDec','panelWHOp');
  
}


function SetupMainNav(){

  var out='<div id=DashNavMenuContainer><strong><a href=javascript:void(null); onclick=DashToggle(0)>&nabla; Menu</a><ul id=DashNavMenu>\n';

  SOLO = '';
  if (GameTypeID==1) SOLO+="<li><br><a class=DashNavMenuMiscLink href='"+SoloProcessURL+"'><STRONG>Process Quarter</STRONG></a>" ;
  if (GameTypeID==1 && SoloGameMode==1) SOLO+= "<li><br><a class=DashNavMenuMiscLink href='"+SoloRestartURL+"'><STRONG>Restart Industry</STRONG></a>";

//  SOLO = (GameTypeID==1)? "<li><br><a class=DashNavMenuMiscLink href='"+SoloProcessURL+"'><STRONG style='color:#9a3600;'>Process Quarter</STRONG></a>" +
//                          "<li><a class=DashNavMenuMiscLink href='"+SoloRestartURL+"'><STRONG style='color:#9a3600;'>Restart Industry</STRONG></a>" : "";

  out += "<li onclick=ToogleNavMenu(this) class=DashNavMenuMarker><span class=DashNavMenuSection>Industry</span>\n";
  out +="<ul class=DashNavMenuDetail>"+
        "<li><a href='javascript:void(null)' class=DashNavMenuMiscLink  style='background-image:url(images/savedecisions.gif)' onclick='SaveDecisionsSetup();CancelBubble(event);'>Save Decisions</a>"+
        "<li><a href='javascript:void(null)' class=DashNavMenuMiscLink style='background-image:url(images/ReviewDecisions.gif)' onclick='ReviewDecisionsSetup();CancelBubble(event);'>Review Other Decisions</a>"+
        "<li><a href='javascript:void(null)' class=DashNavMenuMiscLink style='background-image:url(images/EditTeam.gif)' onclick='EditTeamInfo();CancelBubble(event);'>Edit Team Information</a>"+
        "<li><a href='javascript:void(null)' class=DashNavMenuMiscLink style='background-image:url(images/ViewBulletin.gif)' onclick=\"drillpanel('panelBulletin');CancelBubble(event);\">View Bulletin</a></li>"+
        "<li><a href='javascript:void(null)' class=DashNavMenuMiscLink style='background-image:url(images/ViewPerformance.gif)' onclick='OpenPerfReport();CancelBubble(event);'>Performance Report</a>"+
        "<li><a href='javascript:void(null)' class=DashNavMenuMiscLink style='background-image:url(images/ViewSummary.gif)' onclick='OpenSummaryReport();CancelBubble(event);'>Summary Report</a>"+
        "<li><a href='javascript:void(null)' class=DashNavMenuTipLink onclick=AreaTip('Play');>Tips</a>"+
        SOLO + 
        "<br></ul></li>";


  out += "<li onclick=ToogleNavMenu(this) class=DashNavMenuMarker><span class=DashNavMenuSection>Marketing</span>\n";
  out +="<ul class=DashNavMenuDetail>"+
        "<li><a href='javascript:void(null)' class=DashNavMenuDecisionLink onclick=\"drillpanel('panelMRKT');CancelBubble(event);\">Marketing Decisions</a></li>"+
        "<li><a href='javascript:void(null)' class=DashNavMenuDecisionLink onclick=\"drillpanel('panelCompInfoDec');CancelBubble(event);\">Research</a></li>"+
        "<li><a href='javascript:void(null)' class=DashNavMenuCostLink onclick=\"drillpanel('panelMRKTCost');CancelBubble(event);\">Costs</a></li>"+
        "<li><a href='javascript:void(null)' class=DashNavMenuReportLink onclick=\"drillpanel('panelSAReport');CancelBubble(event);\">S & A Report</a></li>"+
        "<li><a href='javascript:void(null)' onclick=ViewMarketReport() class=DashNavMenuReportLink >Research Report</a></li>"+
        "<li><a href='javascript:void(null)' class=DashNavMenuTipLink onclick=AreaTip('Mrkt');>Marketing Tips</a>"+
        "</ul></li>";


  out += "<li onclick=ToogleNavMenu(this) class=DashNavMenuMarker><span class=DashNavMenuSection>Operations</span>\n";
  out +="<ul class=DashNavMenuDetail>"+
        "<li><a href='javascript:void(null)' class=DashNavMenuDecisionLink onclick=\"drillpanel('panelOPERDec');CancelBubble(event);\">Operating Decisions</a></li>"+
        "<li><a href='javascript:void(null)' class=DashNavMenuDecisionLink onclick=\"drillpanel('panelPlantDec');CancelBubble(event);\">Plant Decisions</a></li>"+
        "<li><a href='javascript:void(null)' class=DashNavMenuCostLink onclick=\"drillpanel('panelPAC');CancelBubble(event);\">Operating Costs</a></li>"+
        "<li><a href='javascript:void(null)' class=DashNavMenuCostLink onclick=\"drillpanel('panelMIC');CancelBubble(event);\">Material & Inv Costs</a></li>"+
        "<li><a href='javascript:void(null)' class=DashNavMenuReportLink onclick=\"drillpanel('panelWHOp');CancelBubble(event);\">Warehouse Report</a></li>"+
        "<li><a href='javascript:void(null)' class=DashNavMenuReportLink onclick=\"drillpanel('panelPlant');CancelBubble(event);\">Workforce & Plant</a></li>"+
        "<li><a href='javascript:void(null)' class=DashNavMenuReportLink onclick=\"drillpanel('panelRM');CancelBubble(event);\">Raw Material Report</a></li>"+
        "<li><a href='javascript:void(null)' class=DashNavMenuReportLink onclick=\"drillpanel('panelCOGS');CancelBubble(event);\">COGS Report</a></li>"+
        "<li><a href='javascript:void(null)' class=DashNavMenuTipLink onclick=AreaTip('Oper');>Operations Tips</a>"+
        "</ul></li>";

  out += "<li onclick=ToogleNavMenu(this) class=DashNavMenuMarker><span class=DashNavMenuSection>Finance</span>\n";
  out +="<ul class=DashNavMenuDetail>"+
        "<li><a href='javascript:void(null)' class=DashNavMenuDecisionLink onclick=\"drillpanel('panelFINADec');CancelBubble(event);\">Financial</a></li>"+
        "<li><a href='javascript:void(null)' class=DashNavMenuReportLink onclick=\"drillpanel('panelBalSheet');CancelBubble(event);\">Balance Sheet</a></li>"+
        "<li><a href='javascript:void(null)' class=DashNavMenuReportLink onclick=\"drillpanel('panelCashFlow');CancelBubble(event);\">Cash Flow</a></li>"+
        "<li><a href='javascript:void(null)' class=DashNavMenuReportLink onclick=\"drillpanel('panelIncome');CancelBubble(event);\">Income Statement</a></li>"+
        "<li><a href='javascript:void(null)' class=DashNavMenuReportLink onclick=\"drillpanel('panelRatio');CancelBubble(event);\">Ratios</a></li>"+
        "<li><a href='javascript:void(null)' class=DashNavMenuTipLink onclick=AreaTip('Fina');>Finance Tips</a>"+

        "</ul></li>";

  out += "<li onclick=ToogleNavMenu(this) class=DashNavMenuMarker><span class=DashNavMenuSection>Panels</span>\n";
  out +="<ul class=DashNavMenuDetail>"+
        "<li><a href='javascript:void(null)' class=DashNavMenuMiscLink onclick=\"ViewDecisionPanels();CancelBubble(event);\">View All Decisions</a></li>"+
        "<li><a href='javascript:void(null)' class=DashNavMenuMiscLink onclick=\"PrintAllPanels();CancelBubble(event);\">Print Active Panels</a></li>"+
        "<li><a href='javascript:void(null)' class=DashNavMenuMiscLink onclick=\"CascadePanels();CancelBubble(event);\">Cascade Panels</a></li>"+
        "<li><a href='javascript:void(null)' class=DashNavMenuMiscLink onclick=\"HideAllPanels();CancelBubble(event);\">Close Panels</a></li>"+
        "</ul></li>";


  out += "<li onclick=ToogleNavMenu(this) class=DashNavMenuMarker><span class=DashNavMenuSection>Help</span>\n";
  out +="<ul class=DashNavMenuDetail>"+
        "<li><a class=DashNavMenuHelpLink href='javascript:void(null)' style='background-image:url(images/map.gif)' onclick=\"showMap('panelMain');CancelBubble(event);\">Micromatic Map</a></li>"+
        "<li><a class=DashNavMenuTipLink  href='javascript:void(null)' onclick=TipOfDay();>Helpful Tips</a>"+
        "<li><a class=DashNavMenuHelpLink href='javascript:void(null)' onclick='ViewHelpVideo(1);CancelBubble(event);'>Welcome to Micromatic</a>"+
        "<li><a class=DashNavMenuHelpLink href='javascript:void(null)' onclick='ViewHelpVideo(2);CancelBubble(event);'>Making First Decisions!</a>"+
        "<li><a class=DashNavMenuHelpLink href='javascript:void(null)' onclick='ViewHelpVideo(7);CancelBubble(event);'>Understand Your Status</a>"+
        "<li><a class=DashNavMenuHelpLink href='javascript:void(null)' onclick='ViewHelpVideo(0);CancelBubble(event);'>More...</a>"+
        "</ul></li>";





  out+='</ul></div>\n';
  
  return out;
}
var VideoMSG = new Array();
var VideoTitle = new Array();
var VideoTag = new Array();
var VideoURL = new Array();
VideoTitle[0]='Welcome to the Micromatic Video Tutorial Center'
VideoMSG[0]='Choose one of the video tutorials listed below to get started.';

VideoTitle[1]='Welcome to Micromatic'
VideoTag[1]='Welcome to Micromatic'

VideoMSG[1]='In Micromatic you are managing a small manufacturing business in an industry of other, similar-sized companies that are competing against each other.  In Micromatic you will learn: '+
  '<ul><li>the importance of a business and strategic plan to guide business decisions'+
  '<li>the relationship between marketing, operations and finance'+
  '<li>the operational issues of production, inventory, plant and labor force'+
  '</ul>'+
  'In this video you will get a high level overview of using the simulation, making your decisions and viewing your results. 18 minutes.'

VideoURL[1]='http://oaktreesim.com/studenttutorials/V4_Student_Welcome_skin.swf';

VideoTitle[2]='<strong>Making Quarter 1 Decisions -- A Must See</strong>'
VideoTag[2]='Making Q1 Decisions'
VideoMSG[2]='Watch this tutorial before making your first round of decisions. It is a must see; it will help you to get understand you simulated business. This tutorial shows you how to get started on making the first quarter decisions and what are the effects of those decisions.  Be sure your are using a fast internet connection (15MB).    20 minutes.';
VideoURL[2]='http://oaktreesim.com/studenttutorials/Making Quarter 1 Decisions_skin.swf';


VideoTitle[3]='Viewing Micromatic Reports -- Part 1 of 2'
VideoTag[3]='Viewing Reports Part 1'

VideoMSG[3]='The best way to know how your company is doing is by viewing the included reports within Micromatic.  These reports summarize all aspects of your business. Some of these reports are displayed within simulation panels themselves.  The longer, more complex reports will open directly to Microsoft Excel.  <br><br>Before making you current round of decisions be sure to read and understand these reports; they will help you to direct your company. <br><br>This is the first of a 2 part series on Micromatic reports.  In this tutorial we discuss internal reports to Micromatic. 8 minutes.'
VideoURL[3]='http://oaktreesim.com/studenttutorials/Viewing Reports Part 1_skin.swf';

VideoTitle[4]='Viewing Micromatic Reports -- Part 2 of 2'
VideoTag[4]='Viewing Reports Part 2'
VideoMSG[4]='The best way to know how your company is doing is by viewing the included reports within Micromatic.  These reports summarize all aspects of your business. Some of these reports are displayed within simulation panels themselves.  The longer, more complex reports will open directly to Microsoft Excel.  <br><br>Before making you current round of decisions be sure to read and understand these reports; they will help you to direct your company. <br><br>This is the second of a 2 part series on Micromatic reports. In this tutorial we discuss external, Excel-based reports to Micromatic. 7 minutes.'
VideoURL[4]='http://oaktreesim.com/studenttutorials/Viewing Reports Part 2_skin.swf';

VideoTitle[5]='Embedded Graphs within Micromatic'
VideoTag[5]='Embedded Graphs'

VideoMSG[5]='This tutorial discusses the 2 types of embedded graphs within Micromatic and gives you some great ideas on how to better utilize the graphs to better undertand how your business is doing. 3 minutes.'
VideoURL[5]='http://oaktreesim.com/studenttutorials/Embedded Graphs_skin.swf';

VideoTitle[6]='Micromatic Map'
VideoTag[6]='Micromatic Map'
VideoMSG[6]='This tutorial discusses how to use the Micromatic Map to find your way around the simulation and to understand how the various areas of business interact. 6 minutes.'
VideoURL[6]='http://oaktreesim.com/studenttutorials/Micromatic Map_skin.swf';
 
VideoTitle[7]='Understanding How You Are Doing'
VideoTag[7]='Understanding Status'
VideoMSG[7]='In this tutorial we discuss using the game performance and company summary reports as a means of understanding your current status in the simulation. You are shown what to look for within this reports. 11 minutes.'
VideoURL[7]='http://oaktreesim.com/studenttutorials/Understanding How You Are Doing In Micromatic_skin.swf';

VideoTitle[8]='Micromatic Dashboard'
VideoTag[8]='Dashboard'
VideoMSG[8]='This tutorial discusses how to use the Micromatic Dashboard. The dashboard provides a quick overview of your entire simulation and allows you to navigate very quickly. 4 minutes.'
VideoURL[8]='http://oaktreesim.com/studenttutorials/Micromatic Dashboard_skin.swf';

VideoTitle[10]='The Business Consultant'
VideoTag[10]='Business Consultant'
VideoMSG[10]='This tutorial discusses how to use the Business consultant to learn the simulation more quickly and to find and monitor problem areas within your business. 3 minutes.'
VideoURL[10]='http://oaktreesim.com/studenttutorials/MMV4_Consultant_skin.swf';

VideoTitle[9]='Saving Your Micromatic Decisions'
VideoTag[9]='Saving Decisions'
VideoMSG[9]='This tutorial discusses one of the most common areas of misunderstanding with Micromatic: Saving Your Decisions. Confusion over how to save your decisions and which decisions will be used is important to avoid in the simulation. 7 minutes.'
VideoURL[9]='http://oaktreesim.com/studenttutorials/Saving Micromatic Decisions_skin.swf';

VideoTitle[11]='New Features in Micromatic'
VideoTag[11]='New Features'
VideoMSG[11]='This tutorial discusses how to get the most out of Micromatic.  There are a lot of new features to make your experience of learning the simulation easier and using the simulation more intuitive. 9 minutes.'
VideoURL[11]='http://oaktreesim.com/studenttutorials/New Features in Micromatic_skin.swf';




function CheckHelpVideo(){
if (GameLogins == 1){
  ShowIntroVideoMessage(1);
} else if (GameLogins == 2){
  ShowIntroVideoMessage(2);
}
}
function ShowIntroVideoMessage(MessageID){
    return;

   if (MessageID>2) return;
  currentpanel="VideoPopupContainer";
  var IntroMSG;

  if (MessageID==1) IntroMSG='Congratulations, you have been hired as CEO of a small manufacturing company! There are several similar sized companies that you will be competing against. The business is established and you will be making decisions that will impact the success or failure of this company in the future. <p>  '+
  'You have the opportunity to put your knowledge to work in a simulated environment. Take the game seriously and you will grasp some key concepts, such as: '+
  '<ul><li>the importance of a business and strategic plan to guide business decisions'+
  '<li>the relationship between the three main financial statements'+
  '<li>the relationship between marketing, operations and finance'+
  '<li>the operational issues of production, inventory, plant and labor force'+
  '</ul>'+
  'As CEO, you will be making a number of decisions. These decisions will be impacted by the economy and your competitors. These impacts will be shown each time your instructor processes the decision round - which is reflected as a quarter in your business. The business will run in a very condensed manner and the instructor will determine how many quarters (or decision rounds) will be completed before the end of the game. <p> '+
  'As in real life, you will make some mistakes and not understand everything at first. Learn from the mistakes and move on quickly. You will soon be making educated decisions that make sense for the business and be rewarded for the effort. '+
  '<p>'+
  'To be successful in managing a business you will balance decisions in group dynamics, facts, common sense and intuition. Online help is available in many ways in the tool - use it and you will be successful in less time. '+
  '<p>'+
  'In this video you will get a high level overview of using the simulation, making your decisions and viewing your results.'
  if (MessageID==2) IntroMSG='Welcome back to Micromatic. '+VideoMSG[2];

  div = document.getElementById('VideoPopupContainer');
  div.style.visibility="visible";
  var TheMessage='<h3>'+VideoTitle[MessageID]+'</h3>'+IntroMSG+
  '<p>A great way to get started is to <a href=javascript:void(null) onclick=ViewHelpVideo('+MessageID+')><strong>watch this video</strong></a>!!'

  
  document.getElementById('VideoPopup').innerHTML=TheMessage;
}

function CloseVideoPanel(){
  hidepanel('VideoPopupContainer');
  document.getElementById('VideoPopup').innerHTML ='';
}


var GlobalEmbedVideoURL=''
function ViewHelpVideo(VideoID){
  if (VideoID>0) RecordObjectAction('VideoCenter','Open',VideoTag[VideoID])
  var VidList='<span class=VideoSelection><strong>Video Tutorials to Choose From:</strong><ul>';
  for (var p=1;p<VideoTitle.length;p++) {
    VidList += "<li><a href=javascript:void(null) onclick=ViewHelpVideo("+p+")>"+VideoTitle[p]+"</a></li>";
  }
  VidList+="</ul></span>";
  var VMSG = '<img border=0 src=images/NowPlaying.gif><span class=VideoMessage>'+VideoMSG[VideoID]+'</span>'
  currentpanel="VideoPopupContainer";
  div = document.getElementById('VideoPopupContainer');
  div.style.visibility="visible";

  if (VideoID==0) document.getElementById('VideoPopup').innerHTML = '<h3>'+VideoTitle[VideoID]+'</h3>'+
  '<table><tr><td valign=top width=600>In this Video Tutorial Center you will find demonstration videos on many different aspects of Micromatic.  Watching these videos is a great way to learn the simulation or to brush up on parts you may have forgotten.</td><td valign=top class=VideoMessageContainer>'+VMSG+VidList+'</td></tr></table>';
  
if (VideoID>0) document.getElementById('VideoPopup').innerHTML = '<h3>Tutorial: '+VideoTitle[VideoID]+'</h3>'+
  '<table><tr><td valign=top ><object   width=800 height=600 classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" ID="Captivate1">'+
  '<param name="movie" value="'+VideoURL[VideoID]+'"><param name=quality value=high><param name=loop value=0>'+
  '<embed src="'+VideoURL[VideoID]+'"  width=800 height=600  loop=0 quality=high pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" menu="false"></embed>'+
  '</object></td><td valign=top class=VideoMessageContainer>'+VMSG+VidList+'</td></tr></table>';
  
  GlobalEmbedVideoURL=VideoURL[VideoID];
  setTimeout('SurfacePanel("VideoPopupContainer")',200);
  if (VideoID>0) setTimeout('CheckVideoPlaying('+VideoID+')',5000);
  
}
function CheckVideoPlaying(VideoID){
  if (VideoID==0) return;
  if (document.getElementById('VideoPopupContainer').style.visibility=="visible"
      && GlobalEmbedVideoURL==VideoURL[VideoID]){
     setTimeout('CheckVideoPlaying('+VideoID+')',000);
  } else {
    RecordObjectAction('VideoCenter','Close',VideoTag[VideoID]);
    SendInActions();
    GlobalEmbedVideoURL=''
  }
}
function ToogleNavMenu(obj){
  sub = obj.getElementsByTagName('ul')[0];
  if (sub.style.display=='' || sub.style.display=='none'){
    sub.style.display='block';
    obj.style.backgroundImage='url(images/LeftMenuGradientSelected.gif)';
  } else {
    sub.style.display='none';
    obj.style.backgroundImage='url(images/LeftMenuGradient.gif)';
  }
  
}
function PromoteArea(Area,NoMove){
 DisplayPromotePopup(Area,NoMove);
 RemoveMinPanel('PromoteContainer'+Area)
}
function GetPerfValue(TheVar,Digits){
  var TheVal='';
  if (document.getElementById(TheVar)) TheVal = parseFloat(FormattingStrip(document.getElementById(TheVar).innerHTML));
  if (!TheField[TheVar]) return 0;
  var ElementType = TheField[TheVar].Format;
  if (!Digits && TheField[TheVar].Digits) Digits = TheField[TheVar].Digits;
  
  if (Digits==null || Digits=='') Digits = 0;
  if (TheVal=='' ||   TheVal==null || TheVal==undefined || TheVal=='undefined') TheVal=0;
  
  if (ElementType=='') TheVal=formatField(TheVar,TheVal,'','',Digits,false);
  if (ElementType=='Currency')TheVal = formatField(TheVar,TheVal,MainCurrency,'',Digits,false);
  if (ElementType=='Currency:Euro')TheVal = formatField(TheVar,TheVal,AltCurrency,'',Digits,false);

  return TheVal;
}
function UpdateCompanyPerformanceDetail(TheLabel,TheVar,ThePanel,Digits){
  return  "<td><a href=javascript:void(null); onclick=showpanel('"+ThePanel+"');>"+TheLabel+"</a></td><td align=right>"+GetPerfValue(TheVar,Digits)+"</td><td>&nbsp;</td>";

}
function UpdateCompanyPerformanceDetail3(TheLabel,TheVar,ThePanel){
  return  "<td><a href=javascript:void(null); onclick=showpanel('"+ThePanel+"');>"+TheLabel+"</a></td><td  align=right>"+GetPerfValue(TheVar+'A1')+"&nbsp;&bull;&nbsp;"+GetPerfValue(TheVar+'A2')+"&nbsp;&bull;&nbsp;"+GetPerfValue(TheVar+'A3')+"</td><td>&nbsp;</td>";

}
function UpdateCompanyPerformanceAtAGlance(){
  var TheOut='<table border=0 colspacing=5>';
  TheOut+=
          "<tr>"+
          UpdateCompanyPerformanceDetail3('Units Available','WHOAvail','panelWHOp')+
          UpdateCompanyPerformanceDetail3('Stock Outs','WHOLostSales','panelWHOp')+
          UpdateCompanyPerformanceDetail3('Actual Demand','MDActSales','panelMRKT')+
          "</tr>"+
          "<tr>"+
          UpdateCompanyPerformanceDetail3('Production Potential','WFProd','panelPlant')+
          UpdateCompanyPerformanceDetail3('Plant Capacity','WFProd','panelPlant')+
          UpdateCompanyPerformanceDetail3('Raw Mat Inv','RMFinInvUnit','panelRM')+    
          "</tr>"+
          "<tr>"+
          UpdateCompanyPerformanceDetail('Total S&A Expense','SARTotExp','panelSAReport')+
          UpdateCompanyPerformanceDetail('Warehouse Costs','WHOTotalWHCost','panelWHOp')+
          UpdateCompanyPerformanceDetail('COGS per Unit','CGTotManCostPerUnit','panelCOGS',2)+
          "</tr>"+
          "<tr>"+
          UpdateCompanyPerformanceDetail('Net Income','ISNIncomeCurrent','panelIncome')+
          UpdateCompanyPerformanceDetail('Cash Balance','CFEndCash','panelCashFlow')+
          UpdateCompanyPerformanceDetail('Return on Sales','RatRetSale','panelRatio',2)+
          "</tr>";
          
  TheOut+="</table>";
  document.getElementById('CompanyPerformanceStats').innerHTML=TheOut;
  setTimeout('UpdateCompanyPerformanceAtAGlance()',2000);
}
function BuildDashLinks(){
  return "<div id=DashLinks>"+
         "<a href=javascript:void(null); id=DashLink0 style='display:none;' onclick=DashToggle(0)>&lt;Menu&gt;</a>"+
         "<a href=javascript:void(null); id=DashLink1 style='display:none;' onclick=DashToggle(1)>&lt;Overall&gt;</a>"+
         "<a href=javascript:void(null); id=DashLink2 style='display:none;' onclick=DashToggle(2)>&lt;Tools&gt;</a>"+
         "<a href=javascript:void(null); id=DashLink3 style='display:none;' onclick=DashToggle(3)>&lt;Company Glance&gt;</a>"+
         "<a href=javascript:void(null); id=DashLink4 style='display:none;' onclick=DashToggle(4)>&lt;Areas&gt;</a></div>";
        }
 function DashToggle(id){
    TheLink = 'DashLink'+id;
    TheDiv = '';
    if (id==0)TheDiv='DashNavMenuContainer';
    if (id==1)TheDiv='DashFirstRow';
    if (id==2)TheDiv='DashContainerTools'; 
    if (id==3)TheDiv='DashGlance';
    if (id==4)TheDiv='DashAreas';
   if(!document.getElementById(TheLink).style ||
        !document.getElementById(TheLink).style.display || 
         document.getElementById(TheLink).style.display=='block'){
         document.getElementById(TheLink).style.display = 'none'; 
         document.getElementById(TheDiv).style.display = '';    
   } else {
       document.getElementById(TheLink).style.display = ''; 
       document.getElementById(TheDiv).style.display = 'none'; 
   }

 }
 var Tips = new Array();
 function BuildTipsArray(TipTitle,TipText,TipIndex,TipCategory){
   var pos=Tips.length;
   Tips[pos] = new Object();
   Tips[pos].Text=TipText;
   Tips[pos].Title=TipTitle;
   Tips[pos].Index=TipIndex;
   Tips[pos].Category=TipCategory;   
 }
 
 // Play Tips Here....
 BuildTipsArray("Display More of Micromatic At A Time",
                "<ul><li>Switch your browser window to <b>Full Screen</b> mode by pressing F11."+
                "<li>Change the zoom setting on your browser by pressing <b>Control -</b> (zoom out)  and <b>Control +</b> (zoom in)."+
                "<li>In most panels you can press the <b>&nabla;</b> located at the section heading to minimize the section."+
                "</ul>","Display More On the Screen","Play");
 BuildTipsArray("Watch The tutorials","To help you get started there are many video tutorials available in the video tutorial center.  The <b>Welcome to Micromatic</b> is a great place to start. You will need a fast internet connection and a browser that supports shockwave (swf) video files. ","Watch The Tutorials","Play");
 BuildTipsArray("Drill Down for More Information","On most charts in Micromatic you can click on the detail portion of the chart to get more information.","Drill Down on Charts","Play");
 BuildTipsArray("Look for YELLOW and RED warning lights on your charts","Areas of concern are indicated on the charts with either a yellow marker (moderate) or a red marker and background (extreme). Don't ignore these markers. They are indicating that something is going wrong with your business.  Click on the chart to get more information.","Chart Warning Indicators","Play"); 
 BuildTipsArray("Timing is crucial","Each of the decisions you make have a timeframe associated with them.  Many of your decisions do not take effect immediately. Click on the label next to each decision variable and read the <b>Quick Tip</b>.  It will tell you what the timing for the decision is.","Timing of Decisions","Play");
 BuildTipsArray("After processing a quarter, review how your company performed.","When you first return to your company after a quarter has been processed you should first review the <b>Performance Summary Report</b>. Check to see if you sold as much as you thought. How are you doing compared to the rest of the industry?","Using the Performance Summary Report","Play");
 
 //General Business
 BuildTipsArray("Good Management is a BALANCING ACT!","Do not sell a product you can not produce or produce many products you can not sell.  Balance your marketing, operations and finance so that you are able to sell as many products as you can produce at as high of a price point as possible.  Early stage businesses live and die on cashflow.  Know your cash position at all times.  Watch your COGS carefully; produce your products where you are most efficient.","Balancing All Areas","General");         
 
 //Marketing Tips Here....
 BuildTipsArray("Remember to consider whether your sales forecast is realistic.","Just because you enter the number you want to sell, doesn’t mean that is how many you will sell. What has been your historical accuracy on forecasted vs. actual sales?","Actual vs Forecasted Sales","Mrkt");
 BuildTipsArray("Do Your Market Research!","You can not effectively manage your company if you have no idea what your competition is doing.  You should not execute your strategy in a vacuum.  Early and periodically in the simulation you should buy market information to help you to make your decisions. Before setting your strategy you need to project what the market demand will be.","Do Market Research","Mrkt");
 BuildTipsArray("Don't sell like Walmart unless you can produce like Walmart.","A lowest price strategy is fine as long as you can produce very high volumes of goods very efficiently.  You must keep your COGS extremely low to be successful with this strategy.","Selling at the Lowest Price","Mrkt");
 
 //Operations Tips Here....
 BuildTipsArray("Before you finalize your decisions, make sure that you check your per unit COGS.","Compare COGS to your selling price. Is there a sufficient margin (price - COGS) to cover your S&A expenditures?  With this margin, how many units would you have to sell to cover your fixed costs?","Check COGS Before Saving","Oper");
 BuildTipsArray("Be careful when leasing. It is a long term commitment","Before agreeing to a lease be sure you have the money to pay for the lease and the demand for your product.  Leases are long term commitments you must pay whether your are selling your product or not. You can not terminate a lease early.","Careful With Leases","Oper");
 BuildTipsArray("Don’t forget about controlling your manufacturing costs. It does no good to sell a lot and lose money.","Efficient management of your labor force is critical to your success. Efficient utilization of labor, materials, and production facilities is your goal.","Efficient Production","Oper");
 BuildTipsArray("Large amounts of inventory costs you a lot of money.  Run a lean operation.","Watch that your inventory of either raw materials or finished goods are not building up too large.  Large inventories choke a manufacturing operation and consume much of your available cash.","Controlling Inventory","Oper");
 BuildTipsArray("Are your workers being productive as they should be?","Human capital is the most expense part of your operation.  You need to invest in training your workers and in maintaining your plants in order for your workers to produce your product efficiency. Watch your worker productivity closely and act quickly if you see it dropping.","Getting The Most From Your Workers","Oper");
 BuildTipsArray("Is it time to invest in new technology?","Be watchful as new <b>Technological Improvements</b> (machines, computers, material handling, etc) come along.  Sometimes they will make sense to your operation; sometimes not.  Before purchasing a tech improvement calculate your expected Return On Investment.  Will the improvement give you a significant advantage in the market?","Deciding on Tech Improvements","Oper");
 
 //Finance Tips Here....
 BuildTipsArray("Remember to monitor your cash flow needs.","Your banker will double your interest charges if you do not have sufficient cash to pay your bills. Are your interest expenses consuming your operating profit? Too much debt?","Watch Cashflows","Fina");
 BuildTipsArray("Watch your financials. They are the reason why you are in business.","Every decision you make will somehow affect your financial position.  Watch your cashflow and income statements carefully.  They are not the same thing.  Before proceeding in the simulation research what the purpose of a Cashflow vs. Income statement is.","Cashflow vs Income","Fina");
 BuildTipsArray("All expenses are not created equal.  Variable expenses are much easier to manage than fixed ones.","Fixed expenses are those that do not fluctuate with changes in production activity level or sales volume; Variable expenses are those that respond directly and proportionately to changes in your production/sales volumes.  Coordinating variable expenses with your revenue is much easier than with your fixed expenses.","Fixed vs. Variable Expenses","Fina");
 
 
 
 function TipOfDayDetail(TipPos){
     div = document.getElementById('ExplainPopup');
     div.style.left    = 300;
     div.style.top     = 300;
     newImage = "url(images/ExplainHelpfulTip.gif)";
     div.style.backgroundImage = newImage;
     if (!TipPos || TipPos==undefined || TipPos<0 || TipPos>=Tips.length) TipPos=0;
     setCookie("TipPosition",TipPos);
     var Pos=1.0*TipPos+1;
     var AreaTipLabel='Helpful Tip';
     var TheTip="<i>"+Tips[TipPos].Title+"</i><p>"+Tips[TipPos].Text;
     Pos=Pos+" of "+Tips.length;    
     div.innerHTML="<table width=100%><tr><td align=left>"+
     "<b>"+AreaTipLabel+" "+Pos+"</b> <a href=javascript:void(null) onclick=PrevTipOfDay()>&lt;&lt;</a> | <a href=javascript:void(null) onclick=TipOfDay()>&gt;&gt;</a></td><td align=right valign=center><a href=javascript:void(null) onclick=HideExplain()><img src=images/closepopup.gif border=0 style='margin-right:25px;'></a></td></tr></table>"+
     TipSelectBox(TipPos)+
     "<div id=scroll_box>"+TheTip+"</div>";
     div.style.visibility='visible';
   }
   function TipSelectPortion(TheLabel,Category,TipPos){
     var TheOut='';
     TheOut+="<option value=-1>+++++ "+TheLabel+" +++++";
     for (var i=0;i<Tips.length;i++){
       var sel=''; 
       if (i==TipPos)sel="selected";
       if (Tips[i].Category==Category) TheOut+="<option value="+i+" "+sel+">"+Tips[i].Index;
     }
     TheOut+="<option value=-1> ";
     
   return TheOut;
   }
function TipSelectBox(TipPos){
  var TheOut="<p>Tips: <select id=TipSelector onchange=ShowTipFromSelector()>";
  TheOut+=TipSelectPortion('How to Play Tips','Play',TipPos);
  TheOut+=TipSelectPortion('Management Tips','General',TipPos);
  TheOut+=TipSelectPortion('Marketing Tips','Mrkt',TipPos);
  TheOut+=TipSelectPortion('Operations Tips','Oper',TipPos);
  TheOut+=TipSelectPortion('Finance Tips','Fina',TipPos);
  TheOut+="</select><p>";
  return TheOut;
   }
 function PrevTipOfDay(){
   var TipPos=getCookie("TipPosition");
   if (!TipPos) TipPos=0;
   TipPos = 1.0*TipPos - 1;
   if (TipPos<0) TipPos=Tips.length-1;
   TipOfDayDetail(TipPos);

 }
function ShowTipFromSelector(){
   var TheID=document.getElementById('TipSelector')[document.getElementById('TipSelector').selectedIndex].value;
   if (TheID==-1) return;
   TipOfDayDetail(TheID);  
}
function GetTipPos(){
   var TipPos=getCookie("TipPosition");
   if (!TipPos) TipPos=-1;
   TipPos = 1.0*TipPos + 1;
   if (TipPos>=Tips.length) TipPos=0;
   return TipPos;
}

function TipOfDay(){
   TipOfDayDetail(GetTipPos());
 }
function AreaTip(TheArea){
   var TipPos=GetTipPos();
   if (Tips[TipPos].Category != TheArea){
        for (var i=0;i<Tips.length;i++){
          if (Tips[i].Category==TheArea){
             TipPos=i;
             i=Tips.length;
          }
       }
   }

   TipOfDayDetail(TipPos);
 }
         
function SetupMainDashboard(){
  var out = BuildDashLinks()+
  "<div id=DashFirstRow>"+
           "<div id=DashContainer class=UtilColors><table width=350><td><strong><a href=javascript:void(null) onclick=DashToggle(1)>&nabla; Overall</strong></a> <font size=-4>(Lower Rank Indicates Better Performance)</font></td>"+
                                   "<td align=right><a href=javascript:void(null); onclick=PromoteArea(0)><img src=images/Expand0.gif alt='See More Graphs' title='See More Graphs' border=0></a></td></tr></table>";
  out += "<div id=panelMainEJDiv1 class=MMEJDiv></div>"
  out +="</div>";
    

  SOLO = '';
  if (GameTypeID==1) SOLO+="<li><a href='"+SoloProcessURL+"'><STRONG>Process Quarter</STRONG></a>" ;
  if (GameTypeID==1 && SoloGameMode==1) SOLO+= "<li><a href='"+SoloRestartURL+"'><STRONG>Restart Industry</STRONG></a>";

  out += "<div id=DashContainerTools><ul>"+
        "<li>Decisions: <a href='javascript:void(null)' onclick='SaveDecisionsSetup();CancelBubble(event);'>Save</a> &bull; "+
        "<a href='javascript:void(null)' onclick='ReviewDecisionsSetup();CancelBubble(event);'>Review</a>"+
        "<li>View: <a href='javascript:void(null)' onclick=\"drillpanel('panelBulletin');CancelBubble(event);\">Bulletin</a> &bull; "+
        "<a href='javascript:void(null)' onclick='ViewMarketReport();CancelBubble(event);'>Research</a>"+
        "<li>RPTs: <a href='javascript:void(null)' onclick='OpenPerfReport();CancelBubble(event);'>Perform</a> &bull;"+
        "<a href='javascript:void(null)' onclick='OpenSummaryReport();CancelBubble(event);'> Summary</a>"+
        "<li>Show: <a href='javascript:void(null);' onclick=RestoreLayout();>Prev Config</a> &bull; <a href='javascript:void(null);' onclick=ShowAllPanels();>All</a> &bull; <a href='javascript:void(null);' onclick=ViewDecisionPanels();>Decs</a>"+
        "<li>Panel: <a href='javascript:void(null);' onclick=PrintAllPanels();>Print</a> &bull; <a href='javascript:void(null);' onclick=CascadePanels();>Cascade</a> &bull; "+
        "<a href='javascript:void(null);' onclick=HideAllPanels();>Close</a>"+
        "<li>Help: <a href='javascript:void(null)' onclick='ViewHelpVideo(0);CancelBubble(event);'>Video Tutorials</a> &bull; "+
        "<a href='javascript:void(null)' onclick=\"TipOfDay();CancelBubble(event);\">Tips</a>"+
        SOLO + 
         "</ul>"+
         "</div>";
out +=  "</div>";
         
  
  
  out += "<div id=DashAreas>";
  out += "<div class=DashAreaContainer><table width=180><td valign=bottom><h3 style='color:#9b3700'><a href=javascript:void(null) onclick=DashToggle(4)  style='font-size:8pt;'>&nabla;Marketing</a></h3></td><td align=right>" +
        BuildAreaLeftLinks(1) +
        "</td></tr><td colspan=2><h4 style='color:#9b3700'>Sales & Expense</h4></td></tr></table>" +
        "<div id=panelMainEJDiv2 class=DashChartAreaDiv style='color:#9b3700'></div>" +
        "</div>";


out += "<div class=DashAreaContainer><table width=180><td valign=bottom><h3 style='color:#008399; '><a href=javascript:void(null) onclick=DashToggle(4)  style='font-size:8pt;'>Operations</a></h3></td><td align=right>" +
        BuildAreaLeftLinks(2) +
        "</td></tr><td colspan=2><h4 style='color:#008399'>COGS & Net Inv</h4></td></tr></table>" +
        "<div id=panelMainEJDiv3 class=DashChartAreaDiv style='color:#008399'></div>" +
        "</div>";



out += "<div class=DashAreaContainer><table width=180><td valign=bottom><h3 style='color:#43601c'><a href=javascript:void(null) onclick=DashToggle(4) style='font-size:8pt;'>Finance</a></h3></td><td align=right>" +
        BuildAreaLeftLinks(3) +
        "</td></tr><td colspan=2><h4 style='color:#43601c'>Income & Stock Price</h4></td></tr></table>" +
        "<div id=panelMainEJDiv4 class=DashChartAreaDiv style='color:#43601c'></div>" +
        "</div>";
out +=  "</div>";
  out+="<div id=DashGlance style='clear:both;'><h3 class=UtilColors><a href=javascript:void(null) onclick=DashToggle(3)>&nabla;Company at a Glance</a></h3><div id=CompanyPerformanceStats>Loading...</div></div>";
  setTimeout('UpdateCompanyPerformanceAtAGlance()',6000);


  
  return out
  
}
function BuildAreaLeftLinks(Area){
  if (Area == 1 || Area == 2 ){
    out= 
     "<a href=javascript:void(null); onclick=LeftLink("+Area+",'Decision')><img title=Decisions alt=Decisions src=images/Decision"+Area+".gif border=0></a>"+
     "<a href=javascript:void(null); onclick=LeftLink("+Area+",'Cost')><img title=Costs alt=Costs src=images/Cost"+Area+".gif border=0></a>"+
     "<a href=javascript:void(null); onclick=LeftLink("+Area+",'Report')><img title=Reports alt=Reports src=images/Report"+Area+".gif border=0></a>"+
     "<a href=javascript:void(null); onclick=PromoteArea("+Area+")><img alt='See More Graphs' title='See More Graphs' src=images/Expand"+Area+".gif border=0></a>"
   } else {
    out=
     "<a href=javascript:void(null); onclick=LeftLink("+Area+",'Decision')><img alt=Decisions title=Decisions src=images/Decision"+Area+".gif border=0></a>"+
     "<a href=javascript:void(null); onclick=LeftLink("+Area+",'Report')><img alt=Costs title=Costs src=images/Report"+Area+".gif border=0></a>"+
     "<a href=javascript:void(null); onclick=PromoteArea("+Area+")><img title='See More Graphs' alt='See More Graphs' src=images/Expand"+Area+".gif border=0></a>";
   }
   return "<div class=DashLeftLinkContainer>"+out+"</div>";
          
    
}
function LeftLink(Area,PanelType){
  if (Area==1){
     if (PanelType=='Decision'){
        drillpanel('panelCompInfoDec');
        drillpanel('panelMRKT',50);
     }
     if (PanelType=='Cost') drillpanel('panelMRKTCost');
     if (PanelType=='Report') drillpanel('panelSAReport');
  } else if (Area==2){

     if (PanelType=='Decision'){
        drillpanel('panelPlantDec');
        drillpanel('panelOPERDec',50);
     }
     if (PanelType=='Cost'){
        drillpanel('panelPAC');
        drillpanel('panelMIC',50);
     }
     if (PanelType=='Report'){
       drillpanel('panelWHOp');
       drillpanel('panelPlant',50);
       drillpanel('panelRM',100);
       drillpanel('panelCOGS',150);
     }       
  } else {


     if (PanelType=='Decision'){
        drillpanel('panelFINADec');
     }
     if (PanelType=='Report'){
       drillpanel('panelRatio');
       drillpanel('panelCashFlow',50);
       drillpanel('panelIncome',100);
       drillpanel('panelBalSheet',150);
     }       
  }
}


function OldSetup(){
  Stuff += "<table cellspacing=0 cellpadding=0 class=alt>";
  Stuff += "<tr><td class=alt>";
  Stuff += SetupMainArea("MRKT",MSG["Marketing"]);

  Stuff += SetupMainArea("OPER",MSG["Operations"]);
  Stuff += SetupMainArea("FINA",MSG["Finance"]);
  Stuff += "</td></tr></table>";

  Stuff += "<td class=alt valign=top>";
  Stuff += "<h3 class=AreaHeading>"+MSG["Game"]+"</h3>"+
                   "<table cellpadding=0 cellspacing=0 width=100%>"+
                    "<tr class=UtilLink><td><a class=MainLink href='javascript:void(null);'  onmouseover=StartExplanationClock('panelSavedDecisions'); onmouseout=HE(); onclick=SaveDecisionsSetup();><nobr>"+MSG["Save Decisions"]+"</nobr></a>"+
                    "<tr class=UtilLink><td><a class=MainLink href='javascript:void(null);'  onmouseover=StartExplanationClock('panelReviewDecisions'); onmouseout=HE(); onclick=ReviewDecisionsSetup();><nobr>"+MSG["Review Decisions"]+"</nobr></a>"+
                    "<tr class=UtilLink><td><a class=MainLink href='javascript:void(null);'  onmouseover=StartExplanationClock('panelTeamInfo'); onmouseout=HE();  onclick=EditTeamInfo();><nobr>Edit Team Information</nobr></a>"+
                   "<tr class=UtilLink><td><a class=MainLink href='javascript:void(null);'   onmouseover=StartExplanationClock('panelBulletin'); onmouseout=HE();  onclick=showpanel('panelBulletin');><nobr>"+MSG["Quarter Bulletin"]+"</nobr></a>"+
                   "<tr class=UtilLink><td><a class=MainLink href='javascript:void(null);'   onmouseover=StartExplanationClock('PerformanceReport'); onmouseout=HE(); onclick=OpenPerfReport();><nobr>"+MSG["PerfReview"]+"</nobr></a>"+
                   "<tr class=UtilLink><td><a class=MainLink href='javascript:void(null);'   onmouseover=StartExplanationClock('SummaryReport'); onmouseout=HE(); onclick=OpenSummaryReport();><nobr>"+MSG["GameSummary"]+"</nobr></a>"
var AlertText='Business Consultant Report'
if (typeof ShowAlert !='undefined' && ShowAlert==1) AlertText="<SPAN class=AlertText>Business Consultant Report</SPAN>";

if (BusConsultant)   Stuff += "<tr class=UtilLink><td><a class=MainLink href='javascript:void(null);'  onmouseover=StartExplanationClock('BusinessConsultant'); onmouseout=HE();  onclick=OpenBusConsultReport();><nobr>"+AlertText+"</nobr></a>";
  Stuff += "<tr class=UtilLink><td><a class=MainLink href='javascript:void(null);'   onmouseover=StartExplanationClock('IndustryCentral'); onmouseout=HE();   onclick=setTimeout(\"GameSelector();\",500);>Industry Central</a>";
if (GameTypeID==1){
  Stuff += "<tr class=UtilLink><td class=DecisionLinkFont><a class=MainLink    onmouseover=StartExplanationClock('ProcessQuarter'); onmouseout=HE();  href='"+SoloProcessURL+"'><nobr>"+MSG["Process Quarter"]+"</nobr></a>"+
                   "<tr class=UtilLink><td class=DecisionLinkFont><a class=MainLink   onmouseover=StartExplanationClock('RestartGame'); onmouseout=HE();  href='"+SoloRestartURL+"' ><nobr>"+MSG["Restart Game"]+"</nobr></a>"
}
  Stuff += "</table>";
  Sep = "&nbsp;|&nbsp;";
  Stuff += "<h3 class=AreaHeading>Panels</h3>"
                  + "<table border=0 cellpadding=0 colspacing=10 >"+
                    "<tr><td><font style='font-size:12pt; margin-left:25px;'>View Panels:</font></td><td  align=left><a class=MainLink href='javascript:void(null);' onclick=ShowAllPanels();><nobr>All</nobr></a>"+
                    Sep + 
                    "<a class=MainLink href='javascript:void(null);' onclick=ViewDecisionPanels();>Decisions Only</nobr></a>"+
                    "<tr><td ><font style='font-size:12pt; margin-left:25px;'>Print Panels:</font></td><td align=left><a class=MainLink href='javascript:void(null);' onclick=PrintDecisionPanels();>Decisions</nobr></a>"+
                    Sep + 
                    "<a class=MainLink href='javascript:void(null);' onclick=setTimeout(\"PrintAllPanels();\",500);>Active</nobr></a>"+
                    "<tr ><td valign=top><font style='font-size:12pt;  margin-left:25px;'>Panels:</font></td><td align=left>"+
                    "<a class=MainLink href='javascript:void(null);' onclick=CascadePanels();><nobr>Cascade</nobr></a>"+
                    Sep + 
                    "<a class=MainLink href='javascript:void(null);' onclick=TileScreen();><nobr>Tile</nobr></a>"+
                    "<br>" + 
                    "<a class=MainLink href='javascript:void(null);' onclick=showpanel('panelSearchArea');><nobr>Search</nobr></a>"+
                    Sep + 
                    "<a class=MainLink href='javascript:void(null);' onclick=HideAllPanels();><nobr>Close</nobr></a></td></tr>"+
                    "</table>";

  Stuff += "<h3 class=AreaHeading>Finding Your Way Around</h3>"+
                  "<table cellpadding=0 cellspacing=0 width=100%>"+
                  "<tr class=UtilLink><td><a class=MainLink href='javascript:void(null);' onclick=showMap('panelMain')>Micromatic Map</a></td></tr>"+
                  "<tr class=UtilLink><td><a class=MainLink target=_blank_ href='http://moodle.mgmt.mnsu.edu/Making Decisions in Micromatic Solo.htm'><img src=images/VideoIcon.gif border=0> Making Micromatic Decisions</a></td></tr>"+
                  "<tr class=UtilLink><td><a class=MainLink target=_blank_ href='http://moodle.mgmt.mnsu.edu/Viewing Micromatic Reports -- Excel.htm'><img src=images/VideoIcon.gif border=0> Viewing Reports</a></td></tr>"+
                  "<tr class=UtilLink><td><a class=MainLink target=_blank_ href='http://moodle.mgmt.mnsu.edu/Understanding How Your Are Doing In Micromatic.htm'><img src=images/VideoIcon.gif border=0> Understanding Your Status</a></td></tr>"+
                  "<tr class=UtilLink><td><a class=MainLink href='javascript:void(null);' onclick=showMap('panelMain')>Micromatic Map</a></td></tr>"+
                  "<tr class=UtilLink><td><a class=MainLink target=_blank_ onclick='ViewHelpVideo(0);CancelBubble(event);' href='javascript:void(null);'>More...</a></td></tr>"+
                  "</table>";


//  Stuff += "</td></tr></table></td><td valign=top>";


  Stuff += "<table cellspacing=0 cellpadding=3 class=alt>";
}


function SetupMainArea(Area,AreaTitle){
  ReturnString = "<a href='javascript:void(null);' onclick=ShowAreaPanels('"+Area+"'); onmouseover=StartExplanationClock('"+Area+"'); onmouseout=HE();><h3 class=AreaHeading>" 
  ReturnString = ReturnString + AreaTitle + "</h3></a><table width=100% cellpadding=0 cellspacing=0>";
  for (var p=0;p<ThePanels.length;p++) {
      pan = document.getElementById(ThePanels[p]);
      if (pan.PanelArea==Area){
        fontclass='';
        typeclass = "ReportLink";
        typelabel = " (R)";
        if (pan.PanelType && pan.PanelType=="Decision"){
          typeclass = "DecisionLink";
          fontclass= "class=DecisionLinkFont"
          typelabel = " (D)";
        }
        if (pan.PanelType && pan.PanelType=="Cost"){
          typeclass = "CostLink";
          typelabel = " (C)";
        }

          ReturnString += "<tr class="+typeclass+"><td><nobr><a "+
                          "onmouseover=StartExplanationClock('"+ThePanels[p]+"'); onmouseout=HE(); "+
                          "class=MainLink href=\"javascript:void(null);\" onclick=\"showpanel('"+ThePanels[p]+"');\" >" +
                          "<font "+fontclass+">"+ pan.PanelTitle + typelabel+ "</font></a></nobr></td></tr>"
      }
  }
  if (ShowExcel!=1) ShowExcel = getCookie("ShowExcel");
  if (ShowExcel==1 && CompInfoURL.indexOf('ShowExcel')==-1) CompInfoURL = CompInfoURL+'&ShowExcel=1';
  
  if (Area=="MRKT")  ReturnString += "<tr class=ReportLink><td><a class=MainLink onmouseover=StartExplanationClock('MarketingReport'); onmouseout=HE(); target=new href='"+CompInfoURL+"' ><font>"+MSG["CompInfo"]+"(R)</font></a>"

  ReturnString += "</table>";
  return ReturnString;
}


function BuildDashCharts(){
    if (!CheckEnoughQuarter("panelMainEJDiv1")) return false;

   var chart = new EJSC.Chart("panelMainEJDiv1", {
      title: " " ,
                allow_mouse_wheel_zoom: false,

	            axis_bottom: { caption: "Quarter" , 
	                formatter: new EJSC.NumberFormatter({ forced_decimals: 0 }),
	                crosshair: { show: true } 
	            } ,
      axis_left: { caption: "Rank" , crosshair: { show: true },
      	                           grid:{show:false}
            } ,
      axis_right: { caption: "Points" , crosshair: { show: true },
      	                           grid:{show:false}

                  } ,

      show_legend: true, 
      legend_title:'Overall Performance',
      show_title: false,          
      auto_zoom: 'y' ,
      auto_find_point_by_x: true,
      onShowHint: function(point, series, chart, hint, hover_select) {
                        if (hover_select == "hover") {
                        } else {    
                          PromoteArea(0);
                        }

                    return '<nobr>[series_title]<br>Quarter [x] = [y]</nobr><br>Click on graph to get more info.';
                  }
     });
   
   
   
     
   chart.addSeries(new EJSC.BarSeries(
	  	            new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('CurrentRank',1)),
	  	            { title: "Current Rank", color:'rgb(197,184,169)'
	  	            }
	  	          ));
   chart.addSeries(new EJSC.LineSeries(
	  	            new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('CurrentIndexPoints',1)),
	  	            { title: "Current Index Pts", color:'rgb(197,184,169)',
	  	                         y_axis: "right"
	  	            }
	  	          ));
   chart.addSeries(new EJSC.BarSeries(
	  	            new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('GTDRank',1)),
	  	            { title: "GTD Rank", color:'rgb(103,89,73)'
	  	            }
	  	          ));
   chart.addSeries(new EJSC.LineSeries(
	  	            new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('GTDIndexPoints',1)),
	  	            { title: "GTD Index Pts",
	  	                         y_axis: "right", color:'rgb(103,89,73)'
	  	            }
	  	          ));          
              setTimeout('ClearLegend()',4000);
              SetLegendOff('panelMainEJDiv1',chart)

          
          
          

    ///////////////////////////////////////////////////////////////////////////      
    /// MARKETING Dashboard chart      
    var chart2 = new EJSC.Chart('panelMainEJDiv2', {
	            title: " " ,
	                      allow_mouse_wheel_zoom: false,

	            axis_bottom: { caption: "Quarter" , 
	                formatter: new EJSC.NumberFormatter({ forced_decimals: 0 }),
	                crosshair: { show: true } 
	            } ,
	            axis_right: {  visible: false,
	                           grid:{show:false}
	                        },
	            
	            axis_left: {  visible: false,
	                           grid:{show:false}
	                        },
	            
	            show_legend: false,          
	            show_title: false,          
	            auto_zoom: 'y' ,
	            auto_find_point_by_x: true,
                    onShowHint: function(point, series, chart, hint, hover_select) {
                        if (hover_select == "hover") {
                        } else {    
                          PromoteArea(1);
                        }

                    return '<nobr>[series_title]<br>Quarter [x] = [y]</nobr>';
                  }
	           });
	           
          chart2.addSeries(new EJSC.LineSeries(
	  	            new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('ISNetSalesCurrent')),
	  	            { title: "Net Sales", color:'rgb(163,75,28)',
	  	              y_axis_formatter: new EJSC.NumberFormatter( { thousand_separator:',', forced_decimals: 0 } )

	  	            }
	  	          ));
         chart2.addSeries(new EJSC.LineSeries(
           new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('SARTotExp')),
           { title: "Sales Expense",color:'rgb(234,151,109)',
           y_axis_formatter: new EJSC.NumberFormatter( { thousand_separator:',', forced_decimals: 0 } )

           }
         ));


          
    ///////////////////////////////////////////////////////////////////////////      
    /// OPERATIONS Dashboard chart      
    var chart3 = new EJSC.Chart('panelMainEJDiv3', {
	            title: " " , color:'rgb(166,179,143)',
	                      allow_mouse_wheel_zoom: false,

	            axis_bottom: { caption: "Quarter" , 
	                formatter: new EJSC.NumberFormatter({ forced_decimals: 0 }),
	                crosshair: { show: true } 
	            } ,
	            axis_right: {  visible: false,
	                           grid:{show:false}
	                        },
	            
	            axis_left: {  visible: false, caption: "" , grid:{show:false}, crosshair: { show: true } } ,
	            legend_title:'Cash',
	            show_legend: false,          
	            show_title: false,          
	            auto_zoom: 'y' ,
	            auto_find_point_by_x: true,
                    onShowHint: function(point, series, chart, hint, hover_select) {
                        if (hover_select == "hover") {
                        } else {    
                          PromoteArea(2);
                        }

                    return '<nobr>[series_title]<br>Quarter [x] = [y]</nobr>';
                  }
	           });
	           
          chart3.addSeries(new EJSC.LineSeries(
	  	            new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('CGTotCOGSPerUnit')),
	  	            { title: "COGS", color:'rgb(0,92,104)'
	  	            }
	  	          ));
	
         var TheString = ''
         for (var i=0;i<=MaxQuarter-1;i++){       
	    if (TheString !='') TheString+=","
	    TheValue = EJGetValue('WHOEndInvA1',i)+ EJGetValue('WHOEndInvA2',i) + EJGetValue('WHOEndInvA3',i) 
	               - EJGetValue('WHOLostSalesA1',i) - EJGetValue('WHOLostSalesA2',i)- EJGetValue('WHOLostSalesA3',i);
            TheString+=i.toString() + "|" + TheValue.toString();
         }



         chart3.addSeries(new EJSC.AreaSeries(
           new EJSC.CSVStringDataHandler(TheString),
           { title: "Net Inventory", color:'rgb(0,131,153)',
             y_axis_formatter: new EJSC.NumberFormatter( { thousand_separator:',', forced_decimals: 0 } ),
             y_axis: "right"
           }
         ));
	  	          

    ///////////////////////////////////////////////////////////////////////////      
    /// FINANCE Dashboard chart      
    var chart4 = new EJSC.Chart('panelMainEJDiv4', {
	            title: " " ,
	                      allow_mouse_wheel_zoom: false,

	            axis_bottom: { caption: "Quarter" , 
	                formatter: new EJSC.NumberFormatter({ forced_decimals: 0 }),
	                crosshair: { show: true } 
	            } ,
	            axis_right: {  visible: false,
	                           grid:{show:false}
	                        },
	            
	            axis_left: {  visible: false, caption: "" , grid:{show:false}, crosshair: { show: true } } ,
	            legend_title:'Cash',
	            show_legend: false,          
	            show_title: false,          
	            auto_zoom: 'y' ,
	            auto_find_point_by_x: true,
                    onShowHint: function(point, series, chart, hint, hover_select) {
                        if (hover_select == "hover") {
                        } else {    
                          PromoteArea(3);
                        }

                    return '<nobr>[series_title]<br>Quarter [x] = [y]</nobr>';
                  }
	           });
	           
          chart4.addSeries(new EJSC.BarSeries(
	  	            new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('ISNIncomeCurrent')),
	  	            { title: "Net Income",  color:'rgb(110,127,82)',
	  	              y_axis_formatter: new EJSC.NumberFormatter( { thousand_separator:',', forced_decimals: 0 } )
	  	            }
	  	          ));
         chart4.addSeries(new EJSC.AreaSeries(
           new EJSC.CSVStringDataHandler(BuildDataStringByQuarter('BSStockPrice')),
           { title: "Stock Price", color:'rgb(166,179,143)',
             y_axis: "right"
           }
         ));
	  	          

          
          
          
  }





////////////////////////////////////////////////////////////


function FadeOpacityPanel(elemId, fromOpacity, toOpacity, time, fps){
  if (IsIE()){
    // disable the fade in IE because setopacity on panels works but it too slow
    //document.getElementById(elemId).style.filter = "progid:DXImageTransform.Microsoft.Blinds(Duration=2)";
    //document.getElementById(elemId).filters[0].apply();
    hidepanel(elemId);
    //document.getElementById(elemId).filters[0].play();
    return;
  }
  var steps = Math.ceil(fps * (time / 1000));
  var timeper=time/steps; 
  var delta = (toOpacity - fromOpacity) / steps; 
  window.status='steps='+steps+' delta='+delta+' time per step='+timeper+' fromopacity='+fromOpacity
  FadeOpacityStep(elemId, 0, steps, fromOpacity, 
                  delta, timeper);
}

function FadeOpacityStep(elemId, stepNum, steps, fromOpacity, 
                         delta, timePerStep){
   SetOpacity(document.getElementById(elemId), 
             Math.round(parseInt(fromOpacity) + (delta * stepNum)));
   timePerStep=Math.round(timePerStep);
   if (stepNum < steps){
     setTimeout("FadeOpacityStep('" + elemId + "', " + (stepNum+1) 
              + ", " + steps + ", " + fromOpacity + ", "
              + delta + ", " + timePerStep + ");", 
                  timePerStep);
    } else {
    hidepanel(elemId);
    }

}


function SetOpacity(elem, opacityAsInt){
  var opacityAsDecimal = opacityAsInt;

    if (opacityAsInt > 100)
        opacityAsInt = opacityAsDecimal = 100; 
    else if (opacityAsInt < 0)
        opacityAsInt = opacityAsDecimal = 0; 

   opacityAsDecimal /= 100;
   if (opacityAsInt < 1)  opacityAsInt = 1; // IE7 bug, text smoothing cuts out if 0

    elem.style.opacity = (opacityAsDecimal);
    elem.style.filter  = "alpha(opacity=" + opacityAsInt + ")";
}

