<?php
include_once("system/settings.php"); //logging settings and other general settings

error_reporting(E_ALL ^ E_NOTICE);
session_start();
start_log();

$error_handler = set_error_handler("engineErrorHandler");

$raw_file = $_GET['raw_file'];

elog(0,"convert2web  raw_file={$raw_file} ");
/*
if (!isset($raw_file))
{
  if ($handle = opendir("raw_uploaded/"))
      {
           
            echo "These are the raw files..click to conver them<br>";

      
            while (false !== ($file = readdir($handle)))
            {
                echo "<a href=\"convert2web.php?raw_file=raw_uploaded/".$file."\" target=\"convert\">Convert {$file}</a> <br>";
            }
      }
    return;
}
*/

include ($raw_file);
include ('chart_templates/current_template.php');

elog(0,"convert2web  include completed stage1 ");
$path_parts = pathinfo($raw_file);

  $new_chart_type="";
  defineChartTypes();
//print_r($new_chart_type);

/*
 * $path_parts = pathinfo('/www/htdocs/index.html');
 * echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n"; // since PHP 5.2.0
 *
 * /www/htdocs
index.html
html
index
 */

//store the new dashboard files in the dash directory.. this could be setup in a cofiguration file and the variables read from there
$dash_file="dash/".str_replace(".php", "", $path_parts['filename'])."_dash.php";
$db_file="dbconfig/".str_replace(".php", "", $path_parts['filename'])."_db.php";


$dash_file_handle = fopen($dash_file, "w");
$db_file_handle = fopen($db_file,"w");


$plet_list =""; //comma separated list of all parameters
$qlet_list =""; //comma separated list of all qlets and glets

$dr_map = array(

  'MS Access .mdb - sun.jdbc.odbc.JdbcOdbcDriver' => 'access',
  'Excel File - sun.jdbc.odbc.JdbcOdbcDriver' => 'excel'     ,
  'SQL Server5 - net.sourceforge.jtds.jdbc.Driver' => 'mssql',
  'SQL Server3 - net.sourceforge.jtds.jdbc.Driver' => 'mssql',
  'Oracle Service Name - oracle.jdbc.driver.OracleDriver' => 'oci8',
  'MySQL - com.mysql.jdbc.Driver'                   => 'mysql',
  'Oracle - oracle.jdbc.driver.OracleDriver'    => 'oci8',
  'ODBC - sun.jdbc.odbc.JdbcOdbcDriver'  => 'odbc'

);

$db_array="";

$used_db="";

$lowest_y_location=9999;



//print_r($g);

$original_plet_id=""; //stores the mapping to orignial to new plet id
$percent = 'percentof';

process();



function process()
{
 global $db;
 global $p;
 global $q;
 global $g;
 global $db_array;
 global $used_db;
 global $lowest_y_location;
 global $dash_file_handle;
 global $dash_file;
 global $path_parts;
 global $dashboard_name;
 global $plet_list;
 global $qlet_list;
 /*
  * //Important settings
$debug="0"; //1=on and 0=off
$dashboard_report = "Hospital Dashboard";
$dashboard_id = "t1"; //ID should not have any white spaces
$button_text="Go";
$database_config="hospital_db.php"; //this is populated from the designer

  */
 elog(0,"convert2web  process started ");
 $d="$";
     fwrite($dash_file_handle, "<?php\n");

 fwrite($dash_file_handle,"{$d}debug='0';\n");

 if (!isset($dashboard_name)) $dashboard_name=$path_parts['filename'];

 fwrite($dash_file_handle,"{$d}dashboard_report='{$dashboard_name}';\n");
 fwrite($dash_file_handle,"{$d}dashboard_id='{$path_parts['filename']}';\n");
 fwrite($dash_file_handle,"{$d}button_text='Go';\n");
 fwrite($dash_file_handle,"{$d}database_config='dbconfig/{$path_parts['filename']}_db.php';\n");
 fwrite($dash_file_handle,"{$d}d_options['use_plet_positions']= true; //this will place each parameter at its own x,y location, setting to false will use the grouping feature\n");
  fwrite($dash_file_handle,"{$d}d_options['grid_height_offset']=-80;//this is the offset added to the actual height for accomodating the caption,pager and column header height\n");
  fwrite($dash_file_handle,"{$d}d_options['top_button_offset']=0;//Push all the objects down by this pixel height.\n");
  fwrite($dash_file_handle,"{$d}d_options['top_button_display']=true;//Display the Go button?\n");
 
  $percent_fn=<<<FFF

  {$d}num_format = 'number_format';
  
  {$d}percent = 'percentof';
function percentof({$d}value,{$d}percent)
{
  return ({$d}value*{$d}percent)/100;
}
FFF;

  fwrite($dash_file_handle,"\n\n".$percent_fn."\n\n");

  $get_position_fn=<<<PPP
  {$d}get_position = 'getPosition';
/*
* Total height /total width of the canvas
offset = deduct this from the actual height or widht
per = percentage of the remaining height or width and based on this return the relative position
*/
function getPosition({$d}total_height,{$d}offset,{$d}per)
{
  return {$d}total_height - (({$d}total_height-{$d}offset)*{$d}per)/100;
}
PPP;

fwrite($dash_file_handle,"\n\n".$get_position_fn."\n\n");

fwrite($dash_file_handle,"\n\n\n");

 getDbConnections(); //process all connections
$go_button_x=0;
$go_button_y=0;

 $p_cnt=0;

 elog(0,"convert2web  adding parameters stg1 ");
 //elog(0,"convert2web  adding parameters ".print_r($p));
 if (isset($p))
 {
    foreach ($p as $k => $v)
    {
        $p_cnt++;
        elog(0,"{$p_cnt} => {$k}");
        $plet_list[$p_cnt]=cleanText($k);
        getPletDefinition($k);

        /*
         * x_position'] = '129';
$p['track_p34']['y_position'] = '3';
$p['track_p34']['width'] = '100';
$p['track_p34']['height'] = '50';
         */
        if ($p[$k]['x_position']+ $p[$k]['width'] > $go_button_x)
            {
             $go_button_x = $p[$k]['x_position']+ $p[$k]['width'] + 20;
            }

        if ($p[$k]['y_position'] > $go_button_y) { $go_button_y = $p[$k]['y_position'] ;}

    }
 }
 else {
       elog(0,"convert2web  ***NO Parameters to process stg2 ");
 }

  fwrite($dash_file_handle,"{$d}d_options['top_button_x_location']={$go_button_x};//X position where the Go button will appear\n");
  fwrite($dash_file_handle,"{$d}d_options['top_button_y_location']={$d}d_options['top_button_offset'] +15;//Y Position of the Go button\n");
  fwrite($dash_file_handle,"{$d}d_options['top_button_width']=40;//Width of the Go button\n");
  fwrite($dash_file_handle,"{$d}d_options['top_button_height']=20;//Height of the Go Button\n");
  fwrite($dash_file_handle,"{$d}d_options['use_go_checkobx_x_location']={$go_button_x}+{$d}d_options['top_button_width']+5 ;//X- position of the Checkbox. The checkbox is used to disable AutoRefresh when you change the drop down value\n");

  elog(0,"d_options to file");
  //array_walk($plet_list, 'cleanText');//remove any special characters
  elog(0,"plet list array =".print_r($plet_list,true));
    $p_str = " = array ('".implode("' , '",$plet_list)."');\n\n\n";
elog(0,"plet str ={$p_str}");

    fwrite($dash_file_handle,"{$d}plet['list']". $p_str); //write a list of plets

    fwrite($dash_file_handle,"{$d}plet_group['list'] =array('g1'); \n");
    fwrite($dash_file_handle,"{$d}plet_group['g1']['label']='Select Values'; \n");
    fwrite($dash_file_handle,"{$d}plet_group['g1']['members']". $p_str); //write a list of plets

    fwrite($dash_file_handle,"{$d}plet_group['g1']['width']=700; \n");

    fwrite($dash_file_handle,"\n\n/******************************Parameter End********************************/\n");
elog(0,"convert2web  Parameter End ");
    fwrite($dash_file_handle,"{$d}qlet['relative_position']=true;// \n\n");
    $q_cnt=0;
    elog(0,"convert2web  adding Qlets******  ");
    //elog(0,"convert2web  Qlet list".print_r($q,true));
    if (isset($q))
    {
    foreach ($q as $k => $v)
    {
        elog(0,"{$q_cnt} -- {$k} => {$v}");
        //add to the display list only if it has the number of columns as this portlet could be a drill into portlet
       if ($q[$k]['number_of_columns']>0  && $q[$k]['RunOnStart']=='Y')
       {

           $q_cnt++;
         $qlet_list[$q_cnt]=cleanText($k);
       }
       else
       {    if ($q[$k]['number_of_columns']<=0 )
           {
           echo "<b>Please NOTE:   </b>Portlet {$k} does not have any columns.. <br>Make sure that the portlet is showing data when you do <b>[Publish to Web from desktop]</b>.<br>";
           elog(0," Portlet {$k} does not have any columns.. Make sure that the portlet is showing data when you do [Publish to Web from desktop]");
           }
       }
        getQletDefinition($k);
    }
    }
    else elog(0,"convert2web  No Qlets found*** ");

    if (isset($g))
    {
    foreach ($g as $k => $v)
    {
        //add to the display list only if it has the number of columns as this portlet could be a drill into portlet
       if ($g[$k]['number_of_columns']>0 && $g[$k]['RunOnStart']=='Y')
       {
           $q_cnt++;
         $qlet_list[$q_cnt]=cleanText($k);
       }
       else
       {    if ($g[$k]['number_of_columns']<=0 )
           {
           echo "Portlet {$k} does not have any columns.. Make sure that the portlet is showing data when you do [Publish to Web from desktop].<br>";
           elog(0,"Portlet {$k} does not have any columns.. Make sure that the portlet is showing data when you do [Publish to Web from desktop]");
           }
       }

        getGletDefinition($k);
    }
    }
    //array_walk($qlet_list, 'cleanText');//remove any special characters


    $q_str = "{$d}qlet['list'] = array ('".implode("' , '",$qlet_list)."');\n\n\n";

    fwrite($dash_file_handle, $q_str); //write a list of plets

    fwrite($dash_file_handle,"\n\n\n");
    fwrite($dash_file_handle,"{$d}d_options['lowest_y_location'] = {$lowest_y_location}");

    fwrite($dash_file_handle,"\n\n\n");

    

    fwrite($dash_file_handle,"\n?>");
    fclose($dash_file_handle);

writeDBConfig();

  echo "Conversion complete..<br>";
  echo "Total Parameters = ".count($plet_list)."<br>";
  echo "Total Portlets = ".count($qlet_list)."<br>";

  echo "Click below link to view the dashboard<br>";
  echo "<a href=\"report_engine.php?report={$dash_file}\">{$dash_file}</a><br>";

}//process
//print_r($original_plet_id);

function writeDBConfig()
{
 elog(0,"writeDBConfig start");
    global $used_db;
    global $db_array;
    global $db_file_handle;// = fopen($db_file,"w");;

    fwrite($db_file_handle, "<?php\n");
    $d="$";
    //print_r($used_db);
    //print_r($db_array);
    foreach ($used_db as $k => $v)
    {
        //echo "---------->". $db_array[$k];
         //echo $k." ".$v;
        fwrite($db_file_handle,"{$d}db_array['{$k}']['type']='{$db_array[$k]['type']}'; \n");
        fwrite($db_file_handle,"{$d}db_array['{$k}']['host']='{$db_array[$k]['host']}'; \n");
        fwrite($db_file_handle,"{$d}db_array['{$k}']['port']='{$db_array[$k]['port']}'; \n");
        fwrite($db_file_handle,"{$d}db_array['{$k}']['name']='{$db_array[$k]['name']}'; \n");
        fwrite($db_file_handle,"{$d}db_array['{$k}']['user']='{$db_array[$k]['user']}'; \n");
        fwrite($db_file_handle,"{$d}db_array['{$k}']['pass']='{$db_array[$k]['pass']}'; \n");
        /*
        if ($db_array[$k]['type']=="excel")
        {
            fwrite($db_file_handle,"{$d}db_array['{$k}']['use_local_excel_cache']='Y'; //not used in current release \n");

        }
        else
        {
               fwrite($db_file_handle,"{$d}db_array['{$k}']['use_local_excel_cache']='N'; //not used in current release\n");
        }
         fwrite($db_file_handle,"{$d}db_array['{$k}']['multi_user_excel_cache']='N';//not used in current release \n");
         */
    }

    fwrite($db_file_handle,"\n?>");
    fclose($db_file_handle);
}

function getDbConnections()
{
    elog(0,"getDbConnections start");
    global $db;
    global $dr_map;
    global $db_array;
    global $used_db;
//    print_r($dr_map);
    
    foreach ($db as $k => $v)
    {
        $db_name=$db[$k]['connectName'];
        $split_str = explode("#", $db[$k]['dbUrl']); //split the host, port and url
        $db_array[$db_name]['host']="";
        $db_array[$db_name]['port']="";
        $db_array[$db_name]['name']="";
        $db_array[$db_name]['user']=$db[$k]['user'];
        $db_array[$db_name]['pass']=$db[$k]['password'];

        //echo "processing ----- [{$k}]\n";
        $db_array[$db_name]['type']=$dr_map[$db[$k]['driver']]; //get the php adodb driver name
        if (startsWith("Excel", $db[$k]['driver']) || startsWith("MS Access", $db[$k]['driver']))
        {                

          $db_array[$db_name]['name']=$split_str[0];
          
        } 
        else 
        {
          $db_array[$db_name]['host']=$split_str[0];
          $db_array[$db_name]['port']=$split_str[1];
          $db_array[$db_name]['name']=$split_str[2];
        }
    }
    
 //   print_r($db_array);
}

function getPletConnectionName($plet_id)
{
    elog(0,"getDbConnections start");
    global $db;
    global $db_array;
    global $used_db;
    global $p;
    global $q;
    global $g;

    //$p['plet_id']['Connection'] = "C:/nil/sankar_infocaptor.xls - C:/nil/sankar_infocaptor.xls";
    $k=$db[$p[$plet_id]['Connection']]['connectName'];
    $used_db[$k]=1;
    return $k;
    
}

function getQletConnectionName($qlet_id)
{

    global $db;
    global $db_array;
    global $used_db;
    global $p;
    global $q;
    global $g;

    //$p['plet_id']['Connection'] = "C:/nil/sankar_infocaptor.xls - C:/nil/sankar_infocaptor.xls";
    $k=$db[$q[$qlet_id]['Connection']]['connectName'];
    $used_db[$k]=1;
    return $k;

}

function getGletConnectionName($glet_id)
{
    global $db;
    global $db_array;
    global $used_db;
    global $p;
    global $q;
    global $g;

    //$p['plet_id']['Connection'] = "C:/nil/sankar_infocaptor.xls - C:/nil/sankar_infocaptor.xls";
    $k=$db[$g[$glet_id]['Connection']]['connectName'];
    $used_db[$k]=1;
    return $k;

}


function getQletDefinition($qlet_id)
{
    elog(0,"getQletDefinition({$qlet_id})");
 global $db;
 global $p;
 global $q;
 global $g;
 global $db_array;
 global $used_db;
 global $lowest_y_location;
 global $dash_file_handle;



 fwrite($dash_file_handle,"\n\n/************** {$qlet_id} *********************/\n");
 $d="$";
 $clean_qlet_id = preg_replace("/[^A-Za-z0-9_]/","",$qlet_id);
$qlet_str="";

 $qlet_str.="{$d}qlet['{$clean_qlet_id}']['id']='{$qlet_id}' ;\n";
 $qlet_str.="{$d}qlet['{$clean_qlet_id}']['name']='{$q[$qlet_id]['Name']}' ;\n";
$qlet_str.="{$d}qlet['{$clean_qlet_id}']['type']='table' ;\n";
 $qlet_str.="{$d}qlet['{$clean_qlet_id}']['connection']='".getQletConnectionName($qlet_id)."' ;\n";
$glet_str.="{$d}qlet['{$glet_id}']['original_type']='table' ;\n";

 $qlet_str.="{$d}qlet['{$clean_qlet_id}']['width']={$q[$qlet_id]['width']} ;\n";
 $qlet_str.="{$d}qlet['{$clean_qlet_id}']['height']={$q[$qlet_id]['height']} ;\n";

 $qlet_str.="{$d}qlet['{$clean_qlet_id}']['x_position']={$q[$qlet_id]['x_position']} ;\n";
 $qlet_str.="{$d}qlet['{$clean_qlet_id}']['y_position']={$q[$qlet_id]['y_position']} ;\n";

 //calculate the lowest y location so that we can later adjust the relative position
 $y_pos=$q[$qlet_id]['y_position']*1;
 if ($y_pos<$lowest_y_location) $lowest_y_location=$y_pos;

 $qlet_str.="{$d}qlet['{$clean_qlet_id}']['max_rows']={$q[$qlet_id]['MaxRows']} ;\n";
// $qlet_str.="{$d}qlet['{$clean_qlet_id}']['column_names']={$q[$qlet_id]['MaxRows']} ;\n";

 $qlet_str.="{$d}qlet['{$clean_qlet_id}']['number_of_columns']={$q[$qlet_id]['number_of_columns']} ;\n";

 $col_names = implode("','", $q[$qlet_id]['column_names']); //convert array to comma separated string

 $col_size = implode(",", $q[$qlet_id]['column_sizes'] );

if ($q[$qlet_id]['number_of_columns']>0)
 {
 $edit_option = array_fill(0,$q[$qlet_id]['number_of_columns'],"editable:true");
 }
 $edit_option[0]="editable:false";
 addDateFunction($edit_option,$q[$qlet_id]['column_type']); //add a datepicker for date type columns



 array_walk($q[$qlet_id]['column_type'], 'convertClass');//convert java.String to alignment type
 $col_class = implode ("','",$q[$qlet_id]['column_type']);

 array_walk($q[$qlet_id]['column_type'], 'convertClass2Alignment');//convert java.String to alignment type

 $col_alignment = implode ("','",$q[$qlet_id]['column_type']);


 $qlet_str.="{$d}qlet['{$clean_qlet_id}']['show_pager']= false  ;\n";
 $qlet_str.="{$d}qlet['{$clean_qlet_id}']['column_names']= array('{$col_names}' ) ;\n";
 $qlet_str.="{$d}qlet['{$clean_qlet_id}']['column_display_names']= array('{$col_names}' ) ;\n";
 $qlet_str.="{$d}qlet['{$clean_qlet_id}']['column_alignment']= array('{$col_alignment}' ) ;\n";
 $qlet_str.="{$d}qlet['{$clean_qlet_id}']['column_class']= array('{$col_class}' ) ;\n";
 $qlet_str.="{$d}qlet['{$clean_qlet_id}']['column_width']= array({$col_size} ) ;\n";

 $qlet_str.="\n//Make sure the primary column is marked as non-editable.\n";
 $edit_options_str = implode ("\",\"",$edit_option);
 $qlet_str.="{$d}qlet['{$clean_qlet_id}']['edit_options']= array(\"{$edit_options_str}\" ) ;\n";

 $qlet_str.="{$d}qlet['{$clean_qlet_id}']['insert_template']=''; \n";
 $qlet_str.="{$d}qlet['{$clean_qlet_id}']['edit_template']=''; \n";
 $qlet_str.="{$d}qlet['{$clean_qlet_id}']['delete_template']=''; \n";

 $qlet_str.="{$d}qlet['{$clean_qlet_id}']['template'] =".<<<EOD
 <<<EOT

  jQuery("#{$clean_qlet_id}").jqGrid({
    #url#,
    datatype: 'xml',
    mtype: 'POST',
    #column_names#,
    #column_model#,
    #pager_str#,
    rowNum:100,
    rowList:[100,200,300],
    sortname: '{$sort}',
    sortorder: "desc",
    rowHeight:10,
    scrollOffset:0,
    viewrecords: true,
        height:#height#,
        width:{{$d}qlet['{$clean_qlet_id}']['width']},
    imgpath: 'themes/basic/images',
        #edit_url#,
    caption: '{{$d}qlet['{$clean_qlet_id}']['name']}',
                footerrow : false,
        userDataOnFooter : false,
        viewsortcols: false,
        altRows:true,
        ExpandColClick: true,
        altclass: 'other_row',
        mtype:'POST',
        loadError : function(xhr,st,err)
        {
    	//jQuery("#status").html("Type: "+st+"; Response: "+ xhr.status + " "+xhr.statusText);
        },
        loadComplete: function()
        {

        }
  }).navGrid('#pager_{$clean_qlet_id}',{view:true,edit:true,add:true,del:true});
EOT;


EOD;
 $qlet_str.="{$d}qlet['{$clean_qlet_id}']['background_color']= '' ;\n";
 $qlet_str.="{$d}qlet['{$clean_qlet_id}']['enable_column_sort']= 'Y' ;\n";
 $qlet_str.="{$d}qlet['{$clean_qlet_id}']['dynamic_script']= <<<EOD\n {$q[$qlet_id]['dynamicScript']} \nEOD;\n";
 $qlet_str.="{$d}qlet['{$clean_qlet_id}']['total_script']= <<<EOD\n {$q[$qlet_id]['totals']} \nEOD;\n";
 $qlet_str.="{$d}qlet['{$clean_qlet_id}']['sql']= <<<EOD\n ". convertOldSql( $q[$qlet_id]['sql'])." \nEOD;\n";

 //echo $qlet_str;

 fwrite($dash_file_handle,$qlet_str);

fwrite($dash_file_handle,"\n\n");
}

function getGletDefinition($glet_id)
{
    elog(0,"getGletDefinition({$glet_id})");
 global $db;
 global $p;
 global $q;
 global $g;
 global $db_array;
 global $used_db;
 global $lowest_y_location;
 global $dash_file_handle;
global  $new_chart_type;
global $template;
 //echo "processing glet - ".$glet_id;

 $d="$";
 fwrite($dash_file_handle,"\n\n/************** {$plet_id} *********************/\n");
$clean_glet_id = preg_replace("/[^A-Za-z0-9_]/","",$glet_id);

$glet_str="";

//echo "<br> {$glet_id} -->".$g[$glet_id]['ChartType'] ;
//echo "<br> ".$new_chart_type[ $g[$glet_id]['ChartType'] ];

$chart_type_code = $new_chart_type[ $g[$glet_id]['ChartType'] ];

 fwrite($dash_file_handle,"\n\n/************** {$glet_id} *********************/\n");
 $glet_str.="{$d}qlet['{$clean_glet_id}']['id']='{$clean_glet_id}' ;\n";
 $glet_str.="{$d}qlet['{$clean_glet_id}']['name']='{$g[$glet_id]['Name']}' ;\n";
$glet_str.="{$d}qlet['{$clean_glet_id}']['type']=  '{$new_chart_type[ $g[$glet_id]['ChartType'] ]}' ;\n";
 $glet_str.="{$d}qlet['{$clean_glet_id}']['connection']='".getGletConnectionName($glet_id)."' ;\n";
$glet_str.="{$d}qlet['{$clean_glet_id}']['original_type']='chart' ;\n";

 $glet_str.="{$d}qlet['{$clean_glet_id}']['width']={$g[$glet_id]['width']} ;\n";
 $glet_str.="{$d}qlet['{$clean_glet_id}']['height']={$g[$glet_id]['height']} ;\n";

 $glet_str.="{$d}qlet['{$clean_glet_id}']['x_position']={$g[$glet_id]['x_position']} ;\n";
 $glet_str.="{$d}qlet['{$clean_glet_id}']['y_position']={$g[$glet_id]['y_position']} ;\n";

 //calculate the lowest y location so that we can later adjust the relative position
 $y_pos=$g[$glet_id]['y_position']*1;
 if ($y_pos<$lowest_y_location) $lowest_y_location=$y_pos;

 $glet_str.="{$d}qlet['{$clean_glet_id}']['max_rows']={$g[$glet_id]['MaxRows']} ;\n";
 //$glet_str.="{$d}qlet['{$clean_glet_id}']['column_names']={$g[$glet_id]['MaxRows']} ;\n";

 $glet_str.="{$d}qlet['{$clean_glet_id}']['number_of_columns']={$g[$glet_id]['number_of_columns']} ;\n";

 $col_names = implode("','", $g[$glet_id]['column_names']); //convert array to comma separated string

 $col_size = implode(",", $g[$glet_id]['column_sizes'] );

 array_walk($g[$glet_id]['column_type'], 'convertClass2Alignment');//convert java.String to alignment type

 $col_alignment = implode ("','",$g[$glet_id]['column_type']);

 $glet_str.="{$d}qlet['{$clean_glet_id}']['column_names']= array('{$col_names}' ) ;\n";
 $glet_str.="{$d}qlet['{$clean_glet_id}']['column_display_names']= array('{$col_names}' ) ;\n";
 $glet_str.="{$d}qlet['{$clean_glet_id}']['column_alignment']= array('{$col_alignment}' ) ;\n";
 $glet_str.="{$d}qlet['{$clean_glet_id}']['column_width']= array({$col_size} ) ;\n";
 $glet_str.="{$d}qlet['{$clean_glet_id}']['display_tooltip']= true  ;\n";
 if (isset($template['tooltip'][$new_chart_type[ $g[$glet_id]['ChartType'] ]]))
     {
     $glet_str.="{$d}qlet['{$clean_glet_id}']['tooltip_template']= <<<EOD\n{$template['tooltip'][$new_chart_type[ $g[$glet_id]['ChartType'] ]]}\nEOD;\n";
     }
else
    {
     $glet_str.="{$d}qlet['{$clean_glet_id}']['tooltip_template']= \"{$template['tooltip']['general']}\"  ;\n";
    }
  $html_color=convertColorStr($g[$glet_id]['BackgroundColor']);
 $glet_str.="{$d}qlet['{$clean_glet_id}']['background_color']= 'FFFFFF' ;\n";
 //$glet_str.="{$d}qlet['{$clean_glet_id}']['dynamic_script']= <<<EOD\n {$g[$glet_id]['dynamicScript']} \nEOD;\n";
 $glet_str.="{$d}qlet['{$clean_glet_id}']['total_script']= <<<EOD\n {$g[$glet_id]['totals']} \nEOD;\n";
 $glet_str.="{$d}qlet['{$clean_glet_id}']['sql']= <<<EOD\n ". convertOldSql( $g[$glet_id]['sql'])." \nEOD;\n";

if ($chart_type_code=="gauge_meter")
{
  $glet_str.="{$d}qlet['{$clean_glet_id}']['chart_margin']= array(left =>'15',right=>'15',top=>'25',bottom=>'45');\n";
}
else
{
   $glet_str.="{$d}qlet['{$clean_glet_id}']['chart_margin']= array(left =>'35',right=>'15',top=>'25',bottom=>'45');\n";
}
  $glet_str.="{$d}qlet['{$clean_glet_id}']['chart_size']=
                           array(
                                 width=>{$d}qlet['{$clean_glet_id}']['width'] - {$d}qlet['{$clean_glet_id}']['chart_margin']['left']- {$d}qlet['{$clean_glet_id}']['chart_margin']['right']
                                ,height =>{$d}qlet['{$clean_glet_id}']['height'] - {$d}qlet['{$clean_glet_id}']['chart_margin']['top']- {$d}qlet['{$clean_glet_id}']['chart_margin']['bottom']-20
                                 );
                                 \n";
  $glet_str.="{$d}qlet['{$clean_glet_id}']['chart_position']=
                           array(
                                 top_x=> {$d}qlet['{$clean_glet_id}']['chart_margin']['left']
                                ,top_y => {$d}qlet['{$clean_glet_id}']['chart_margin']['top']
                                 );
                                 \n";
if ($chart_type_code=="gauge_meter")
{
  $glet_str.="{$d}qlet['{$clean_glet_id}']['legend']=
                           array(
                                 width=> {$d}qlet['{$clean_glet_id}']['width'] - {$d}qlet['{$clean_glet_id}']['chart_margin']['left']- {$d}qlet['{$clean_glet_id}']['chart_margin']['right']
                                ,height => {$d}qlet['{$clean_glet_id}']['height']*.2
                                ,top_x=> {$d}qlet['{$clean_glet_id}']['chart_margin']['left']
                                ,top_y => {$d}qlet['{$clean_glet_id}']['height'] - {$d}qlet['{$clean_glet_id}']['height']*.2
                                ,label_max_length =>10
                                 );
                                 \n";
}
else
{
  $glet_str.="{$d}qlet['{$clean_glet_id}']['legend']=
                           array(
                                 width=> {$d}qlet['{$clean_glet_id}']['width'] - {$d}qlet['{$clean_glet_id}']['chart_margin']['left']- {$d}qlet['{$clean_glet_id}']['chart_margin']['right']
                                ,height => 20
                                ,top_x=> {$d}qlet['{$clean_glet_id}']['chart_margin']['left']
                                ,top_y => {$d}qlet['{$clean_glet_id}']['height'] - 20
                                ,label_max_length =>10
                                 );
                                 \n";
}


 if (startsWith("gauge",$chart_type_code) )
 {
     if ($chart_type_code=="gauge_dial")
     {
       $glet_str.=getGaugeDetails($clean_glet_id,$glet_id,$chart_type_code);
     }
     else if ($chart_type_code=="gauge_meter")
     {
         $glet_str.=getMeterDetails($clean_glet_id,$glet_id,$chart_type_code);
     }    

 }


 $temp = str_replace("#portlet_id#","'{$clean_glet_id}'",$template[$new_chart_type[ $g[$glet_id]['ChartType'] ]]);
 $glet_str.="{$d}qlet['{$clean_glet_id}']['template']= <<<EOD\n{$temp}\nEOD;\n";

 //echo $glet_str;
 fwrite($dash_file_handle,$glet_str);
 fwrite($dash_file_handle,"\n\n");
}


function getGaugeDetails($clean_glet_id,$glet_id, $chart_type_code)
{
    elog(0,"getGaugeDetails(({$clean_glet_id},{$glet_id}, {$chart_type_code})");
    global $g;
    $d="$";
    if ($chart_type_code=="gauge_dial")
    {
        $glet_str="";
        $glet_str.="{$d}title_height=20;\n";
        $glet_str.="{$d}qlet['{$clean_glet_id}']['x_center']= {$d}qlet['{$clean_glet_id}']['width']/2 ;\n";
        $glet_str.="{$d}qlet['{$clean_glet_id}']['y_center']= ({$d}qlet['{$clean_glet_id}']['height']- {$d}title_height)/2 +{$d}title_height ;\n";
        $glet_str.="{$d}qlet['{$clean_glet_id}']['radius']= min ({$d}qlet['{$clean_glet_id}']['width'], {$d}qlet['{$clean_glet_id}']['height']- {$d}title_height)/2 -10 ;//radius of the outer circle\n";
        $glet_str.="{$d}qlet['{$clean_glet_id}']['range_radius']= {$d}qlet['{$clean_glet_id}']['radius']*0.915 ;//radius of the colorful ranges\n";
        $glet_str.="{$d}qlet['{$clean_glet_id}']['tick_radius']= {$d}qlet['{$clean_glet_id}']['range_radius'] * 0.90;//radius of the number markers\n";
        $glet_str.="{$d}qlet['{$clean_glet_id}']['number_radius']= {$d}qlet['{$clean_glet_id}']['tick_radius'] * 0.90;//\n";
        $glet_str.="{$d}qlet['{$clean_glet_id}']['major_ticks']= 
                                array(
                                      color     => '000000' ,
                                      length    => 10,
                                      thickness => 3,
                                      number_of_parts => 10); //0 is for auto- engine will compute the increment automatically by dividing the range into 10 equal parts,
                   \n";

        $glet_str.="{$d}qlet['{$clean_glet_id}']['minor_ticks']= 
                                array(
                                      color     => '000000' ,
                                      length    => 5,
                                      thickness => 1,
                                      number_of_parts => 4); //this will divide the major tick into equal parts. 0 will indicate to divide the major ticks into 10 equal parts
                   \n";
        
        $glet_str.="\n//ticks_range_angle is the span of the dial that will use to display the ticks and numbers.\n";
       $glet_str.="{$d}qlet['{$clean_glet_id}']['ticks_range_angle']= array(start_angle => -120, end_angle =>120);//The 12 o'clock position is the zero angle position. Anything clockwise from 12'0clock position is positive angle and anything anti-clockwise is -ve angle. For complete circle use -180 to +180.\n";        

       $glet_str.="{$d}qlet['{$clean_glet_id}']['tick_numbers']= array(font_size => {$d}qlet['{$clean_glet_id}']['radius']*0.15, color =>'000000');//The 12 o'clock position is the zero angle position. Anything clockwise from 12'0clock position is positive angle and anything anti-clockwise is -ve angle. For complete circle use -180 to +180.\n";
$glet_str.="\n
//\n
//\n
//the gauge is divided into multiple sections. typically it has 3 sections but you may have as many of them as needed
//each section is defined by a numeric range and has its own color
//the range is defined between start and end value. The attribute define the properties of the section such as color etc
       ";

//get the ranges from the dynamic script
preg_match_all("/StandardDialRange\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*new(.*)\)/",$g[$glet_id]['dynamicScript'],$matches);
$total_ranges = count($matches[0]);

       $glet_str.=<<<EOD
            {$d}qlet['{$clean_glet_id}']['range']=

             array(
             
EOD;
   for ($r=0;$r<$total_ranges;$r++)
   {
        $hexcolor = convertColorStr($matches[3][$r]);
        $hexcolor = str_replace("#","",$hexcolor);
        $glet_str.=<<<EOD
              array( start_value => {$matches[1][$r]},
                      end_value => {$matches[2][$r]},
                      attributes => "<circle x='#x_center#' y='#y_center#' radius='#radius#' fill_color='{$hexcolor}' fill_alpha='100' line_thickness='1' line_color='{$hexcolor}' line_alpha='90' />"
                    )
EOD;
      if ($r<$total_ranges-1)  $glet_str.=" , \n";
   }

   $glet_str.="
             );\n";


       
$glet_str.="{$d}qlet['{$clean_glet_id}']['pointer']['radius']={$d}qlet['{$clean_glet_id}']['radius'] - 5; //\n";
$glet_str.="
//relative co-ordinates from the center of the gauge. This polygon will define the shape of the pointer
//for e.g if you need a 2 pixel thick line, then you just need a 4 (x,y) points relative to the center of the gauge
";
$glet_str.="{$d}qlet['{$clean_glet_id}']['pointer']['points']=
                                  array(
                                         array ( x => 3.5, y => 0),
                                         array ( x => 0, y => -{$d}qlet['{$clean_glet_id}']['pointer']['radius']),
                                         array ( x => -0, y => -{$d}qlet['{$clean_glet_id}']['pointer']['radius']),
                                         array ( x => -3.5 , y=> 0),
                                       );
                                         ";

$glet_str.="
{$d}qlet['{$clean_glet_id}']['pointer']['attributes']=<<<EOD
<polygon fill_color='DEffff' fill_alpha='90' line_alpha='0'>
EOD;

";

$glet_str.="
{$d}qlet['{$clean_glet_id}']['pointer']['value']=
                                   array(
                                           decimals=>0 , decimal_str => '.' , thousand_separator => ','
                                         );
";

$glet_str.="{$d}qlet['{$clean_glet_id}']['text_x']={$d}qlet['{$clean_glet_id}']['x_center']-{$d}qlet['{$clean_glet_id}']['radius'] * 0.90;\n";

$glet_str.="{$d}qlet['{$clean_glet_id}']['text_y']={$d}qlet['{$clean_glet_id}']['y_center']+{$d}qlet['{$clean_glet_id}']['radius'] * 0.22;\n";
$glet_str.="{$d}qlet['{$clean_glet_id}']['text_width']={$d}qlet['{$clean_glet_id}']['radius'] * 1.80;\n";
/*
$glet_str.="{$d}qlet['{$clean_glet_id}']['template']=<<<EOD



	<circle  x='#x_center#' y='#y_center#' radius='#radius#' fill_color='FFFFFF' fill_alpha='100' line_thickness='6' line_color='333333' line_alpha='90' />

     	#range_code#


        <circle x='#x_center#' y='#y_center#' radius='40' fill_color='FFFFFF' fill_alpha='255' line_thickness='0' line_alpha='50' />
	#radial_ticks#

        #radial_numbers#
        #pointer_code#

        <circle x='#x_center#' y='#y_center#' radius='80' start='135' end='225' fill_color='111111' fill_alpha='80' />
        <circle x='#x_center#' y='#y_center#' radius='20' fill_color='111111' fill_alpha='100' line_thickness='5' line_alpha='50' />





	<text x='{{$d}qlet['{$clean_glet_id}']['text_x']}' y='{{$d}qlet['{$clean_glet_id}']['text_y']}' width='100' size='12' color='cccfff' alpha='70' align='center'>#pointer_value# \rUnit</text>


EOD;

";
*/
    }
    
    return $glet_str;
}

function getMeterDetails($clean_glet_id,$glet_id, $chart_type_code)
{
    global $g;
    $d="$";
    if ($chart_type_code=="gauge_meter")
    {
        $glet_str="";
        $glet_str.="{$d}title_height=20;\n";
        $glet_str.="{$d}qlet['{$clean_glet_id}']['x_center']= {$d}qlet['{$clean_glet_id}']['width']/2 ;\n";
        $glet_str.="{$d}qlet['{$clean_glet_id}']['y_center']= ({$d}qlet['{$clean_glet_id}']['height']- {$d}title_height)/2 +{$d}title_height ;\n";
        $glet_str.="{$d}qlet['{$clean_glet_id}']['radius']= min ({$d}qlet['{$clean_glet_id}']['width'], {$d}qlet['{$clean_glet_id}']['height']- {$d}title_height)/2 -10 ;//radius of the outer circle\n";
        $glet_str.="{$d}qlet['{$clean_glet_id}']['range_radius']= {$d}qlet['{$clean_glet_id}']['radius']*0.915 ;//radius of the colorful ranges\n";
        $glet_str.="{$d}qlet['{$clean_glet_id}']['tick_radius']= {$d}qlet['{$clean_glet_id}']['range_radius'] * 0.90;//radius of the number markers\n";
        $glet_str.="{$d}qlet['{$clean_glet_id}']['number_radius']= {$d}qlet['{$clean_glet_id}']['tick_radius'] * 0.90;//\n";
        $glet_str.="{$d}qlet['{$clean_glet_id}']['major_ticks']=
                                array(
                                      color     => '000000' ,
                                      length    => 10,
                                      thickness => 3,
                                      number_of_parts => 10); //0 is for auto- engine will compute the increment automatically by dividing the range into 10 equal parts,
                   \n";

        $glet_str.="{$d}qlet['{$clean_glet_id}']['minor_ticks']=
                                array(
                                      color     => '000000' ,
                                      length    => 5,
                                      thickness => 1,
                                      number_of_parts => 4); //this will divide the major tick into equal parts. 0 will indicate to divide the major ticks into 10 equal parts
                   \n";

        $glet_str.="\n//ticks_range_angle is the span of the dial that will use to display the ticks and numbers.\n";
       $glet_str.="{$d}qlet['{$clean_glet_id}']['ticks_range_angle']= array(start_angle => -90, end_angle =>90);//The 12 o'clock position is the zero angle position. Anything clockwise from 12'0clock position is positive angle and anything anti-clockwise is -ve angle. For complete circle use -180 to +180.\n";

       $glet_str.="{$d}qlet['{$clean_glet_id}']['tick_numbers']= array(font_size => {$d}qlet['{$clean_glet_id}']['radius']*0.15, color =>'000000');//The 12 o'clock position is the zero angle position. Anything clockwise from 12'0clock position is positive angle and anything anti-clockwise is -ve angle. For complete circle use -180 to +180.\n";
$glet_str.="\n
//\n
//\n
//the gauge is divided into multiple sections. typically it has 3 sections but you may have as many of them as needed
//each section is defined by a numeric range and has its own color
//the range is defined between start and end value. The attribute define the properties of the section such as color etc
       ";

//get the ranges from the dynamic script
preg_match_all("/MeterInterval\(\s*(\"\w+\")\s*,\s*new\s*Range\s*\(\s*(\d+\\.*\d*)\s*,\s*(\d+\\.*\d*)\s*\)\s*,\s*.+\s*,\s*new\s+.+\s*,\s*new\s*(.*)\s*\)\s*\)/",$g[$glet_id]['dynamicScript'],$matches);
$total_ranges = count($matches[0]);

       $glet_str.=<<<EOD
            {$d}qlet['{$clean_glet_id}']['range']=

             array(

EOD;
   for ($r=0;$r<$total_ranges;$r++)
   {
        $hexcolor = convertColorStr($matches[4][$r]);
        $hexcolor = str_replace("#","",$hexcolor);
        $glet_str.=<<<EOD
              array( start_value => {$matches[2][$r]},
                      end_value => {$matches[3][$r]},
                      label => {$matches[1][$r]},
                      attributes => "<circle x='#x_center#' y='#y_center#' radius='#radius#' fill_color='{$hexcolor}' fill_alpha='100' line_thickness='1' line_color='{$hexcolor}' line_alpha='90' />"
                    )
EOD;
      if ($r<$total_ranges-1)  $glet_str.=" , \n";
   }

   $glet_str.="
             );\n";



$glet_str.="{$d}qlet['{$clean_glet_id}']['pointer']['radius']={$d}qlet['{$clean_glet_id}']['radius'] - 5; //\n";
$glet_str.="
//relative co-ordinates from the center of the gauge. This polygon will define the shape of the pointer
//for e.g if you need a 2 pixel thick line, then you just need a 4 (x,y) points relative to the center of the gauge
";
$glet_str.="{$d}qlet['{$clean_glet_id}']['pointer']['points']=
                                  array(
                                         array ( x => 3.5, y => 0),
                                         array ( x => 0, y => -{$d}qlet['{$clean_glet_id}']['pointer']['radius']),
                                         array ( x => -0, y => -{$d}qlet['{$clean_glet_id}']['pointer']['radius']),
                                         array ( x => -3.5 , y=> 0),
                                       );
                                         ";

$glet_str.="
{$d}qlet['{$clean_glet_id}']['pointer']['attributes']=<<<EOD
<polygon fill_color='DEffff' fill_alpha='90' line_alpha='0'>
EOD;

";

$glet_str.="
{$d}qlet['{$clean_glet_id}']['pointer']['value']=
                                   array(
                                           decimals=>0 , decimal_str => '.' , thousand_separator => ','
                                         );
";

$glet_str.="{$d}qlet['{$clean_glet_id}']['text_x']={$d}qlet['{$clean_glet_id}']['x_center']-{$d}qlet['{$clean_glet_id}']['radius'] * 0.90;\n";

$glet_str.="{$d}qlet['{$clean_glet_id}']['text_y']={$d}qlet['{$clean_glet_id}']['y_center']+{$d}qlet['{$clean_glet_id}']['radius'] * 0.22;\n";
$glet_str.="{$d}qlet['{$clean_glet_id}']['text_width']={$d}qlet['{$clean_glet_id}']['radius'] * 1.80;\n";

$glet_str.= <<<MOD

{$d}qlet['{$clean_glet_id}']['legend_xml']="";

{$d}range_count=count({$d}qlet['{$clean_glet_id}']['range']);
{$d}lx={$d}qlet['{$clean_glet_id}']['legend']['top_x'];
{$d}ly={$d}qlet['{$clean_glet_id}']['legend']['top_y'];

{$d}lw={$d}qlet['{$clean_glet_id}']['legend']['width']/{$d}range_count;
{$d}ls={$d}qlet['{$clean_glet_id}']['radius']*0.13;

for ({$d}i=0;{$d}i<{$d}range_count;{$d}i++)
{
{$d}ly={$d}qlet['{$clean_glet_id}']['legend']['top_y']+{$d}ls;
  {$d}bullet={$d}qlet['{$clean_glet_id}']['range'][{$d}i]['attributes'];
 {$d}bullet=str_ireplace('#radius#',{$d}ls,{$d}bullet );
 {$d}bullet=str_ireplace('#x_center#',{$d}lx+{$d}lw/2,{$d}bullet );
 {$d}bullet=str_ireplace('#y_center#',{$d}ly,{$d}bullet );

 {$d}qlet['{$clean_glet_id}']['legend_xml'].={$d}bullet;
 {$d}ly={$d}qlet['{$clean_glet_id}']['legend']['top_y']+{$d}qlet['{$clean_glet_id}']['legend']['height']/2;

 {$d}align_txt="center";
 if ({$d}i==0) {$d}align_txt="left";
 else if ({$d}i=={$d}range_count-1) {$d}align_txt="right";
 else {$d}align_txt="center";

 {$d}qlet['{$clean_glet_id}']['legend_xml'].="<text x='{{$d}lx}' y='{{$d}ly}' width='{{$d}lw}' height='100'
         align='center'
         rotation='0'
         size='{{$d}ls}'
         color='000000'
         alpha='100'
         >{{$d}qlet['{$clean_glet_id}']['range'][{$d}i]['label']}</text>";
 {$d}lx={$d}lx+{$d}lw;
}

MOD;

/*
$glet_str.="{$d}qlet['{$clean_glet_id}']['template']=<<<EOD



	<circle  x='#x_center#' y='#y_center#' radius='#radius#' fill_color='FFFFFF' fill_alpha='100' line_thickness='6' line_color='333333' line_alpha='90' />

     	#range_code#


        <circle x='#x_center#' y='#y_center#' radius='40' fill_color='FFFFFF' fill_alpha='255' line_thickness='0' line_alpha='50' />
	#radial_ticks#

        #radial_numbers#
        #pointer_code#

        <circle x='#x_center#' y='#y_center#' radius='80' start='135' end='225' fill_color='111111' fill_alpha='80' />
        <circle x='#x_center#' y='#y_center#' radius='20' fill_color='111111' fill_alpha='100' line_thickness='5' line_alpha='50' />





	<text x='{{$d}qlet['{$clean_glet_id}']['text_x']}' y='{{$d}qlet['{$clean_glet_id}']['text_y']}' width='100' size='12' color='cccfff' alpha='70' align='center'>#pointer_value# \rUnit</text>


EOD;

";
*/
    }

    return $glet_str;
}


function convertFontStr($java_font_str)
{
    //$java_font_str = 'java.awt.Font[family=Arial,name=Arial,style=plain,size=12]'
    $java_font_str= str_replace("java.awt.Font[","",$java_font_str);
    $java_font_str= str_replace("]","",$java_font_str);
    $java_font_str= str_replace("=",":",$java_font_str);
    $java_font_str= str_replace(",",";",$java_font_str);
    $java_font_str= str_replace("family","font-family",$java_font_str);
    $java_font_str= str_replace("name","font-name",$java_font_str);
    $java_font_str= str_replace("style","font-style",$java_font_str);
    $java_font_str= str_replace("size","font-size",$java_font_str);

    return $java_font_str."px"; //px is appended for the font size
}

function convertColorStr($java_color_str)
{
    //'java.awt.Color[r=0,g=0,b=0]' ;
    $java_color_str = str_replace("java.awt.Color[","",$java_color_str);
    $java_color_str = str_replace("]","",$java_color_str);
    $java_color_str = str_replace("Color","",$java_color_str);
    $java_color_str = str_replace("(","",$java_color_str);
    $java_color_str = str_replace(")","",$java_color_str);
    $java_color_str = str_replace(" ","",$java_color_str);
    $c=explode(",",$java_color_str);
    $r=str_replace("r=","",$c[0]);
    $g=str_replace("g=","",$c[1]);
    $b=str_replace("b=","",$c[2]);
    
    $r = intval($r); $g = intval($g);
    $b = intval($b);

    $r = dechex($r<0?0:($r>255?255:$r));
    $g = dechex($g<0?0:($g>255?255:$g));
    $b = dechex($b<0?0:($b>255?255:$b));

    $color = (strlen($r) < 2?'0':'').$r;
    $color .= (strlen($g) < 2?'0':'').$g;
    $color .= (strlen($b) < 2?'0':'').$b;
    return '#'.$color;
    
    
}

function getPletDefinition($plet_id)
{
 global $db;
 global $p;
 global $q;
 global $g;
 global $db_array;
 global $used_db;
 global $original_plet_id;
global $dash_file_handle;



 fwrite($dash_file_handle,"\n\n/************** {$plet_id} *********************/\n");
$clean_plet_id = preg_replace("/[^A-Za-z0-9_]/","",$plet_id);
 $d="$";

       $split_str = explode("_", $plet_id); //split the pletid, the last part stores the original plet id
       $original_plet_id[$split_str[count($split_str)-1]] = $plet_id;

 $plet_str="";
 if ($p[$plet_id]['DataType'] == 'DATE')
 {
   $plet_str.=  "{$d}plet['{$clean_plet_id}']['type']='date' ;\n" ;
   $plet_str.=  "{$d}plet['{$clean_plet_id}']['data_type']='DATA_TYPE' ;\n" ;
 }
 else if ($p[$plet_id]['DataType'] == 'FIELD')
 {
      $plet_str.=  "{$d}plet['{$clean_plet_id}']['type']='text' ;\n" ;
      $plet_str.=  "{$d}plet['{$clean_plet_id}']['data_type']='CHAR' ;\n" ;
 }
 else if ($p[$plet_id]['DataType'] == 'PLET')
 {
   if ($p[$plet_id]['Editable']=="Y")
   {
     $plet_str.=  "{$d}plet['{$clean_plet_id}']['type']='text' ;\n" ;
   }
   else
   {
        $plet_str.=  "{$d}plet['{$clean_plet_id}']['type']='dynamic_lov' ;\n" ;
   }
   $plet_str.=  "{$d}plet['{$clean_plet_id}']['data_type']='CHAR' ;\n" ;

 }

 $plet_str.="{$d}plet['{$clean_plet_id}']['id']='{$clean_plet_id}' ;\n";
 $plet_str.="{$d}plet['{$clean_plet_id}']['name']='{$p[$plet_id]['Name']}' ;\n";
$plet_str.="{$d}plet['{$clean_plet_id}']['raw_type']='{$p[$plet_id]['DataType']}' ;\n";
 $plet_str.="{$d}plet['{$clean_plet_id}']['connection']='".getPletConnectionName($plet_id)."' ;\n";


 $plet_str.="{$d}plet['{$clean_plet_id}']['width']={$p[$plet_id]['width']} ;\n";
$plet_str.="{$d}plet['{$clean_plet_id}']['height']={$p[$plet_id]['height']} - 27 ;\n";

 $plet_str.="{$d}plet['{$clean_plet_id}']['x_position']={$p[$plet_id]['x_position']} ;\n";
 $plet_str.="{$d}plet['{$clean_plet_id}']['y_position']={$p[$plet_id]['y_position']} ;\n";

 $frmt_str = getFormatStr($p[$plet_id]['description']);

 $plet_str.="{$d}plet['{$clean_plet_id}']['format']='{$frmt_str}' ;\n";

 $html_font_str= convertFontStr($p[$plet_id]['Font']);
 $plet_str.="{$d}plet['{$clean_plet_id}']['font']='{$html_font_str}' ;\n";

 $html_color=convertColorStr($p[$plet_id]['FontColor']);
 $plet_str.="{$d}plet['{$clean_plet_id}']['font_color']='{$html_color}' ;\n";

 $html_color=convertColorStr($p[$plet_id]['BackgroundColor']);
 $plet_str.="{$d}plet['{$clean_plet_id}']['background_color']='{$html_color}' ;\n";



  if ($p[$plet_id]['DataType'] == 'DATE')
 {

  if (startsWith('From',$p[$plet_id]['Name']))
  {
     $plet_str.="{$d}plet['{$clean_plet_id}']['default_value']=date('m/1/Y') ;//NOTE: you can provide any default value as string e.g 1/1/2010\n";
  }
  else
  {
      $plet_str.="{$d}plet['{$clean_plet_id}']['default_value']=date('m/t/Y') ;//NOTE: you can provide any default value as string e.g 12/31/2010\n";
  }
 }
 else
     $plet_str.="{$d}plet['{$clean_plet_id}']['default_value']='{$p[$plet_id]['LastSavedValue']}' ;\n";


 $plet_str.="{$d}plet['{$clean_plet_id}']['enable_all']='{$p[$plet_id]['EnableAllValue']}' ;\n";
  $plet_str.="{$d}plet['{$clean_plet_id}']['all_label']='ALL' ;\n";
  $plet_str.="{$d}plet['{$clean_plet_id}']['all_value']='%' ;\n";
  $plet_str.="{$d}plet['{$clean_plet_id}']['display_members']='1';  //value decides whether it is a multilist combo or single selection ;\n";
  $plet_str.="{$d}plet['{$clean_plet_id}']['control_type']='LIST';  //In future, other values could be radio,slider,checkbox etc ;\n";
  $plet_str.="{$d}plet['{$clean_plet_id}']['default_null_value']='%';  // ;\n";
 $plet_str.="{$d}plet['{$clean_plet_id}']['static_values']='' ;\n";
  $plet_str.="{$d}plet['{$clean_plet_id}']['static_display_values']= {$d}plet['{$clean_plet_id}']['static_values']  ;\n";


if ($p[$plet_id]['DataType'] == 'PLET')
{
  if (preg_replace("/\'/","",$p[$plet_id]['IDColumn1'])!==$p[$plet_id]['IDColumn1'])
  {
   
    $plet_str.="{$d}plet['{$clean_plet_id}']['sql']= <<<EOD\n select \n {$p[$plet_id]['ValueColumn']} \n {$p[$plet_id]['sql']} \nEOD;\n";
  }
  else
  {
   
    $plet_str.="{$d}plet['{$clean_plet_id}']['sql']= <<<EOD\n select \n {$p[$plet_id]['ValueColumn']} \n,{$p[$plet_id]['IDColumn1']} \n {$p[$plet_id]['sql']} \nEOD;\n";
  }
}
else
    {
    $plet_str.="{$d}plet['{$clean_plet_id}']['sql']= <<<EOD\n{$p[$plet_id]['sql']}\nEOD;\n";
    }

//echo $plet_str."</br>\n";
 fwrite($dash_file_handle,$plet_str);


fwrite($dash_file_handle,"\n\n");

}//getPletDefinition($plet_id)

function getFormatStr($old_frmt)
{
  $old_frmt = str_replace("MMM","M",$old_frmt);
  $old_frmt = str_replace("MM","mm",$old_frmt);
 // $old_frmt = str_replace("M","m",$old_frmt);
  //$old_frmt = str_replace("yyyy","yy",$old_frmt);
  $old_frmt = str_replace("yy","y",$old_frmt);

  return $old_frmt;
}

 function startsWith($needle, $haystack)
 {
     return preg_match('/^'.preg_quote($needle)."/", $haystack);
 }

 function endsWith($needle, $haystack)
 {
     return preg_match("/".preg_quote($needle) .'$/', $haystack);
 }

function convertClass2Alignment(&$item1)
{
    if ($item1=='String')
    {
        $item1='left';
    }
    else
    {
        $item1='right';
    }
}

function cleanText($item1)
{
    $item1 = preg_replace("/[^A-Za-z0-9_]/","",$item1);
    return $item1;
   
}

function convertClass(&$item1)
{
    $item1 = str_replace("java.lang.","",$item1);


}



function convertOldSql($old_sql)
{
    global $original_plet_id;
    if  (!(isset($original_plet_id))) return $old_sql;

    $o_sql=$old_sql;
    $o_sql = str_replace("G_PARAM<", "#~", $o_sql);
    $o_sql = str_replace(":Display>", "#~", $o_sql);
    $o_sql = str_replace(":ID1>", "#~", $o_sql);
    $o_sql = str_replace(":ID2>", "#~", $o_sql);
    $o_sql = str_replace(":ID3>", "#~", $o_sql);
    $o_sql = str_replace(":ID4>", "#~", $o_sql);
    $o_sql = str_replace(":ID5>", "#~", $o_sql);

//echo "converted..".$o_sql;
    foreach ($original_plet_id as $k => $v)
    {
       // echo "$k - $v <br>\n";
       $o_sql = str_replace("#~".$k."#~","PVAL['".$v."']",$o_sql);
       //echo $o_sql;
    }

 return $o_sql;
}

//mapping of java to flash chart types
function defineChartTypes()
{
    global $new_chart_type;
    
    $new_chart_type['Bar']='chart_column';
    $new_chart_type['Bar3D']='chart_column';
    $new_chart_type['WaterFall']='chart_column';
    $new_chart_type['Pie']='chart_pie';
    $new_chart_type['Pie3D']='chart_3d pie';
    $new_chart_type['MultiPie']='chart_column';
    $new_chart_type['MultiPie3D']='chart_3d column';
    $new_chart_type['StackedBar']='chart_stacked column';
    $new_chart_type['StackedBar3D']='chart_stacked 3d column';
    $new_chart_type['Line']='chart_line';
    $new_chart_type['Line3D']='chart_line';
    $new_chart_type['Ring']='chart_donut';
    $new_chart_type['Area']='chart_area';
    $new_chart_type['StackedArea']='chart_stacked area';
    $new_chart_type['Meter']='gauge_meter';
    $new_chart_type['Thermometer']='gauge_thermometer';
    $new_chart_type['Dial']='gauge_dial';
    $new_chart_type['X-Y Series']='chart_line';
    $new_chart_type['Time Series']='chart_line';
    $new_chart_type['Bubble']='chart_bubble';
    $new_chart_type['Scatter']='chart_scatter';
    $new_chart_type['Polar']='chart_polar';


}

function addDateFunction(&$edit_option,$column_class)
{

 $cnt=count($column_class);
 for ($i=0;$i<$cnt; $i++)
   {
     
     if ($column_class[$i]=="java.sql.Date")
         {
           $edit_option[$i].=<<<EOD

                            ,editoptions: { size: 12,
				   dataInit: function(el)
                                            {
                                              $(el).datepicker({ dateFormat: 'mm/dd/yy' });
                                            }
					 }
EOD;

           //echo $edit_option[$i];
         }

  }
  return $edit_option;
}

function engineErrorHandler($errno, $errstr, $errfile, $errline)
{


global $dashboard_id;
global $dashboard_report;
global $report_file;
global $debug;

    //include_once "error_util.php";


 elog(-1,"------ \n   errno={$errno} \n   errstr={$errstr} \n   errfile={$errfile} \n   errline={$errline}");
    switch ($errno) {

	case E_WARNING:
             elog(-2,"convert2web engineErrorHandler E_WARNING= ".errorKill($errstr));
	   break;
	case E_NOTICE:
             elog(-3,"convert2web. engineErrorHandler  E_NOTICE= ".errorKill($errstr));
  	//echo "-------->Run-time notices.";
	  // $_SESSION["log_".$report_file]['error_e_notice'][$errno."-".$errline]=errorKill($errstr);
	   break;


    case E_USER_ERROR:
         elog(-1,"convert2web. engineErrorHandler  E_USER_Error= ".errorKill($errstr));
       // $_SESSION["log_".$report_file]['error_e_user_error'][$errno."-".$errline]=errorKill($errstr);
        break;

    case E_USER_WARNING:
         elog(-2,"convert2web. engineErrorHandler  E_USER_WARNING= ".errorKill($errstr));
	//$_SESSION["log_".$report_file]['error_e_user_warning'][$errno."-".$errline]=errorKill($errstr);


        break;

    case E_USER_NOTICE:
         elog(-3,"convert2web. engineErrorHandler  E_USER_NOTICE= ".errorKill($errstr));
    //$_SESSION["log_".$report_file]['error_e_user_notice'][$errno."-".$errline]=errorKill($errstr);

        break;

    default:
         elog(-1,"convert2web. engineErrorHandler  Other Error= ".errorKill($errstr));
       // $_SESSION["log_".$report_file]['error_e_other'][$errno."-".$errline]=errorKill($errstr);
	//echo "-----#### Other Error {$errno} #####------.";
        	//errorKill($errstr);
        break;
    }


    /* Don't execute PHP internal error handler */
    return true;
}

function errorKill($info)
{

    $out="<br>MSG='$info'";
    $bt=debug_backtrace();
    $sp=0;
    $trace="";
    foreach($bt as $k=>$v)
    {
        extract($v);
        $file=substr($file,1+strrpos($file,"/"));

        $trace.=str_repeat("&nbsp;",++$sp); //spaces(++$sp);
        $trace.="file=$file, line=$line, function=$function<br>";
    }
    $out.="<br>".$trace;
    if(substr($info,0,4)=="XXX ") // special errrors when db is inaccessible
    {
        $out=str_replace("<br>","\n",$out);
        $out=str_replace("&nbsp;"," ",$out);

    }
  return $out;

}

function start_log()
{
    $fd = fopen("log/conv_".session_id().".log", "w");
// append date/time to message
$str = "[" . date("Y/m/d h:i:s", mktime()) . "] " . "converstion start";
// write string
fwrite($fd, $str . "\n");
// close file
fclose($fd);

}

function elog($level, $msg)
{

    global $logging_enabled;
    global $log_level;

if (!($logging_enabled=='Y' && $log_level<=$level)) return;
// open file
$fd = fopen("log/conv_".session_id().".log", "a");
// append date/time to message
$str = "[" . date("Y/m/d h:i:s", mktime()) . "] " . $msg;
// write string
fwrite($fd, $str . "\n");
// close file
fclose($fd);
}

?>