Added an alternative way of presenting tax included on invoices.
[fa-stable.git] / includes / ui / ui_view.inc
1 <?php
2 /**********************************************************************
3     Copyright (C) FrontAccounting, LLC.
4         Released under the terms of the GNU General Public License, GPL, 
5         as published by the Free Software Foundation, either version 3 
6         of the License, or (at your option) any later version.
7     This program is distributed in the hope that it will be useful,
8     but WITHOUT ANY WARRANTY; without even the implied warranty of
9     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
10     See the License here <http://www.gnu.org/licenses/gpl-3.0.html>.
11 ***********************************************************************/
12 include_once($path_to_root . "/admin/db/voiding_db.inc");
13 include_once($path_to_root . "/includes/types.inc");
14
15 //--------------------------------------------------------------------------------------
16
17 function get_supplier_trans_view_str($type, $trans_no, $label="", $icon=false, 
18         $class='', $id='')
19 {
20         $viewer = "purchasing/view/";
21         if ($type == ST_PURCHORDER)
22                 $viewer .= "view_po.php";
23         elseif ($type == ST_SUPPINVOICE)
24                 $viewer .= "view_supp_invoice.php";
25         elseif ($type == ST_SUPPCREDIT)
26                 $viewer .= "view_supp_credit.php";
27         elseif ($type == ST_SUPPAYMENT)
28                 $viewer .= "view_supp_payment.php";
29         elseif ($type == ST_SUPPRECEIVE)
30                 $viewer .= "view_grn.php";
31         else
32                 return null;
33         $viewer .= "?trans_no=$trans_no";
34
35         if ($label == "")
36                 $label = $trans_no;
37
38         return viewer_link($label, $viewer, $class, $id,  $icon);
39 }
40
41 //--------------------------------------------------------------------------------------
42
43 function get_gl_view_str($type, $trans_no, $label="", $force=false, $class='', $id='')
44 {
45         if (!$force && !user_show_gl_info())
46                 return "";
47
48         $icon = false;
49         if ($label == "")
50         {
51                 $label = _("GL");
52                 $icon = ICON_GL;
53         }       
54
55         return viewer_link($label, 
56                 "gl/view/gl_trans_view.php?type_id=$type&trans_no=$trans_no", 
57                 $class, $id, $icon);
58 }
59
60 //--------------------------------------------------------------------------------------
61
62 function get_gl_view_str_cell($type, $trans_no, $label="")
63 {
64         $str = get_gl_view_str($type, $trans_no, $label);
65         if ($str != "")
66                 return "<td>$str</td>";
67 }
68
69 //--------------------------------------------------------------------------------------
70
71 function get_customer_trans_view_str($type, $trans_no, $label="", $icon=false, 
72         $class='', $id='')
73 {
74         $viewer = "sales/view/";
75
76         if ($type == ST_SALESINVOICE)
77                 $viewer .= "view_invoice.php";
78         elseif ($type == ST_CUSTCREDIT)
79                 $viewer .= "view_credit.php";
80         elseif ($type == ST_CUSTPAYMENT)
81                 $viewer .= "view_receipt.php";
82         elseif ($type == ST_CUSTDELIVERY)
83                 $viewer .= "view_dispatch.php";
84         elseif ($type == ST_SALESORDER || $type == ST_SALESQUOTE)
85                 $viewer .= "view_sales_order.php";
86         else
87                 return null;
88
89   if(!is_array($trans_no)) $trans_no = array($trans_no);
90
91   $lbl = $label;
92   $preview_str = '';
93
94   foreach($trans_no as $trans) {
95         if ($label == "")
96                 $lbl = $trans;
97         if($preview_str!='') $preview_str .= ',';
98
99         $preview_str .= viewer_link($lbl, $viewer."?trans_no=$trans&trans_type=$type", 
100                 $class, $id, $icon);
101
102   }
103   return $preview_str;
104 }
105
106 //--------------------------------------------------------------------------------------
107
108 function get_banking_trans_view_str($type, $trans_no, $label="", 
109         $icon=false, $class='', $id='')
110 {
111         if ($label == "")
112                 $label = $trans_no;
113
114         if ($type == ST_BANKTRANSFER)
115                 $viewer = "bank_transfer_view.php";
116         elseif ($type == ST_BANKPAYMENT)
117                 $viewer = "gl_payment_view.php";
118         elseif ($type == ST_BANKDEPOSIT)
119                 $viewer = "gl_deposit_view.php";
120         else
121                 return null;
122
123         return viewer_link($label, "gl/view/$viewer?trans_no=$trans_no", 
124                 $class, $id,  $icon);
125 }
126
127 //--------------------------------------------------------------------------------------
128
129 function get_inventory_trans_view_str($type, $trans_no, $label="", 
130         $icon=false, $class='', $id='')
131 {
132         $viewer = "inventory/view/";
133
134         if ($type == ST_INVADJUST)
135                 $viewer .= "view_adjustment.php";
136         elseif ($type == ST_LOCTRANSFER)
137                 $viewer .= "view_transfer.php";
138         else
139                 return null;
140         $viewer .= "?trans_no=$trans_no";
141
142         if ($label == "")
143                 $label = $trans_no;
144
145         return viewer_link($label, $viewer, $class, $id,  $icon);
146 }
147
148 //--------------------------------------------------------------------------------------
149
150 function get_manufacturing_trans_view_str($type, $trans_no, $label="", 
151         $icon=false, $class='', $id='')
152 {
153         $viewer = "manufacturing/view/";
154
155         if ($type == ST_MANUISSUE)
156                 $viewer .= "wo_issue_view.php";
157         elseif ($type == ST_MANURECEIVE)
158                 $viewer .= "wo_production_view.php";
159         elseif ($type == ST_WORKORDER)
160                 $viewer .= "work_order_view.php";
161         else
162                 return null;
163
164         $viewer .= "?trans_no=$trans_no";
165
166         if ($label == "")
167                 $label = $trans_no;
168
169         return viewer_link($label, $viewer, $class, $id,  $icon);
170 }
171
172 //--------------------------------------------------------------------------------------
173
174 function get_dimensions_trans_view_str($type, $trans_no, $label="", $icon=false, 
175         $class='', $id='')
176 {
177         if ($type == ST_DIMENSION)
178                 $viewer = "dimensions/view/view_dimension.php?trans_no=$trans_no";
179         else
180                 return null;
181
182         if ($label == "")
183                 $label = $trans_no;
184
185         return viewer_link($label, $viewer, $class, $id,  $icon);
186 }
187 /*
188         Journal entry or cost update postings link
189 */
190 function get_journal_trans_view_str($type, $trans_no, $label="", $icon=false, 
191         $class='', $id='')
192 {
193         if ($type == ST_JOURNAL || $type == ST_COSTUPDATE)
194                 $viewer = "gl/view/gl_trans_view.php?type_id=$type&trans_no=$trans_no";
195         else
196                 return null;
197
198         if ($label == "")
199                 $label = $trans_no;
200
201         return viewer_link($label, $viewer, $class, $id,  $icon);
202 }
203
204 //--------------------------------------------------------------------------------------
205
206 function get_trans_view_str($type, $trans_no, $label="", $icon=false, 
207         $class='', $id='')
208 {
209         $view_str = get_customer_trans_view_str($type, $trans_no, $label, $icon, $class, $id);
210         if ($view_str != null)
211                 return $view_str;
212
213         $view_str = get_supplier_trans_view_str($type, $trans_no, $label, $icon, $class, $id);
214         if ($view_str != null)
215                 return $view_str;
216
217         $view_str = get_banking_trans_view_str($type, $trans_no, $label, $icon, $class, $id);
218         if ($view_str != null)
219                 return $view_str;
220
221         $view_str = get_inventory_trans_view_str($type, $trans_no, $label, $icon, $class, $id);
222         if ($view_str != null)
223                 return $view_str;
224
225         $view_str = get_manufacturing_trans_view_str($type, $trans_no, $label, $icon, $class, $id);
226         if ($view_str != null)
227                 return $view_str;
228
229         $view_str = get_dimensions_trans_view_str($type, $trans_no, $label, $icon, $class, $id);
230         if ($view_str != null)
231                 return $view_str;
232
233         $view_str = get_journal_trans_view_str($type, $trans_no, $label, $icon, $class, $id);
234         if ($view_str != null)
235                 return $view_str;
236
237         return null;
238 }
239
240 //--------------------------------------------------------------------------------------
241 // Displays currency exchange rate for given date.
242 // When there is no exrate for today, 
243 // gets it form ECB and stores in local database.
244 //
245 function exchange_rate_display($from_currency, $to_currency, $date_, $edit_rate=false)
246 {
247     global $Ajax;
248
249         if ($from_currency != $to_currency)
250         {
251                 $comp_currency = get_company_currency();
252                 if ($from_currency == $comp_currency)
253                         $currency = $to_currency;
254                 else
255                         $currency = $from_currency;
256                 $rate = 0;
257                 if ($date_ == Today()) {
258                         $rate = get_date_exchange_rate($currency, $date_);
259                         if (!$rate) {
260                                 $row = get_currency($currency);
261                                 if ($row['auto_update']) {
262                                         $rate = retrieve_exrate($currency, $date_);
263                                         if ($rate) 
264                                                 add_exchange_rate($currency, $date_, $rate, $rate);
265                                 }
266                         }
267                 }
268                 if (!$rate)
269                         $rate = get_exchange_rate_from_home_currency($currency, $date_);
270                 if ($from_currency != $comp_currency)
271                         $rate = 1 / ($rate / get_exchange_rate_from_home_currency($to_currency, $date_));
272
273                 $rate = number_format2($rate, user_exrate_dec());
274                 if ($edit_rate)
275                         text_row(_("Exchange Rate:"), '_ex_rate', $rate, 8, 8, null, "", " $from_currency = 1 $to_currency"); 
276                 else
277                 label_row(_("Exchange Rate:"),"<span style='vertical-align:top;' id='_ex_rate'>$rate</span> $from_currency = 1 $to_currency" );
278                 $Ajax->addUpdate('_ex_rate','_ex_rate', $rate);
279         }
280 }
281
282 //--------------------------------------------------------------------------------------
283
284 function is_voided_display($type, $id, $label)
285 {
286         $void_entry = get_voided_entry($type, $id);
287
288         if ($void_entry == null)
289                 return false;
290
291         start_table(TABLESTYLE, "width=50%");
292         echo "<tr><td align=center><font color=red>$label</font><br>";
293         echo "<font color=red>" . _("Date Voided:") . " " . sql2date($void_entry["date_"]) . "</font><br>";
294         if (strlen($void_entry["memo_"]) > 0)
295                 echo "<center><font color=red>" . _("Memo:") . " " . $void_entry["memo_"] . "</font></center><br>";
296         echo "</td></tr>";
297         end_table(1);
298
299         return true;
300 }
301
302 //--------------------------------------------------------------------------------------
303
304 function comments_display_row($type, $id)
305 {
306         $comments = get_comments($type, $id);
307         if ($comments and db_num_rows($comments))
308         {
309                 echo "<tr><td colspan=15>";
310         while ($comment = db_fetch($comments))
311         {
312                 echo $comment["memo_"] . "<br>";
313         }
314                 echo "</td></tr>";
315         }
316 }
317
318 //--------------------------------------------------------------------------------------
319
320 function get_comments_string($type, $type_no)
321 {
322         $str_return = "";
323         $result = get_comments($type, $type_no);
324         while ($comment = db_fetch($result))
325         {
326                 if (strlen($str_return))
327                         $str_return = $str_return . " \n";
328                 $str_return = $str_return . $comment["memo_"];
329         }
330         return $str_return;
331 }
332
333 //--------------------------------------------------------------------------------------
334
335 function view_stock_status($stock_id, $description=null, $echo=true)
336 {
337         global $path_to_root;
338         if ($description)
339                 //hyperlink_params_separate($path_to_root . "/inventory/inquiry/stock_status.php", (user_show_codes()?$stock_id . " - ":"") . $description, "stock_id=$stock_id");
340                 $preview_str = "<a target='_blank' href='$path_to_root/inventory/inquiry/stock_status.php?stock_id=$stock_id' onclick=\"javascript:openWindow(this.href,this.target); return false;\" >". (user_show_codes()?$stock_id . " - ":"") . $description."</a>";
341         else
342                 //hyperlink_params_separate($path_to_root . "/inventory/inquiry/stock_status.php", $stock_id, "stock_id=$stock_id");
343                 $preview_str = "<a target='_blank' href='$path_to_root/inventory/inquiry/stock_status.php?stock_id=$stock_id' onclick=\"javascript:openWindow(this.href,this.target); return false;\" >$stock_id</a>";
344         if($echo)
345                 echo $preview_str;
346         return $preview_str;
347 }
348
349 function view_stock_status_cell($stock_id, $description=null)
350 {
351         echo "<td>";
352         view_stock_status($stock_id, $description);
353         echo "</td>";
354 }
355
356 //--------------------------------------------------------------------------------------
357
358 function display_debit_or_credit_cells($value)
359 {
360         $value = round2($value, user_price_dec());
361         if ($value >= 0)
362         {
363                 amount_cell($value);
364                 label_cell("");
365         }
366         elseif ($value < 0)
367         {
368                 label_cell("");
369                 amount_cell(abs($value));
370         }
371 }
372
373 //--------------------------------------------------------------------------------------
374
375 function display_customer_trans_tax_details($tax_items, $columns)
376 {
377         global $alternative_tax_include_on_docs;
378         $first = true;
379     while ($tax_item = db_fetch($tax_items))
380     {
381         $tax = number_format2($tax_item['amount'],user_price_dec());
382         if ($tax_item['included_in_price'])
383         {
384                         if (isset($alternative_tax_include_on_docs) && $alternative_tax_include_on_docs == 1)
385                         {
386                                 if ($first)
387                                         label_row(_("Total Tax Excluded"), number_format2($tax_item['net_amount'], user_price_dec()),
388                                                 "colspan=$columns align=right", "align=right");
389                         label_row($tax_item['tax_type_name'] . " (" . $tax_item['rate'] . "%)",
390                                 $tax, "colspan=$columns align=right", "align=right");
391                         $first = false;
392                 }
393                 else
394                         label_row(_("Included") . " " . $tax_item['tax_type_name'] . " (" . $tax_item['rate'] . "%) " .
395                                 _("Amount") . ": $tax", "", "colspan=$columns align=right", "align=right");
396         }                       
397         else
398                 label_row($tax_item['tax_type_name'] . " (" . $tax_item['rate'] . "%)",
399                         $tax, "colspan=$columns align=right", "align=right");
400     }
401 }
402
403 //--------------------------------------------------------------------------------------
404
405 function display_supp_trans_tax_details($tax_items, $columns)
406 {
407     while ($tax_item = db_fetch($tax_items))
408     {
409         $tax = number_format2(abs($tax_item['amount']),user_price_dec());
410         if ($tax_item['included_in_price'])
411                 label_row(_("Included") . " " . $tax_item['tax_type_name'] . " (" . $tax_item['rate'] . "%) " .
412                         _("Amount") . ": $tax", "colspan=$columns align=right", "align=right");
413         else
414                 label_row($tax_item['tax_type_name'] . " (" . $tax_item['rate'] . "%)",
415                         $tax, "colspan=$columns align=right", "align=right");
416     }
417 }
418
419 //--------------------------------------------------------------------------------------
420
421 function display_edit_tax_items($taxes, $columns, $tax_included, $leftspan=0)
422 {
423         $total = 0;
424
425     foreach ($taxes as $taxitem)
426     {
427         if ($tax_included)
428         {
429                 label_row(_("Included") . " " . $taxitem['tax_type_name'] . " (" . $taxitem['rate'] . "%) " .
430                         _("Amount:") . " " . number_format2($taxitem['Value'],user_price_dec()), "", "colspan=$columns align=right", "align=right",$leftspan);
431         }
432         else
433         {
434                 label_row($taxitem['tax_type_name'] . " (" . $taxitem['rate'] . "%)",
435                         number_format2($taxitem['Value'],user_price_dec()), "colspan=$columns align=right", "align=right",$leftspan);
436                 $total +=  round2($taxitem['Value'], user_price_dec());
437         }
438     }
439
440     return $total;
441 }
442
443 //--------------------------------------------------------------------------------------
444
445 function display_footer_exit()
446 {
447         br(2);
448         end_page(false, false, true);
449         exit;
450 }
451
452 //--------------------------------------------------------------------------------------
453
454 function display_allocations($alloc_result, $total)
455 {
456         global $systypes_array;
457
458         if (!$alloc_result || db_num_rows($alloc_result) == 0)
459                 return;
460
461     display_heading2(_("Allocations"));
462
463     start_table(TABLESTYLE, "width=80%");
464
465     $th = array( _("Type"), _("Number"), _("Date"), _("Total Amount"),
466         _("Left to Allocate"), _("This Allocation"));
467         table_header($th);
468     $k = $total_allocated = 0;
469
470     while ($alloc_row = db_fetch($alloc_result))
471     {
472
473         alt_table_row_color($k);
474
475         label_cell($systypes_array[$alloc_row['type']]);
476         label_cell(get_trans_view_str($alloc_row['type'],$alloc_row['trans_no']));
477         label_cell(sql2date($alloc_row['tran_date']));
478         $alloc_row['Total'] = round2($alloc_row['Total'], user_price_dec());
479         $alloc_row['amt'] = round2($alloc_row['amt'], user_price_dec());
480         amount_cell($alloc_row['Total']);
481         //amount_cell($alloc_row['Total'] - $alloc_row['PrevAllocs'] - $alloc_row['amt']);
482         amount_cell($alloc_row['Total'] - $alloc_row['amt']);
483         amount_cell($alloc_row['amt']);
484         end_row();
485
486         $total_allocated += $alloc_row['amt'];
487     }
488     start_row();
489         label_cell(_("Total Allocated:"), "align=right colspan=5");
490         amount_cell($total_allocated);
491         end_row();
492         start_row();
493     label_cell(_("Left to Allocate:"), "align=right colspan=5");
494     $total = round2($total, user_price_dec());
495     amount_cell($total - $total_allocated);
496     end_row();
497
498     end_table(1);
499 }
500
501 //--------------------------------------------------------------------------------------
502
503 function display_allocations_from($person_type, $person_id, $type, $type_no, $total)
504 {
505         switch ($person_type)
506         {
507                 case PT_CUSTOMER :
508                         $alloc_result = get_allocatable_to_cust_transactions($person_id, $type_no, $type);
509                         display_allocations($alloc_result, $total);
510                         return;
511                 case PT_SUPPLIER :
512                         $alloc_result = get_allocatable_to_supp_transactions($person_id, $type_no, $type);
513                         display_allocations($alloc_result, $total);
514                         return;
515         }
516 }
517
518 //--------------------------------------------------------------------------------------
519 //
520 //      Expands selected quick entry $id into GL posings and adds to cart.
521 //              returns calculated amount posted to bank GL account.
522 //
523 function display_quick_entries(&$cart, $id, $base, $type, $descr='')
524 {
525         $bank_amount = 0;
526         
527         if (!isset($id) || $id == null || $id == "")
528         {
529                 display_error( _("No Quick Entries are defined."));
530                 set_focus('totamount');
531         }
532         else
533         {
534                 if ($type == QE_DEPOSIT)
535                         $base = -$base;
536                 if ($type != QE_SUPPINV)        // only one quick entry on journal/bank transaction
537                         $cart->clear_items();
538                 $qe = get_quick_entry($id);
539                 if ($qe['bal_type'] == 1)
540                 {
541                         if ($qe['base_amount'] == 1.0) // monthly
542                                 $begin = begin_month($cart->tran_date);
543                         else
544                         {
545                                 if (is_account_balancesheet($qe['base_desc'])) // total
546                                         $begin = "";
547                                 else
548                                         $begin = begin_fiscalyear(); // from fiscalyear begin
549                         }               
550                         $base = get_gl_trans_from_to($begin, $cart->tran_date, $qe['base_desc']);
551                                 
552                 }
553                 if ($descr != '') $qe['description'] .= ': '.$descr;
554                 $result = get_quick_entry_lines($id);
555                 if (db_num_rows($result) == 0)
556                 {
557                         display_error( _("No Quick Entry lines are defined."));
558                         set_focus('totamount');
559                 }       
560                 $totrate = 0;
561                 while ($row = db_fetch($result))
562                 {
563                         $qe_lines[] = $row;
564
565                         switch (strtolower($row['action'])) {
566                                 case "t": // post taxes calculated on base amount
567                                 case "t+": // ditto & increase base amount
568                                 case "t-": // ditto & reduce base amount
569                                         if (substr($row['action'],0,1) != 'T') 
570                                                 $totrate += get_tax_type_default_rate($row['dest_id']);
571                         }
572                 }
573                 $first = true;
574                 $taxbase = 0;
575                 foreach($qe_lines as $qe_line)
576                 {
577                         switch (strtolower($qe_line['action'])) {
578                                 case "=": // post current base amount to GL account
579                                         $part = $base;
580                                         break;
581                                 case "a": // post amount to GL account and reduce base
582                                         $part = $qe_line['amount'];
583                                         break;
584                                 case "a+": // post amount to GL account and increase base
585                                         $part = $qe_line['amount']; $base += $part;
586                                         break;
587                                 case "a-": // post amount to GL account and reduce base
588                                         $part = $qe_line['amount']; $base -= $part;
589                                         break;
590                                 case "%":       // store acc*amount% to GL account
591                                         $part = round2($base * $qe_line['amount'] / 100, user_price_dec());
592                                         break;
593                                 case "%+":      // ditto & increase base amount
594                                         $part = round2($base * $qe_line['amount'] / 100, user_price_dec());
595                                         $base += $part;
596                                         break;
597                                 case "%-":      // ditto & reduce base amount
598                                         $part = round2($base * $qe_line['amount'] / 100, user_price_dec());
599                                         $base -= $part;
600                                         break;
601                                 case "t": // post taxes calculated on base amount
602                                 case "t+": // ditto & increase base amount
603                                 case "t-": // ditto & reduce base amount
604                                         if ($first)
605                                         {
606                                                 $taxbase = $base/($totrate+100);
607                                                 $first = false;
608                                         }
609
610                                         if (substr($qe_line['action'],0,1) != 'T') 
611                                                 $part = $taxbase;
612                                         else
613                                                 $part = $base/100;
614                                         $item_tax = get_tax_type($qe_line['dest_id']);
615                                         //if ($type == QE_SUPPINV && substr($qe_line['action'],0,1) != 'T')
616                                         if ($type == QE_SUPPINV)
617                                         {
618                                                 $taxgroup = $cart->tax_group_id;
619                                                 $rates = 0;
620                                                 $res = get_tax_group_items($cart->tax_group_id);
621                                                 while ($row = db_fetch($res))
622                                                         $rates += $row['rate'];
623                                                 if ($rates == 0)
624                                                         continue 2;
625                                         }
626                                         $tax = round2($part * $item_tax['rate'],  user_price_dec());
627                                         if ($tax==0) continue 2;
628                                         $gl_code = ($type == QE_DEPOSIT || ($type == QE_JOURNAL && $base < 0)) 
629                                                 ? $item_tax['sales_gl_code'] : $item_tax['purchasing_gl_code'];
630                                         if (!is_tax_gl_unique($gl_code)) {
631                                                 display_error(_("Cannot post to GL account used by more than one tax type."));
632                                                 break 2;
633                                         }
634                                         if ($type != QE_SUPPINV)
635                                                 $cart->add_gl_item($gl_code, 
636                                                         $qe_line['dimension_id'], $qe_line['dimension2_id'], 
637                                                         $tax, $qe['description']);
638                                         else 
639                                         {
640                                                 $acc_name = get_gl_account_name($gl_code);
641                                                 $cart->add_gl_codes_to_trans($gl_code, 
642                                                         $acc_name, $qe_line['dimension_id'], 
643                                                         $qe_line['dimension2_id'], $tax, $qe['description']);
644                                         }
645                                         if (strpos($qe_line['action'], '+'))
646                                                 $base += $tax;
647                                         elseif (strpos($qe_line['action'], '-'))
648                                                 $base -= $tax;
649                                         continue 2;
650                         }
651                         if ($type != QE_SUPPINV)
652                                 $cart->add_gl_item($qe_line['dest_id'], $qe_line['dimension_id'],
653                                         $qe_line['dimension2_id'], $part, $qe['description']);
654                         else 
655                         {
656                                 $acc_name = get_gl_account_name($qe_line['dest_id']);
657                                 $cart->add_gl_codes_to_trans($qe_line['dest_id'], 
658                                         $acc_name, $qe_line['dimension_id'], 
659                                         $qe_line['dimension2_id'], $part, $qe['description']);
660                         }
661                 }
662         }       
663         return $bank_amount;
664 }
665
666 //--------------------------------------------------------------------------------------
667 //
668 //      Simple English version of number to words conversion.
669 //
670 function _number_to_words($number) 
671
672     $Bn = floor($number / 1000000000); /* Billions (giga) */ 
673     $number -= $Bn * 1000000000; 
674     $Gn = floor($number / 1000000);  /* Millions (mega) */ 
675     $number -= $Gn * 1000000; 
676     $kn = floor($number / 1000);     /* Thousands (kilo) */ 
677     $number -= $kn * 1000; 
678     $Hn = floor($number / 100);      /* Hundreds (hecto) */ 
679     $number -= $Hn * 100; 
680     $Dn = floor($number / 10);       /* Tens (deca) */ 
681     $n = $number % 10;               /* Ones */
682
683     $res = ""; 
684
685     if ($Bn) 
686         $res .= _number_to_words($Bn) . " Billion"; 
687     if ($Gn) 
688         $res .= (empty($res) ? "" : " ") . _number_to_words($Gn) . " Million"; 
689     if ($kn) 
690         $res .= (empty($res) ? "" : " ") . _number_to_words($kn) . " Thousand"; 
691     if ($Hn) 
692         $res .= (empty($res) ? "" : " ") . _number_to_words($Hn) . " Hundred"; 
693
694     $ones = array("", "One", "Two", "Three", "Four", "Five", "Six", 
695         "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", 
696         "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eightteen", 
697         "Nineteen"); 
698     $tens = array("", "", "Twenty", "Thirty", "Fourty", "Fifty", "Sixty", 
699         "Seventy", "Eigthy", "Ninety"); 
700
701     if ($Dn || $n) 
702     { 
703         if (!empty($res)) 
704             $res .= " and "; 
705         if ($Dn < 2) 
706             $res .= $ones[$Dn * 10 + $n]; 
707         else 
708         { 
709             $res .= $tens[$Dn]; 
710             if ($n) 
711                 $res .= "-" . $ones[$n]; 
712         } 
713     } 
714
715     if (empty($res)) 
716         $res = "zero"; 
717     return $res; 
718
719
720 function price_in_words($amount, $document=0)
721 {
722         global $Hooks;
723         // use local price_in_words() if the hook is defined
724         if (method_exists($Hooks, 'price_in_words'))
725         {
726                 return $Hooks->price_in_words($amount, $document);
727         }
728         // Only usefor Remittance and Receipts as default
729         if (!($document == ST_SUPPAYMENT || $document == ST_CUSTPAYMENT || $document == ST_CHEQUE))
730                 return "";
731         if ($amount < 0 || $amount > 999999999999)
732                 return "";
733         $dec = user_price_dec();
734         if ($dec > 0)
735         {
736                 $divisor = pow(10, $dec);       
737                 $frac = round2($amount - floor($amount), $dec) * $divisor;
738                 $frac = sprintf("%0{$dec}d", $frac);
739                 $and = _("and");
740         $frac = " $and $frac/$divisor";
741     }
742     else
743         $frac = "";
744     return _number_to_words(intval($amount)) . $frac;
745 }    
746
747 function get_js_open_window($width, $height)
748 {
749         $js ="function openWindow(url, title)\n"
750                 . "{\n"
751                 . " var left = (screen.width - $width) / 2;\n"
752                 . " var top = (screen.height - $height) / 2;\n"
753                 . " return window.open(url, title, 'width=$width,height=$height,left='+left+',top='+top+',screenX='+left+',screenY='+top+',status=no,scrollbars=yes');\n"
754                 . "}\n";
755         return $js;
756 }
757
758 /*
759   Setting focus on element $name in $form.
760   If $form<0 $name is element id.
761 */
762 function set_focus($name, $form_no=0) {
763   global $Ajax;
764         $Ajax->addFocus(true, $name);
765     $_POST['_focus'] = $name;
766 }
767 //
768 //      Set default focus on first field $name if not set yet
769 //      Returns unique name if $name=null
770 //      
771 function default_focus($name=null, $form_no=0) {
772         static $next; 
773         if ($name==null) 
774                 $name = uniqid('_el',true);
775     if (!isset($_POST['_focus'])) {
776           set_focus($name);
777     }
778         return $name;
779 }
780 /*
781         Reset focus to next control element (e.g. link).
782 */
783 function reset_focus()
784 {
785         unset($_POST['_focus']);
786 }
787
788 function get_js_png_fix()
789 {
790         $js = "function fixPNG(myImage)\n"
791                 . "{\n"
792                 . " var arVersion = navigator.appVersion.split(\"MSIE\")\n"
793                 . " var version = parseFloat(arVersion[1])\n"
794         . " if ((version >= 5.5) && (version < 7) && (document.body.filters))\n"
795         . " {\n"
796         . "  var imgID = (myImage.id) ? \"id='\" + myImage.id + \"' \" : \"\"\n"
797                 . "  var imgClass = (myImage.className) ? \"class='\" + myImage.className + \"' \" : \"\"\n"
798                 . "  var imgTitle = (myImage.title) ?\n"
799                 . "    \"title='\" + myImage.title  + \"' \" : \"title='\" + myImage.alt + \"' \"\n"
800                 . "  var imgStyle = \"display:inline-block;\" + myImage.style.cssText\n"
801                 . "  var strNewHTML = \"<span \" + imgID + imgClass + imgTitle\n"
802         . "    + \" style=\\\"\" + \"width:\" + myImage.width\n"
803         . "    + \"px; height:\" + myImage.height\n"
804         . "    + \"px;\" + imgStyle + \";\"\n"
805         . "    + \"filter:progid:DXImageTransform.Microsoft.AlphaImageLoader\"\n"
806         . "    + \"(src=\'\" + myImage.src + \"\', sizingMethod='scale');\\\"></span>\"\n"
807                 . "  myImage.outerHTML = strNewHTML\n"
808         . " }\n"
809                 . "}\n";
810         return $js;
811 }
812
813 function get_js_date_picker()
814 {
815     global $go_debug;
816     $fpath = company_path().'/js_cache/'.'date_picker.js';
817
818     if (!file_exists($fpath) || $go_debug) {
819
820         global $dateseps, $date_system;
821
822         $how = user_date_format();                              // 0 = us/ca, 1 = eu, au, nz, 2 = jp, sw
823         $sep = $dateseps[user_date_sep()];              // date separator
824         $wstart = (($date_system == 1 || $date_system == 2 || $date_system == 3) ? 6 : ($how == 0 ? 0 : 1));    // weekstart (sun = 0, mon = 1)
825         $months = array(_("January"),_("February"),_("March"),_("April"),_("May"),_("June"),_("July"),_("August"),_("September"),_("October"),_("November"),_("December"));
826         $wdays = array(_("Su"),_("Mo"),_("Tu"),_("We"),_("Th"),_("Fr"),_("Sa"));
827         $wno = _("W"); // week no
828         $back = _("Back");
829         if ($date_system == 1)
830                 list($cyear, $cmon, $cday) = gregorian_to_jalali(date("Y"), date("n"), date("j"));
831         else if ($date_system == 2)
832                 list($cyear, $cmon, $cday) = gregorian_to_islamic(date("Y"), date("n"), date("j"));
833
834
835         $js = "
836 function positionInfo(object) {
837   var p_elm = object;
838   this.getElementLeft = getElementLeft;
839   function getElementLeft() {
840     var x = 0;
841     var elm;
842     if(typeof(p_elm) == 'object'){
843       elm = p_elm;
844     } else {
845       elm = document.getElementById(p_elm);
846     }
847     while (elm != null) {
848       x+= elm.offsetLeft;
849       elm = elm.offsetParent;
850     }
851     return parseInt(x);
852   }
853   this.getElementWidth = getElementWidth;
854   function getElementWidth(){
855     var elm;
856     if(typeof(p_elm) == 'object'){
857       elm = p_elm;
858     } else {
859       elm = document.getElementById(p_elm);
860     }
861     return parseInt(elm.offsetWidth);
862   }
863   this.getElementRight = getElementRight;
864   function getElementRight(){
865     return getElementLeft(p_elm) + getElementWidth(p_elm);
866   }
867   this.getElementTop = getElementTop;
868   function getElementTop() {
869     var y = 0;
870     var elm;
871     if(typeof(p_elm) == 'object'){
872       elm = p_elm;
873     } else {
874       elm = document.getElementById(p_elm);
875     }
876     while (elm != null) {
877       y+= elm.offsetTop;
878       elm = elm.offsetParent;
879     }
880     return parseInt(y);
881   }
882   this.getElementHeight = getElementHeight;
883   function getElementHeight(){
884     var elm;
885     if(typeof(p_elm) == 'object'){
886       elm = p_elm;
887     } else {
888       elm = document.getElementById(p_elm);
889     }
890     return parseInt(elm.offsetHeight);
891   }
892   this.getElementBottom = getElementBottom;
893   function getElementBottom(){
894     return getElementTop(p_elm) + getElementHeight(p_elm);
895   }
896 }
897 function CC() {
898   var calendarId = 'CC';
899   var currentYear = 0;
900   var currentMonth = 0;
901   var currentDay = 0;
902   var selectedYear = 0;
903   var selectedMonth = 0;
904   var selectedDay = 0;
905   var months = ['$months[0]','$months[1]','$months[2]','$months[3]','$months[4]','$months[5]','$months[6]','$months[7]','$months[8]','$months[9]','$months[10]','$months[11]'];
906   var wdays = ['$wdays[0]', '$wdays[1]', '$wdays[2]', '$wdays[3]', '$wdays[4]', '$wdays[5]', '$wdays[6]'];
907   var dateField = null;
908   function getProperty(p_property){
909     var p_elm = calendarId;
910     var elm = null;
911     if(typeof(p_elm) == 'object'){
912       elm = p_elm;
913     } else {
914       elm = document.getElementById(p_elm);
915     }
916     if (elm != null){
917       if(elm.style){
918         elm = elm.style;
919         if(elm[p_property]){
920           return elm[p_property];
921         } else {
922           return null;
923         }
924       } else {
925         return null;
926       }
927     }
928   }
929   function setElementProperty(p_property, p_value, p_elmId){
930     var p_elm = p_elmId;
931     var elm = null;
932     if(typeof(p_elm) == 'object'){
933       elm = p_elm;
934     } else {
935       elm = document.getElementById(p_elm);
936     }
937     if((elm != null) && (elm.style != null)){
938       elm = elm.style;
939       elm[ p_property ] = p_value;
940     }
941   }
942   function setProperty(p_property, p_value) {
943     setElementProperty(p_property, p_value, calendarId);
944   }
945   function getDaysInMonth(year, month) {
946 ";
947         if ($date_system == 1)
948                 $js .= "
949     return [31,31,31,31,31,31,30,30,30,30,30,(((((((year - ((year > 0) ? 474 : 473)) % 2820) + 474) + 38) * 682) % 2816) < 682 ? 30 : 29)][month-1];
950 ";
951         else if ($date_system == 2)
952                 $js .= "
953     return [30,29,30,29,30,29,30,29,30,29,30,(((((11 * year) + 14) % 30) < 11) ? 30 : 29)][month-1];
954 ";
955         else
956                 $js .= "
957     return [31,((!(year % 4 ) && ( (year % 100 ) || !( year % 400 ) ))?29:28),31,30,31,30,31,31,30,31,30,31][month-1];
958 ";
959         $js .= "
960   }
961   function getDayOfWeek(year, month, day) {
962 ";
963         if ($date_system == 1 || $date_system == 2)
964         {
965                 $js .= "
966         function mod(a, b)
967         {
968             return a - (b * Math.floor(a / b));
969         }
970         function jwday(j)
971         {
972             return mod(Math.floor((j + 1.5)), 7);
973         }
974 ";
975         if ($date_system == 1)
976                 $js .= "
977     var epbase, epyear, t;
978     epbase = year - ((year >= 0) ? 474 : 473);
979     epyear = 474 + mod(epbase, 2820);
980     t = day + ((month <= 7) ? ((month - 1) * 31) : (((month - 1) * 30) + 6)) +
981       Math.floor(((epyear * 682) - 110) / 2816) + (epyear - 1) * 365 +
982       Math.floor(epbase / 2820) * 1029983 + (1948320.5 - 1);
983 ";
984         else if ($date_system == 2)
985                 $js .= "
986         var t;
987         t = Math.floor((11 * year + 3) / 30) + 354 * year + 30 * month -
988           Math.floor((month - 1) / 2) + day + 1948440 - 385;
989 ";
990         $js .= "
991     return jwday(t);
992 ";
993         }
994         else
995                 $js .= "
996     var date = new Date(year,month-1,day)
997     return date.getDay();
998 ";
999         $js .= "
1000   }
1001   this.clearDate = clearDate;
1002   function clearDate() {
1003     dateField.value = '';
1004     hide();
1005   }
1006   this.getWeek = getWeek;
1007   function getWeek(year, month, day) {
1008 ";
1009         if ($how == 0)
1010                 $js .= "  day++;";
1011         $js .= "
1012     var date = new Date(year,month-1,day);
1013     var D = date.getDay();
1014     if(D == 0) D = 7;
1015     date.setDate(date.getDate() + (4 - D));
1016     var YN = date.getFullYear();
1017     var ZBDoCY = Math.floor((date.getTime() - new Date(YN, 0, 1, -6)) / 86400000);
1018     var WN = 1 + Math.floor(ZBDoCY / 7);
1019     return WN;
1020   }
1021   this.setDate = setDate;
1022   function setDate(year, month, day) {
1023     if (dateField) {
1024       if (month < 10) {month = '0' + month;}
1025       if (day < 10) {day = '0' + day;}
1026 ";
1027         if ($how == 0)
1028                 $js .= "
1029       var dateString = month+'$sep'+day+'$sep'+year;
1030 ";
1031         else if ($how == 1)
1032                 $js .= "
1033       var dateString = day+'$sep'+month+'$sep'+year;
1034 ";
1035         else
1036                 $js .= "
1037       var dateString = year+'$sep'+month+'$sep'+day;
1038 ";
1039         $js .= "
1040       dateField.value = dateString;
1041           setFocus(dateField.name);
1042         if(dateField.getAttribute('aspect')=='cdate')
1043       setElementProperty('color', (dateField.value==user.date ? 'black':'red'), dateField);
1044           if (dateField.className=='searchbox')
1045                 dateField.onblur();
1046       hide();
1047     }
1048     return;
1049   }
1050   this.changeMonth = changeMonth;
1051   function changeMonth(change) {
1052     currentMonth += change;
1053     currentDay = 0;
1054     if(currentMonth > 12) {
1055       currentMonth = 1;
1056       currentYear++;
1057     } else if(currentMonth < 1) {
1058       currentMonth = 12;
1059       currentYear--;
1060     }
1061     calendar = document.getElementById(calendarId);
1062     calendar.innerHTML = calendarDrawTable();
1063   }
1064   this.changeYear = changeYear;
1065   function changeYear(change) {
1066     currentYear += change;
1067     currentDay = 0;
1068     calendar = document.getElementById(calendarId);
1069     calendar.innerHTML = calendarDrawTable();
1070   }
1071   function getCurrentYear() {
1072     var year = new Date().getYear();
1073     if(year < 1900) year += 1900;
1074     return year;
1075   }
1076   function getCurrentMonth() {
1077     return new Date().getMonth() + 1;
1078   }
1079   function getCurrentDay() {
1080     return new Date().getDate();
1081   }
1082   function calendarDrawTable() {
1083     var dayOfMonth = 1;
1084     var wstart = $wstart;
1085     var wno = '&nbsp;$wno&nbsp;';
1086     var validDay = 0;
1087     var startDayOfWeek = getDayOfWeek(currentYear, currentMonth, dayOfMonth);
1088     var daysInMonth = getDaysInMonth(currentYear, currentMonth);
1089     var css_class = null; //CSS class for each day
1090     var table = \"<table cellspacing='0' cellpadding='0' border='0'>\";
1091     table += \"<tr class='header'>\";
1092     table += \"  <td colspan='2' class='previous'><a href='javascript:changeCCMonth(-1);'>&lt;</a><br><a href='javascript:changeCCYear(-1);'>&laquo;</a></td>\";
1093     table += \"  <td colspan='4' class='title'>\" + months[currentMonth-1] + \"<br>\" + currentYear + \"</td>\";
1094     table += \"  <td colspan='2' class='next'><a href='javascript:changeCCMonth(1);'>&gt;</a><br><a href='javascript:changeCCYear(1);'>&raquo;</a></td>\";
1095     table += \"</tr>\";
1096     table += \"<tr>\";
1097     table += \"<th class='weekno'>\"+wno+\"</th>\";
1098     for (var n=0; n<7; n++)
1099         table += \"<th>\" + wdays[(wstart+n)%7]+\"</th>\";
1100     table += \"</tr>\";
1101     for(var week=0; week < 6; week++) {
1102       table += \"<tr>\";
1103       for(var n=0; n < 7; n++) {
1104         dayOfWeek = (wstart+n)%7;
1105         if(week == 0 && startDayOfWeek == dayOfWeek) {
1106           validDay = 1;
1107         } else if (validDay == 1 && dayOfMonth > daysInMonth) {
1108           validDay = 0;
1109         }
1110         if (n==0)
1111         {
1112                 if (dayOfMonth > daysInMonth)
1113                         table += \"<td class='empty'>&nbsp;</td>\";
1114                 else
1115                         table += \"<td class='weekno'>\"+getWeek(currentYear, currentMonth, dayOfMonth)+\"</td>\";
1116         }
1117         if(validDay) {
1118           if (dayOfMonth == selectedDay && currentYear == selectedYear && currentMonth == selectedMonth) {
1119             css_class = 'current';
1120 ";
1121         if ($date_system == 1 || $date_system == 2 || $date_system == 3)
1122                 $js .= "
1123           } else if (dayOfWeek == 5) {
1124 ";
1125         else
1126                 $js .= "
1127           } else if (dayOfWeek == 0 || dayOfWeek == 6) {
1128 ";
1129                 $js .= "
1130             css_class = 'weekend';
1131           } else {
1132             css_class = 'weekday';
1133           }
1134           table += \"<td><a class='\"+css_class+\"' href=\\\"javascript:setCCDate(\"+currentYear+\",\"+currentMonth+\",\"+dayOfMonth+\")\\\">\"+dayOfMonth+\"</a></td>\";
1135           dayOfMonth++;
1136         } else {
1137           table += \"<td class='empty'>&nbsp;</td>\";
1138         }
1139       }
1140       table += \"</tr>\";
1141     }
1142     table += \"<tr class='header'><th colspan='8' style='padding: 3px;text-align:center;'><a href='javascript:hideCC();'>$back</a></td></tr>\";
1143     table += \"</table>\";
1144     return table;
1145   }
1146   this.show = show;
1147   function show(field) {
1148     can_hide = 0;
1149     if (dateField == field) {
1150       return;
1151     } else {
1152       dateField = field;
1153     }
1154     if(dateField) {
1155       try {
1156         var dateString = new String(dateField.value);
1157         var dateParts = dateString.split('$sep');
1158 ";
1159         if ($how == 0)
1160                 $js .= "
1161         selectedMonth = parseInt(dateParts[0],10);
1162         selectedDay = parseInt(dateParts[1],10);
1163         selectedYear = parseInt(dateParts[2],10);
1164 ";
1165         else if ($how == 1)
1166                 $js .= "
1167         selectedDay = parseInt(dateParts[0],10);
1168         selectedMonth = parseInt(dateParts[1],10);
1169         selectedYear = parseInt(dateParts[2],10);
1170 ";
1171         else
1172                 $js .= "
1173         selectedYear = parseInt(dateParts[0],10);
1174         selectedMonth = parseInt(dateParts[1],10);
1175         selectedDay = parseInt(dateParts[2],10);
1176 ";
1177         $js .= "
1178       } catch(e) {}
1179     }
1180     if (!(selectedYear && selectedMonth && selectedDay)) {
1181 ";
1182         if ($date_system == 1 || $date_system == 2)
1183         {
1184                 $js .= "
1185       selectedMonth = $cmon;
1186       selectedDay = $cday;
1187       selectedYear = $cyear;
1188 ";
1189         }
1190         else
1191         {
1192                 $js .= "
1193       selectedMonth = getCurrentMonth();
1194       selectedDay = getCurrentDay();
1195       selectedYear = getCurrentYear();
1196 ";
1197         }
1198         $js .= "
1199     }
1200     currentMonth = selectedMonth;
1201     currentDay = selectedDay;
1202     currentYear = selectedYear;
1203     if(document.getElementById){
1204       calendar = document.getElementById(calendarId);
1205       calendar.innerHTML = calendarDrawTable(currentYear, currentMonth);
1206       var fieldPos = new positionInfo(dateField);
1207       var calendarPos = new positionInfo(calendarId);
1208       var x = fieldPos.getElementLeft();
1209       var y = fieldPos.getElementBottom();
1210       setProperty('left', x + 'px');
1211       setProperty('top', y + 'px');
1212       setProperty('display', 'block');
1213       if (document.all) {
1214         setElementProperty('left', x + 'px', 'CCIframe');
1215         setElementProperty('top', y + 'px', 'CCIframe');
1216         setElementProperty('width', calendarPos.getElementWidth() + 'px', 'CCIframe');
1217         setElementProperty('height', calendarPos.getElementHeight() + 'px', 'CCIframe');
1218         setElementProperty('display', 'block', 'CCIframe');
1219       }
1220     }
1221   }
1222   this.hide = hide;
1223   function hide() {
1224     if(dateField) {
1225       setProperty('display', 'none');
1226       setElementProperty('display', 'none', 'CCIframe');
1227       dateField = null;
1228     }
1229   }
1230   this.visible = visible;
1231   function visible() {
1232     return dateField
1233   }
1234   this.can_hide = can_hide;
1235   var can_hide = 0;
1236 }
1237 var cC = new CC();
1238 function date_picker(textField) {
1239   cC.show(textField);
1240 }
1241 function hideCC() {
1242   if (cC.visible()) {
1243     cC.hide();
1244   }
1245 }
1246 function setCCDate(year, month, day) {
1247   cC.setDate(year, month, day);
1248 }
1249 function changeCCYear(change) {
1250   cC.changeYear(change);
1251 }
1252 function changeCCMonth(change) {
1253   cC.changeMonth(change);
1254 }
1255 document.write(\"<iframe id='CCIframe' src='javascript:false;' frameBorder='0' scrolling='no'></iframe>\");
1256 document.write(\"<div id='CC'></div>\");";
1257
1258      cache_js_file($fpath, $js);
1259     }
1260     add_js_ufile($fpath);
1261
1262  return '';
1263 }
1264
1265 function alert($msg)
1266 {
1267         echo "\n<script type=\"text/javascript\">\n"
1268                 . "<!--\n"
1269                 . "alert('$msg');\n"
1270                 . "-->\n"
1271                 . "</script>\n";
1272 }
1273
1274 if (!function_exists('_vd'))
1275 {
1276         function _vd($mixed, $title = '', $exit = false)
1277         {
1278         // Only the site admin is able to proceed here.
1279         $str = (!empty($title) ? ($title .':') : '') .'<pre>';
1280         $str .= print_r($mixed, true); //var_dump($mixed);
1281         $str .= "</pre>\n";
1282                 display_notification('<table><tr><td>'.$str.'</td></tr></table>');
1283         if ($exit)
1284                 exit;
1285         }
1286 }
1287
1288 function display_backtrace($cond=true, $msg='') {
1289
1290         if ($cond) {
1291                 if ($msg) 
1292                         $str = "<center><span class='headingtext'>$msg</span></center>\n";
1293                 else
1294                         $str = '';
1295                 $str .= '<table border=0>';
1296         $trace = debug_backtrace();
1297                 foreach($trace as $trn => $tr) {
1298                         if (!$trn) continue;
1299                         $str .= '<tr><td>';
1300                         $str .= $tr['file'].':'.$tr['line'].': ';
1301                         $str .= '</td><td>';
1302                         if (isset($tr['type'])) {
1303                                 if($tr['type'] == '::') {
1304                                         $str .= $tr['class'].'::';
1305                                 } else if($tr['type'] == '->') {
1306                                         $str .= '('.$tr['class'].' Object)'.'->';
1307                                 }
1308                         }
1309                         foreach($tr['args'] as $n=>$a) {
1310                                 if (is_object($tr['args'][$n]))
1311                                         $tr['args'][$n] = "(".get_class($tr['args'][$n])." Object)";
1312                                 if (is_array($tr['args'][$n]))
1313                                         $tr['args'][$n] = "(Array[".count($tr['args'][$n])."])";
1314                                 else
1315                                         $tr['args'][$n] = "'".$tr['args'][$n]."'";
1316                         }
1317                         $str .= $tr['function'].'('. implode(',',$tr['args']).')</td>';
1318
1319                         $str .= '</tr>';
1320                 }
1321                 
1322                 $str .= '</table>';
1323         display_error($str);
1324         }
1325 }
1326
1327 ?>