Merged changes in main branch up to v.2.1.2
[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 == systypes::po())
22                 $viewer .= "view_po.php";
23         elseif ($type == 20)
24                 $viewer .= "view_supp_invoice.php";
25         elseif ($type == 21)
26                 $viewer .= "view_supp_credit.php";
27         elseif ($type == 22)
28                 $viewer = "view_supp_payment.php";
29         elseif ($type == 25)
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 == 10)
77                 $viewer .= "view_invoice.php";
78         elseif ($type == 11)
79                 $viewer .= "view_credit.php";
80         elseif ($type == 12)
81                 $viewer .= "view_receipt.php";
82         elseif ($type == 13)
83                 $viewer .= "view_dispatch.php";
84         elseif ($type == 30)
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", 
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 == 4)
115                 $viewer = "bank_transfer_view.php";
116         elseif ($type == 1)
117                 $viewer = "gl_payment_view.php";
118         elseif ($type == 2)
119                 $viewer = "gl_deposit_view.php";
120         elseif ($type == 0)
121                 return $label;
122         else
123                 return null;
124
125         return viewer_link($label, "gl/view/$viewer?trans_no=$trans_no", 
126                 $class, $id,  $icon);
127 }
128
129 //--------------------------------------------------------------------------------------
130
131 function get_inventory_trans_view_str($type, $trans_no, $label="", 
132         $icon=false, $class='', $id='')
133 {
134         $viewer = "inventory/view/";
135
136         if ($type == systypes::inventory_adjustment())
137                 $viewer .= "view_adjustment.php";
138         elseif ($type == systypes::location_transfer())
139                 $viewer .= "view_transfer.php";
140         else
141                 return null;
142         $viewer .= "?trans_no=$trans_no";
143
144         if ($label == "")
145                 $label = $trans_no;
146
147         return viewer_link($label, $viewer, $class, $id,  $icon);
148 }
149
150 //--------------------------------------------------------------------------------------
151
152 function get_manufacturing_trans_view_str($type, $trans_no, $label="", 
153         $icon=false, $class='', $id='')
154 {
155         $viewer = "manufacturing/view/";
156
157         if ($type == 28)
158                 $viewer .= "wo_issue_view.php";
159         elseif ($type == 29)
160                 $viewer .= "wo_production_view.php";
161         elseif ($type == systypes::work_order())
162                 $viewer .= "work_order_view.php";
163         else
164                 return null;
165
166         $viewer .= "?trans_no=$trans_no";
167
168         if ($label == "")
169                 $label = $trans_no;
170
171         return viewer_link($label, $viewer, $class, $id,  $icon);
172 }
173
174 //--------------------------------------------------------------------------------------
175
176 function get_dimensions_trans_view_str($type, $trans_no, $label="", $icon=false, 
177         $class='', $id='')
178 {
179         if ($type == 40)
180                 $viewer = "dimensions/view_dimension.php?trans_no=$trans_no";
181         else
182                 return null;
183
184         if ($label == "")
185                 $label = $trans_no;
186
187         return viewer_link($label, $viewer, $class, $id,  $icon);
188 }
189
190 //--------------------------------------------------------------------------------------
191
192 function get_trans_view_str($type, $trans_no, $label="", $icon=false, 
193         $class='', $id='')
194 {
195         $view_str = get_customer_trans_view_str($type, $trans_no, $label, $icon, $class, $id);
196         if ($view_str != null)
197                 return $view_str;
198
199         $view_str = get_supplier_trans_view_str($type, $trans_no, $label, $icon, $class, $id);
200         if ($view_str != null)
201                 return $view_str;
202
203         $view_str = get_banking_trans_view_str($type, $trans_no, $label, $icon, $class, $id);
204         if ($view_str != null)
205                 return $view_str;
206
207         $view_str = get_inventory_trans_view_str($type, $trans_no, $label, $icon, $class, $id);
208         if ($view_str != null)
209                 return $view_str;
210
211         $view_str = get_manufacturing_trans_view_str($type, $trans_no, $label, $icon, $class, $id);
212         if ($view_str != null)
213                 return $view_str;
214
215         $view_str = get_dimensions_trans_view_str($type, $trans_no, $label, $icon, $class, $id);
216         if ($view_str != null)
217                 return $view_str;
218
219         return null;
220 }
221
222 //--------------------------------------------------------------------------------------
223 // Displays currency exchange rate for given date.
224 // When there is no exrate for today, 
225 // gets it form ECB and stores in local database.
226 //
227 function exchange_rate_display($from_currency, $to_currency, $date_, $edit_rate=false)
228 {
229     global $Ajax;
230
231         if ($from_currency != $to_currency)
232         {
233                 $comp_currency = get_company_currency();
234                 if ($from_currency == $comp_currency)
235                         $currency = $to_currency;
236                 else
237                         $currency = $from_currency;
238                 $rate = 0;
239                 if ($date_ == Today()) {
240                         $rate = get_date_exchange_rate($currency, $date_);
241                         if (!$rate) {
242                                 $rate = get_ecb_rate($currency);
243                                 if ($rate) 
244                                         add_exchange_rate($currency, $date_, $rate, $rate);
245                         }
246                 }
247                 if (!$rate)
248                         $rate = get_exchange_rate_from_home_currency($currency, $date_);
249                 if ($from_currency != $comp_currency)
250                         $rate = 1 / ($rate / get_exchange_rate_from_home_currency($to_currency, $date_));
251
252                 $rate = number_format2($rate, user_exrate_dec());
253                 if ($edit_rate)
254                         text_row(_("Exchange Rate:"), '_ex_rate', $rate, 8, 8, null, "", " $from_currency = 1 $to_currency"); 
255                 else
256                 label_row(_("Exchange Rate:"),"<span id='_ex_rate'>$rate</span> $from_currency = 1 $to_currency" );
257                 $Ajax->addUpdate('_ex_rate','_ex_rate', $rate);
258         }
259 }
260
261 //--------------------------------------------------------------------------------------
262
263 function is_voided_display($type, $id, $label)
264 {
265         global $table_style;
266         $void_entry = get_voided_entry($type, $id);
267
268         if ($void_entry == null)
269                 return false;
270
271         start_table("width=50% $table_style");
272         echo "<tr><td align=center><font color=red>$label</font><br>";
273         echo "<font color=red>" . _("Date Voided:") . " " . sql2date($void_entry["date_"]) . "</font><br>";
274         if (strlen($void_entry["memo_"]) > 0)
275                 echo "<center><font color=red>" . _("Memo:") . " " . $void_entry["memo_"] . "</font></center><br>";
276         echo "</td></tr>";
277         end_table(1);
278
279         return true;
280 }
281
282 //--------------------------------------------------------------------------------------
283
284 function comments_display_row($type, $id)
285 {
286         $comments = get_comments($type, $id);
287         if ($comments and db_num_rows($comments))
288         {
289                 echo "<tr><td colspan=15>";
290         while ($comment = db_fetch($comments))
291         {
292                 echo $comment["memo_"] . "<br>";
293         }
294                 echo "</td></tr>";
295         }
296 }
297
298 //--------------------------------------------------------------------------------------
299
300 function get_comments_string($type, $type_no)
301 {
302         $str_return = "";
303         $result = get_comments($type, $type_no);
304         while ($comment = db_fetch($result))
305         {
306                 if (strlen($str_return))
307                         $str_return = $str_return . " \n";
308                 $str_return = $str_return . $comment["memo_"];
309         }
310         return $str_return;
311 }
312
313 //--------------------------------------------------------------------------------------
314
315 function view_stock_status($stock_id, $description=null, $echo=true)
316 {
317         global $path_to_root;
318         if ($description)
319                 //hyperlink_params_separate($path_to_root . "/inventory/inquiry/stock_status.php", (user_show_codes()?$stock_id . " - ":"") . $description, "stock_id=$stock_id");
320                 $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>";
321         else
322                 //hyperlink_params_separate($path_to_root . "/inventory/inquiry/stock_status.php", $stock_id, "stock_id=$stock_id");
323                 $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>";
324         if($echo)
325                 echo $preview_str;
326         return $preview_str;
327 }
328
329 function view_stock_status_cell($stock_id, $description=null)
330 {
331         echo "<td>";
332         view_stock_status($stock_id, $description);
333         echo "</td>";
334 }
335
336 //--------------------------------------------------------------------------------------
337
338 function display_debit_or_credit_cells($value)
339 {
340         if ($value > 0)
341         {
342                 amount_cell($value);
343                 label_cell("");
344         }
345         elseif ($value < 0)
346         {
347                 label_cell("");
348                 amount_cell(abs($value));
349         }
350         else
351         {
352                 //label_cell("");
353                 amount_cell(0);
354                 label_cell("");
355         }
356 }
357
358 //--------------------------------------------------------------------------------------
359
360 function display_customer_trans_tax_details($tax_items, $columns)
361 {
362     while ($tax_item = db_fetch($tax_items))
363     {
364         $tax = number_format2($tax_item['amount'],user_price_dec());
365         if ($tax_item['included_in_price'])
366                 label_row(_("Included") . " " . $tax_item['tax_type_name'] . " (" . $tax_item['rate'] . "%) " .
367                         _("Amount") . ": $tax", "", "colspan=$columns align=right", "align=right");
368         else
369                 label_row($tax_item['tax_type_name'] . " (" . $tax_item['rate'] . "%)",
370                         $tax, "colspan=$columns align=right", "align=right");
371     }
372 }
373
374 //--------------------------------------------------------------------------------------
375
376 function display_supp_trans_tax_details($tax_items, $columns)
377 {
378     while ($tax_item = db_fetch($tax_items))
379     {
380         $tax = number_format2(abs($tax_item['amount']),user_price_dec());
381         if ($tax_item['included_in_price'])
382                 label_row(_("Included") . " " . $tax_item['tax_type_name'] . " (" . $tax_item['rate'] . "%) " .
383                         _("Amount") . ": $tax", "colspan=$columns align=right", "align=right");
384         else
385                 label_row($tax_item['tax_type_name'] . " (" . $tax_item['rate'] . "%)",
386                         $tax, "colspan=$columns align=right", "align=right");
387     }
388 }
389
390 //--------------------------------------------------------------------------------------
391
392 function display_edit_tax_items($taxes, $columns, $tax_included, $leftspan=0)
393 {
394         $total = 0;
395
396     foreach ($taxes as $taxitem)
397     {
398         if ($tax_included)
399         {
400                 label_row(_("Included") . " " . $taxitem['tax_type_name'] . " (" . $taxitem['rate'] . "%) " .
401                         _("Amount:") . " " . number_format2($taxitem['Value'],user_price_dec()), "", "colspan=$columns align=right", "align=right",$leftspan);
402         }
403         else
404         {
405                 label_row($taxitem['tax_type_name'] . " (" . $taxitem['rate'] . "%)",
406                         number_format2($taxitem['Value'],user_price_dec()), "colspan=$columns align=right", "align=right",$leftspan);
407                 $total +=  round2($taxitem['Value'], user_price_dec());
408         }
409     }
410
411     return $total;
412 }
413
414 //--------------------------------------------------------------------------------------
415
416 function display_footer_exit()
417 {
418         br(2);
419         end_page();
420         exit;
421 }
422
423 //--------------------------------------------------------------------------------------
424
425 function display_allocations($alloc_result, $total)
426 {
427         global $table_style;
428
429         if (!$alloc_result || db_num_rows($alloc_result) == 0)
430                 return;
431
432     display_heading2(_("Allocations"));
433
434     start_table("$table_style width=80%");
435
436     $th = array( _("Type"), _("Number"), _("Date"), _("Total Amount"),
437         _("Left to Allocate"), _("This Allocation"));
438         table_header($th);
439     $k = $total_allocated = 0;
440
441     while ($alloc_row = db_fetch($alloc_result))
442     {
443
444         alt_table_row_color($k);
445
446         label_cell(systypes::name($alloc_row['type']));
447         label_cell(get_trans_view_str($alloc_row['type'],$alloc_row['trans_no']));
448         label_cell(sql2date($alloc_row['tran_date']));
449         $alloc_row['Total'] = round2($alloc_row['Total'], user_price_dec());
450         $alloc_row['amt'] = round2($alloc_row['amt'], user_price_dec());
451         amount_cell($alloc_row['Total']);
452         //amount_cell($alloc_row['Total'] - $alloc_row['PrevAllocs'] - $alloc_row['amt']);
453         amount_cell($alloc_row['Total'] - $alloc_row['amt']);
454         amount_cell($alloc_row['amt']);
455         end_row();
456
457         $total_allocated += $alloc_row['amt'];
458     }
459     start_row();
460         label_cell(_("Total Allocated:"), "align=right colspan=5");
461         amount_cell($total_allocated);
462         end_row();
463         start_row();
464     label_cell(_("Left to Allocate:"), "align=right colspan=5");
465     $total = round2($total, user_price_dec());
466     amount_cell($total - $total_allocated);
467     end_row();
468
469     end_table(1);
470 }
471
472 //--------------------------------------------------------------------------------------
473
474 function display_allocations_from($person_type, $person_id, $type, $type_no, $total)
475 {
476         switch ($person_type)
477         {
478                 case payment_person_types::customer() :
479                         $alloc_result = get_allocatable_to_cust_transactions($person_id, $type_no, $type);
480                         display_allocations($alloc_result, $total);
481                         return;
482                 case payment_person_types::supplier() :
483                         $alloc_result = get_allocatable_to_supp_transactions($person_id, $type_no, $type);
484                         display_allocations($alloc_result, $total);
485                         return;
486         }
487 }
488
489 //--------------------------------------------------------------------------------------
490 //
491 //      Expands selected quick entry $id into GL posings and adds to cart.
492 //              returns calculated amount posted to bank GL account.
493 //
494 function display_quick_entries(&$cart, $id, $base, $type, $descr='')
495 {
496         $bank_amount = 0;
497         
498         if (!isset($id) || $id == null || $id == "")
499         {
500                 display_error( _("No Quick Entries are defined."));
501                 set_focus('totamount');
502         }
503         else
504         {
505                 if ($type == QE_DEPOSIT)
506                         $base = -$base;
507                 if ($type != QE_SUPPINV)        // only one quick entry on journal/bank transaction
508                         $cart->clear_items();
509                 $qe = get_quick_entry($id);
510                 if ($descr != '') $qe['description'] .= ': '.$descr;
511                 $qe_lines = get_quick_entry_lines($id);
512                 while ($qe_line = db_fetch($qe_lines))
513                 {
514                         switch (strtolower($qe_line['action'])) {
515                                 case "=": // post current base amount to GL account
516                                         $part = $base;
517                                         break;
518                                 case "a": // post amount to GL account and reduce base
519                                         $part = $qe_line['amount'];
520                                         break;
521                                 case "a+": // post amount to GL account and increase base
522                                         $part = $qe_line['amount']; $base += $part;
523                                         break;
524                                 case "a-": // post amount to GL account and reduce base
525                                         $part = $qe_line['amount']; $base -= $part;
526                                         break;
527                                 case "%":       // store acc*amount% to GL account
528                                         $part = round2($base * $qe_line['amount'] / 100, user_price_dec());
529                                         break;
530                                 case "%+":      // ditto & increase base amount
531                                         $part = round2($base * $qe_line['amount'] / 100, user_price_dec());
532                                         $base += $part;
533                                         break;
534                                 case "%-":      // ditto & reduce base amount
535                                         $part = round2($base * $qe_line['amount'] / 100, user_price_dec());
536                                         $base -= $part;
537                                         break;
538                                 case "t": // post taxes calculated on base amount
539                                 case "t+": // ditto & increase base amount
540                                 case "t-": // ditto & reduce base amount
541                                         $taxes = get_taxes_for_item_tax($qe_line['dest_id']);
542                                         $tax_total = 0;
543                                         foreach ($taxes as $index => $item_tax) {
544                                                 if(substr($qe_line['action'],0,1) != 'T')
545                                                         $tax = round2($base * $item_tax['rate'] 
546                                                                 / ($item_tax['rate'] + 100),  user_price_dec());
547                                                 else
548                                                         $tax = round2($base * $item_tax['rate'] / 100,  user_price_dec());
549
550                                                 $gl_code = ($type == QE_DEPOSIT || ($type == QE_JOURNAL && $base < 0)) 
551                                                         ? $item_tax['sales_gl_code'] : $item_tax['purchasing_gl_code'];
552                                                 $tax_total += $tax;
553                                                 if ($type != QE_SUPPINV)
554                                                         $cart->add_gl_item($gl_code, 
555                                                                 $qe_line['dimension_id'], $qe_line['dimension2_id'], 
556                                                                 $tax, $qe['description']);
557                                                 else 
558                                                 {
559                                                         $acc_name = get_gl_account_name($gl_code);
560                                                         $cart->add_gl_codes_to_trans($gl_code, 
561                                                                 $acc_name, $qe_line['dimension_id'], 
562                                                                 $qe_line['dimension2_id'], $tax, $qe['description']);
563                                                 }
564                                         }
565                                         if (strpos($qe_line['action'], '+'))
566                                                 $base += $tax_total;
567                                         elseif (strpos($qe_line['action'], '-'))
568                                                 $base -= $tax_total;
569                                         continue 2;
570                         }
571                         if ($type != QE_SUPPINV)
572                                 $cart->add_gl_item($qe_line['dest_id'], $qe_line['dimension_id'],
573                                         $qe_line['dimension2_id'], $part, $qe['description']);
574                         else 
575                         {
576                                 $acc_name = get_gl_account_name($qe_line['dest_id']);
577                                 $cart->add_gl_codes_to_trans($qe_line['dest_id'], 
578                                         $acc_name, $qe_line['dimension_id'], 
579                                         $qe_line['dimension2_id'], $part, $qe['description']);
580                         }
581                 }
582         }       
583         return $bank_amount;
584 }
585
586
587 function get_js_open_window($width, $height)
588 {
589         $js ="function openWindow(url, title)\n"
590                 . "{\n"
591                 . " var left = (screen.width - $width) / 2;\n"
592                 . " var top = (screen.height - $height) / 2;\n"
593                 . " return window.open(url, title, 'width=$width,height=$height,left='+left+',top='+top+',screenX='+left+',screenY='+top+',status=no,scrollbars=yes');\n"
594                 . "}\n";
595         return $js;
596 }
597
598 /*
599   Setting focus on element $name in $form.
600   If $form<0 $name is element id.
601 */
602 function set_focus($name, $form_no=0) {
603   global $Ajax;
604         $Ajax->addFocus(true, $name);
605     $_POST['_focus'] = $name;
606 }
607 //
608 //      Set default focus on first field $name if not set yet
609 //      Returns unique name if $name=null
610 //      
611 function default_focus($name=null, $form_no=0) {
612         static $next; 
613         if ($name==null) 
614                 $name = uniqid('_el',true);
615     if (!isset($_POST['_focus'])) {
616           set_focus($name);
617     }
618         return $name;
619 }
620
621 function get_js_png_fix()
622 {
623         $js = "function fixPNG(myImage)\n"
624                 . "{\n"
625                 . " var arVersion = navigator.appVersion.split(\"MSIE\")\n"
626                 . " var version = parseFloat(arVersion[1])\n"
627         . " if ((version >= 5.5) && (version < 7) && (document.body.filters))\n"
628         . " {\n"
629         . "  var imgID = (myImage.id) ? \"id='\" + myImage.id + \"' \" : \"\"\n"
630                 . "  var imgClass = (myImage.className) ? \"class='\" + myImage.className + \"' \" : \"\"\n"
631                 . "  var imgTitle = (myImage.title) ?\n"
632                 . "    \"title='\" + myImage.title  + \"' \" : \"title='\" + myImage.alt + \"' \"\n"
633                 . "  var imgStyle = \"display:inline-block;\" + myImage.style.cssText\n"
634                 . "  var strNewHTML = \"<span \" + imgID + imgClass + imgTitle\n"
635         . "    + \" style=\\\"\" + \"width:\" + myImage.width\n"
636         . "    + \"px; height:\" + myImage.height\n"
637         . "    + \"px;\" + imgStyle + \";\"\n"
638         . "    + \"filter:progid:DXImageTransform.Microsoft.AlphaImageLoader\"\n"
639         . "    + \"(src=\'\" + myImage.src + \"\', sizingMethod='scale');\\\"></span>\"\n"
640                 . "  myImage.outerHTML = strNewHTML\n"
641         . " }\n"
642                 . "}\n";
643         return $js;
644 }
645
646 function get_js_date_picker()
647 {
648     global $comp_path, $go_debug;
649     $fpath = $comp_path.'/'.user_company().'/js_cache/'.'date_picker.js';
650
651     if (!file_exists($fpath) || $go_debug) {
652
653         global $dateseps, $date_system;
654
655         $how = user_date_format();                              // 0 = us/ca, 1 = eu, au, nz, 2 = jp, sw
656         $sep = $dateseps[user_date_sep()];              // date separator
657         $wstart = (($date_system == 1 || $date_system == 2) ? 6 : ($how == 0 ? 0 : 1));                 // weekstart (sun = 0, mon = 1)
658         $months = array(_("January"),_("February"),_("March"),_("April"),_("May"),_("June"),_("July"),_("August"),_("September"),_("October"),_("November"),_("December"));
659         $wdays = array(_("Su"),_("Mo"),_("Tu"),_("We"),_("Th"),_("Fr"),_("Sa"));
660         $wno = _("W"); // week no
661         $back = _("Back");
662         if ($date_system == 1)
663                 list($cyear, $cmon, $cday) = gregorian_to_jalali(date("Y"), date("n"), date("j"));
664         else if ($date_system == 2)
665                 list($cyear, $cmon, $cday) = gregorian_to_islamic(date("Y"), date("n"), date("j"));
666
667
668         $js = "
669 function positionInfo(object) {
670   var p_elm = object;
671   this.getElementLeft = getElementLeft;
672   function getElementLeft() {
673     var x = 0;
674     var elm;
675     if(typeof(p_elm) == 'object'){
676       elm = p_elm;
677     } else {
678       elm = document.getElementById(p_elm);
679     }
680     while (elm != null) {
681       x+= elm.offsetLeft;
682       elm = elm.offsetParent;
683     }
684     return parseInt(x);
685   }
686   this.getElementWidth = getElementWidth;
687   function getElementWidth(){
688     var elm;
689     if(typeof(p_elm) == 'object'){
690       elm = p_elm;
691     } else {
692       elm = document.getElementById(p_elm);
693     }
694     return parseInt(elm.offsetWidth);
695   }
696   this.getElementRight = getElementRight;
697   function getElementRight(){
698     return getElementLeft(p_elm) + getElementWidth(p_elm);
699   }
700   this.getElementTop = getElementTop;
701   function getElementTop() {
702     var y = 0;
703     var elm;
704     if(typeof(p_elm) == 'object'){
705       elm = p_elm;
706     } else {
707       elm = document.getElementById(p_elm);
708     }
709     while (elm != null) {
710       y+= elm.offsetTop;
711       elm = elm.offsetParent;
712     }
713     return parseInt(y);
714   }
715   this.getElementHeight = getElementHeight;
716   function getElementHeight(){
717     var elm;
718     if(typeof(p_elm) == 'object'){
719       elm = p_elm;
720     } else {
721       elm = document.getElementById(p_elm);
722     }
723     return parseInt(elm.offsetHeight);
724   }
725   this.getElementBottom = getElementBottom;
726   function getElementBottom(){
727     return getElementTop(p_elm) + getElementHeight(p_elm);
728   }
729 }
730 function CC() {
731   var calendarId = 'CC';
732   var currentYear = 0;
733   var currentMonth = 0;
734   var currentDay = 0;
735   var selectedYear = 0;
736   var selectedMonth = 0;
737   var selectedDay = 0;
738   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]'];
739   var wdays = ['$wdays[0]', '$wdays[1]', '$wdays[2]', '$wdays[3]', '$wdays[4]', '$wdays[5]', '$wdays[6]'];
740   var dateField = null;
741   function getProperty(p_property){
742     var p_elm = calendarId;
743     var elm = null;
744     if(typeof(p_elm) == 'object'){
745       elm = p_elm;
746     } else {
747       elm = document.getElementById(p_elm);
748     }
749     if (elm != null){
750       if(elm.style){
751         elm = elm.style;
752         if(elm[p_property]){
753           return elm[p_property];
754         } else {
755           return null;
756         }
757       } else {
758         return null;
759       }
760     }
761   }
762   function setElementProperty(p_property, p_value, p_elmId){
763     var p_elm = p_elmId;
764     var elm = null;
765     if(typeof(p_elm) == 'object'){
766       elm = p_elm;
767     } else {
768       elm = document.getElementById(p_elm);
769     }
770     if((elm != null) && (elm.style != null)){
771       elm = elm.style;
772       elm[ p_property ] = p_value;
773     }
774   }
775   function setProperty(p_property, p_value) {
776     setElementProperty(p_property, p_value, calendarId);
777   }
778   function getDaysInMonth(year, month) {
779 ";
780         if ($date_system == 1)
781                 $js .= "
782     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];
783 ";
784         else if ($date_system == 2)
785                 $js .= "
786     return [30,29,30,29,30,29,30,29,30,29,30,(((((11 * year) + 14) % 30) < 11) ? 30 : 29)][month-1];
787 ";
788         else
789                 $js .= "
790     return [31,((!(year % 4 ) && ( (year % 100 ) || !( year % 400 ) ))?29:28),31,30,31,30,31,31,30,31,30,31][month-1];
791 ";
792         $js .= "
793   }
794   function getDayOfWeek(year, month, day) {
795 ";
796         if ($date_system == 1 || $date_system == 2)
797         {
798                 $js .= "
799         function mod(a, b)
800         {
801             return a - (b * Math.floor(a / b));
802         }
803         function jwday(j)
804         {
805             return mod(Math.floor((j + 1.5)), 7);
806         }
807 ";
808         if ($date_system == 1)
809                 $js .= "
810     var epbase, epyear, t;
811     epbase = year - ((year >= 0) ? 474 : 473);
812     epyear = 474 + mod(epbase, 2820);
813     t = day + ((month <= 7) ? ((month - 1) * 31) : (((month - 1) * 30) + 6)) +
814       Math.floor(((epyear * 682) - 110) / 2816) + (epyear - 1) * 365 +
815       Math.floor(epbase / 2820) * 1029983 + (1948320.5 - 1);
816 ";
817         else if ($date_system == 2)
818                 $js .= "
819         var t;
820         t = Math.floor((11 * year + 3) / 30) + 354 * year + 30 * month -
821           Math.floor((month - 1) / 2) + day + 1948440 - 385;
822 ";
823         $js .= "
824     return jwday(t);
825 ";
826         }
827         else
828                 $js .= "
829     var date = new Date(year,month-1,day)
830     return date.getDay();
831 ";
832         $js .= "
833   }
834   this.clearDate = clearDate;
835   function clearDate() {
836     dateField.value = '';
837     hide();
838   }
839   this.getWeek = getWeek;
840   function getWeek(year, month, day) {
841 ";
842         if ($how == 0)
843                 $js .= "  day++;";
844         $js .= "
845     var date = new Date(year,month-1,day);
846     var D = date.getDay();
847     if(D == 0) D = 7;
848     date.setDate(date.getDate() + (4 - D));
849     var YN = date.getFullYear();
850     var ZBDoCY = Math.floor((date.getTime() - new Date(YN, 0, 1, -6)) / 86400000);
851     var WN = 1 + Math.floor(ZBDoCY / 7);
852     return WN;
853   }
854   this.setDate = setDate;
855   function setDate(year, month, day) {
856     if (dateField) {
857       if (month < 10) {month = '0' + month;}
858       if (day < 10) {day = '0' + day;}
859 ";
860         if ($how == 0)
861                 $js .= "
862       var dateString = month+'$sep'+day+'$sep'+year;
863 ";
864         else if ($how == 1)
865                 $js .= "
866       var dateString = day+'$sep'+month+'$sep'+year;
867 ";
868         else
869                 $js .= "
870       var dateString = year+'$sep'+month+'$sep'+day;
871 ";
872         $js .= "
873       dateField.value = dateString;
874           setFocus(dateField.name);
875         if(dateField.getAttribute('aspect')=='cdate')
876       setElementProperty('color', (dateField.value==user.date ? 'black':'red'), dateField);
877           if (dateField.className=='searchbox')
878                 dateField.onblur();
879       hide();
880     }
881     return;
882   }
883   this.changeMonth = changeMonth;
884   function changeMonth(change) {
885     currentMonth += change;
886     currentDay = 0;
887     if(currentMonth > 12) {
888       currentMonth = 1;
889       currentYear++;
890     } else if(currentMonth < 1) {
891       currentMonth = 12;
892       currentYear--;
893     }
894     calendar = document.getElementById(calendarId);
895     calendar.innerHTML = calendarDrawTable();
896   }
897   this.changeYear = changeYear;
898   function changeYear(change) {
899     currentYear += change;
900     currentDay = 0;
901     calendar = document.getElementById(calendarId);
902     calendar.innerHTML = calendarDrawTable();
903   }
904   function getCurrentYear() {
905     var year = new Date().getYear();
906     if(year < 1900) year += 1900;
907     return year;
908   }
909   function getCurrentMonth() {
910     return new Date().getMonth() + 1;
911   }
912   function getCurrentDay() {
913     return new Date().getDate();
914   }
915   function calendarDrawTable() {
916     var dayOfMonth = 1;
917     var wstart = $wstart;
918     var wno = '&nbsp;$wno&nbsp;';
919     var validDay = 0;
920     var startDayOfWeek = getDayOfWeek(currentYear, currentMonth, dayOfMonth);
921     var daysInMonth = getDaysInMonth(currentYear, currentMonth);
922     var css_class = null; //CSS class for each day
923     var table = \"<table cellspacing='0' cellpadding='0' border='0'>\";
924     table += \"<tr class='header'>\";
925     table += \"  <td colspan='2' class='previous'><a href='javascript:changeCCMonth(-1);'>&lt;</a><br><a href='javascript:changeCCYear(-1);'>&laquo;</a></td>\";
926     table += \"  <td colspan='4' class='title'>\" + months[currentMonth-1] + \"<br>\" + currentYear + \"</td>\";
927     table += \"  <td colspan='2' class='next'><a href='javascript:changeCCMonth(1);'>&gt;</a><br><a href='javascript:changeCCYear(1);'>&raquo;</a></td>\";
928     table += \"</tr>\";
929     table += \"<tr>\";
930     table += \"<th class='weekno'>\"+wno+\"</th>\";
931     for (var n=0; n<7; n++)
932         table += \"<th>\" + wdays[(wstart+n)%7]+\"</th>\";
933     table += \"</tr>\";
934     for(var week=0; week < 6; week++) {
935       table += \"<tr>\";
936       for(var n=0; n < 7; n++) {
937         dayOfWeek = (wstart+n)%7;
938         if(week == 0 && startDayOfWeek == dayOfWeek) {
939           validDay = 1;
940         } else if (validDay == 1 && dayOfMonth > daysInMonth) {
941           validDay = 0;
942         }
943         if (n==0)
944         {
945                 if (dayOfMonth > daysInMonth)
946                         table += \"<td class='empty'>&nbsp;</td>\";
947                 else
948                         table += \"<td class='weekno'>\"+getWeek(currentYear, currentMonth, dayOfMonth)+\"</td>\";
949         }
950         if(validDay) {
951           if (dayOfMonth == selectedDay && currentYear == selectedYear && currentMonth == selectedMonth) {
952             css_class = 'current';
953 ";
954         if ($date_system == 1 || $date_system == 2)
955                 $js .= "
956           } else if (dayOfWeek == 5) {
957 ";
958         else
959                 $js .= "
960           } else if (dayOfWeek == 0 || dayOfWeek == 6) {
961 ";
962                 $js .= "
963             css_class = 'weekend';
964           } else {
965             css_class = 'weekday';
966           }
967           table += \"<td><a class='\"+css_class+\"' href=\\\"javascript:setCCDate(\"+currentYear+\",\"+currentMonth+\",\"+dayOfMonth+\")\\\">\"+dayOfMonth+\"</a></td>\";
968           dayOfMonth++;
969         } else {
970           table += \"<td class='empty'>&nbsp;</td>\";
971         }
972       }
973       table += \"</tr>\";
974     }
975     table += \"<tr class='header'><th colspan='8' style='padding: 3px;text-align:center;'><a href='javascript:hideCC();'>$back</a></td></tr>\";
976     table += \"</table>\";
977     return table;
978   }
979   this.show = show;
980   function show(field) {
981     can_hide = 0;
982     if (dateField == field) {
983       return;
984     } else {
985       dateField = field;
986     }
987     if(dateField) {
988       try {
989         var dateString = new String(dateField.value);
990         var dateParts = dateString.split('$sep');
991 ";
992         if ($how == 0)
993                 $js .= "
994         selectedMonth = parseInt(dateParts[0],10);
995         selectedDay = parseInt(dateParts[1],10);
996         selectedYear = parseInt(dateParts[2],10);
997 ";
998         else if ($how == 1)
999                 $js .= "
1000         selectedDay = parseInt(dateParts[0],10);
1001         selectedMonth = parseInt(dateParts[1],10);
1002         selectedYear = parseInt(dateParts[2],10);
1003 ";
1004         else
1005                 $js .= "
1006         selectedYear = parseInt(dateParts[0],10);
1007         selectedMonth = parseInt(dateParts[1],10);
1008         selectedDay = parseInt(dateParts[2],10);
1009 ";
1010         $js .= "
1011       } catch(e) {}
1012     }
1013     if (!(selectedYear && selectedMonth && selectedDay)) {
1014 ";
1015         if ($date_system == 1 || $date_system == 2)
1016         {
1017                 $js .= "
1018       selectedMonth = $cmon;
1019       selectedDay = $cday;
1020       selectedYear = $cyear;
1021 ";
1022         }
1023         else
1024         {
1025                 $js .= "
1026       selectedMonth = getCurrentMonth();
1027       selectedDay = getCurrentDay();
1028       selectedYear = getCurrentYear();
1029 ";
1030         }
1031         $js .= "
1032     }
1033     currentMonth = selectedMonth;
1034     currentDay = selectedDay;
1035     currentYear = selectedYear;
1036     if(document.getElementById){
1037       calendar = document.getElementById(calendarId);
1038       calendar.innerHTML = calendarDrawTable(currentYear, currentMonth);
1039       var fieldPos = new positionInfo(dateField);
1040       var calendarPos = new positionInfo(calendarId);
1041       var x = fieldPos.getElementLeft();
1042       var y = fieldPos.getElementBottom();
1043       setProperty('left', x + 'px');
1044       setProperty('top', y + 'px');
1045       setProperty('display', 'block');
1046       if (document.all) {
1047         setElementProperty('left', x + 'px', 'CCIframe');
1048         setElementProperty('top', y + 'px', 'CCIframe');
1049         setElementProperty('width', calendarPos.getElementWidth() + 'px', 'CCIframe');
1050         setElementProperty('height', calendarPos.getElementHeight() + 'px', 'CCIframe');
1051         setElementProperty('display', 'block', 'CCIframe');
1052       }
1053     }
1054   }
1055   this.hide = hide;
1056   function hide() {
1057     if(dateField) {
1058       setProperty('display', 'none');
1059       setElementProperty('display', 'none', 'CCIframe');
1060       dateField = null;
1061     }
1062   }
1063   this.visible = visible;
1064   function visible() {
1065     return dateField
1066   }
1067   this.can_hide = can_hide;
1068   var can_hide = 0;
1069 }
1070 var cC = new CC();
1071 function date_picker(textField) {
1072   cC.show(textField);
1073 }
1074 function hideCC() {
1075   if (cC.visible()) {
1076     cC.hide();
1077   }
1078 }
1079 function setCCDate(year, month, day) {
1080   cC.setDate(year, month, day);
1081 }
1082 function changeCCYear(change) {
1083   cC.changeYear(change);
1084 }
1085 function changeCCMonth(change) {
1086   cC.changeMonth(change);
1087 }
1088 document.write(\"<iframe id='CCIframe' src='javascript:false;' frameBorder='0' scrolling='no'></iframe>\");
1089 document.write(\"<div id='CC'></div>\");";
1090
1091      cache_js_file($fpath, $js);
1092     }
1093     add_js_ufile($fpath);
1094
1095  return '';
1096 }
1097
1098 function alert($msg)
1099 {
1100         echo "\n<script type=\"text/javascript\">\n"
1101                 . "<!--\n"
1102                 . "alert('$msg');\n"
1103                 . "-->\n"
1104                 . "</script>\n";
1105 }
1106
1107 if (!function_exists('_vd'))
1108 {
1109         function _vd($mixed, $title = '', $exit = false)
1110         {
1111         // Only the site admin is able to proceed here.
1112         $str = (!empty($title) ? ($title .':') : '') .'<pre>';
1113         $str .= print_r($mixed, true); //var_dump($mixed);
1114         $str .= "</pre>\n";
1115                 display_error('<table><tr><td>'.$str.'</td></tr></table>');
1116         if ($exit)
1117                 exit;
1118         }
1119 }
1120
1121 function display_backtrace($cond=true, $msg='') {
1122
1123         if ($cond) {
1124                 if ($msg) 
1125                         $str = "<center><span class='headingtext'>$msg</span></center>\n";
1126                 else
1127                         $str = '';
1128                 $str .= '<table border=0>';
1129         $trace = debug_backtrace();
1130                 foreach($trace as $trn => $tr) {
1131                         if (!$trn) continue;
1132                         $str .= '<tr><td>';
1133                         $str .= $tr['file'].':'.$tr['line'].': ';
1134                         $str .= '</td><td>';
1135                         if (isset($tr['type'])) {
1136                                 if($tr['type'] == '::') {
1137                                         $str .= $tr['class'].'::';
1138                                 } else if($tr['type'] == '->') {
1139                                         $str .= '('.$tr['class'].' Object)'.'->';
1140                                 }
1141                         }
1142                         foreach($tr['args'] as $n=>$a) {
1143                                 if (is_object($tr['args'][$n]))
1144                                         $tr['args'][$n] = "(".get_class($tr['args'][$n])." Object)";
1145                                 if (is_array($tr['args'][$n]))
1146                                         $tr['args'][$n] = "(Array[".count($tr['args'][$n])."])";
1147                                 else
1148                                         $tr['args'][$n] = "'".$tr['args'][$n]."'";
1149                         }
1150                         $str .= $tr['function'].'('. implode(',',$tr['args']).')</td>';
1151
1152                         $str .= '</tr>';
1153                 }
1154                 
1155                 $str .= '</table>';
1156         display_error($str);
1157         }
1158 }
1159
1160 ?>