19e94b3e188dff830cdc5f0d7c18d54748580d8c
[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     while ($tax_item = db_fetch($tax_items))
378     {
379         $tax = number_format2($tax_item['amount'],user_price_dec());
380         if ($tax_item['included_in_price'])
381                 label_row(_("Included") . " " . $tax_item['tax_type_name'] . " (" . $tax_item['rate'] . "%) " .
382                         _("Amount") . ": $tax", "", "colspan=$columns align=right", "align=right");
383         else
384                 label_row($tax_item['tax_type_name'] . " (" . $tax_item['rate'] . "%)",
385                         $tax, "colspan=$columns align=right", "align=right");
386     }
387 }
388
389 //--------------------------------------------------------------------------------------
390
391 function display_supp_trans_tax_details($tax_items, $columns)
392 {
393     while ($tax_item = db_fetch($tax_items))
394     {
395         $tax = number_format2(abs($tax_item['amount']),user_price_dec());
396         if ($tax_item['included_in_price'])
397                 label_row(_("Included") . " " . $tax_item['tax_type_name'] . " (" . $tax_item['rate'] . "%) " .
398                         _("Amount") . ": $tax", "colspan=$columns align=right", "align=right");
399         else
400                 label_row($tax_item['tax_type_name'] . " (" . $tax_item['rate'] . "%)",
401                         $tax, "colspan=$columns align=right", "align=right");
402     }
403 }
404
405 //--------------------------------------------------------------------------------------
406
407 function display_edit_tax_items($taxes, $columns, $tax_included, $leftspan=0)
408 {
409         $total = 0;
410
411     foreach ($taxes as $taxitem)
412     {
413         if ($tax_included)
414         {
415                 label_row(_("Included") . " " . $taxitem['tax_type_name'] . " (" . $taxitem['rate'] . "%) " .
416                         _("Amount:") . " " . number_format2($taxitem['Value'],user_price_dec()), "", "colspan=$columns align=right", "align=right",$leftspan);
417         }
418         else
419         {
420                 label_row($taxitem['tax_type_name'] . " (" . $taxitem['rate'] . "%)",
421                         number_format2($taxitem['Value'],user_price_dec()), "colspan=$columns align=right", "align=right",$leftspan);
422                 $total +=  round2($taxitem['Value'], user_price_dec());
423         }
424     }
425
426     return $total;
427 }
428
429 //--------------------------------------------------------------------------------------
430
431 function display_footer_exit()
432 {
433         br(2);
434         end_page(false, false, true);
435         exit;
436 }
437
438 //--------------------------------------------------------------------------------------
439
440 function display_allocations($alloc_result, $total)
441 {
442         global $systypes_array;
443
444         if (!$alloc_result || db_num_rows($alloc_result) == 0)
445                 return;
446
447     display_heading2(_("Allocations"));
448
449     start_table(TABLESTYLE, "width=80%");
450
451     $th = array( _("Type"), _("Number"), _("Date"), _("Total Amount"),
452         _("Left to Allocate"), _("This Allocation"));
453         table_header($th);
454     $k = $total_allocated = 0;
455
456     while ($alloc_row = db_fetch($alloc_result))
457     {
458
459         alt_table_row_color($k);
460
461         label_cell($systypes_array[$alloc_row['type']]);
462         label_cell(get_trans_view_str($alloc_row['type'],$alloc_row['trans_no']));
463         label_cell(sql2date($alloc_row['tran_date']));
464         $alloc_row['Total'] = round2($alloc_row['Total'], user_price_dec());
465         $alloc_row['amt'] = round2($alloc_row['amt'], user_price_dec());
466         amount_cell($alloc_row['Total']);
467         //amount_cell($alloc_row['Total'] - $alloc_row['PrevAllocs'] - $alloc_row['amt']);
468         amount_cell($alloc_row['Total'] - $alloc_row['amt']);
469         amount_cell($alloc_row['amt']);
470         end_row();
471
472         $total_allocated += $alloc_row['amt'];
473     }
474     start_row();
475         label_cell(_("Total Allocated:"), "align=right colspan=5");
476         amount_cell($total_allocated);
477         end_row();
478         start_row();
479     label_cell(_("Left to Allocate:"), "align=right colspan=5");
480     $total = round2($total, user_price_dec());
481     amount_cell($total - $total_allocated);
482     end_row();
483
484     end_table(1);
485 }
486
487 //--------------------------------------------------------------------------------------
488
489 function display_allocations_from($person_type, $person_id, $type, $type_no, $total)
490 {
491         switch ($person_type)
492         {
493                 case PT_CUSTOMER :
494                         $alloc_result = get_allocatable_to_cust_transactions($person_id, $type_no, $type);
495                         display_allocations($alloc_result, $total);
496                         return;
497                 case PT_SUPPLIER :
498                         $alloc_result = get_allocatable_to_supp_transactions($person_id, $type_no, $type);
499                         display_allocations($alloc_result, $total);
500                         return;
501         }
502 }
503
504 //--------------------------------------------------------------------------------------
505 //
506 //      Expands selected quick entry $id into GL posings and adds to cart.
507 //              returns calculated amount posted to bank GL account.
508 //
509 function display_quick_entries(&$cart, $id, $base, $type, $descr='')
510 {
511         $bank_amount = 0;
512         
513         if (!isset($id) || $id == null || $id == "")
514         {
515                 display_error( _("No Quick Entries are defined."));
516                 set_focus('totamount');
517         }
518         else
519         {
520                 if ($type == QE_DEPOSIT)
521                         $base = -$base;
522                 if ($type != QE_SUPPINV)        // only one quick entry on journal/bank transaction
523                         $cart->clear_items();
524                 $qe = get_quick_entry($id);
525                 if ($qe['bal_type'] == 1)
526                 {
527                         if ($qe['base_amount'] == 1.0) // monthly
528                                 $begin = begin_month($cart->tran_date);
529                         else
530                         {
531                                 if (is_account_balancesheet($qe['base_desc'])) // total
532                                         $begin = "";
533                                 else
534                                         $begin = begin_fiscalyear(); // from fiscalyear begin
535                         }               
536                         $base = get_gl_trans_from_to($begin, $cart->tran_date, $qe['base_desc']);
537                                 
538                 }
539                 if ($descr != '') $qe['description'] .= ': '.$descr;
540                 $result = get_quick_entry_lines($id);
541                 if (db_num_rows($result) == 0)
542                 {
543                         display_error( _("No Quick Entry lines are defined."));
544                         set_focus('totamount');
545                 }       
546                 $totrate = 0;
547                 while ($row = db_fetch($result))
548                 {
549                         $qe_lines[] = $row;
550
551                         switch (strtolower($row['action'])) {
552                                 case "t": // post taxes calculated on base amount
553                                 case "t+": // ditto & increase base amount
554                                 case "t-": // ditto & reduce base amount
555                                         if (substr($row['action'],0,1) != 'T') 
556                                                 $totrate += get_tax_type_default_rate($row['dest_id']);
557                         }
558                 }
559                 $first = true;
560                 $taxbase = 0;
561                 foreach($qe_lines as $qe_line)
562                 {
563                         switch (strtolower($qe_line['action'])) {
564                                 case "=": // post current base amount to GL account
565                                         $part = $base;
566                                         break;
567                                 case "a": // post amount to GL account and reduce base
568                                         $part = $qe_line['amount'];
569                                         break;
570                                 case "a+": // post amount to GL account and increase base
571                                         $part = $qe_line['amount']; $base += $part;
572                                         break;
573                                 case "a-": // post amount to GL account and reduce base
574                                         $part = $qe_line['amount']; $base -= $part;
575                                         break;
576                                 case "%":       // store acc*amount% to GL account
577                                         $part = round2($base * $qe_line['amount'] / 100, user_price_dec());
578                                         break;
579                                 case "%+":      // ditto & increase base amount
580                                         $part = round2($base * $qe_line['amount'] / 100, user_price_dec());
581                                         $base += $part;
582                                         break;
583                                 case "%-":      // ditto & reduce base amount
584                                         $part = round2($base * $qe_line['amount'] / 100, user_price_dec());
585                                         $base -= $part;
586                                         break;
587                                 case "t": // post taxes calculated on base amount
588                                 case "t+": // ditto & increase base amount
589                                 case "t-": // ditto & reduce base amount
590                                         if ($first)
591                                         {
592                                                 $taxbase = $base/($totrate+100);
593                                                 $first = false;
594                                         }
595
596                                         if (substr($qe_line['action'],0,1) != 'T') 
597                                                 $part = $taxbase;
598                                         else
599                                                 $part = $base/100;
600                                         $item_tax = get_tax_type($qe_line['dest_id']);
601                                         //if ($type == QE_SUPPINV && substr($qe_line['action'],0,1) != 'T')
602                                         if ($type == QE_SUPPINV)
603                                         {
604                                                 $taxgroup = $cart->tax_group_id;
605                                                 $rates = 0;
606                                                 $res = get_tax_group_items($cart->tax_group_id);
607                                                 while ($row = db_fetch($res))
608                                                         $rates += $row['rate'];
609                                                 if ($rates == 0)
610                                                         continue 2;
611                                         }
612                                         $tax = round2($part * $item_tax['rate'],  user_price_dec());
613                                         if ($tax==0) continue 2;
614                                         $gl_code = ($type == QE_DEPOSIT || ($type == QE_JOURNAL && $base < 0)) 
615                                                 ? $item_tax['sales_gl_code'] : $item_tax['purchasing_gl_code'];
616                                         if (!is_tax_gl_unique($gl_code)) {
617                                                 display_error(_("Cannot post to GL account used by more than one tax type."));
618                                                 break 2;
619                                         }
620                                         if ($type != QE_SUPPINV)
621                                                 $cart->add_gl_item($gl_code, 
622                                                         $qe_line['dimension_id'], $qe_line['dimension2_id'], 
623                                                         $tax, $qe['description']);
624                                         else 
625                                         {
626                                                 $acc_name = get_gl_account_name($gl_code);
627                                                 $cart->add_gl_codes_to_trans($gl_code, 
628                                                         $acc_name, $qe_line['dimension_id'], 
629                                                         $qe_line['dimension2_id'], $tax, $qe['description']);
630                                         }
631                                         if (strpos($qe_line['action'], '+'))
632                                                 $base += $tax;
633                                         elseif (strpos($qe_line['action'], '-'))
634                                                 $base -= $tax;
635                                         continue 2;
636                         }
637                         if ($type != QE_SUPPINV)
638                                 $cart->add_gl_item($qe_line['dest_id'], $qe_line['dimension_id'],
639                                         $qe_line['dimension2_id'], $part, $qe['description']);
640                         else 
641                         {
642                                 $acc_name = get_gl_account_name($qe_line['dest_id']);
643                                 $cart->add_gl_codes_to_trans($qe_line['dest_id'], 
644                                         $acc_name, $qe_line['dimension_id'], 
645                                         $qe_line['dimension2_id'], $part, $qe['description']);
646                         }
647                 }
648         }       
649         return $bank_amount;
650 }
651
652 //--------------------------------------------------------------------------------------
653 //
654 //      Simple English version of number to words conversion.
655 //
656 function _number_to_words($number) 
657
658     $Bn = floor($number / 1000000000); /* Billions (giga) */ 
659     $number -= $Bn * 1000000000; 
660     $Gn = floor($number / 1000000);  /* Millions (mega) */ 
661     $number -= $Gn * 1000000; 
662     $kn = floor($number / 1000);     /* Thousands (kilo) */ 
663     $number -= $kn * 1000; 
664     $Hn = floor($number / 100);      /* Hundreds (hecto) */ 
665     $number -= $Hn * 100; 
666     $Dn = floor($number / 10);       /* Tens (deca) */ 
667     $n = $number % 10;               /* Ones */
668
669     $res = ""; 
670
671     if ($Bn) 
672         $res .= _number_to_words($Bn) . " Billion"; 
673     if ($Gn) 
674         $res .= (empty($res) ? "" : " ") . _number_to_words($Gn) . " Million"; 
675     if ($kn) 
676         $res .= (empty($res) ? "" : " ") . _number_to_words($kn) . " Thousand"; 
677     if ($Hn) 
678         $res .= (empty($res) ? "" : " ") . _number_to_words($Hn) . " Hundred"; 
679
680     $ones = array("", "One", "Two", "Three", "Four", "Five", "Six", 
681         "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", 
682         "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eightteen", 
683         "Nineteen"); 
684     $tens = array("", "", "Twenty", "Thirty", "Fourty", "Fifty", "Sixty", 
685         "Seventy", "Eigthy", "Ninety"); 
686
687     if ($Dn || $n) 
688     { 
689         if (!empty($res)) 
690             $res .= " and "; 
691         if ($Dn < 2) 
692             $res .= $ones[$Dn * 10 + $n]; 
693         else 
694         { 
695             $res .= $tens[$Dn]; 
696             if ($n) 
697                 $res .= "-" . $ones[$n]; 
698         } 
699     } 
700
701     if (empty($res)) 
702         $res = "zero"; 
703     return $res; 
704
705
706 function price_in_words($amount, $document=0)
707 {
708         global $Hooks;
709         // use local price_in_words() if the hook is defined
710         if (method_exists($Hooks, 'price_in_words'))
711         {
712                 return $Hooks->price_in_words($amount, $document);
713         }
714         // Only usefor Remittance and Receipts as default
715         if (!($document == ST_SUPPAYMENT || $document == ST_CUSTPAYMENT || $document == ST_CHEQUE))
716                 return "";
717         if ($amount < 0 || $amount > 999999999999)
718                 return "";
719         $dec = user_price_dec();
720         if ($dec > 0)
721         {
722                 $divisor = pow(10, $dec);       
723                 $frac = round2($amount - floor($amount), $dec) * $divisor;
724                 $frac = sprintf("%0{$dec}d", $frac);
725                 $and = _("and");
726         $frac = " $and $frac/$divisor";
727     }
728     else
729         $frac = "";
730     return _number_to_words(intval($amount)) . $frac;
731 }    
732
733 function get_js_open_window($width, $height)
734 {
735         $js ="function openWindow(url, title)\n"
736                 . "{\n"
737                 . " var left = (screen.width - $width) / 2;\n"
738                 . " var top = (screen.height - $height) / 2;\n"
739                 . " return window.open(url, title, 'width=$width,height=$height,left='+left+',top='+top+',screenX='+left+',screenY='+top+',status=no,scrollbars=yes');\n"
740                 . "}\n";
741         return $js;
742 }
743
744 /*
745   Setting focus on element $name in $form.
746   If $form<0 $name is element id.
747 */
748 function set_focus($name, $form_no=0) {
749   global $Ajax;
750         $Ajax->addFocus(true, $name);
751     $_POST['_focus'] = $name;
752 }
753 //
754 //      Set default focus on first field $name if not set yet
755 //      Returns unique name if $name=null
756 //      
757 function default_focus($name=null, $form_no=0) {
758         static $next; 
759         if ($name==null) 
760                 $name = uniqid('_el',true);
761     if (!isset($_POST['_focus'])) {
762           set_focus($name);
763     }
764         return $name;
765 }
766 /*
767         Reset focus to next control element (e.g. link).
768 */
769 function reset_focus()
770 {
771         unset($_POST['_focus']);
772 }
773
774 function get_js_png_fix()
775 {
776         $js = "function fixPNG(myImage)\n"
777                 . "{\n"
778                 . " var arVersion = navigator.appVersion.split(\"MSIE\")\n"
779                 . " var version = parseFloat(arVersion[1])\n"
780         . " if ((version >= 5.5) && (version < 7) && (document.body.filters))\n"
781         . " {\n"
782         . "  var imgID = (myImage.id) ? \"id='\" + myImage.id + \"' \" : \"\"\n"
783                 . "  var imgClass = (myImage.className) ? \"class='\" + myImage.className + \"' \" : \"\"\n"
784                 . "  var imgTitle = (myImage.title) ?\n"
785                 . "    \"title='\" + myImage.title  + \"' \" : \"title='\" + myImage.alt + \"' \"\n"
786                 . "  var imgStyle = \"display:inline-block;\" + myImage.style.cssText\n"
787                 . "  var strNewHTML = \"<span \" + imgID + imgClass + imgTitle\n"
788         . "    + \" style=\\\"\" + \"width:\" + myImage.width\n"
789         . "    + \"px; height:\" + myImage.height\n"
790         . "    + \"px;\" + imgStyle + \";\"\n"
791         . "    + \"filter:progid:DXImageTransform.Microsoft.AlphaImageLoader\"\n"
792         . "    + \"(src=\'\" + myImage.src + \"\', sizingMethod='scale');\\\"></span>\"\n"
793                 . "  myImage.outerHTML = strNewHTML\n"
794         . " }\n"
795                 . "}\n";
796         return $js;
797 }
798
799 function get_js_date_picker()
800 {
801     global $go_debug;
802     $fpath = company_path().'/js_cache/'.'date_picker.js';
803
804     if (!file_exists($fpath) || $go_debug) {
805
806         global $dateseps, $date_system;
807
808         $how = user_date_format();                              // 0 = us/ca, 1 = eu, au, nz, 2 = jp, sw
809         $sep = $dateseps[user_date_sep()];              // date separator
810         $wstart = (($date_system == 1 || $date_system == 2 || $date_system == 3) ? 6 : ($how == 0 ? 0 : 1));    // weekstart (sun = 0, mon = 1)
811         $months = array(_("January"),_("February"),_("March"),_("April"),_("May"),_("June"),_("July"),_("August"),_("September"),_("October"),_("November"),_("December"));
812         $wdays = array(_("Su"),_("Mo"),_("Tu"),_("We"),_("Th"),_("Fr"),_("Sa"));
813         $wno = _("W"); // week no
814         $back = _("Back");
815         if ($date_system == 1)
816                 list($cyear, $cmon, $cday) = gregorian_to_jalali(date("Y"), date("n"), date("j"));
817         else if ($date_system == 2)
818                 list($cyear, $cmon, $cday) = gregorian_to_islamic(date("Y"), date("n"), date("j"));
819
820
821         $js = "
822 function positionInfo(object) {
823   var p_elm = object;
824   this.getElementLeft = getElementLeft;
825   function getElementLeft() {
826     var x = 0;
827     var elm;
828     if(typeof(p_elm) == 'object'){
829       elm = p_elm;
830     } else {
831       elm = document.getElementById(p_elm);
832     }
833     while (elm != null) {
834       x+= elm.offsetLeft;
835       elm = elm.offsetParent;
836     }
837     return parseInt(x);
838   }
839   this.getElementWidth = getElementWidth;
840   function getElementWidth(){
841     var elm;
842     if(typeof(p_elm) == 'object'){
843       elm = p_elm;
844     } else {
845       elm = document.getElementById(p_elm);
846     }
847     return parseInt(elm.offsetWidth);
848   }
849   this.getElementRight = getElementRight;
850   function getElementRight(){
851     return getElementLeft(p_elm) + getElementWidth(p_elm);
852   }
853   this.getElementTop = getElementTop;
854   function getElementTop() {
855     var y = 0;
856     var elm;
857     if(typeof(p_elm) == 'object'){
858       elm = p_elm;
859     } else {
860       elm = document.getElementById(p_elm);
861     }
862     while (elm != null) {
863       y+= elm.offsetTop;
864       elm = elm.offsetParent;
865     }
866     return parseInt(y);
867   }
868   this.getElementHeight = getElementHeight;
869   function getElementHeight(){
870     var elm;
871     if(typeof(p_elm) == 'object'){
872       elm = p_elm;
873     } else {
874       elm = document.getElementById(p_elm);
875     }
876     return parseInt(elm.offsetHeight);
877   }
878   this.getElementBottom = getElementBottom;
879   function getElementBottom(){
880     return getElementTop(p_elm) + getElementHeight(p_elm);
881   }
882 }
883 function CC() {
884   var calendarId = 'CC';
885   var currentYear = 0;
886   var currentMonth = 0;
887   var currentDay = 0;
888   var selectedYear = 0;
889   var selectedMonth = 0;
890   var selectedDay = 0;
891   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]'];
892   var wdays = ['$wdays[0]', '$wdays[1]', '$wdays[2]', '$wdays[3]', '$wdays[4]', '$wdays[5]', '$wdays[6]'];
893   var dateField = null;
894   function getProperty(p_property){
895     var p_elm = calendarId;
896     var elm = null;
897     if(typeof(p_elm) == 'object'){
898       elm = p_elm;
899     } else {
900       elm = document.getElementById(p_elm);
901     }
902     if (elm != null){
903       if(elm.style){
904         elm = elm.style;
905         if(elm[p_property]){
906           return elm[p_property];
907         } else {
908           return null;
909         }
910       } else {
911         return null;
912       }
913     }
914   }
915   function setElementProperty(p_property, p_value, p_elmId){
916     var p_elm = p_elmId;
917     var elm = null;
918     if(typeof(p_elm) == 'object'){
919       elm = p_elm;
920     } else {
921       elm = document.getElementById(p_elm);
922     }
923     if((elm != null) && (elm.style != null)){
924       elm = elm.style;
925       elm[ p_property ] = p_value;
926     }
927   }
928   function setProperty(p_property, p_value) {
929     setElementProperty(p_property, p_value, calendarId);
930   }
931   function getDaysInMonth(year, month) {
932 ";
933         if ($date_system == 1)
934                 $js .= "
935     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];
936 ";
937         else if ($date_system == 2)
938                 $js .= "
939     return [30,29,30,29,30,29,30,29,30,29,30,(((((11 * year) + 14) % 30) < 11) ? 30 : 29)][month-1];
940 ";
941         else
942                 $js .= "
943     return [31,((!(year % 4 ) && ( (year % 100 ) || !( year % 400 ) ))?29:28),31,30,31,30,31,31,30,31,30,31][month-1];
944 ";
945         $js .= "
946   }
947   function getDayOfWeek(year, month, day) {
948 ";
949         if ($date_system == 1 || $date_system == 2)
950         {
951                 $js .= "
952         function mod(a, b)
953         {
954             return a - (b * Math.floor(a / b));
955         }
956         function jwday(j)
957         {
958             return mod(Math.floor((j + 1.5)), 7);
959         }
960 ";
961         if ($date_system == 1)
962                 $js .= "
963     var epbase, epyear, t;
964     epbase = year - ((year >= 0) ? 474 : 473);
965     epyear = 474 + mod(epbase, 2820);
966     t = day + ((month <= 7) ? ((month - 1) * 31) : (((month - 1) * 30) + 6)) +
967       Math.floor(((epyear * 682) - 110) / 2816) + (epyear - 1) * 365 +
968       Math.floor(epbase / 2820) * 1029983 + (1948320.5 - 1);
969 ";
970         else if ($date_system == 2)
971                 $js .= "
972         var t;
973         t = Math.floor((11 * year + 3) / 30) + 354 * year + 30 * month -
974           Math.floor((month - 1) / 2) + day + 1948440 - 385;
975 ";
976         $js .= "
977     return jwday(t);
978 ";
979         }
980         else
981                 $js .= "
982     var date = new Date(year,month-1,day)
983     return date.getDay();
984 ";
985         $js .= "
986   }
987   this.clearDate = clearDate;
988   function clearDate() {
989     dateField.value = '';
990     hide();
991   }
992   this.getWeek = getWeek;
993   function getWeek(year, month, day) {
994 ";
995         if ($how == 0)
996                 $js .= "  day++;";
997         $js .= "
998     var date = new Date(year,month-1,day);
999     var D = date.getDay();
1000     if(D == 0) D = 7;
1001     date.setDate(date.getDate() + (4 - D));
1002     var YN = date.getFullYear();
1003     var ZBDoCY = Math.floor((date.getTime() - new Date(YN, 0, 1, -6)) / 86400000);
1004     var WN = 1 + Math.floor(ZBDoCY / 7);
1005     return WN;
1006   }
1007   this.setDate = setDate;
1008   function setDate(year, month, day) {
1009     if (dateField) {
1010       if (month < 10) {month = '0' + month;}
1011       if (day < 10) {day = '0' + day;}
1012 ";
1013         if ($how == 0)
1014                 $js .= "
1015       var dateString = month+'$sep'+day+'$sep'+year;
1016 ";
1017         else if ($how == 1)
1018                 $js .= "
1019       var dateString = day+'$sep'+month+'$sep'+year;
1020 ";
1021         else
1022                 $js .= "
1023       var dateString = year+'$sep'+month+'$sep'+day;
1024 ";
1025         $js .= "
1026       dateField.value = dateString;
1027           setFocus(dateField.name);
1028         if(dateField.getAttribute('aspect')=='cdate')
1029       setElementProperty('color', (dateField.value==user.date ? 'black':'red'), dateField);
1030           if (dateField.className=='searchbox')
1031                 dateField.onblur();
1032       hide();
1033     }
1034     return;
1035   }
1036   this.changeMonth = changeMonth;
1037   function changeMonth(change) {
1038     currentMonth += change;
1039     currentDay = 0;
1040     if(currentMonth > 12) {
1041       currentMonth = 1;
1042       currentYear++;
1043     } else if(currentMonth < 1) {
1044       currentMonth = 12;
1045       currentYear--;
1046     }
1047     calendar = document.getElementById(calendarId);
1048     calendar.innerHTML = calendarDrawTable();
1049   }
1050   this.changeYear = changeYear;
1051   function changeYear(change) {
1052     currentYear += change;
1053     currentDay = 0;
1054     calendar = document.getElementById(calendarId);
1055     calendar.innerHTML = calendarDrawTable();
1056   }
1057   function getCurrentYear() {
1058     var year = new Date().getYear();
1059     if(year < 1900) year += 1900;
1060     return year;
1061   }
1062   function getCurrentMonth() {
1063     return new Date().getMonth() + 1;
1064   }
1065   function getCurrentDay() {
1066     return new Date().getDate();
1067   }
1068   function calendarDrawTable() {
1069     var dayOfMonth = 1;
1070     var wstart = $wstart;
1071     var wno = '&nbsp;$wno&nbsp;';
1072     var validDay = 0;
1073     var startDayOfWeek = getDayOfWeek(currentYear, currentMonth, dayOfMonth);
1074     var daysInMonth = getDaysInMonth(currentYear, currentMonth);
1075     var css_class = null; //CSS class for each day
1076     var table = \"<table cellspacing='0' cellpadding='0' border='0'>\";
1077     table += \"<tr class='header'>\";
1078     table += \"  <td colspan='2' class='previous'><a href='javascript:changeCCMonth(-1);'>&lt;</a><br><a href='javascript:changeCCYear(-1);'>&laquo;</a></td>\";
1079     table += \"  <td colspan='4' class='title'>\" + months[currentMonth-1] + \"<br>\" + currentYear + \"</td>\";
1080     table += \"  <td colspan='2' class='next'><a href='javascript:changeCCMonth(1);'>&gt;</a><br><a href='javascript:changeCCYear(1);'>&raquo;</a></td>\";
1081     table += \"</tr>\";
1082     table += \"<tr>\";
1083     table += \"<th class='weekno'>\"+wno+\"</th>\";
1084     for (var n=0; n<7; n++)
1085         table += \"<th>\" + wdays[(wstart+n)%7]+\"</th>\";
1086     table += \"</tr>\";
1087     for(var week=0; week < 6; week++) {
1088       table += \"<tr>\";
1089       for(var n=0; n < 7; n++) {
1090         dayOfWeek = (wstart+n)%7;
1091         if(week == 0 && startDayOfWeek == dayOfWeek) {
1092           validDay = 1;
1093         } else if (validDay == 1 && dayOfMonth > daysInMonth) {
1094           validDay = 0;
1095         }
1096         if (n==0)
1097         {
1098                 if (dayOfMonth > daysInMonth)
1099                         table += \"<td class='empty'>&nbsp;</td>\";
1100                 else
1101                         table += \"<td class='weekno'>\"+getWeek(currentYear, currentMonth, dayOfMonth)+\"</td>\";
1102         }
1103         if(validDay) {
1104           if (dayOfMonth == selectedDay && currentYear == selectedYear && currentMonth == selectedMonth) {
1105             css_class = 'current';
1106 ";
1107         if ($date_system == 1 || $date_system == 2 || $date_system == 3)
1108                 $js .= "
1109           } else if (dayOfWeek == 5) {
1110 ";
1111         else
1112                 $js .= "
1113           } else if (dayOfWeek == 0 || dayOfWeek == 6) {
1114 ";
1115                 $js .= "
1116             css_class = 'weekend';
1117           } else {
1118             css_class = 'weekday';
1119           }
1120           table += \"<td><a class='\"+css_class+\"' href=\\\"javascript:setCCDate(\"+currentYear+\",\"+currentMonth+\",\"+dayOfMonth+\")\\\">\"+dayOfMonth+\"</a></td>\";
1121           dayOfMonth++;
1122         } else {
1123           table += \"<td class='empty'>&nbsp;</td>\";
1124         }
1125       }
1126       table += \"</tr>\";
1127     }
1128     table += \"<tr class='header'><th colspan='8' style='padding: 3px;text-align:center;'><a href='javascript:hideCC();'>$back</a></td></tr>\";
1129     table += \"</table>\";
1130     return table;
1131   }
1132   this.show = show;
1133   function show(field) {
1134     can_hide = 0;
1135     if (dateField == field) {
1136       return;
1137     } else {
1138       dateField = field;
1139     }
1140     if(dateField) {
1141       try {
1142         var dateString = new String(dateField.value);
1143         var dateParts = dateString.split('$sep');
1144 ";
1145         if ($how == 0)
1146                 $js .= "
1147         selectedMonth = parseInt(dateParts[0],10);
1148         selectedDay = parseInt(dateParts[1],10);
1149         selectedYear = parseInt(dateParts[2],10);
1150 ";
1151         else if ($how == 1)
1152                 $js .= "
1153         selectedDay = parseInt(dateParts[0],10);
1154         selectedMonth = parseInt(dateParts[1],10);
1155         selectedYear = parseInt(dateParts[2],10);
1156 ";
1157         else
1158                 $js .= "
1159         selectedYear = parseInt(dateParts[0],10);
1160         selectedMonth = parseInt(dateParts[1],10);
1161         selectedDay = parseInt(dateParts[2],10);
1162 ";
1163         $js .= "
1164       } catch(e) {}
1165     }
1166     if (!(selectedYear && selectedMonth && selectedDay)) {
1167 ";
1168         if ($date_system == 1 || $date_system == 2)
1169         {
1170                 $js .= "
1171       selectedMonth = $cmon;
1172       selectedDay = $cday;
1173       selectedYear = $cyear;
1174 ";
1175         }
1176         else
1177         {
1178                 $js .= "
1179       selectedMonth = getCurrentMonth();
1180       selectedDay = getCurrentDay();
1181       selectedYear = getCurrentYear();
1182 ";
1183         }
1184         $js .= "
1185     }
1186     currentMonth = selectedMonth;
1187     currentDay = selectedDay;
1188     currentYear = selectedYear;
1189     if(document.getElementById){
1190       calendar = document.getElementById(calendarId);
1191       calendar.innerHTML = calendarDrawTable(currentYear, currentMonth);
1192       var fieldPos = new positionInfo(dateField);
1193       var calendarPos = new positionInfo(calendarId);
1194       var x = fieldPos.getElementLeft();
1195       var y = fieldPos.getElementBottom();
1196       setProperty('left', x + 'px');
1197       setProperty('top', y + 'px');
1198       setProperty('display', 'block');
1199       if (document.all) {
1200         setElementProperty('left', x + 'px', 'CCIframe');
1201         setElementProperty('top', y + 'px', 'CCIframe');
1202         setElementProperty('width', calendarPos.getElementWidth() + 'px', 'CCIframe');
1203         setElementProperty('height', calendarPos.getElementHeight() + 'px', 'CCIframe');
1204         setElementProperty('display', 'block', 'CCIframe');
1205       }
1206     }
1207   }
1208   this.hide = hide;
1209   function hide() {
1210     if(dateField) {
1211       setProperty('display', 'none');
1212       setElementProperty('display', 'none', 'CCIframe');
1213       dateField = null;
1214     }
1215   }
1216   this.visible = visible;
1217   function visible() {
1218     return dateField
1219   }
1220   this.can_hide = can_hide;
1221   var can_hide = 0;
1222 }
1223 var cC = new CC();
1224 function date_picker(textField) {
1225   cC.show(textField);
1226 }
1227 function hideCC() {
1228   if (cC.visible()) {
1229     cC.hide();
1230   }
1231 }
1232 function setCCDate(year, month, day) {
1233   cC.setDate(year, month, day);
1234 }
1235 function changeCCYear(change) {
1236   cC.changeYear(change);
1237 }
1238 function changeCCMonth(change) {
1239   cC.changeMonth(change);
1240 }
1241 document.write(\"<iframe id='CCIframe' src='javascript:false;' frameBorder='0' scrolling='no'></iframe>\");
1242 document.write(\"<div id='CC'></div>\");";
1243
1244      cache_js_file($fpath, $js);
1245     }
1246     add_js_ufile($fpath);
1247
1248  return '';
1249 }
1250
1251 function alert($msg)
1252 {
1253         echo "\n<script type=\"text/javascript\">\n"
1254                 . "<!--\n"
1255                 . "alert('$msg');\n"
1256                 . "-->\n"
1257                 . "</script>\n";
1258 }
1259
1260 if (!function_exists('_vd'))
1261 {
1262         function _vd($mixed, $title = '', $exit = false)
1263         {
1264         // Only the site admin is able to proceed here.
1265         $str = (!empty($title) ? ($title .':') : '') .'<pre>';
1266         $str .= print_r($mixed, true); //var_dump($mixed);
1267         $str .= "</pre>\n";
1268                 display_notification('<table><tr><td>'.$str.'</td></tr></table>');
1269         if ($exit)
1270                 exit;
1271         }
1272 }
1273
1274 function display_backtrace($cond=true, $msg='') {
1275
1276         if ($cond) {
1277                 if ($msg) 
1278                         $str = "<center><span class='headingtext'>$msg</span></center>\n";
1279                 else
1280                         $str = '';
1281                 $str .= '<table border=0>';
1282         $trace = debug_backtrace();
1283                 foreach($trace as $trn => $tr) {
1284                         if (!$trn) continue;
1285                         $str .= '<tr><td>';
1286                         $str .= $tr['file'].':'.$tr['line'].': ';
1287                         $str .= '</td><td>';
1288                         if (isset($tr['type'])) {
1289                                 if($tr['type'] == '::') {
1290                                         $str .= $tr['class'].'::';
1291                                 } else if($tr['type'] == '->') {
1292                                         $str .= '('.$tr['class'].' Object)'.'->';
1293                                 }
1294                         }
1295                         foreach($tr['args'] as $n=>$a) {
1296                                 if (is_object($tr['args'][$n]))
1297                                         $tr['args'][$n] = "(".get_class($tr['args'][$n])." Object)";
1298                                 if (is_array($tr['args'][$n]))
1299                                         $tr['args'][$n] = "(Array[".count($tr['args'][$n])."])";
1300                                 else
1301                                         $tr['args'][$n] = "'".$tr['args'][$n]."'";
1302                         }
1303                         $str .= $tr['function'].'('. implode(',',$tr['args']).')</td>';
1304
1305                         $str .= '</tr>';
1306                 }
1307                 
1308                 $str .= '</table>';
1309         display_error($str);
1310         }
1311 }
1312
1313 ?>