Эх сурвалжийг харах

Merge branch 'chamilo19'

Conflicts:
	404.php
	documentation/changelog.html
	documentation/dependencies.html
	documentation/installation_guide.html
	documentation/optimization.html
	main/admin/careers.php
	main/admin/course_category.php
	main/admin/course_edit.php
	main/admin/course_import.php
	main/admin/index.php
	main/admin/session_import.php
	main/admin/session_list.php
	main/admin/user_add.php
	main/admin/user_list.php
	main/auth/courses.php
	main/auth/courses_controller.php
	main/auth/inscription.php
	main/auth/profile.php
	main/calendar/agenda.inc.php
	main/calendar/agenda.lib.php
	main/coursecopy/classes/Announcement.class.php
	main/coursecopy/classes/Attendance.class.php
	main/coursecopy/classes/Course.class.php
	main/coursecopy/classes/CourseArchiver.class.php
	main/coursecopy/classes/CourseBuilder.class.php
	main/coursecopy/classes/CourseRecycler.class.php
	main/coursecopy/classes/CourseRestorer.class.php
	main/coursecopy/classes/CourseSelectForm.class.php
	main/css/base.css
	main/css/bootstrap.css
	main/css/chamilo/images/header-logo.png
	main/css/responsive.css
	main/document/create_audio.php
	main/document/document.php
	main/document/download.php
	main/exercice/answer.class.php
	main/exercice/exercise.class.php
	main/exercice/exercise.lib.php
	main/exercice/exercise_result.class.php
	main/exercice/exercise_result.php
	main/exercice/exercise_show.php
	main/exercice/exercise_submit.php
	main/exercice/fill_blanks.class.php
	main/exercice/question.class.php
	main/exercice/question_list_admin.inc.php
	main/exercice/question_pool.php
	main/exercice/testcategory.class.php
	main/gradebook/index.php
	main/gradebook/lib/be/category.class.php
	main/gradebook/lib/fe/flatviewtable.class.php
	main/gradebook/lib/scoredisplay.class.php
	main/inc/ajax/agenda.ajax.php
	main/inc/ajax/exercise.ajax.php
	main/inc/ajax/model.ajax.php
	main/inc/global.inc.php
	main/inc/lib/add_course.lib.inc.php
	main/inc/lib/add_courses_to_session_functions.lib.php
	main/inc/lib/autoload.class.php
	main/inc/lib/banner.lib.php
	main/inc/lib/career.lib.php
	main/inc/lib/course.lib.php
	main/inc/lib/course_home.lib.php
	main/inc/lib/display.lib.php
	main/inc/lib/document.lib.php
	main/inc/lib/exercise_show_functions.lib.php
	main/inc/lib/groupmanager.lib.php
	main/inc/lib/javascript/jqgrid/js/jquery.jqGrid.min.js
	main/inc/lib/javascript/jquery.lp_minipanel.js
	main/inc/lib/link.lib.php
	main/inc/lib/log.class.php
	main/inc/lib/login.lib.php
	main/inc/lib/main_api.lib.php
	main/inc/lib/message.lib.php
	main/inc/lib/pear/HTML/QuickForm.php
	main/inc/lib/promotion.lib.php
	main/inc/lib/security.lib.php
	main/inc/lib/sessionmanager.lib.php
	main/inc/lib/symfony/Monolog/Handler/NativeMailerHandler.php
	main/inc/lib/usermanager.lib.php
	main/inc/lib/userportal.lib.php
	main/inc/local.inc.php
	main/install/index.php
	main/install/update-db-1.8.7-1.8.8.inc.php
	main/install/version.php
	main/lang/basque/course_info.inc.php
	main/lang/english/trad4all.inc.php
	main/lang/greek/admin.inc.php
	main/lang/greek/course_home.inc.php
	main/lang/greek/courses.inc.php
	main/lang/greek/messages.inc.php
	main/lang/greek/registration.inc.php
	main/lang/greek/reservation.inc.php
	main/lang/greek/survey.inc.php
	main/lang/greek/trad4all.inc.php
	main/lang/spanish/admin.inc.php
	main/lang/spanish/trad4all.inc.php
	main/mySpace/index.php
	main/newscorm/learnpath.class.php
	main/newscorm/scorm_api.php
	main/social/search.php
	main/survey/survey.lib.php
	main/template/default/admin/settings_index.tpl
	main/template/default/agenda/month.tpl
	main/template/default/layout/footer.tpl
	main/template/default/layout/head.tpl
	main/template/default/layout/login_form.tpl
	main/upload/upload_word.php
	main/user/user_import.php
	main/wiki/wiki.inc.php
	main/work/view.php
	main/work/work.lib.php
	main/work/work.php
	tests/phpunit/classes/UserManagerTest.lib.php
Julio Montoya 11 жил өмнө
parent
commit
e6a6c08c28
100 өөрчлөгдсөн 10129 нэмэгдсэн , 5264 устгасан
  1. 146 14
      documentation/changelog.html
  2. 28 16
      documentation/credits.html
  3. 1 1
      documentation/dependencies.html
  4. 3 0
      documentation/installation_guide.html
  5. 12 12
      documentation/installation_guide_es_ES.html
  6. 57 3
      documentation/optimization.html
  7. BIN
      favicon.ico
  8. 42 41
      main/admin/careers.php
  9. 45 27
      main/admin/course_category.php
  10. 7 5
      main/admin/course_edit.php
  11. 58 44
      main/admin/course_import.php
  12. 12 33
      main/admin/index.php
  13. 3 5
      main/admin/promotions.php
  14. 141 163
      main/admin/user_add.php
  15. 5 3
      main/admin/user_information.php
  16. 89 74
      main/admin/user_list.php
  17. 18 18
      main/auth/courses.php
  18. 26 18
      main/auth/courses_controller.php
  19. 5 8
      main/auth/inscription.php
  20. 122 224
      main/auth/profile.php
  21. 192 354
      main/calendar/agenda.inc.php
  22. 945 0
      main/calendar/agenda.lib.php
  23. 2 1
      main/course_home/activity.php
  24. 3 1
      main/course_info/infocours.php
  25. 50 50
      main/coursecopy/classes/Announcement.class.php
  26. 18 17
      main/coursecopy/classes/Attendance.class.php
  27. 299 297
      main/coursecopy/classes/Course.class.php
  28. 19 13
      main/coursecopy/classes/CourseArchiver.class.php
  29. 619 659
      main/coursecopy/classes/CourseBuilder.class.php
  30. 36 21
      main/coursecopy/classes/CourseRecycler.class.php
  31. 337 453
      main/coursecopy/classes/CourseRestorer.class.php
  32. 4 3
      main/coursecopy/classes/CourseSelectForm.class.php
  33. 3 0
      main/coursecopy/classes/Resource.class.php
  34. 36 0
      main/coursecopy/classes/Work.class.php
  35. 680 0
      main/cron/import_csv.php
  36. 151 184
      main/css/base.css
  37. BIN
      main/css/chamilo_electric_blue/images/header-logo.png
  38. BIN
      main/css/chamilo_green/images/header-logo.png
  39. BIN
      main/css/chamilo_orange/images/header-logo.png
  40. BIN
      main/css/chamilo_red/images/header-logo.png
  41. 0 2
      main/css/journal/bootstrap.css
  42. 0 2
      main/css/readable/bootstrap.css
  43. 14 0
      main/css/responsive.css
  44. BIN
      main/css/send_inv.png
  45. BIN
      main/css/send_inv_off.png
  46. BIN
      main/css/send_msg.png
  47. 0 2
      main/css/simplex/bootstrap.css
  48. 0 2
      main/css/spacelab/bootstrap.css
  49. 402 445
      main/document/create_audio.php
  50. 61 182
      main/document/document.php
  51. 10 10
      main/document/download.php
  52. 1 1
      main/document/upload.php
  53. 4 3
      main/dropbox/dropbox_class.inc.php
  54. 4 1
      main/exercice/admin.php
  55. 423 434
      main/exercice/answer.class.php
  56. 2350 0
      main/exercice/exercise.lib.php
  57. 25 12
      main/exercice/exercise_result.class.php
  58. 1 1
      main/exercice/showinframes.php
  59. 67 65
      main/gradebook/index.php
  60. 49 51
      main/gradebook/lib/be/forumthreadlink.class.php
  61. 497 492
      main/gradebook/lib/fe/flatviewtable.class.php
  62. 2 2
      main/gradebook/lib/fe/scoredisplayform.class.php
  63. 2 1
      main/gradebook/lib/gradebook_data_generator.class.php
  64. 246 248
      main/gradebook/lib/scoredisplay.class.php
  65. 10 2
      main/group/group_category.php
  66. BIN
      main/img/icons/22/course_na.png
  67. BIN
      main/img/icons/32/platform.png
  68. BIN
      main/img/icons/48/platform.png
  69. BIN
      main/img/logo.gif
  70. BIN
      main/img/logo.png
  71. 142 1
      main/inc/ajax/admin.ajax.php
  72. 5 7
      main/inc/ajax/agenda.ajax.php
  73. 1 1
      main/inc/ajax/course.ajax.php
  74. 25 0
      main/inc/ajax/form.ajax.php
  75. 47 3
      main/inc/ajax/model.ajax.php
  76. 30 0
      main/inc/ajax/session.ajax.php
  77. 3 1
      main/inc/lib/add_courses_to_session_functions.lib.php
  78. 1 1
      main/inc/lib/add_many_session_to_category_functions.lib.php
  79. 21 1
      main/inc/lib/career.lib.php
  80. 46 0
      main/inc/lib/course.lib.php
  81. 62 132
      main/inc/lib/exercise_show_functions.lib.php
  82. 2 0
      main/inc/lib/formvalidator/FormValidator.class.php
  83. 7 2
      main/inc/lib/group_portal_manager.lib.php
  84. 4 0
      main/inc/lib/groupmanager.lib.php
  85. 316 313
      main/inc/lib/javascript/jqgrid/js/jquery.jqGrid.min.js
  86. 51 14
      main/inc/lib/link.lib.php
  87. 6 7
      main/inc/lib/login.lib.php
  88. 1 1
      main/inc/lib/pclzip/pclzip.lib.php
  89. 388 0
      main/inc/lib/pear/Exception.php
  90. 50 0
      main/inc/lib/pear/HTML/QuickForm/Rule/CAPTCHA.php
  91. 58 53
      main/inc/lib/promotion.lib.php
  92. 460 2
      main/inc/lib/sessionmanager.lib.php
  93. 1 1
      main/inc/lib/social.lib.php
  94. 0 3
      main/inc/lib/usermanager.lib.php
  95. 6 0
      main/lang/arabic/admin.inc.php
  96. 7 0
      main/lang/arabic/agenda.inc.php
  97. 3 0
      main/lang/arabic/announcements.inc.php
  98. 1 0
      main/lang/arabic/course_home.inc.php
  99. 2 0
      main/lang/arabic/courses.inc.php
  100. 1 1
      main/lang/arabic/document.inc.php

+ 146 - 14
documentation/changelog.html

@@ -44,7 +44,6 @@
 <p><i>Note: most #wxyz references are issue numbers you can find in <a href="http://support.chamilo.org/projects/chamilo-18/issues" target="_blank">our public bug tracking system</a>. Some references marked BT#xyz are developments made externally for BeezNest customers and integrated into Chamilo. The details of these tasks cannot be seen for confidentiality reasons, but the code change is public and can be reviewed by anyone.</i></p>
 <p>&nbsp;</p>
 
-
 <h1>Chamilo 1.10.0 - ???, 31st of ???, 2012</h1>
 <h3>Release notes - summary</h3>
 <p>Chamilo 1.10.0 is a major stable version with loads of added features.</p>
@@ -68,39 +67,170 @@
   <li></li>
 </ul>
 
-<h1>Chamilo 1.9.6 - Mystery, 18th of April, 2013</h1>
+<h1>Chamilo 1.9.8 - Mystery name, Mystery date, 2013</h1>
 <h3>Release notes - summary</h3>
-<p>Chamilo 1.9.6 is a minor stable version with a series of improvements on top of 1.9.4.</p>
+<p>Chamilo 1.9.8 is a minor stable version with a series of improvements on top of 1.9.6.</p>
 <h3>Release name</h3>
-<p><a href="http://en.wikipedia.org/wiki/Mystery">Mystery</a> is a name we give new versions before we know their name. </p>
+<p><a href="http://fr.wikipedia.org/wiki/">City name</a> is a city ... </p>
+<h3>Security</h3>
+<ul>
+  <li></li>
+</ul>
 <h3>New Features</h3>
 <ul>
-  <li>Documents gallery now creates thumbnails to speed rendering up (#4536)</li>
-  <li>New "Impress" visualization for learning paths (#4595)</li>
-  <li>Show weight of current teacher's documents in session (#5298)</li>
-  <li>Show user data in admin tracking (#5723)</li>
-  <li>User import through CSV now accepts language (#5746)</li>
-  <li>Written assignments can be downloaded by teacher (#5805)</li>
+  <li></li>
 </ul>
 <h3>Improvements</h3>
 <ul>
+  <li>Increased maximum lifetime of videoconference sessions - now 5h (#6261)</li>
   <li></li>
 </ul>
 <h3>Debugging</h3>
 <ul>
   <li></li>
 </ul>
-<h3>Third-Party Libraries additions/updates</h3>
+<h3>Stylesheets and theming</h3>
 <ul>
   <li></li>
 </ul>
-<h3>Removals</h3>
+<h3>Web services</h3>
 <ul>
   <li></li>
 </ul>
+
+
+<h1>Chamilo 1.9.6 - Rochefort, 4th of June, 2013</h1>
+<h3>Release notes - summary</h3>
+<p>Chamilo 1.9.6 is a minor stable version with security patches and a series of improvements on top of 1.9.4.</p>
+<h3>Release name</h3>
+<p><a href="http://fr.wikipedia.org/wiki/Rochefort_%28Belgique%29">Rochefort</a> is a small city in the South of Belgium, that has existed at least since year 1041 and has shown impressive resilience and stability, which we think 1.9.6 has reached as well. Rochefort's Brewery produces a very nice trappist beer exported even to Peru! As we are getting ready for a larger battle, getting Chamilo LMS every day to a larger community, we thought we'd make a last quiet stop and salute the little town where several contributors of Chamilo have set foot in the past.</p>
+<h3>Security</h3>
+<ul>
+  <li>Fixed XSS vulnerabilities in announcement, blog and chat tools - see <a href="https://support.chamilo.org/projects/chamilo-18/wiki/Security_issues">our security page for details</a></li>
+  <li>Fixed unreported design flaw in e-mail password resetter</li>
+</ul>
+<h3>New Features</h3>
+<ul>
+  <li>Documents gallery now creates thumbnails to speed rendering up (#4536)</li>
+  <li>New "Impress" visualization for learning paths (#4595)</li>
+  <li>Show weight of current teacher's documents in session (#5298)</li>
+  <li>Added system tracking for homepage edition (#5597)</li>
+  <li>Show user data in admin tracking (#5723)</li>
+  <li>User import through CSV now accepts language (#5746)</li>
+  <li>Online-text assignments can be downloaded by teacher (#5805)</li>
+  <li>Added improved permissions checker to installer to avoid HTTP 500 Server error page when entering the course on a Security Enhanced server (#5863)</li>
+  <li>Added feature to "Mark all as read" in social messaging (#6019)</li>
+</ul>
+<h3>Improvements</h3>
+<ul>
+  <li>Fixed wrong uploader user reference in e-mail sent to teacher when assignment is uploaded (#5970)</li>
+  <li>Added return link on top of courses tree on homepage (#5986)</li>
+  <li>Set minimum certification score to 75 by default in gradebook (#6001)</li>
+  <li>Changed "Edit settings" label in groups edition (#6003)</li>
+  <li>Improved (visually) the procedure to add new friends in the social network (#6015)</li>
+  <li>Added "Re:[subject]" as title to answers in social messaging (#6018)</li>
+  <li>Authorize .psd files uploads in custom stylesheet uploads to avoid frustration (#6038)</li>
+  <li>Updated logo of all Chamilo styles with the new logo</li>
+  <li>Improved visualization of very long assignments titles (cut at 27 chars)(#6163)</li>
+  <li>Reverted the order of columns in gradebook flat view graphics (linked to #5883 but not exactly the topic)</li>
+</ul>
+<h3>Debugging</h3>
+<ul>
+  <li>Fixed filter function in agenda tool (#2238)</li>
+  <li>Fixed bug preventing HotPotatoes exercises from opening for students (#3993)</li>
+  <li>Fixed missing conclusion text for exercises when seen from LP (#4227)</li>
+  <li>Fixed bug changing forum post as main thread when edited by admin (#4271)</li>
+  <li>Fixed bug preventing the creation of links in assignments description (#4374)</li>
+  <li>Fixed confusing message for expired session (#4797)</li>
+  <li>Fixed bug preventing import of large course backup files (#5334)</li>
+  <li>Fixed confusing Nanogong text in admin settings (#5400)</li>
+  <li>Fixed fonts size in Windows 7 (#5410)</li>
+  <li>Fixed messaging isolation bug in multi-URL installations (#5441)</li>
+  <li>Fixed bug importing backup copy (#5460)</li>
+  <li>Fixed bug in survey not showing questions when invitation sent by mail (#5529)</li>
+  <li>Fixed header in backup progress page (#5540)</li>
+  <li>Fixed teacher viewing more folders in drop-down list (#5555)</li>
+  <li>Fixed side panel not hiding in learning path when using through mobile device (#5563)</li>
+  <li>Fixed 1.9.4 installation bug (#5565)</li>
+  <li>Fixed wrong number of questions in survey list (#5567)</li>
+  <li>Fixed reverse numbering of courses and users in sessions reporting block (#5594)</li>
+  <li>Fixed users import from CSV in groups (#5603)</li>
+  <li>Fixed groups too visible (#5608)</li>
+  <li>Fixed score bug in exercise showing different scores to student and teacher (#5623)</li>
+  <li>Fixed bug preventing edition of groups (#5625)</li>
+  <li>Fixed visual bug in admin section, caused by mobile tweaks (#5660)</li>
+  <li>Fixed bug in course code handling when importing users through CSV in course (#5670)</li>
+  <li>Fixed crypto bug when upgrading from 1.8.8.4 to 1.9.2 (#5685)</li>
+  <li>Fixed users edition bug after upgrading from 1.8.8.4 to 1.9.2 (#5687)</li>
+  <li>Fixed wrong link in mail sent to user when a test has been reviewed by the teacher (#5697)</li>
+  <li>Fixed bug in teacher report chart in admin dashboard (#5713)</li>
+  <li>Fixed bug in end of HotPotatoes tests (#5719)</li>
+  <li>Fixed quick toolbar icons not showing nicely in IE (#5733)</li>
+  <li>Fixed e-mail sender for teacher announcements (#5738)</li>
+  <li>Fixed missing images after backup restoration (#5765)</li>
+  <li>Fixed bug preventing user from changing his stylesheet (#5767)</li>
+  <li>Fixed notice message in local.inc.php (#5769)</li>
+  <li>Fixed display bugs in IE (#5775)</li>
+  <li>Fixed "FillGroup" confusing translation (#5778)</li>
+  <li>Fixed students limit in a class (#5804)</li>
+  <li>Removed mail sending to students when exercise is "exam" type (#5807)</li>
+  <li>Fixed group chat history not being logged in documents (#5837)</li>
+  <li>Fixed missing removal of survey invitations and answers on delete_user() call (#5847)</li>
+  <li>Fixed course subcategories not showing after adding new course on same category (#5850)</li>
+  <li>Fixed learning path view in student mode (#5855)</li>
+  <li>Removed double course code info in admin courses list (#5865)</li>
+  <li>Fixed bug preventing the printing of the gradebook flat view page (#5883)</li>
+  <li>Fixed bug in BigBlueButton videoconference plugin to enable audio (#5884)</li>
+  <li>Fixed several issues in recording of videoconference sessions (#5885)</li>
+  <li>Fixed bug preventing the update of users picture (#5903)</li>
+  <li>Fixed minor notice message about is_courseCoach (#5909)</li>
+  <li>Fixed message when max_upload_filesize reached (#5938)</li>
+  <li>Fixed downloadability of assignment when "invisible" (#5947)</li>
+  <li>Fixed PDF export to include images (#5948)</li>
+  <li>Fixed translation quirks for Spanish (#5949)</li>
+  <li>Fixed bug removing students answers when modifying question (#5950)</li>
+  <li>Fixed issue giving wrong time info in backup filename (#5951)</li>
+  <li>Fixed horizontal/vertical view in survey questions (#5956)</li>
+  <li>Fixed big issue in IE7&amp;8 preventing to move to the next question in exercises (#5957)</li>
+  <li>Fixed bug not showing phone number in student details (#5958)</li>
+  <li>Fixed list of sessions not showing sessions (#5960)</li>
+  <li>Fixed issue blocking the switch between tabs in session view (#5961)</li>
+  <li>Fixed list of assignments not showing course assignments in session (#5963)</li>
+  <li>Fixed issue uploading custom stylesheets (#5967)</li>
+  <li>Fixed display issue in scoring system (gradebook) (#5969)</li>
+  <li>Re-applied chart appearing in session view (#5971)</li>
+  <li>Fixed missing title attribute in links on course homepage (#5976)</li>
+  <li>Fixed missing images in glossary export (#5979)</li>
+  <li>Fixed locking of user subscription to session when name contains special character (#5981)</li>
+  <li>Aligned pager icons in images gallery (#5982)</li>
+  <li>Minor orthographic fixes (#5985,#5987,#6002,#6063 and many others not referenced)</li>
+  <li>Fixed CSS for categories list on homepage (#5989)</li>
+  <li>Fixed missing results after exercise taken in learning path (#5990)</li>
+  <li>Fixed style between course title and teacher name in courses tree on homepage (#5991)</li>
+  <li>Fixed alignment in questions list for small screen resolutions (#5995)</li>
+  <li>Fixed SQL error in update-db-1.8.7-1.8.8.inc.php (#5998)</li>
+  <li>Fixed bug preventing change of password in profile (#5999, #6127)</li>
+  <li>Fixed bug preventing display of documents templates when adding an element to the learning path (#6000)</li>
+  <li>Fixed security issue allowing a student to take hiddn tests through the progress page (#6014)</li>
+  <li>Fixed SQL error when uploading file to dropbox without destination (#6034)</li>
+  <li>Fixed regression for score in forum threads (#6035)</li>
+  <li>Fixed issue deleting one document at a time through course recycling feature (#6045)</li>
+  <li>Fixed visibility of files in group documents for sender when just uploaded (#6046)</li>
+  <li>Fixed bug preventing the re-enabling of the table of contents in learning paths (#6047)</li>
+  <li>Fixed minor issue loading glyphicons from bootstrap.css (#6049)</li>
+  <li>Fixed issue in Portuguese date format (#6054)</li>
+  <li>Fixed security issue with reset password e-mail (#6113)</li>
+  <li>Fixed warning in gradebook (#6122)</li>
+  <li>Fixed bug preventing session coach to import users in his session even when authorized by admin (#6141)</li>
+  <li>Fixed display issue in long HotPotatoes tests (#6150)</li>
+  <li>Fixed learning path student view issue created from improvements to user experience (#6154)</li>
+  <li>Fixed bug with jqgrid column titles character set not showing properly (#6159)</li>
+  <li>Fixed missing variable definition in check_abs_path() function (#5705)</li>
+  <li>Fixed bug whereby non-admin coaches can't see the details of an exam in a session (#6160)</li>
+</ul>
 <h3>Stylesheets and theming</h3>
 <ul>
-  <li></li>
+  <li>Updated Chamilo logo in default styles</li>
 </ul>
 <h3>Web services</h3>
 <ul>
@@ -379,6 +509,7 @@
   <li>Added session-box-text and session-item elements to improve styling</li>
   <li>Modified #main_content to #top_main_content to avoid double #main_content id on the same page</li>
 </ul>
+  
 
 
 <h1>Chamilo 1.9.2 - Hanga Roa, 27th of September, 2012</h1>
@@ -476,6 +607,7 @@
   <li>Social network: An user could not modify its own official code, even if configured to be possible (#5538)</li>
 </ul>
 
+
 <h1>Chamilo 1.9.0 - Vogüé, 31st of July, 2012</h1>
 
 <h3>Release notes - summary</h3>
@@ -536,7 +668,7 @@ This version of Chamilo includes a few new features.
   <li>Assignments: The teacher can now download all files from a specific assignment in one Zip (#4687)</li>
   <li>Documents: Added Flash(TM) webcam photoboot, whereby teachers (or students through groups) can take pictures from their webcam, wich get uploaded to the documents tool directly (#4856) (enable through admin settings)</li>
   <li>Plugins: Added plugin for School Server of OLPC Perú project (Squid proxy filtering from course) (#4925)</li>
-  <li>Exerciss: Added new type of questions that automate the repartition of score between available answers (#5012)</li>
+  <li>Exercises: Added new type of questions that automate the repartition of score between available answers (#5012)</li>
   <li>Exercises: Time counter now changes color at 3, then 1 minute to increase awareness of student, and appears nicely in all-questions-on-one-page exercises (#5043, #5267)</li>
   <li>System: The stats collection of Chamilo.org is now automatic. If you want to disable this feature, edit admin/index.php and look for fsockopen() (#5104)</li>
   <li>Global: Improvements for iPad(TM) and iPhone(TM) by disabling auto-capitalization (#5116)</li>

+ 28 - 16
documentation/credits.html

@@ -62,6 +62,7 @@ In the following credits, when possible, we tried to put the latest contributors
 <ul>
   <li>Julio Allen Montoya Armas (gugli100@gmail.com) - Lead developer - BeezNest, France</li>
   <li>Yannick Warnier (yannick.warnier@beeznest.com) - Technical coordinator, Project Leader - BeezNest, Peru</li>
+  <li>Yoselyn Castillo (yoselyn.castillo@beeznest.com) - Maintainer developer - BeezNest, Cuba</li>
   <li>Coursenligne45 - Anonymous reporter and contributor to many bugfixes - France</li>
   <li>Hubert Borderiou - Developer responsible for exercises categories and many other practical fixes - Université de Grenoble, France</li>
   <li>Juan Carlos Raña Trabado - Independent developer and mastermind for documents, wiki and other pedagogical tools - Spain</li>
@@ -73,17 +74,24 @@ In the following credits, when possible, we tried to put the latest contributors
 
 <h2>Previous versions</h2>
 <ul>
-  <li>BeezNest Latino (ex Dokeos Latinoamérica) (2008-2012)
+  <li>BeezNest Latino (2007-2013) (aka Dokeos Latinoamérica from 2007-2009)
   <ul>
       <li>Yannick Warnier (ywarnier@beeznest.org) - Lead developer</li>
       <li>Julio Allen Montoya Armas (gugli100@gmail.com) - Lead Latino developer</li>
       <li>Christian Fasanando (christian534@hotmail.com) - 2009-2010</li>
+      <li>Yoselyn Castillo (yoselyn.castillo@beeznest.com) - Maintainer developer</li>
     </ul>
     </li>
-    <li>Independent (2008-2012)
+    <li>Independent (2008-2013)
     <ul>
-      <li> Juan Carlos Raña Trabado - considerable work on the wiki integration and improvements, and the FCKEditor/Mimetex extension as well as *many* FCKEditor's file manager and other modules improvements, as well as a continuous stream of recommendations that helped shape 1.8.5 and 1.8.6.*</li>
-      <li> Ivan Tcholakov - various bugfixes in 1.8.6.*, very accurate bug reporting contributions and a considerable work in the integration of a new version of FCKEditor, along with a bunch of useful plugins and an exceptional work on internationalization</li>
+      <li>Juan Carlos Raña Trabado - considerable work on the wiki integration and improvements, and the FCKEditor/Mimetex extension as well as *many* FCKEditor's file manager and other modules improvements, as well as a continuous stream of recommendations that helped shape 1.8.5 and 1.8.6.*</li>
+      <li>Ivan Tcholakov - various bugfixes in 1.8.6.*, very accurate bug reporting contributions and a considerable work in the integration of a new version of FCKEditor, along with a bunch of useful plugins and an exceptional work on internationalization</li>
+      <li>Coursenligne45 - Anonymous reporter and contributor to many bugfixes - France</li>
+    </ul>
+    </li>
+    <li>Université de Grenoble, France (2011-2013)
+    <ul>
+      <li>Hubert Borderiou - Reporter and occasional developer</li>
     </ul>
     </li>
     <li>Dokeos (2004-2009)
@@ -123,15 +131,15 @@ In the following credits, when possible, we tried to put the latest contributors
 <a name="quality-assurance"></a>
 <h1>Quality Assurance</h1>
 <ul>
-  <li>Yannick Warnier as QA coordinator</li>
-  <li>Yoselyn Castillo</li>
-  <li>Jeremy Saavedra</li>
-  <li>Coursenligne on the forum</li>
-  <li>Noa Orizales, through numerous implementations in Spain</li>
-  <li>Hector Lacherre and colleagues from USIL, Lima</li>
-  <li>Carlos Vargas</li>
-  <li>Arthur Portugal</li>
-  <li>Ricardo Rodriguez</li>
+  <li>Yannick Warnier as QA coordinator (2008-2013)</li>
+  <li>Noa Orizales, through numerous implementations in Spain (2008-2013)</li>
+  <li>Coursenligne on the forum (2012-2013)</li>
+  <li>Yoselyn Castillo (2012-2013)</li>
+  <li>Jeremy Saavedra (2012)</li>
+  <li>Hector Lacherre and colleagues from USIL, Lima (2008-2011)</li>
+  <li>Carlos Vargas (2009)</li>
+  <li>Arthur Portugal (2009)</li>
+  <li>Ricardo Rodriguez (2009)</li>
 </ul>
 
 <a name="performance"></a>
@@ -549,8 +557,13 @@ There are too much translators to list them all. Please check http://translate.c
 <a name="documentation"></a>
 <h1>Documentation</h1>
 <ul>
-  <li>Arnaud Ligot</li>
+  <li>Yannick Warnier</li>
+  <li>Steve Miller</li>
+  <li>Anaël Boulier</li>
+  <li>Laura Guirao</li>
+  <li>José Garcia</li>
   <li>Jerome Warnier</li>
+  <li>Arnaud Ligot</li>
   <li>Andrew Lynn (alynn@strathclyde.ac.be)</li>
   <li>Emmanuel Pecquet (emmanuel.pecquet@wanadoo.fr) </li>
   <li>Nikolai Stiehl (nikolai.stiehl@web.de)</li>
@@ -562,10 +575,8 @@ There are too much translators to list them all. Please check http://translate.c
   <li>Roan Embrechts (roan.embrechts@vub.ac.be)</li>
   <li>Hugues Peeters</li>
   <li>René Haentjens</li>
-  <li>Yannick Warnier</li>
   <li>Arthur Portugal</li>
   <li>Sergio Infante Montero, for (humble) technical documentation translation to Spanish</li>
-  <li>Steve Miller</li>
 </ul>
 
 <a name="special-thanks"></a>
@@ -665,6 +676,7 @@ Note that we are infinitely grateful to our translators, having made the spread
   <li>Jeremy Saavedra, for bug reports in LMS 1.9.2</li>
   <li>Ricel Leite, for bug reports and fixes in LMS 1.9.4</li>
   <li>Fausto Puppo, for bug reports and testing on exercises and learning paths in LMS 1.9.4</li>
+  <li>Carlos del Solar, for bug reports and testing on exercises and learning paths in LMS 1.9.4</li>
   <li>Alexander Hu, for bug reports in LMS 1.9.4</li>
   <li>Fernando Muñoz (occasionally via Secunia SVCRP) for multiple security vulnerability reports in Chamilo 1.8-1.9</li>
   <li>All the supporting parents, partners, children, friends, colleagues and sometimes students, of the very special geeks that we are, for their continous support and inspiration</li> 

+ 1 - 1
documentation/dependencies.html

@@ -57,7 +57,7 @@ required information to install it.</p>
 <a name="dependencies"></a>
 <h2>Dependencies - client-side</h2>
 <ul>
-  <li>Any modern browser (IE6 *excluded*). Safari is known to have minor issues with the WYSIWYG editor.</li>
+  <li>Any modern browser (IE6 is obviously *excluded*). Safari is known to have small issues with the WYSIWYG editor.</li>
   <li>Optional: Flash plugin (only required for a few features)</li>
 </ul>
 <h2>Dependencies - server-side</h2>

+ 3 - 0
documentation/installation_guide.html

@@ -109,6 +109,7 @@ previously required to choose between multiple databases and a deprecated single
 
 <hr style="width: 100%; height: 2px;" />
 <h2><a name="2._Installation_of_Chamilo_LMS"></a><span style="font-weight: bold;">2. Installation of Chamilo LMS</span></h2>
+
 <h3>Configuring your web server to allow .htaccess overrides</h3>
 Starting from 1.10, Chamilo LMS allows friendly URLs if using Apache. As it is based on .htaccess and rewrites, you will be required to <b>AllowOverride All</b> (and possibly enable the ModRewrite extension for Apache). This means that, inside your Apache configuration (or your VirtualHost configuration), you will need to have a block similar to this (the directory given is the same as in the <i>DocumentRoot</i> directive):
 <pre>
@@ -264,7 +265,9 @@ And optionally (for more features) the following PHP modules:
 </ul>
 
 To get the best out of Chamilo, you need to finetune your PHP settings. Consider : <br />
+
 <ul>
+
   <li>Editing php.ini file (on Windows can be located at 
   <span style="font-weight: bold;">C:\xampp\php\php.ini</span>, 
   on Ubuntu : 

+ 12 - 12
documentation/installation_guide_es_ES.html

@@ -261,7 +261,7 @@ date.timezone = 'America/Lima'
 </p>
 
 <hr />
-<h2><a name="3._Upgrade_from_a_previous_version_of"></a>3. Actualizar desde una versión previa de Chamilo LMS (1.*) o Dok€os (<2.0)</h2>
+<h2><a name="3._Upgrade_from_a_previous_version_of"></a>3. Actualizar desde una versión previa de Chamilo LMS (1.*) o Dok€os (&lt;2.0)</h2>
 
 <p>
 Antes de actualizar, le recomendamos <b>seriamente</b> que haga una copia de seguridad de los directorios
@@ -282,7 +282,7 @@ Dado que se trata sólo de un cambio de versión menor  previa de Chamilo 1.9.*,
 <li>Revisar que no ha dejado alguna hoja de estilo personalizada o imagen (si es que tiene, asegúrese de guardar una copia de respaldo)</li>
 <li>Descargar el paquete de instalación de Chamilo 1.9 desde la página de descarga de Chamilo</li>
 <li>Descomprimir los nuevos archivos de Chamilo 1.9 sobre los archivos de la versión anterior (o descomprimirlos en una nueva carpeta y después copiarlos sobre los archivos de la versión anterior)</li>
-<li>Editar el archivo main/inc/conf/configuration.php: hacia el final del archivo, localizar el número de la versión (p.e. ‘1.9.2’) y cambiarlo por la nueva versión (p.e.‘1.9.4’)</li>
+<li>Editar el archivo main/inc/conf/configuration.php: hacia el final del archivo, localizar el número de la versión (p.e. ‘1.9.4’) y cambiarlo por la nueva versión (p.e.‘1.9.8’)</li>
 <li>Ya está! Ningún otro procedimiento de actualización es requerido.</li>
 </ul>
 </p>
@@ -420,11 +420,11 @@ Escribir en la línea de comandos:
   <li>mkdir /var/www/chamilo/version_antigua</li>
   <li>mv /var/www/chamilo/* /var/www/chamilo/version_antigua/</li>
   <li>chmod -R 0777 /var/www/chamilo/version_antigua/</li>
-  <li>wget http://www.chamilo.org/files/chamilo-1.9.tar.gz</li>
-  <li>tar zxvf chamilo-1.9.tar.gz</li>
-  <li>sudo cp -ra chamilo-1.9/* /var/www/chamilo/</li>
-  <li>rm chamilo-1.9.tar.gz</li>
-  <li>sudo rm -r chamilo-1.9/</li>
+  <li>wget http://www.chamilo.org/files/chamilo-1.9.8.tar.gz</li>
+  <li>tar zxvf chamilo-1.9.8.tar.gz</li>
+  <li>sudo cp -ra chamilo-1.9.8/* /var/www/chamilo/</li>
+  <li>rm chamilo-1.9.8.tar.gz</li>
+  <li>sudo rm -r chamilo-1.9.8/</li>
 </ul>
 
 <br />
@@ -706,7 +706,7 @@ sudo /etc/init.d/apache2 restart
 </pre>
 </p>
 <p>
-A continuación, vaya a la página de administración -> Ajustes de configuración -> Buscar y habilitar la herramienta de búsqueda. Siga las recomendaciones de la página para obtener la suite completa de indexación instalada. Una vez que haya terminado, todos los documentos importados en su portal Chamilo en un formato reconocido serán indexados y buscados. En formación de administradores de Chamilo ( el cual puede preguntar a cualquier <a href="http://www.chamilo.org/en/providers">Proveedor Oficial de Chamilo</a>) incluyen una revisión completa de la función de búsqueda de texto completo.
+A continuación, vaya a la página de administración -&gt; Ajustes de configuración -&gt; Buscar y habilitar la herramienta de búsqueda. Siga las recomendaciones de la página para obtener la suite completa de indexación instalada. Una vez que haya terminado, todos los documentos importados en su portal Chamilo en un formato reconocido serán indexados y buscados. En formación de administradores de Chamilo ( el cual puede preguntar a cualquier <a href="http://www.chamilo.org/en/providers">Proveedor Oficial de Chamilo</a>) incluyen una revisión completa de la función de búsqueda de texto completo.
 </p>
 
 <hr style="width: 100%; height: 2px;" />
@@ -718,11 +718,11 @@ Nota: Este paso requiere un servidor dedicado o un servidor dedicado virtual ya
 En Debian o Ubuntu 11.10 y superior, instale LibreOffice.org v3 e iniciarlo como un servidor en segundo plano:
 <pre>
 sudo apt-get install libreoffice
-sudo soffice "--accept=socket,host=127.0.0.1,port=2002,tcpNoDelay=1;urp;" --headless --nodefault --nofirststartwizard --nolockcheck --nologo --norestore
+sudo soffice -accept="socket,host=127.0.0.1,port=2002,tcpNoDelay=1;urp;" -headless -nodefault -nofirststartwizard -nolockcheck -nologo -norestore &amp;
 </pre>
 </p>
 <p>
-A continuación, vaya a la página de administración -> Chamilo Rapid y establecer el host a "localhost" y el puerto a "2002". Guarde los cambios. Vaya a su curso, en la pantalla de herramientas de aprendizaje y verá que apareció un nuevo icono. Importar tu PPT. Esto debería funcionar.
+A continuación, vaya a la página de administración -&gt; Chamilo Rapid y establecer el host a "localhost" y el puerto a "2002". Guarde los cambios. Vaya a su curso, en la pantalla de herramientas de aprendizaje y verá que apareció un nuevo icono. Importar tu PPT. Esto debería funcionar.
 </p>
 <p>
 Nota: A veces, esto no se resuelve tan fácilmente. Usted probablemente tenga que solicitar la asistencia de algún administrador de sistemas con un poco de experiencia en  Java y PHP, o siempre podrá preguntar a uno de los proveedores oficiales de Chamilo para asistirle (pregunte por un contrato comercial garantizado).
@@ -751,11 +751,11 @@ Como Chamilo se hace más popular y atraviesa muchas fronteras ahora, es frecuen
 <p>
 Esto fácilmente se puede modificar editando el archivo main/inc/lib/internationalization_database/name_order_conventions.php, buscando nuestro idioma y cambiando los campos. Es tan simple que se explica por sí mismo y se ve así:
 <pre>
-'simpl_chinese' => array( 'format' => 'title last_name first_name', 'sort_by' => 'last_name' ), // Eastern order
+'simpl_chinese' =&gt; array( 'format' =&gt; 'title last_name first_name', 'sort_by' =&gt; 'last_name' ), // Eastern order
 </pre>
 Siéntase libre de cambiar esto a
 <pre>
-'simpl_chinese' => array( 'format' => 'title first_name lastname', 'sort_by' => 'last_name' ), // Eastern order
+'simpl_chinese' =&gt; array( 'format' =&gt; 'title first_name lastname', 'sort_by' =&gt; 'last_name' ), // Eastern order
 </pre>
 por ejemplo. El efecto debería ser inmediato.
 </p>

+ 57 - 3
documentation/optimization.html

@@ -38,8 +38,10 @@
 
 
 <h2><b>Contents</b></h2>
+
 <ol>
-  <li><a href="#1.Using-XCache">Using xCache or APC</a></li>
+
+  <li><a href="#1.Using-XCache">Using xCache, APC or Memcache</a></li>
   <li><a href="#2.Slow-queries">Slow queries</a></li>
   <li><a href="#3.Indexes-caching">Indexes caching</a></li>
   <li><a href="#4.Sessions-directories">Sessions directories</a></li>
@@ -47,6 +49,7 @@
   <li><a href="#6.Zlib-compression">Zlib compressed output</a></li>
   <li><a href="#7.High-numbers-memory">Memory considerations for high numbers of users</a></li>
   <li><a href="#8.HTTP-caching-media">HTTP caching for media</a></li>
+  <li><a href="#9.Avoid-non-fixed-values">Avoiding non-fixed values</a></li>
 </ol>
 
 <h2><a name="1.Using-XCache"></a>1. Using xCache or APC</h2>
@@ -94,6 +97,44 @@ if(!empty($_course['id'])) {
 }
 </pre>
 Note that, as xCache is a shared caching system, it is very important to prefix your variables with a domain name or some kind of identifier, otherwise it would end up in disaster if you use a shared server for several portals.<br />
+If you use php5-memcache, then this piece of code would look like this (you need to adjust depending on your settings):
+<pre>
+    global $_configuration;
+    $_course    = api_get_course_info();
+    $course_id  = api_get_course_id();
+    $user_id    = api_get_user_id();
+
+    $html = '';
+    $xc = method_exists('Memcache','add');
+    if ($xc) {
+        // Make sure the server is available
+        $xm = new Memcache;
+        $xm->addServer('localhost', 11211);
+        $xc = $xc && ($xm->getServerStatus('localhost',11211)!=0);
+        // The following concatenates the name of the database + the id of the
+        // access url to make it a unique variable prefix for the variables to
+        // be stored
+        $xs = $_configuration['main_database'].'_'.$_configuration['access_url'].'_';
+    }
+    $number = 0;
+    if ((api_get_setting('showonline', 'world') == 'true' AND !$user_id) OR (api_get_setting('showonline', 'users') == 'true' AND $user_id) OR (api_get_setting('showonline', 'course') == 'true' AND $user_id AND $course_id)) {
+        if ($xc && $xm->get($xs.'wio_count_simple')) {
+            $number = $xm->get($xs.'wio_count_simple');
+        } else {
+            $number = who_is_online_count(api_get_setting('time_limit_whosonline'));
+            $xm->set($xs.'wio_count_simple',$number,0,30);
+        }
+
+        $number_online_in_course = 0;
+        if(!empty($_course['id'])) {
+            if ($xc && $xm->get($xs.'wio_count_simple_'.$_course['id'])) {
+                $number_online_in_course = $xm->get($xs.'wio_count_simple_'.$_course['id']);
+            } else {
+                $number_online_in_course = who_is_online_in_this_course_count($user_id, api_get_setting('time_limit_whosonline'), $_course['id']);
+                $xm->set($xs.'wio_count_simple_'.$_course['id'],$number_online_in_course,0,30);
+            }
+        }
+</pre>
 <br />
 An optional additional caching mechanism you may use is the realpath_cache_size and realpath_cache_ttl php.ini parameters. See <a href="http://php.net/manual/en/ini.core.php">the PHP documentation</a> for more details.
 <br />
@@ -160,7 +201,6 @@ ALTER TABLE session_rel_course_rel_user ENGINE=INNODB;
 </pre>
 If used on large tables, this might take a considerable time (can take around 60s for a million rows), so try to execute at night or during lower usage periods.
 </p>
-
 <hr />
 <h2><a name="3.Indexes-caching"></a>3. Indexes caching</h2>
 One good reference: <a href="http://dev.mysql.com/doc/refman/5.1/en/multiple-key-caches.html">MySQL documentation on multiple key caches</a><br />
@@ -301,9 +341,23 @@ These settings explicitly mention the file MIME types that will be put in cache,
 If you want to change some content put in cache by the client, though, you will need to change the name of the file (and its reference in the HTML/PHP file that includes it).<br />
 This is an easy way to massively reduce your bandwidth (80% reduction?), the speed of page loading for your users and the use of resources on your web server.
 </p>
+
+<h2><a name="#9.Avoid-non-fixed-values"></a>Avoiding non-fixed values</h2>
+Many things in Chamilo are written focusing on the ease of use, even for the administrator. Sometimes, these settings are weighing a little bit more on the system. This is the case, between others, of the mail.conf.php file (being loaded unconditionally) and its CONSTANT "IS_WINDOWS_OS", which is defined by a function call (api_is_windows_os()) at the beginning of main_api.lib.php.
+
+The definition of this constant (which is executed at *every* page load) can easily be avoided, and the only place where it is used inconditionally (mail.conf.php) can be modified to set the line as you expect it (depending on whether you use sendmail/exim or smtp).
+<pre>
+$platform_email['SMTP_MAILER']       = 'smtp';
+</pre>
+or
+<pre>
+$platform_email['SMTP_MAILER']       = 'mail';
+</pre>
+In fact, the complete loading of mail.conf.php can also be avoided if loaded conditionally (with <i>require_once</i>) when sending an e-mail (which is the only case where it is useful).
+<hr />
 <h2>Authors</h2>
 <ul>
-<li>Yannick Warnier, Zend Certified PHP Engineer, BeezNest Belgium SPRL, <a href="mailto:yannick.warnier@beeznest.com">yannick.warnier@beeznest.com</a></li>
+<li>Yannick Warnier, Zend Certified PHP Engineer, BeezNest Belgium SPRL, <a href="mailto:ywarnier@beeznest.net">ywarnier@beeznest.net</a></li>
 </ul>
 </div>
 </body>

BIN
favicon.ico


+ 42 - 41
main/admin/careers.php

@@ -2,7 +2,7 @@
 /* For licensing terms, see /license.txt */
 
 /**
- * @package chamilo.admin
+ *  @package chamilo.admin
  */
 
 // Language files that need to be included.
@@ -15,39 +15,40 @@ $this_section = SECTION_PLATFORM_ADMIN;
 
 api_protect_admin_script();
 
+
 //Add the JS needed to use the jqgrid
 $htmlHeadXtra[] = api_get_jqgrid_js();
 
 // setting breadcrumbs
-$interbreadcrumb[] = array('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
-$interbreadcrumb[] = array('url' => 'career_dashboard.php', 'name' => get_lang('CareersAndPromotions'));
+$interbreadcrumb[]=array('url' => 'index.php','name' => get_lang('PlatformAdmin'));
+$interbreadcrumb[]=array('url' => 'career_dashboard.php','name' => get_lang('CareersAndPromotions'));
 
 $action = isset($_GET['action']) ? $_GET['action'] : null;
 
 $check = Security::check_token('request');
-$token = Security::get_token();
+$token = Security::get_token();    
 
 if ($action == 'add') {
-    $interbreadcrumb[] = array('url' => 'careers.php', 'name' => get_lang('Careers'));
-    $interbreadcrumb[] = array('url' => '#', 'name' => get_lang('Add'));
+    $interbreadcrumb[]=array('url' => 'careers.php','name' => get_lang('Careers'));
+    $interbreadcrumb[]=array('url' => '#','name' => get_lang('Add'));
 } elseif ($action == 'edit') {
-    $interbreadcrumb[] = array('url' => 'careers.php', 'name' => get_lang('Careers'));
-    $interbreadcrumb[] = array('url' => '#', 'name' => get_lang('Edit'));
+    $interbreadcrumb[]=array('url' => 'careers.php','name' => get_lang('Careers'));    
+    $interbreadcrumb[]=array('url' => '#','name' => get_lang('Edit'));
 } else {
-    $interbreadcrumb[] = array('url' => '#', 'name' => get_lang('Careers'));
+    $interbreadcrumb[]=array('url' => '#','name' => get_lang('Careers'));
 }
 
 Display::display_header();
 
 //jqgrid will use this URL to do the selects
-$url = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_careers';
+$url            = api_get_path(WEB_AJAX_PATH).'model.ajax.php?a=get_careers';
 
-//The order is important you need to check the the $column variable in the model.ajax.php file
-$columns = array(get_lang('Name'), get_lang('Description'), get_lang('Actions'));
+//The order is important you need to check the the $column variable in the model.ajax.php file 
+$columns        = array(get_lang('Name'), get_lang('Description'), get_lang('Actions'));
 
 //Column config
-$column_model = array(
-    array('name' => 'name', 'index' => 'name', 'width' => '80', 'align' => 'left'),
+$column_model   = array(
+    array('name'=>'name',           'index'=>'name',        'width'=>'80',   'align'=>'left'),
     array(
         'name'     => 'description',
         'index'    => 'description',
@@ -63,11 +64,11 @@ $column_model = array(
         'formatter' => 'action_formatter',
         'sortable'  => 'false'
     )
-);
-//Autowidth
+                       );            
+//Autowidth             
 $extra_params['autowidth'] = 'true';
-//height auto
-$extra_params['height'] = 'auto';
+//height auto 
+$extra_params['height'] = 'auto'; 
 
 //With this function we can add actions to the jgrid (edit, delete, etc)
 $action_links = 'function action_formatter(cellvalue, options, rowObject) {
@@ -93,17 +94,17 @@ $action_links = 'function action_formatter(cellvalue, options, rowObject) {
     '',
     ICON_SIZE_SMALL
 ).'</a>'.
-    '\';
-}';
+                         '\'; 
+                 }';
 ?>
-    <script>
-        $(function () {
-            <?php
-                // grid definition see the $career->display() function
-                echo Display::grid_js('careers',  $url,$columns,$column_model,$extra_params, array(), $action_links,true);
-            ?>
-        });
-    </script>
+<script>
+$(function() {
+<?php 
+    // grid definition see the $career->display() function
+    echo Display::grid_js('careers',  $url,$columns,$column_model,$extra_params, array(), $action_links,true);       
+?> 
+});
+</script>
 <?php
 $career = new Career();
 
@@ -119,14 +120,14 @@ switch ($action) {
         $form = $career->return_form($url, 'add');
 
         // The validation or display
-        if ($form->validate()) {
+        if ($form->validate()) {            
             if ($check) {
-                $values = $form->exportValues();
-                $res    = $career->save($values);
+                $values = $form->exportValues();       
+                $res    = $career->save($values);            
                 if ($res) {
                     Display::display_confirmation_message(get_lang('ItemAdded'));
                 }
-            }
+            }        
             $career->display();
         } else {
             echo '<div class="actions">';
@@ -136,23 +137,23 @@ switch ($action) {
                 '',
                 ICON_SIZE_MEDIUM
             ).'</a>';
-            echo '</div>';
+            echo '</div>';            
             $form->addElement('hidden', 'sec_token');
             $form->setConstants(array('sec_token' => $token));
             $form->display();
         }
         break;
     case 'edit':
-        // Action handling: Editing
+        // Action handling: Editing 
         $url  = api_get_self().'?action='.Security::remove_XSS($_GET['action']).'&id='.intval($_GET['id']);
-        $form = $career->return_form($url, 'edit');
+        $form = $career->return_form($url, 'edit');    
 
         // The validation or display
-        if ($form->validate()) {
+        if ($form->validate()) {            
             if ($check) {
                 $values = $form->exportValues();
-                $career->update_all_promotion_status_by_career_id($values['id'], $values['status']);
-                $res = $career->update($values);
+                $career->update_all_promotion_status_by_career_id($values['id'],$values['status']);               
+                $res    = $career->update($values);
                 if ($values['status']) {
                     Display::display_confirmation_message(
                         sprintf(get_lang('CareerXUnarchived'), $values['name']),
@@ -161,7 +162,7 @@ switch ($action) {
                 } else {
                     Display::display_confirmation_message(sprintf(get_lang('CareerXArchived'), $values['name']), false);
                 }
-            }
+            }            
             $career->display();
         } else {
             echo '<div class="actions">';
@@ -187,7 +188,7 @@ switch ($action) {
         }
         $career->display();
         break;
-    case 'copy':
+    case 'copy':        
         if (api_get_session_id() != 0 && !api_is_allowed_to_session_edit(false, true)) {
             api_not_allowed();
         }
@@ -200,7 +201,7 @@ switch ($action) {
         $career->display();
         break;
     default:
-        $career->display();
+        $career->display();   
         break;
 }
 Display :: display_footer();

+ 45 - 27
main/admin/course_category.php

@@ -24,7 +24,6 @@ $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
 $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
 
 $errorMsg = '';
-
 $id = isset($_GET['id']) ? $_GET['id'] : null;
 
 $categoryCode = isset($_POST['categoryCode']) ? $_POST['categoryCode'] : null;
@@ -36,10 +35,20 @@ $canHaveCourses = 0;
 
 if (!empty($action)) {
     if ($action == 'delete') {
-        deleteNode($id);
-        header('Location: ' . api_get_self() . '?category=' . Security::remove_XSS($category));
-        exit();
-    } elseif (($action == 'add' || $action == 'edit') && $formSent) {
+        if (api_get_multiple_access_url()) {
+            if (api_get_current_access_url_id() == 1) {
+                deleteNode($id);
+                header('Location: ' . api_get_self() . '?category=' . Security::remove_XSS($category));
+                exit();
+            } else {
+                $delError = 1;
+            }
+        } else {
+            deleteNode($_GET['id']);
+            header('Location: ' . api_get_self() . '?category=' . Security::remove_XSS($category));
+            exit();
+        }
+    } elseif (($action == 'add' || $action == 'edit') && $_POST['formSent']) {
         $_POST['categoryCode'] = trim($_POST['categoryCode']);
         $_POST['categoryName'] = trim($_POST['categoryName']);
 
@@ -65,11 +74,11 @@ if (!empty($action)) {
             $sql = "SELECT name, auth_course_child FROM $tbl_category WHERE code='$id'";
             $result = Database::query($sql);
             list($categoryName, $canHaveCourses) = Database::fetch_row($result);
-
             $canHaveCourses = ($canHaveCourses == 'FALSE') ? 0 : 1;
         }
     } elseif ($action == 'moveUp') {
         moveNodeUp($id, $_GET['tree_pos'], $category);
+
         header('Location: ' . api_get_self() . '?category=' . Security::remove_XSS($category));
         exit();
     }
@@ -91,16 +100,16 @@ if (!empty($category)) {
 }
 
 if (empty($action)) {
-    $myquery = "SELECT t1.name,t1.code,t1.parent_id,t1.tree_pos,t1.children_count,COUNT(DISTINCT t3.code) AS nbr_courses
-			 	FROM $tbl_category t1 LEFT JOIN $tbl_category t2 ON t1.code=t2.parent_id LEFT JOIN $tbl_course t3 ON t3.category_code=t1.code
-				WHERE t1.parent_id " . (empty($category) ? "IS NULL" : "='$category'") . "
+    $myquery = "SELECT t1.name,t1.code,t1.parent_id,t1.tree_pos,t1.children_count,COUNT(DISTINCT t3.code) AS nbr_courses 
+			 	FROM $tbl_category t1 LEFT JOIN $tbl_category t2 ON t1.code=t2.parent_id LEFT JOIN $tbl_course t3 ON t3.category_code=t1.code 
+				WHERE t1.parent_id " . (empty($category) ? "IS NULL" : "='$category'") . " 
 				GROUP BY t1.name,t1.code,t1.parent_id,t1.tree_pos,t1.children_count ORDER BY t1.tree_pos";
     $result = Database::query($myquery);
     $Categories = Database::store_result($result);
 }
 
 if ($action == 'add' || $action == 'edit') {
-    ?>
+    if ((api_get_multiple_access_url() && api_get_current_access_url_id() == 1) || !api_get_multiple_access_url() ) { ?>
     <div class="actions">
         <a href="<?php echo api_get_self(); ?>?category=<?php echo Security::remove_XSS($category); ?>"><?php echo Display::return_icon('folder_up.png', get_lang("Back"), '', ICON_SIZE_MEDIUM);
     if (!empty($category)) echo ' (' . Security::remove_XSS($category) . ')'; ?></a>
@@ -126,16 +135,17 @@ if ($action == 'add' || $action == 'edit') {
         <?php
         Display::display_normal_message($errorMsg); //main API
         ?>
+
                     </td>
                 </tr>
 
         <?php
     }
     ?>
+
             <tr>
                 <td nowrap="nowrap"><?php echo get_lang("CategoryCode"); ?> :</td>
-                <td>
-                    <input type="text" name="categoryCode" size="20" maxlength="20" value="<?php echo api_htmlentities(stripslashes($categoryCode), ENT_QUOTES, $charset); ?>" /></td>
+                <td><input type="text" name="categoryCode" size="20" maxlength="20" value="<?php echo api_htmlentities(stripslashes($categoryCode), ENT_QUOTES, $charset); ?>" /></td>
             </tr>
             <tr>
                 <td nowrap="nowrap"><?php echo get_lang("CategoryName"); ?> :</td>
@@ -164,21 +174,23 @@ if ($action == 'add' || $action == 'edit') {
         </table>
     </form>
 
-                <?php
+<?php  } elseif (api_get_multiple_access_url() && api_get_current_access_url_id() != 1) {
+           Display :: display_error_message(get_lang('CourseCategoriesAreGlobal'));
+       }
             } else {
-                ?>
+    if ($delError == 0) {           ?>
     <div class="actions">
-    <?php
-    if (!empty($category) && empty($action)) {
-        $myquery = "SELECT parent_id FROM $tbl_category WHERE code='$category'";
-        $result = Database::query($myquery);
-        $parent_id = 0;
-        if (Database::num_rows($result) > 0) {
-            $parent_id = Database::fetch_array($result);
-        }
+                <?php
+                if (!empty($category) && empty($action)) {
+                    $myquery = "SELECT parent_id FROM $tbl_category WHERE code='$category'";
+                    $result = Database::query($myquery);
+                    $parent_id = 0;
+                    if (Database::num_rows($result) > 0) {
+                        $parent_id = Database::fetch_array($result);
+                    }
 
-        $parent_id['parent_id'] ? $link = ' (' . $parent_id['parent_id'] . ')' : $link = '';
-        ?>
+                    $parent_id['parent_id'] ? $link = ' (' . $parent_id['parent_id'] . ')' : $link = '';
+                    ?>
 
             <a href="<?php echo api_get_self(); ?>?category=<?php echo $parent_id['parent_id']; ?>"><?php echo Display::return_icon('folder_up.png', get_lang("Back"), '', ICON_SIZE_MEDIUM);
         if (!empty($parent_id)) echo $link ?></a>
@@ -216,13 +228,20 @@ if ($action == 'add' || $action == 'edit') {
     } else {
         echo get_lang("NoCategories");
     }
-    ?>
+    } else {
+        Display :: display_error_message(get_lang('CourseCategoriesAreGlobal'));
+        
+    }?>
     </ul>
+
+
+
     <?php
 }
 
 Display::display_footer();
 
+
 function deleteNode($node) {
     global $tbl_category, $tbl_course;
     $node = Database::escape_string($node);
@@ -340,5 +359,4 @@ function compterFils($pere, $cpt) {
     }
 
     return ($cpt + 1);
-}
-
+}

+ 7 - 5
main/admin/course_edit.php

@@ -12,6 +12,7 @@ $this_section = SECTION_PLATFORM_ADMIN;
 
 api_protect_admin_script();
 
+
 $course_table       = Database::get_main_table(TABLE_MAIN_COURSE);
 $course_code = isset($_GET['course_code']) ? $_GET['course_code'] : $_POST['code'];
 
@@ -48,15 +49,17 @@ if (api_is_multiple_url_enabled()) {
 			INNER JOIN $access_url_rel_user_table url_rel_user
 			ON (u.user_id=url_rel_user.user_id) WHERE url_rel_user.access_url_id=".api_get_current_access_url_id()." AND status=1".$order_clause;
 } else {
+	
 	$sql = "SELECT user_id,lastname,firstname FROM $table_user WHERE status='1'".$order_clause;
 }
 
 $res = Database::query($sql);
 $teachers = array();
 
+
 $platform_teachers[0] = '-- '.get_lang('NoManager').' --';
 while ($obj = Database::fetch_object($res)) {
-
+    
 	if (!array_key_exists($obj->user_id,$course_teachers)) {
 		$teachers[$obj->user_id] = api_get_person_name($obj->firstname, $obj->lastname);
 	}
@@ -176,7 +179,6 @@ $(function() {
     '.$extra['jquery_ready_content'].'
 });
 </script>';
-
 $form->addElement('style_submit_button', 'button', get_lang('ModifyCourseInfo'),'onclick="valide()"; class="save"');
 
 // Set some default values
@@ -216,12 +218,12 @@ if ($form->validate()) {
 	} else {
         header('Location: course_list.php');
         exit;
-	}
+    }
 }
-
 Display::display_header($tool_name);
 
 echo "<script>
+
 function valide() {
 	var options = document.getElementById('course_teachers').options;
 	for (i = 0 ; i<options.length ; i++) {
@@ -234,4 +236,4 @@ function valide() {
 // Display the form
 $form->display();
 /* FOOTER */
-Display :: display_footer();
+Display :: display_footer();

+ 58 - 44
main/admin/course_import.php

@@ -56,16 +56,24 @@ function validate_data($courses) {
             }
             $coursecodes[$course['Code']] = 1;
         }
-        /*
         // 3. Check whether teacher exists.
-        if (!UserManager::is_username_empty($course['Teacher'])) {
-            $teacher = UserManager::purify_username($course['Teacher'], $purification_option_for_usernames);
-            if (UserManager::is_username_available($teacher)) {
-                $course['error'] = get_lang('UnknownTeacher').' ('.$teacher.')';
-                $errors[] = $course;
+        $teacherList = getTeacherListInArray($course['Teacher']);
+
+        if (!empty($teacherList)) {
+            foreach ($teacherList as $teacher) {
+                $teacherInfo = api_get_user_info_from_username($teacher);
+                if (empty($teacherInfo)) {
+                    $course['error'] = get_lang('UnknownTeacher').' ('.$teacher.')';
+                    $errors[] = $course;
+                } else {
+                    if ($teacherInfo['status'] != COURSEMANAGER) {
+                        $course['error'] = get_lang('UserIsNotATeacher').' ('.$teacher.')';
+                        $errors[] = $course;
+                    }
+                }
             }
         }
-        */
+
         // 4. Check whether course category exists.
         if (isset($course['CourseCategory']) && strlen($course['CourseCategory']) != 0) {
             $category_table = Database :: get_main_table(TABLE_MAIN_CATEGORY);
@@ -81,59 +89,63 @@ function validate_data($courses) {
     return $errors;
 }
 
+function getTeacherListInArray($teachers)
+{
+    if (!empty($teachers)) {
+        return explode('|', $teachers);
+    }
+    return array();
+}
+
 /**
  * Saves imported data.
  * @param array   List of courses
  */
-function save_data($courses) {
+function save_data($courses) {    
     global $purification_option_for_usernames;
 
     $user_table = Database::get_main_table(TABLE_MAIN_USER);
     $msg = '';
-
+    
     foreach ($courses as $index => $course) {
         $course_language = api_get_valid_language($course['Language']);
-        $titular = $uidCreator = $username = '';
-
-        // Get username from name (firstname lastname).
-        if (!UserManager::is_username_empty($course['Teacher'])) {
-            $teacher = UserManager::purify_username($course['Teacher'], $purification_option_for_usernames);
-            if (UserManager::is_username_available($teacher)) {
-                $sql    = "SELECT username FROM $user_table WHERE ".(api_is_western_name_order(null, $course_language) ? "CONCAT(firstname,' ',lastname)" : "CONCAT(lastname,' ',firstname)")." = '{$course['Teacher']}' LIMIT 1";
-                $rs     = Database::query($sql);
-                $user   = Database::fetch_object($rs);
-                $username = $user->username;
-            } else {
-                $username = $teacher;
+        $username = '';
+
+        $teachers = getTeacherListInArray($course['Teacher']);
+        $teacherList = array();
+        $creatorId = api_get_user_id();
+
+        if (!empty($teachers)) {
+            foreach ($teachers as $teacher) {
+                $teacherInfo = api_get_user_info_from_username($teacher);
+                if (!empty($teacherInfo)) {
+                    $teacherList[] = $teacherInfo;
             }
         }
 
-        // Get name and uid creator from username.
-        if (!empty($username)) {
-            $sql = "SELECT user_id, ".(api_is_western_name_order(null, $course_language) ? "CONCAT(firstname,' ',lastname)" : "CONCAT(lastname,' ',firstname)")." AS name FROM $user_table WHERE username = '".Database::escape_string(UserManager::purify_username($username, $purification_option_for_usernames))."'";
-            $res = Database::query($sql);
-            $teacher    = Database::fetch_object($res);
-            $titular    = $teacher->name;
-            $uidCreator = $teacher->user_id;
-        } else {
-            $titular    = $course['Teacher'];
-            $uidCreator = 1;
         }
-
+        
         $params = array();
         $params['title']            = $course['Title'];
-        $params['wanted_code']      = $course['Code'];
-        $params['tutor_name']       = $titular;
-        $params['course_category']  = $course['CourseCategory'];
+        $params['wanted_code']      = $course['Code'];         
+        $params['tutor_name']       = null;
+        $params['course_category']  = $course['CourseCategory'];        
         $params['course_language']  = $course_language;
-        $params['user_id']          = $uidCreator;
-
+        $params['user_id']          = $creatorId;
+         
         $course_info = CourseManager::create_course($params);
         if (!empty($course_info)) {
-            $msg .= '<a href="'.api_get_path(WEB_COURSE_PATH).$course_info['directory'].'/">'.$course_info['title'].'</a> '.get_lang('Created').'<br />';
+            if (!empty($teacherList)) {
+                foreach ($teacherList as $teacher) {
+                    CourseManager::add_user_to_course($teacher['user_id'], $course_info['code'], COURSEMANAGER);
+                }
+            }
+
+            $msg .= '<a href="'.api_get_path(WEB_COURSE_PATH).$course_info['directory'].'/">
+                    '.$course_info['title'].'</a> '.get_lang('Created').'<br />';
         }
     }
-
+    
     if (!empty($msg)) {
         Display::display_normal_message($msg, false);
     }
@@ -183,7 +195,7 @@ if ($_POST['formSent']) {
         if (!in_array($ext_import_file, $allowed_file_mimetype)) {
             Display :: display_error_message(get_lang('YouMustImportAFileAccordingToSelectedOption'));
         } else {
-            $courses = parse_csv_data($_FILES['import_file']['tmp_name']);
+            $courses = parse_csv_data($_FILES['import_file']['tmp_name']);            
             $errors = validate_data($courses);
             if (count($errors) == 0) {
                 save_data($courses);
@@ -196,7 +208,7 @@ if (count($errors) != 0) {
     $error_message = '<ul>';
     foreach ($errors as $index => $error_course) {
         $error_message .= '<li>'.get_lang('Line').' '.$error_course['line'].': <strong>'.$error_course['error'].'</strong>: ';
-        $error_message .= $error_course['Code'].' '.$error_course['Title'];
+        $error_message .= get_lang('Course').': '.$error_course['Title'].' ('.$error_course['Code'].')';
         $error_message .= '</li>';
     }
     $error_message .= '</ul>';
@@ -211,7 +223,7 @@ if (count($errors) != 0) {
         <input type="file" name="import_file"/>
     </div>
 </div>
-<div class="control-group ">
+<div class="control-group ">    
     <div class="control">
         <button type="submit" class="save" value="<?php echo get_lang('Import'); ?>"><?php echo get_lang('Import'); ?></button>
     </div>
@@ -223,8 +235,10 @@ if (count($errors) != 0) {
 
 <blockquote>
 <pre>
-<strong>Code</strong>;<strong>Title</strong>;<strong>CourseCategory</strong>;<strong>Teacher</strong>;Language
-BIO0015;Biology;BIO;username;english
+<strong>Code</strong>;<strong>Title</strong>;<strong>CourseCategory</strong>;Teacher;Language
+BIO0015;Biology;BIO;teacher1;english
+BIO0016;Maths;MATH;teacher2|teacher3;english
+BIO0017;Language;LANG;;english
 </pre>
 </blockquote>
 

+ 12 - 33
main/admin/index.php

@@ -7,10 +7,10 @@
 /**
  * Code
  */
-
 // Language files that need to be included.
 $language_file = array('admin', 'tracking','coursebackup');
 
+
 // Setting the section (for the tabs).
 $this_section = SECTION_PLATFORM_ADMIN;
 
@@ -116,12 +116,10 @@ if (api_is_platform_admin()) {
 	$items[] = array('url'=>'course_category.php', 			'label' => get_lang('AdminCategories'));
 	$items[] = array('url'=>'subscribe_user2course.php', 	'label' => get_lang('AddUsersToACourse'));
 	$items[] = array('url'=>'course_user_import.php', 		'label' => get_lang('ImportUsersToACourse'));
-
     $items[] = array('url'=>'extra_fields.php?type=course', 	'label' => get_lang('ManageCourseFields'));
 
     $items[] = array('url'=>'extra_fields.php?type=question', 	'label' => get_lang('ManageQuestionFields'));
 
-
     if (api_get_setting('gradebook_enable_grade_model') == 'true') {
         $items[] = array('url'=>'grade_models.php',             'label' => get_lang('GradeModel'));
     }
@@ -149,7 +147,7 @@ if (api_is_platform_admin()) {
     $items[] = array('url'=>'settings.php?category=Plugins','label' => get_lang('Plugins'));
     $items[] = array('url'=>'settings.php?category=Regions','label' => get_lang('Regions'));
     $items[] = array('url'=>'system_announcements.php', 	'label' => get_lang('SystemAnnouncements'));
-    $items[] = array('url'=>api_get_path(WEB_CODE_PATH).'calendar/agenda_js.php?type=admin', 'label' => get_lang('GlobalAgenda'));
+    $items[] = array('url'=> api_get_path(WEB_CODE_PATH).'calendar/agenda_js.php?type=admin', 'label' => get_lang('GlobalAgenda'));
     $items[] = array('url'=>'configure_homepage.php', 		'label' => get_lang('ConfigureHomePage'));
     $items[] = array('url'=>'configure_inscription.php', 	'label' => get_lang('ConfigureInscription'));
     $items[] = array('url'=>'statistics/index.php', 		'label' => get_lang('Statistics'));
@@ -162,9 +160,9 @@ if (api_is_platform_admin()) {
     }
 
     if (api_get_multiple_access_url()) {
-	if (api_is_global_platform_admin()) {
+		if (api_is_global_platform_admin()) {
             	$items[] = array('url'=>'access_urls.php', 	'label' => get_lang('ConfigureMultipleAccessURLs'));
-        }
+            }
     }
 
     if (api_get_setting('allow_reservation') == 'true') {
@@ -189,7 +187,7 @@ $blocks['sessions']['search_form'] = $search_form;
 $items = array();
 $items[] = array('url'=> api_get_path(WEB_CODE_PATH).'session/session_list.php', 'label' => get_lang('ListSession'));
 $items[] = array('url'=> api_get_path(WEB_CODE_PATH).'session/session_add.php', 	'label' => get_lang('AddSession'));
-$items[] = array('url'=> 'session_category_list.php', 	'label' => get_lang('ListSessionCategory'));
+$items[] = array('url'=>'session_category_list.php', 	'label' => get_lang('ListSessionCategory'));
 $items[] = array('url'=> api_get_path(WEB_CODE_PATH).'session/session_import.php', 	'label' => get_lang('ImportSessionListXMLCSV'));
 if (isset($extAuthSource) && isset($extAuthSource['ldap']) && count($extAuthSource['ldap']) > 0) {
     $items[] = array('url'=>'ldap_import_students_to_session.php', 	'label' => get_lang('ImportLDAPUsersIntoSession'));
@@ -226,8 +224,8 @@ if (api_is_platform_admin()) {
 	if (is_dir(api_get_path(SYS_TEST_PATH).'datafiller/')) {
 		$items[] = array('url'=>'filler.php', 	'label' => get_lang('DataFiller'));
 	}
-    $items[] = array('url'=>'archive_cleanup.php', 	'label' => get_lang('ArchiveDirCleanup'));
-	$items[] = array('url'=>'system_management.php', 'label' => get_lang('SystemManagement'));
+	$items[] = array('url'=>'archive_cleanup.php', 	'label' => get_lang('ArchiveDirCleanup'));
+    $items[] = array('url'=>'system_management.php', 'label' => get_lang('SystemManagement'));
 
 	$blocks['settings']['items'] = $items;
     $blocks['settings']['extra'] = null;
@@ -251,7 +249,7 @@ if (api_is_platform_admin()) {
 
     //Skills
     if (api_get_setting('allow_skills_tool') == 'true') {
-        $blocks['skills']['icon']  = Display::return_icon('logo.gif', get_lang('Skills'), array(), ICON_SIZE_SMALL, false);
+        $blocks['skills']['icon']  = Display::return_icon('logo.png', get_lang('Skills'), array(), ICON_SIZE_SMALL, false);
         $blocks['skills']['label'] = get_lang('Skills');
 
         $items = array();
@@ -293,12 +291,13 @@ if (api_is_platform_admin()) {
 	//ob_flush();
 
     //Version check
-    $blocks['version_check']['icon']  = Display::return_icon('logo.gif', 'Chamilo.org', array(), ICON_SIZE_SMALL, false);
+    $blocks['version_check']['icon']  = Display::return_icon('logo.png', 'Chamilo.org', array(), ICON_SIZE_SMALL, false);
 	$blocks['version_check']['label'] = get_lang('VersionCheck');
-	$blocks['version_check']['extra'] = version_check();
+	//$blocks['version_check']['extra'] = version_check();
     $blocks['version_check']['search_form'] = null;
     $blocks['version_check']['items'] = null;
 }
+$admin_ajax_url = api_get_path(WEB_AJAX_PATH).'admin.ajax.php';
 
 $app['template']->assign('blocks', $blocks);
 $app['template']->display('default/admin/settings_index.tpl');
@@ -333,26 +332,6 @@ function version_check() {
     return $return;
 }
 
-/**
- * This setting changes the registration status for the campus
- *
- * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
- * @version August 2006
- *
- * @todo the $_settings should be reloaded here. => write api function for this and use this in global.inc.php also.
- */
-function register_site() {
-    $tbl_settings = Database :: get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
-
-    $sql = "UPDATE $tbl_settings SET selected_value='true' WHERE variable='registered'";
-    Database::query($sql);
-
-    if ($_POST['donotlistcampus']) {
-        $sql = "UPDATE $tbl_settings SET selected_value='true' WHERE variable='donotlistcampus'";
-        Database::query($sql);
-    }
-    // Reload the settings.
-}
 
 
 /**
@@ -394,7 +373,7 @@ function check_system_version() {
 
         $res = _http_request('version.chamilo.org', 80, '/version.php', $data);
 
-        if ($res !== false) {
+        if ($res != 0) {
             $version_info = $res;
 
             if ($system_version != $version_info) {

+ 3 - 5
main/admin/promotions.php

@@ -130,11 +130,9 @@ switch ($action) {
             if ($check) {
                 $values = $form->exportValues();                    
                 $res    = $promotion->update($values);
-                $promotion->update_all_sessions_status_by_promotion_id($values['id'], $values['status']);    
-                if ($values['status']) {
-                    Display::display_confirmation_message(sprintf(get_lang('PromotionXUnarchived'), $values['name']), false);
-                } else {
-                    Display::display_confirmation_message(sprintf(get_lang('PromotionXArchived'), $values['name']), false);
+                $promotion->update_all_sessions_status_by_promotion_id($values['id'], $values['status']);  
+                if ($res) {
+                    Display::display_confirmation_message(get_lang('PromotionUpdated'), $values['name']);
                 }
             }            
             $promotion->display();

+ 141 - 163
main/admin/user_add.php

@@ -1,8 +1,8 @@
 <?php
 /* For licensing terms, see /license.txt */
 /**
- * @package chamilo.admin
- */
+*	@package chamilo.admin
+*/
 
 // Language files that should be included
 $language_file = array('admin', 'registration');
@@ -19,29 +19,30 @@ api_protect_admin_script(true);
 $is_platform_admin = api_is_platform_admin() ? 1 : 0;
 
 $message = null;
+
 $htmlHeadXtra[] = api_get_password_checker_js('#username', '#password');
 $htmlHeadXtra[] = '<script src="'.api_get_path(WEB_LIBRARY_PATH).'javascript/tag/jquery.fcbkcomplete.js" type="text/javascript" language="javascript"></script>';
 $htmlHeadXtra[] = '<link href="'.api_get_path(WEB_LIBRARY_PATH).'javascript/tag/style.css" rel="stylesheet" type="text/css" />';
 if (isset($_configuration['allow_strength_pass_checker']) && $_configuration['allow_strength_pass_checker']) {
-    $htmlHeadXtra[] = '
-    <script>
-        $(document).ready(function() {
-            $("input[name=\'password[password_auto]\']").each(function(index, value) {
-                $(this).click(function() {
-                    var value = $(this).attr("value");
-                    if (value == 0) {
-                        $("#password_progress").show();
-                        $(".password-verdict").show();
-                        $(".error-list").show();
-                    } else {
-                        $("#password_progress").hide();
-                        $(".password-verdict").hide();
-                        $(".error-list").hide();
-                    }
-                });
+$htmlHeadXtra[] = '
+<script>
+    $(document).ready(function() {
+        $("input[name=\'password[password_auto]\']").each(function(index, value) {
+            $(this).click(function() {
+                var value = $(this).attr("value");
+                if (value == 0) {
+                    $("#password_progress").show();
+                    $(".password-verdict").show();
+                    $(".error-list").show();
+                } else {
+                    $("#password_progress").hide();
+                    $(".password-verdict").hide();
+                    $(".error-list").hide();
+                }
             });
         });
-        </script>';
+    });
+    </script>';
 }
 
 $htmlHeadXtra[] = '
@@ -83,38 +84,38 @@ function display_drh_list(){
 </script>';
 
 if (!empty($_GET['message'])) {
-    $message = urldecode($_GET['message']);
+	$message = urldecode($_GET['message']);
 }
 
-$interbreadcrumb[] = array('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
-$interbreadcrumb[] = array("url" => 'user_list.php', "name" => get_lang('UserList'));
+$interbreadcrumb[] = array ('url' => 'index.php', 'name' => get_lang('PlatformAdmin'));
+$interbreadcrumb[] = array ("url" => 'user_list.php', "name" => get_lang('UserList'));
 $tool_name = get_lang('AddUsers');
 
 // Create the form
 $form = new FormValidator('user_add');
 $form->addElement('header', '', $tool_name);
 if (api_is_western_name_order()) {
-    // Firstname
-    $form->addElement('text', 'firstname', get_lang('FirstName'));
-    $form->applyFilter('firstname', 'html_filter');
-    $form->applyFilter('firstname', 'trim');
-    $form->addRule('firstname', get_lang('ThisFieldIsRequired'), 'required');
-    // Lastname
-    $form->addElement('text', 'lastname', get_lang('LastName'));
-    $form->applyFilter('lastname', 'html_filter');
-    $form->applyFilter('lastname', 'trim');
-    $form->addRule('lastname', get_lang('ThisFieldIsRequired'), 'required');
+	// Firstname
+	$form->addElement('text', 'firstname', get_lang('FirstName'));
+	$form->applyFilter('firstname', 'html_filter');
+	$form->applyFilter('firstname', 'trim');
+	$form->addRule('firstname', get_lang('ThisFieldIsRequired'), 'required');
+	// Lastname
+	$form->addElement('text', 'lastname', get_lang('LastName'));
+	$form->applyFilter('lastname', 'html_filter');
+	$form->applyFilter('lastname', 'trim');
+	$form->addRule('lastname', get_lang('ThisFieldIsRequired'), 'required');
 } else {
-    // Lastname
-    $form->addElement('text', 'lastname', get_lang('LastName'));
-    $form->applyFilter('lastname', 'html_filter');
-    $form->applyFilter('lastname', 'trim');
-    $form->addRule('lastname', get_lang('ThisFieldIsRequired'), 'required');
-    // Firstname
-    $form->addElement('text', 'firstname', get_lang('FirstName'));
-    $form->applyFilter('firstname', 'html_filter');
-    $form->applyFilter('firstname', 'trim');
-    $form->addRule('firstname', get_lang('ThisFieldIsRequired'), 'required');
+	// Lastname
+	$form->addElement('text', 'lastname', get_lang('LastName'));
+	$form->applyFilter('lastname', 'html_filter');
+	$form->applyFilter('lastname', 'trim');
+	$form->addRule('lastname', get_lang('ThisFieldIsRequired'), 'required');
+	// Firstname
+	$form->addElement('text', 'firstname', get_lang('FirstName'));
+	$form->applyFilter('firstname', 'html_filter');
+	$form->applyFilter('firstname', 'trim');
+	$form->addRule('firstname', get_lang('ThisFieldIsRequired'), 'required');
 }
 // Official code
 $form->addElement('text', 'official_code', get_lang('OfficialCode'), array('size' => '40'));
@@ -141,25 +142,15 @@ if (api_get_setting('login_is_email') == 'true') {
 $form->addElement('text', 'phone', get_lang('PhoneNumber'));
 // Picture
 $form->addElement('file', 'picture', get_lang('AddPicture'));
-$allowed_picture_types = array('jpg', 'jpeg', 'png', 'gif');
+$allowed_picture_types = array ('jpg', 'jpeg', 'png', 'gif');
 
-$form->addRule(
-    'picture',
-    get_lang('OnlyImagesAllowed').' ('.implode(',', $allowed_picture_types).')',
-    'filetype',
-    $allowed_picture_types
-);
+$form->addRule('picture', get_lang('OnlyImagesAllowed').' ('.implode(',', $allowed_picture_types).')', 'filetype', $allowed_picture_types);
 
 // Username
 if (api_get_setting('login_is_email') != 'true') {
     $form->addElement('text', 'username', get_lang('LoginName'), array('id'=> 'username', 'maxlength' => USERNAME_MAX_LENGTH));
     $form->addRule('username', get_lang('ThisFieldIsRequired'), 'required');
-    $form->addRule(
-        'username',
-        sprintf(get_lang('UsernameMaxXCharacters'), (string)USERNAME_MAX_LENGTH),
-        'maxlength',
-        USERNAME_MAX_LENGTH
-    );
+    $form->addRule('username', sprintf(get_lang('UsernameMaxXCharacters'), (string)USERNAME_MAX_LENGTH), 'maxlength', USERNAME_MAX_LENGTH);
     $form->addRule('username', get_lang('OnlyLettersAndNumbersAllowed'), 'username');
     $form->addRule('username', get_lang('UserTaken'), 'username_available');
 }
@@ -169,30 +160,24 @@ $group = array();
 $auth_sources = 0; //make available wider as we need it in case of form reset (see below)
 $nb_ext_auth_source_added = 0;
 if (isset($extAuthSource) && count($extAuthSource) > 0) {
-    $auth_sources = array();
-    foreach ($extAuthSource as $key => $info) {
-        // @todo : make uniform external authentification configuration (ex : cas and external_login ldap)
-        // Special case for CAS. CAS is activated from Chamilo > Administration > Configuration > CAS
-        // extAuthSource always on for CAS even if not activated
-        // same action for file user_edit.php
-        if (($key == CAS_AUTH_SOURCE && api_get_setting('cas_activate') === 'true') || ($key != CAS_AUTH_SOURCE)) {
-            $auth_sources[$key] = $key;
-            $nb_ext_auth_source_added++;
-        }
-    }
-    if ($nb_ext_auth_source_added > 0) {
-        $group[] = $form->createElement('radio', 'password_auto', null, get_lang('ExternalAuthentication').' ', 2);
-        $group[] = $form->createElement('select', 'auth_source', null, $auth_sources);
-        $group[] = $form->createElement('static', '', '', '<br />');
+	$auth_sources = array();
+	foreach($extAuthSource as $key => $info) {
+	    // @todo : make uniform external authentification configuration (ex : cas and external_login ldap)
+	    // Special case for CAS. CAS is activated from Chamilo > Administration > Configuration > CAS
+	    // extAuthSource always on for CAS even if not activated
+	    // same action for file user_edit.php
+	    if (($key == CAS_AUTH_SOURCE && api_get_setting('cas_activate') === 'true') || ($key != CAS_AUTH_SOURCE)) {
+		    $auth_sources[$key] = $key;
+    		$nb_ext_auth_source_added++;
+		}
+	}
+	if ($nb_ext_auth_source_added > 0) {
+    	$group[] = $form->createElement('radio', 'password_auto', null, get_lang('ExternalAuthentication').' ', 2);
+    	$group[] = $form->createElement('select', 'auth_source', null, $auth_sources);
+    	$group[] = $form->createElement('static', '', '', '<br />');
     }
 }
-$group[] = $form->createElement(
-    'radio',
-    'password_auto',
-    get_lang('Password'),
-    get_lang('AutoGeneratePassword').'<br />',
-    1
-);
+$group[] = $form->createElement('radio', 'password_auto', get_lang('Password'), get_lang('AutoGeneratePassword').'<br />', 1);
 $group[] = $form->createElement('radio', 'password_auto', 'id="radio_user_password"', null, 0);
 $group[] = $form->createElement('password', 'password', null, array('id'=> 'password', 'onkeydown' => 'javascript: password_switch_radio_button();'));
 $form->addGroup($group, 'password', get_lang('Password'), '');
@@ -200,7 +185,6 @@ $form->addGroup($group, 'password', get_lang('Password'), '');
 if (isset($_configuration['allow_strength_pass_checker']) && $_configuration['allow_strength_pass_checker']) {
     $form->addElement('label', null, '<div id="password_progress" style="display:none"></div>');
 }
-
 // Status
 $status = api_get_user_roles();
 
@@ -213,15 +197,15 @@ $form->addElement(
 );
 
 //drh list (display only if student)
-$display = isset($_POST['status']) && $_POST['status'] == STUDENT || !isset($_POST['status']) ? 'block' : 'none';
+$display = isset($_POST['status']) && $_POST['status'] == STUDENT  || !isset($_POST['status']) ? 'block' : 'none';
 
 //@todo remove the drh list here. This code is unused
 $form->addElement('html', '<div id="drh_list" style="display:'.$display.';">');
 
 if (isset($drh_list) && is_array($drh_list)) {
-    foreach ($drh_list as $drh) {
-        $drh_select->addOption(api_get_person_name($drh['firstname'], $drh['lastname']), $drh['user_id']);
-    }
+	foreach ($drh_list as $drh) {
+		$drh_select->addOption(api_get_person_name($drh['firstname'], $drh['lastname']), $drh['user_id']);
+	}
 }
 $form->addElement('html', '</div>');
 
@@ -246,7 +230,7 @@ $group[] = $form->createElement('radio', 'send_mail', null, get_lang('No'), 0);
 $form->addGroup($group, 'mail', get_lang('SendMailToNewUser'), '&nbsp;');
 // Expiration Date
 $form->addElement('radio', 'radio_expiration_date', get_lang('ExpirationDate'), get_lang('NeverExpires'), 0);
-$group = array();
+$group = array ();
 $group[] = $form->createElement('radio', 'radio_expiration_date', null, get_lang('On'), 1);
 $group[] = $form->createElement(
     'datepicker',
@@ -260,12 +244,13 @@ $form->addElement('radio', 'active', get_lang('ActiveAccount'), get_lang('Active
 $form->addElement('radio', 'active', '', get_lang('Inactive'), 0);
 
 $extra_data = UserManager::get_extra_user_data(0, true);
+
 $extraField = new ExtraField('user');
 $return_params = $extraField->set_extra_fields_in_form($form, $extra_data, 'user_add', false, null);
 $jquery_ready_content = $return_params['jquery_ready_content'];
 
 // the $jquery_ready_content variable collects all functions that will be load in the $(document).ready javascript function
-$htmlHeadXtra[] = '<script>
+$htmlHeadXtra[] ='<script>
 $(document).ready(function(){
 	'.$jquery_ready_content.'
 });
@@ -288,49 +273,43 @@ $defaults = array_merge($defaults, $extra_data);
 $form->setDefaults($defaults);
 
 // Submit button
-$html_results_enabled[] = $form->createElement(
-    'style_submit_button',
-    'submit_plus',
-    get_lang('Add').'+',
-    'class="add"'
-);
-$html_results_enabled[] = $form->createElement('style_submit_button', 'submit', get_lang('Add'), 'class="add"');
+$html_results_enabled[] = $form-> createElement ('style_submit_button', 'submit_plus', get_lang('Add').'+', 'class="add"');
+$html_results_enabled[] = $form-> createElement ('style_submit_button', 'submit', get_lang('Add'), 'class="add"');
 $form->addGroup($html_results_enabled);
 
 // Validate form
-if ($form->validate()) {
-    $check = Security::check_token('post');
-    if ($check) {
-        $user = $form->exportValues();
-        $lastname = $user['lastname'];
-        $firstname = $user['firstname'];
-        $official_code = $user['official_code'];
-        $email = $user['email'];
-        $phone = $user['phone'];
-        $username = $user['username'];
-        $status = intval($user['status']);
-        $language = $user['language'];
-        $picture = $_FILES['picture'];
-        $platform_admin = intval($user['admin']['platform_admin']);
-        $send_mail = intval($user['mail']['send_mail']);
-        $hr_dept_id = intval($user['hr_dept_id']);
-
-        if (count($extAuthSource) > 0 && $user['password']['password_auto'] == '2') {
-            $auth_source = $user['password']['auth_source'];
-            $password = 'PLACEHOLDER';
-        } else {
-            $auth_source = PLATFORM_AUTH_SOURCE;
-            $password = $user['password']['password_auto'] == '1' ? api_generate_password(
-            ) : $user['password']['password'];
-        }
+if( $form->validate()) {
+	$check = Security::check_token('post');
+	if ($check) {
+		$user = $form->exportValues();
+		$lastname       = $user['lastname'];
+		$firstname      = $user['firstname'];
+		$official_code  = $user['official_code'];
+		$email          = $user['email'];
+		$phone          = $user['phone'];
+		$username       = $user['username'];
+		$status         = intval($user['status']);
+		$language       = $user['language'];
+		$picture        = $_FILES['picture'];
+		$platform_admin = intval($user['admin']['platform_admin']);
+		$send_mail      = intval($user['mail']['send_mail']);
+		$hr_dept_id     = intval($user['hr_dept_id']);
+
+		if (count($extAuthSource) > 0 && $user['password']['password_auto'] == '2') {
+			$auth_source = $user['password']['auth_source'];
+			$password = 'PLACEHOLDER';
+		} else {
+			$auth_source = PLATFORM_AUTH_SOURCE;
+			$password = $user['password']['password_auto'] == '1' ? api_generate_password() : $user['password']['password'];
+		}
 
-        if ($user['radio_expiration_date'] == '1') {
-            $expiration_date = $user['expiration_date'];
-        } else {
-            $expiration_date = '0000-00-00 00:00:00';
-        }
+		if ($user['radio_expiration_date'] == '1') {
+			$expiration_date = $user['expiration_date'];
+		} else {
+			$expiration_date = '0000-00-00 00:00:00';
+		}
 
-        $active = intval($user['active']);
+		$active = intval($user['active']);
 
         if (api_get_setting('login_is_email') == 'true') {
             $username = $email;
@@ -356,18 +335,18 @@ if ($form->validate()) {
             $send_mail
         );
 
-        Security::clear_token();
-        $tok = Security::get_token();
-        if ($user_id === false) {
-            //If any error ocurred during user creation, print it (api_failureList
-            // stores values as separate words, so rework it
-            $message = '';
-            $message_bits = explode(' ', api_get_last_failure());
-            foreach ($message_bits as $bit) {
-                $message .= ucfirst($bit);
-            }
-        } else {
-            if (!empty($picture['name'])) {
+		Security::clear_token();
+		$tok = Security::get_token();
+		if ($user_id === false) {
+			//If any error ocurred during user creation, print it (api_failureList
+			// stores values as separate words, so rework it
+			$message = '';
+			$message_bits = explode(' ',api_get_last_failure());
+			foreach ($message_bits as $bit) {
+				$message .= ucfirst($bit);
+			}
+		} else {
+ 			if (!empty($picture['name'])) {
                 $picture_uri = UserManager::update_user_picture(
                     $user_id,
                     $_FILES['picture']['name'],
@@ -392,37 +371,36 @@ if ($form->validate()) {
                     null,
                     $language
                 );
-            }
-
-            foreach ($user as $key => $value) {
-                if (substr($key, 0, 6) == 'extra_') { //an extra field
-                    UserManager::update_extra_field_value($user_id, substr($key, 6), $value);
-                }
-            }
-
-            $message = get_lang('UserAdded');
-        }
-        if (isset($user['submit_plus'])) {
-            //we want to add more. Prepare report message and redirect to the same page (to clean the form)
-            header('Location: user_add.php?message='.urlencode($message).'&sec_token='.$tok);
-            exit ();
-        } else {
-            $tok = Security::get_token();
-            header('Location: user_list.php?action=show_message&message='.urlencode($message).'&sec_token='.$tok);
-            exit ();
-        }
-    }
+			}
+
+			foreach ($user as $key => $value) {
+				if (substr($key, 0, 6) == 'extra_') { //an extra field
+					UserManager::update_extra_field_value($user_id, substr($key, 6), $value);
+				}
+			}
+			$message = get_lang('UserAdded');
+		}
+		if (isset($user['submit_plus'])) {
+			//we want to add more. Prepare report message and redirect to the same page (to clean the form)
+			header('Location: user_add.php?message='.urlencode($message).'&sec_token='.$tok);
+			exit ();
+		} else {
+			$tok = Security::get_token();
+			header('Location: user_list.php?action=show_message&message='.urlencode($message).'&sec_token='.$tok);
+			exit ();
+		}
+	}
 } else {
-    if (isset($_POST['submit'])) {
-        Security::clear_token();
-    }
-    $token = Security::get_token();
-    $form->addElement('hidden', 'sec_token');
-    $form->setConstants(array('sec_token' => $token));
+	if (isset($_POST['submit'])) {
+		Security::clear_token();
+	}
+	$token = Security::get_token();
+	$form->addElement('hidden', 'sec_token');
+	$form->setConstants(array('sec_token' => $token));
 }
 
-if (!empty($message)) {
-    $message = Display::return_message(stripslashes($message));
+if (!empty($message)){
+	$message = Display::return_message(stripslashes($message));
 }
 $content = $form->return_form();
 
@@ -430,4 +408,4 @@ $app['title'] = $tool_name;
 $tpl = $app['template'];
 $tpl->assign('message', $message);
 $tpl->assign('content', $content);
-$tpl->display_one_col_template();
+$tpl->display_one_col_template();

+ 5 - 3
main/admin/user_information.php

@@ -87,7 +87,7 @@ $tbl_user                   = Database :: get_main_table(TABLE_MAIN_USER);
 
 $user_id = $user['user_id'];
 
-$sessions = SessionManager::get_sessions_by_user($user_id);
+$sessions = SessionManager::get_sessions_by_user($user_id, true);
 
 $personal_course_list = array();
 if (count($sessions) > 0) {
@@ -117,7 +117,9 @@ if (count($sessions) > 0) {
             $row[] = $tools;
             $data[] = $row;
         }
-        echo Display::page_subheader($session_item['session_name']);
+        $dates = array_filter(array($session_item['date_start'], $session_item['date_end']));
+        echo Display::page_subheader($session_item['session_name'], ' '.implode(' - ', $dates));
+
         Display :: display_sortable_table($header, $data, array (), array(), array ('user_id' => intval($_GET['user_id'])));
     }
 } else {
@@ -213,4 +215,4 @@ if (api_is_multiple_url_enabled()) {
 }
 
 /* FOOTER */
-Display::display_footer();
+Display::display_footer();

+ 89 - 74
main/admin/user_list.php

@@ -17,11 +17,11 @@ $current_access_url_id = api_get_current_access_url_id();
 // Blocks the possibility to delete a user
 $delete_user_available = true;
 if (isset($_configuration['deny_delete_users']) &&  $_configuration['deny_delete_users']) {
-    $delete_user_available = false;
+	$delete_user_available = false;
 }
 $url = api_get_path(WEB_AJAX_PATH).'course.ajax.php?a=get_user_courses';
 $urlSession = api_get_path(WEB_AJAX_PATH).'session.ajax.php?a=get_user_sessions';
-
+        
 $htmlHeadXtra[] = '<script>
 function load_course_list (div_course,my_user_id) {
 	 $.ajax({
@@ -77,7 +77,7 @@ function active_user(element_div) {
 				if (data == 1) {
 					$(ident).attr("src","'.api_get_path(WEB_IMG_PATH).'icons/16/accept.png'.'");
 					$(ident).attr("title","'.get_lang('Lock').'");
-				}
+				} 
                 if (data == 0) {
 					$(ident).attr("src","'.api_get_path(WEB_IMG_PATH).'icons/16/error.png'.'");
 					$(ident).attr("title","'.get_lang('Unlock').'");
@@ -114,24 +114,24 @@ $(document).ready(function() {
 
     var select_val = $("#input_select_extra_data").val();
     if ( document.getElementById(\'extra_data_text\')) {
-
+    
         if (select_val != 0) {
             document.getElementById(\'extra_data_text\').style.display="block";
-            if (document.getElementById(\'input_extra_text\'))
+            if (document.getElementById(\'input_extra_text\')) 
                 document.getElementById(\'input_extra_text\').value = "";
         } else {
             document.getElementById(\'extra_data_text\').style.display="none";
         }
     }
-
-
+    
+    
     $(".agenda_opener").live("click", function() {
         var url = this.href;
         var dialog = $("#dialog");
-
+                
         if ($("#dialog").length == 0) {
             dialog = $(\'<div id="dialog" style="display:hidden"></div> \').appendTo(\'body\');
-        }
+        }     
         // load remote content
         dialog.load(
                 url,
@@ -142,11 +142,11 @@ $(document).ready(function() {
             );
         //prevent the browser to follow the link
         return false;
-    });
+    });    
 });
 
 //Load user calendar
-function load_calendar(user_id, month, year) {
+function load_calendar(user_id, month, year) {  
  	var url = "'.api_get_path(WEB_AJAX_PATH).'agenda.ajax.php?a=get_user_agenda&user_id=" +user_id + "&month="+month+"&year="+year;
 	$("#dialog").load(url);
 }
@@ -165,20 +165,20 @@ api_protect_admin_script(true);
 *	@author Evie Embrechts
 *   @author Yannick Warnier <yannick.warnier@dokeos.com>
 */
-function login_user($user_id) {
+function login_user($user_id) {    
     $user_id = intval($user_id);
-
+    
     if (empty($user_id)) {
         return false;
     }
     if ($user_id != strval(intval($user_id))) {
     	return false;
     }
-
+    
     //Only superadmins can login to admin accounts
     if (!api_global_admin_can_edit_admin($user_id)) {
         return false;
-    }
+    }    
 
     //Load $_user to be sure we clean it before logging in
 	global $uidReset, $loginFailed, $_user;
@@ -219,10 +219,11 @@ function login_user($user_id) {
 			LEFT JOIN $track_e_login_table login
 			ON user.user_id = login.login_user_id
 			WHERE user.user_id = '".$user_id."'
-			ORDER BY login.login_date DESC LIMIT 1";
+			ORDER BY login.login_date DESC LIMIT 1";		
 
 		$sql_result = Database::query($sql_query);
 
+
 		if (Database::num_rows($sql_result) > 0) {
 			// Extracting the user data
 
@@ -269,7 +270,6 @@ function login_user($user_id) {
 		}
 	}
 }
-
 /**
  * Get the total number of users on the platform
  * @see SortableTable#get_total_number_of_items()
@@ -293,7 +293,6 @@ function get_user_data($from, $number_of_items, $column, $direction, $get_count
 
 	$user_table = Database :: get_main_table(TABLE_MAIN_USER);
 	$admin_table = Database :: get_main_table(TABLE_MAIN_ADMIN);
-
 	$select = "SELECT
                  u.user_id				AS col0,
                  u.official_code		AS col2,
@@ -345,7 +344,6 @@ function get_user_data($from, $number_of_items, $column, $direction, $get_count
 		$keyword_status = Database::escape_string($_GET['keyword_status']);
 
 		$query_admin_table = '';
-
         $and_conditions = array();
 
 		if ($keyword_status == SESSIONADMIN) {
@@ -354,6 +352,7 @@ function get_user_data($from, $number_of_items, $column, $direction, $get_count
 			$and_conditions[] = ' a.user_id = u.user_id ';
 		}
 
+		
         if (isset($_GET['keyword_extra_data'])) {
         	if (!empty($_GET['keyword_extra_data']) && !empty($_GET['keyword_extra_data_text'])) {
             	$keyword_extra_data_text = Database::escape_string($_GET['keyword_extra_data_text']);
@@ -391,7 +390,7 @@ function get_user_data($from, $number_of_items, $column, $direction, $get_count
 		}
         if (!empty($and_conditions)) {
             $sql .= implode(' AND ', $and_conditions);
-        }
+		}
 		$sql .= " ) ";
 	}
 
@@ -414,7 +413,6 @@ function get_user_data($from, $number_of_items, $column, $direction, $get_count
     if (!in_array($direction, array('ASC','DESC'))) {
     	$direction = 'ASC';
     }
-
     $column = intval($column);
     $from 	= intval($from);
     $number_of_items = intval($number_of_items);
@@ -425,19 +423,19 @@ function get_user_data($from, $number_of_items, $column, $direction, $get_count
         $user = Database::fetch_array($res);
         return $user['total_rows'];
     }
-
-    $sql .= " ORDER BY col$column $direction ";
+	$sql .= " ORDER BY col$column $direction ";
 	$sql .= " LIMIT $from,$number_of_items";
-    $res = Database::query($sql);
+
+	$res = Database::query($sql);
 
 	$users = array ();
     $t = time();
-	while ($user = Database::fetch_row($res)) {
+	while ($user = Database::fetch_row($res)) {        
 		$image_path 	= UserManager::get_user_picture_path_by_id($user[0], 'web', false, true);
 		$user_profile 	= UserManager::get_picture_user($user[0], $image_path['file'], 22, USER_IMAGE_SIZE_SMALL, ' width="22" height="22" ');
 		if (!api_is_anonymous()) {
 			$photo = '<center><a href="'.api_get_path(WEB_CODE_PATH).'?social/profile.php&u='.$user[0].'" title="'.get_lang('Info').'">
-                            <img src="'.$user_profile['file'].'" '.$user_profile['style'].' alt="'.api_get_person_name($user[2],$user[3]).'" title="'.api_get_person_name($user[2], $user[3]).'" /></a></center>';
+                            <img src="'.$user_profile['file'].'" '.$user_profile['style'].' alt="'.api_get_person_name($user[2],$user[3]).'"  title="'.api_get_person_name($user[2], $user[3]).'" /></a></center>';
 		} else {
 			$photo = '<center><img src="'.$user_profile['file'].'" '.$user_profile['style'].' alt="'.api_get_person_name($user[2], $user[3]).'" title="'.api_get_person_name($user[2], $user[3]).'" /></center>';
 		}
@@ -481,7 +479,7 @@ function user_filter($name, $params, $row) {
  * @return string Some HTML-code with modify-buttons
  */
 function modify_filter($user_id, $url_params, $row) {
-	global $charset, $_admins_list, $delete_user_available;
+	global $charset, $_admins_list, $delete_user_available;    
     $is_admin = false;
     if (is_array($_admins_list)) {
 	    $is_admin   = in_array($user_id,$_admins_list);
@@ -489,19 +487,23 @@ function modify_filter($user_id, $url_params, $row) {
 	$statusname = api_get_status_langvars();
 	$user_is_anonymous = false;
     $current_user_status_label = $row['7'];
-
+        
 	if ($current_user_status_label == $statusname[ANONYMOUS]) {
 		$user_is_anonymous =true;
 	}
 	$result = '';
 	if (!$user_is_anonymous) {
-        $icon = Display::return_icon('course.gif', get_lang('Courses'), array('onmouseout' =>'"clear_course_list (\'div_'.$user_id.'\')" '));
 		$result .= '<a href="javascript:void(0)" onclick="load_course_list(\'div_'.$user_id.'\','.$user_id.')" >
-					'.$icon.'
+					<img onmouseout="clear_course_list (\'div_'.$user_id.'\')" src="../img/icons/22/course.png" title="'.get_lang('Courses').'" alt="'.get_lang('Courses').'"/>
 					<div class="blackboard_hide" id="div_'.$user_id.'">&nbsp;&nbsp;</div>
-					</a>&nbsp;&nbsp;';
+					</a>';
+		$result .= '<a href="javascript:void(0)" onclick="load_session_list(\'div_s_'.$user_id.'\','.$user_id.')" >
+					<img onmouseout="clear_session_list (\'div_s_'.$user_id.'\')" src="../img/icons/22/session.png" title="'.get_lang('Sessions').'" alt="'.get_lang('Sessions').'"/>
+					<div class="blackboard_hide" id="div_s_'.$user_id.'">&nbsp;&nbsp;</div>
+					</a>';
 	} else {
-		$result .= Display::return_icon('course_na.gif',get_lang('Courses')).'&nbsp;&nbsp;';
+		$result .= Display::return_icon('course_na.png',get_lang('Courses')).'&nbsp;&nbsp;';
+		$result .= Display::return_icon('course_na.png',get_lang('Sessions')).'&nbsp;&nbsp;';
 	}
 
 	if (api_is_platform_admin()) {
@@ -529,44 +531,45 @@ function modify_filter($user_id, $url_params, $row) {
             )
         )
     ) {
-        if (!$user_is_anonymous) {
+    	if (!$user_is_anonymous) {
             if (api_global_admin_can_edit_admin($user_id)) {
                 // everything looks good, show "login as" link
                 $result .= '<a href="user_list.php?action=login_as&amp;user_id='.$user_id.'&amp;sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('login_as.gif', get_lang('LoginAs')).'</a>&nbsp;&nbsp;';
             } else {
                 // if this user in particular can't be edited, show disabled
-                $result .= Display::return_icon('login_as_na.gif', get_lang('LoginAs')).'&nbsp;&nbsp;';
+                $result .= Display::return_icon('login_as_na.gif', get_lang('LoginAs')).'&nbsp;&nbsp;';                
             }
-        } else {
+            //$result .= '<a href="user_list.php?action=login_as&amp;user_id='.$user_id.'&amp;sec_token='.$_SESSION['sec_token'].'">'.Display::return_icon('login_as.gif', get_lang('LoginAs')).'</a>&nbsp;&nbsp;';
+    	} else {
             // if anonymous user but other users show the option, show disabled
-            $result .= Display::return_icon('login_as_na.gif', get_lang('LoginAs')).'&nbsp;&nbsp;';
-        }
+    		$result .= Display::return_icon('login_as_na.gif', get_lang('LoginAs')).'&nbsp;&nbsp;';
+    	}
     } // Else don't show anything, because the option is not available at all
 
     //$result .= Display::url('<i class="icon-key icon-large"></i>', 'roles');
-
+    
 	if ($current_user_status_label != $statusname[STUDENT]) {
 		$result .= Display::return_icon('statistics_na.gif', get_lang('Reporting')).'&nbsp;&nbsp;';
 	} else {
 		$result .= '<a href="../mySpace/myStudents.php?student='.$user_id.'">'.Display::return_icon('statistics.gif', get_lang('Reporting')).'</a>&nbsp;&nbsp;';
 	}
 
-	if (api_is_platform_admin(true)) {
-
+	if (api_is_platform_admin(true)) {        
+        
 		if (!$user_is_anonymous && api_global_admin_can_edit_admin($user_id, null, true)) {
             $result .= '<a href="user_edit.php?user_id='.$user_id.'">'.Display::return_icon('edit.png', get_lang('Edit'), array(), ICON_SIZE_SMALL).'</a>&nbsp;';
 		} else {
             $result .= Display::return_icon('edit_na.png', get_lang('Edit'), array(), ICON_SIZE_SMALL).'</a>&nbsp;';
 		}
 	}
-
-
+    
+    
 	if ($is_admin) {
 		$result .= Display::return_icon('admin_star.png', get_lang('IsAdministrator'),array('width'=> ICON_SIZE_SMALL, 'heigth'=> ICON_SIZE_SMALL));
 	} else {
 		$result .= Display::return_icon('admin_star_na.png', get_lang('IsNotAdministrator'));
 	}
-
+	
 
 	// actions for assigning sessions, courses or users
 	if (api_is_session_admin()) {
@@ -582,17 +585,17 @@ function modify_filter($user_id, $url_params, $row) {
 			$result .= '<a href="dashboard_add_sessions_to_user.php?user='.$user_id.'">'.Display::return_icon('view_more_stats.gif', get_lang('AssignSessions')).'</a>&nbsp;&nbsp;';
 		}
 	}
-
-    if (api_is_platform_admin()) {
+	
+    if (api_is_platform_admin()) {        
         $result .= ' <a href="'.api_get_path(WEB_AJAX_PATH).'agenda.ajax.php?a=get_user_agenda&amp;user_id='.$user_id.'" class="agenda_opener">'.Display::return_icon('month.png', get_lang('FreeBusyCalendar'), array(), ICON_SIZE_SMALL).'</a>';
         if ($delete_user_available) {
-            if ($user_id != api_get_user_id() && !$user_is_anonymous && api_global_admin_can_edit_admin($user_id)) {
+            if ($user_id != api_get_user_id() && !$user_is_anonymous && api_global_admin_can_edit_admin($user_id)) {                  
                 // you cannot lock yourself out otherwise you could disable all the accounts including your own => everybody is locked out and nobody can change it anymore.
-                $result .= ' <a href="user_list.php?action=delete_user&amp;user_id='.$user_id.'&amp;'.$url_params.'&amp;sec_token='.Security::getCurrentToken().'"  onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang("ConfirmYourChoice"),ENT_QUOTES,$charset))."'".')) return false;">'.Display::return_icon('delete.png', get_lang('Delete'), array(), ICON_SIZE_SMALL).'</a>';
+                $result .= ' <a href="user_list.php?action=delete_user&amp;user_id='.$user_id.'&amp;'.$url_params.'&amp;sec_token='.$_SESSION['sec_token'].'"  onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang("ConfirmYourChoice"),ENT_QUOTES,$charset))."'".')) return false;">'.Display::return_icon('delete.png', get_lang('Delete'), array(), ICON_SIZE_SMALL).'</a>';
             } else {
                 $result .= Display::return_icon('delete_na.png', get_lang('Delete'), array(), ICON_SIZE_SMALL);
             }
-        }
+        }       
     }
 	return $result;
 }
@@ -625,12 +628,25 @@ function active_filter($active, $url_params, $row) {
     if ($action=='edit') {
         $result = Display::return_icon($image.'.png', get_lang('AccountExpired'), array(), 16);
     } elseif ($row['0']<>$_user['user_id']) {
-    	// you cannot lock yourself out otherwise you could disable all the accounts including your own => everybody is locked out and nobody can change it anymore.
+    	// you cannot lock yourself out otherwise you could disable all the accounts including your own => everybody is locked out and nobody can change it anymore.		
 		$result = Display::return_icon($image.'.png', get_lang(ucfirst($action)), array('onclick'=>'active_user(this);', 'id'=>'img_'.$row['0']), 16).'</a>';
 	}
 	return $result;
 }
 
+/**
+ * Instead of displaying the integer of the status, we give a translation for the status
+ *
+ * @param integer $status
+ * @return string translation
+ *
+ * @version march 2008
+ * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Belgium
+ */
+function status_filter($status) {
+	$statusname = api_get_status_langvars();
+	return $statusname[$status];
+}
 
 $action = isset($_REQUEST["action"]) ? $_REQUEST["action"] : null;
 
@@ -646,7 +662,7 @@ if (isset($_GET['keyword']) || isset($_GET['keyword_firstname'])) {
 $message = '';
 
 if (!empty($action)) {
-	$check = Security::check_token('get');
+	$check = Security::check_token('get');    
 	if ($check) {
 		switch ($action) {
             case 'add_user_to_my_url':
@@ -656,7 +672,7 @@ if (!empty($action)) {
                     $user_info = api_get_user_info($user_id);
                     $message = get_lang('UserAdded').' '.$user_info['firstname'].' '.$user_info['lastname'].' ('.$user_info['username'].')';
                     $message  = Display::return_message($message, 'confirmation');
-                }
+                }                
                 break;
             case 'login_as':
                 $login_as_user_id = $_GET["user_id"];
@@ -680,7 +696,7 @@ if (!empty($action)) {
 				if (api_is_platform_admin()) {
                     $user_to_delete = $_GET['user_id'];
                     $current_user_id = api_get_user_id();
-
+                    
 					if ($delete_user_available && api_global_admin_can_edit_admin($_GET['user_id'])) {
 						if ($user_to_delete != $current_user_id && UserManager :: delete_user($_GET['user_id'])) {
 							$message = Display :: return_message(get_lang('UserDeleted'), 'confirmation');
@@ -705,10 +721,10 @@ if (!empty($action)) {
 							}
 						}
 					}
-					if ($number_of_selected_users == $number_of_deleted_users) {
+					if ($number_of_selected_users == $number_of_deleted_users) {						
                         $message = Display :: return_message(get_lang('SelectedUsersDeleted'), 'confirmation');
 					} else {
-                        $message = Display :: return_message(get_lang('SomeUsersNotDeleted'), 'error');
+                        $message = Display :: return_message(get_lang('SomeUsersNotDeleted'), 'error');						
 					}
 				}
 				break;
@@ -731,7 +747,7 @@ if (api_is_platform_admin()) {
 		 '<a href="'.api_get_path(WEB_CODE_PATH).'admin/user_add.php">'.Display::return_icon('new_user.png',get_lang('AddUsers'),'',ICON_SIZE_MEDIUM).'</a>'.
 		 '</span>';
 }
-$actions .= $form->return_form();
+$actions .=$form->return_form();
 
 if (isset ($_GET['keyword'])) {
 	$parameters = array ('keyword' => Security::remove_XSS($_GET['keyword']));
@@ -745,7 +761,6 @@ if (isset ($_GET['keyword'])) {
 	$parameters['keyword_active'] 		= Security::remove_XSS($_GET['keyword_active']);
 	$parameters['keyword_inactive'] 	= Security::remove_XSS($_GET['keyword_inactive']);
 }
-
 // Create a sortable table with user-data
 $parameters['sec_token'] = Security::get_token();
 
@@ -758,7 +773,7 @@ while ($row_admin = Database::fetch_row($res_admin)) {
 	$_admins_list[] = $row_admin[0];
 }
 
-// display advanced search form
+// display advaced search form
 $form = new FormValidator('advanced_search','get');
 
 $form->addElement('html','<div id="advanced_search_form" style="display:none;">');
@@ -803,6 +818,7 @@ $form->addElement('checkbox', 'check_easy_passwords', null, get_lang('CheckEasyP
 /*
  * @todo fix this code
 $extra_data = UserManager::get_extra_fields( 0,10,5, 'ASC', true, 1);
+var_dump($extra_data);
 $extra_options = array();
 if (!empty($extra_data)) {
     $extra_options[0] = get_lang('All');
@@ -859,7 +875,7 @@ $table->set_header(10, get_lang('Action'), false, 'width="220px"');
 $table->set_column_filter(3, 'user_filter');
 $table->set_column_filter(4, 'user_filter');
 $table->set_column_filter(6, 'email_filter');
-//$table->set_column_filter(7, 'status_filter');
+$table->set_column_filter(7, 'status_filter');
 $table->set_column_filter(8, 'active_filter');
 $table->set_column_filter(10, 'modify_filter');
 
@@ -872,27 +888,27 @@ $extra_search_options = '';
 
 //Try to search the user everywhere
 if ($table->get_total_number_of_items() == 0) {
-
-    if (api_get_multiple_access_url() && isset($_REQUEST['keyword'])) {
+    
+    if (api_get_multiple_access_url() && isset($_REQUEST['keyword'])) {     
         $keyword = Database::escape_string($_REQUEST['keyword']);
         //$conditions = array('firstname' => $keyword, 'lastname' => $keyword, 'username' => $keyword);
         $conditions = array('username' => $keyword);
-        $user_list = UserManager::get_user_list($conditions, array(), false, ' OR ');
+        $user_list = UserManager::get_user_list($conditions, array(), false, ' OR ');        
         if (!empty($user_list)) {
-
+            
             $extra_search_options = Display::page_subheader(get_lang('UsersFoundInOtherPortals'));
-
+            
             $table = new HTML_Table(array('class' => 'data_table'));
             $column = 0;
-            $row = 0;
+            $row = 0;            
             $headers = array(get_lang('User'), 'URL', get_lang('Actions'));
             foreach ($headers as $header) {
                 $table->setHeaderContents($row, $column, $header);
                 $column++;
             }
             $row++;
-
-            foreach ($user_list as $user) {
+            
+            foreach ($user_list as $user) {      
                 $column = 0;
                 $access_info = UrlManager::get_access_url_from_user($user['user_id']);
                 $access_info_to_string = '';
@@ -900,18 +916,18 @@ if ($table->get_total_number_of_items() == 0) {
                 if (!empty($access_info)) {
                     foreach ($access_info as $url_info) {
                         if ($current_access_url_id == $url_info['access_url_id']) {
-                            $add_user = false;
+                            $add_user = false;                            
                         }
                         $access_info_to_string .= $url_info['url'].'<br />';
                     }
                 }
-                if ($add_user) {
+                if ($add_user) {   
                     $row_table = array();
                     $row_table[] =  api_get_person_name($user['firstname'], $user['lastname']).' ('.$user['username'].') ';
                     $row_table[] =  $access_info_to_string;
-                    $url = api_get_self().'?action=add_user_to_my_url&user_id='.$user['user_id'].'&sec_token='.Security::getCurrentToken();
+                    $url = api_get_self().'?action=add_user_to_my_url&user_id='.$user['user_id'].'&sec_token='.$_SESSION['sec_token'];
                     $row_table[] =  Display::url(get_lang('AddUserToMyURL'), $url, array('class' => 'btn'));
-
+                    	
                     foreach ($row_table as $cell) {
                         $table->setCellContents($row, $column, $cell);
                         $table->updateCellAttributes($row, $column, 'align="center"');
@@ -924,13 +940,12 @@ if ($table->get_total_number_of_items() == 0) {
             $extra_search_options .= $table->toHtml();
             $table_result = '';
         }
-    }
+    }    
 }
 
-$app['title'] = $tool_name;
-$tpl = $app['template'];
+$tpl = new Template($tool_name);
 
 $tpl->assign('actions', $actions);
 $tpl->assign('message', $message);
 $tpl->assign('content', $form.$table_result.$extra_search_options);
-//$tpl->display_one_col_template();
+$tpl->display_one_col_template();

+ 18 - 18
main/auth/courses.php

@@ -28,23 +28,23 @@ if (api_get_setting('show_courses_descriptions_in_catalog') == 'true') {
 	            if ($("#dialog").length == 0) {
 	                dialog  = $(\'<div id="dialog" style="display:hidden"></div>\').appendTo(\'body\');
 	            }
-
+	            
 	            // load remote content
 	            dialog.load(
-	                    url,
+	                    url,                    
 	                    {},
 	                    function(responseText, textStatus, XMLHttpRequest) {
 	                        dialog.dialog({
-	                            modal	: true,
-	            				width	: 540,
-	            				height	: 400,
-	                        });
+	                            modal	: true, 
+	            				width	: 540, 
+	            				height	: 400,              
+	                        });	                    
 				});
 	            //prevent the browser to follow the link
 	            return false;
 	        });
         });
-
+        
     </script>';
 }
 
@@ -78,7 +78,7 @@ if (isset($_GET['action']) && in_array($_GET['action'],$actions)) {
 	$action = $_GET['action'];
 }
 
-if ($action == 'createcoursecategory') {
+if ($action == 'createcoursecategory') {	
 	$nameTools = get_lang('CreateCourseCategory');
 }
 if ($action == 'subscribe') {
@@ -99,13 +99,13 @@ $interbreadcrumb[] = array('url' => api_get_path(WEB_PATH).'user_portal.php', 'n
 if (empty($nameTools)) {
 	$nameTools = get_lang('CourseManagement');
 } else {
-
+	
 	if (!in_array($action, array('sortmycourses', 'createcoursecategory', 'display_random_courses', 'display_courses', 'subscribe'))) {
 		$interbreadcrumb[] = array('url' => api_get_path(WEB_CODE_PATH).'auth/courses.php', 'name' => get_lang('CourseManagement'));
 	}
 	if ($action == 'createcoursecategory') {
 		$interbreadcrumb[] = array('url' => api_get_path(WEB_CODE_PATH).'auth/courses.php?action=sortmycourses', 'name' => get_lang('SortMyCourses'));
-	}
+	} 
     $interbreadcrumb[] = array('url' => '#', 'name' => $nameTools);
 }
 
@@ -155,7 +155,7 @@ if ($action == 'deletecoursecategory' && isset($_GET['id'])) {
 // We are creating a new user defined course category (= Create Course Category).
 if (isset($_POST['create_course_category']) && isset($_POST['title_course_category']) && strlen(trim($_POST['title_course_category'])) > 0) {
 	if ($ctok == $_POST['sec_token']) {
-        $courses_controller->add_course_category($_POST['title_course_category']);
+        $courses_controller->add_course_category($_POST['title_course_category']);        
 	}
 }
 
@@ -168,9 +168,9 @@ if (isset($_REQUEST['search_course'])) {
 }
 
 // Subscribe user to course
-if (isset($_REQUEST['subscribe_course'])) {
+if (isset($_REQUEST['subscribe_course'])) {    
     if ($ctok == $_GET['sec_token']) {
-        $courses_controller->subscribe_user($_GET['subscribe_course'], $_GET['search_term'], $_GET['category_code']);
+        $courses_controller->subscribe_user($_GET['subscribe_course'], $_GET['search_term'], $_GET['category_code']);                
     }
 }
 // We are unsubscribing from a course (=Unsubscribe from course).
@@ -188,8 +188,8 @@ if (isset($_POST['unsubscribe'])) {
 	}
 }
 switch ($action) {
-    case 'subscribe_user_with_password':
-        $courses_controller->subscribe_user($_POST['subscribe_user_with_password'], $_POST['search_term'], $_POST['category_code']);
+    case 'subscribe_user_with_password':        
+        $courses_controller->subscribe_user($_POST['subscribe_user_with_password'], $_POST['search_term'], $_POST['category_code']);                       
         exit;
         break;
     case 'createcoursecategory':
@@ -198,16 +198,16 @@ switch ($action) {
     case 'deletecoursecategory':
         $courses_controller->courses_list($action);
         break;
-    case 'sortmycourses':
+    case 'sortmycourses':        
         $courses_controller->courses_list($action);
         break;
-    case 'subscribe':
+    case 'subscribe':                
     case 'display_random_courses':
         if ($user_can_view_page) {
             $courses_controller->courses_categories($action);
         } else {
             api_not_allowed();
-        }
+        }            
         break;
     case 'display_courses':
         $courses_controller->courses_categories($action, $_GET['category_code']);

+ 26 - 18
main/auth/courses_controller.php

@@ -11,6 +11,7 @@
  */
 class CoursesController
 {
+
     private $toolname;
     private $view;
     private $model;
@@ -18,7 +19,7 @@ class CoursesController
     /**
      * Constructor
      */
-    public function __construct() {
+    public function __construct() {		
         $this->toolname = 'auth';
         $actived_theme_path = api_get_template();
         $this->view = new View($this->toolname, $actived_theme_path);
@@ -34,7 +35,7 @@ class CoursesController
     public function courses_list($action, $message = '') {
         $data = array();
         $user_id = api_get_user_id();
-
+        
         $data['user_courses']             = $this->model->get_courses_of_user($user_id);
         $data['user_course_categories']   = $this->model->get_user_course_categories();
         $data['courses_in_category']      = $this->model->get_courses_in_category();
@@ -60,7 +61,7 @@ class CoursesController
      * @param string    error message(optional)
      */
     public function categories_list($action, $message='', $error='') {
-        $data = array();
+        $data = array();            
         $data['user_course_categories'] = $this->model->get_user_course_categories();
         $data['action'] = $action;
         $data['message'] = $message;
@@ -81,24 +82,23 @@ class CoursesController
      */
     public function courses_categories($action, $category_code = null, $message = '', $error = '', $content = null) {
         $data = array();
-        $browse_course_categories = $this->model->browse_course_categories();
-
+        $browse_course_categories = $this->model->browse_course_categories();        
+        
         if ($action == 'display_random_courses') {
             $data['browse_courses_in_category'] = $this->model->browse_courses_in_category(null, 10);
-
         } else {
             if (!isset($category_code)) {
                 $category_code = $browse_course_categories[0][1]['code']; // by default first category
-            }
+            }            
             $data['browse_courses_in_category'] = $this->model->browse_courses_in_category($category_code);
         }
-
+        
         $data['browse_course_categories'] = $browse_course_categories;
         $data['code'] = Security::remove_XSS($category_code);
 
         // getting all the courses to which the user is subscribed to
         $curr_user_id = api_get_user_id();
-        $user_courses = $this->model->get_courses_of_user($curr_user_id);
+        $user_courses = $this->model->get_courses_of_user($curr_user_id);            
         $user_coursecodes = array();
 
         // we need only the course codes as these will be used to match against the courses of the category
@@ -107,14 +107,14 @@ class CoursesController
                 $user_coursecodes[] = $value['code'];
             }
         }
-
+        
         if (api_is_drh()) {
             $courses = CourseManager::get_courses_followed_by_drh(api_get_user_id());
             foreach ($courses as $course) {
                 $user_coursecodes[] = $course['code'];
-            }
+            }            
         }
-
+        
         $data['user_coursecodes'] = $user_coursecodes;
         $data['action']           = $action;
         $data['message']          = $message;
@@ -168,18 +168,26 @@ class CoursesController
     }
 
     /**
-     *
+     * Auto user subcription to a course
      */
     public function subscribe_user($course_code, $search_term, $category_code) {
+        $data = array();
+        $courseInfo = api_get_course_info($course_code);
+        // The course must be open in order to access the auto subscription
+        if (in_array($courseInfo['visibility'], array(COURSE_VISIBILITY_CLOSED, COURSE_VISIBILITY_REGISTERED))) {
+            $error = get_lang('SubscribingNotAllowed');
+            //$message = get_lang('SubscribingNotAllowed');
+        } else {
         $result = $this->model->subscribe_user($course_code);
         if (!$result) {
             $error = get_lang('CourseRegistrationCodeIncorrect');
         } else {
-            //Redirect directly to the course after subscription
-            $message = $result['message'];
-            $content = $result['content'];
+                //Redirect directly to the course after subscription
+                $message = $result['message'];
+                $content = $result['content'];
+            }
         }
-
+        
         if (!empty($search_term)) {
             $this->search_courses($search_term, $message, $error);
         } else {
@@ -205,7 +213,7 @@ class CoursesController
     /**
      * Change course category
      * render to listing view
-     * @param int Course id
+     * @param string    Course code
      * @param int    Category id
      */
     public function change_course_category($courseId, $category_id) {

+ 5 - 8
main/auth/inscription.php

@@ -20,7 +20,6 @@ if (api_get_setting('allow_registration') === 'false') {
 }
 
 $htmlHeadXtra[] = api_get_password_checker_js('#username', '#pass1');
-
 if (!empty($_SESSION['user_language_choice'])) {
     $user_selected_language = $_SESSION['user_language_choice'];
 } elseif (!empty($_SESSION['_user']['language'])) {
@@ -42,7 +41,7 @@ $course_code_redirect = isset($_REQUEST['c']) && !empty($_REQUEST['c']) ? $_REQU
 $exercise_redirect = isset($_REQUEST['e']) && !empty($_REQUEST['e']) ? $_REQUEST['e'] : null;
 
 if (!empty($course_code_redirect)) {
-    Session::write('course_redirect', $course_code_redirect);
+    Session::write('course_redirect',   $course_code_redirect);
     Session::write('exercise_redirect', $exercise_redirect);
 }
 
@@ -63,7 +62,6 @@ if ($user_already_registered_show_terms == false) {
 
     //	EMAIL
     $form->addElement('text', 'email', get_lang('Email'), array('size' => 40));
-
     if (api_get_setting('registration', 'email') == 'true') {
         $form->addRule('email', get_lang('ThisFieldIsRequired'), 'required');
     }
@@ -92,7 +90,7 @@ if ($user_already_registered_show_terms == false) {
 
     //	USERNAME
     if (api_get_setting('login_is_email') != 'true') {
-        $form->addElement('text', 'username', get_lang('UserName'), array('id' => 'username', 'size' => USERNAME_MAX_LENGTH));
+        $form->addElement('text', 'username', get_lang('UserName'), array('size' => USERNAME_MAX_LENGTH));
         $form->applyFilter('username','trim');
         $form->addRule('username', get_lang('ThisFieldIsRequired'), 'required');
         $form->addRule('username', sprintf(get_lang('UsernameMaxXCharacters'), (string)USERNAME_MAX_LENGTH), 'maxlength', USERNAME_MAX_LENGTH);
@@ -103,6 +101,7 @@ if ($user_already_registered_show_terms == false) {
     //	PASSWORD
     $form->addElement('password', 'pass1', get_lang('Password'), array('id' => 'pass1', 'size' => 20, 'autocomplete' => 'off'));
     global $_configuration;
+
     if (isset($_configuration['allow_strength_pass_checker']) && $_configuration['allow_strength_pass_checker']) {
         $form->addElement('label', null, '<div id="password_progress"></div>');
     }
@@ -112,13 +111,11 @@ if ($user_already_registered_show_terms == false) {
     $form->addRule('pass2', get_lang('ThisFieldIsRequired'), 'required');
     $form->addRule(array('pass1', 'pass2'), get_lang('PassTwo'), 'compare');
 
-    //if (CHECK_PASS_EASY_TO_FIND) {
-        //$form->addRule('pass1', get_lang('PassTooEasy').': '.api_generate_password(), 'callback', 'api_check_password');
-    //}
+    if (CHECK_PASS_EASY_TO_FIND)
+        $form->addRule('password1', get_lang('PassTooEasy').': '.api_generate_password(), 'callback', 'api_check_password');
 
     //	PHONE
     $form->addElement('text', 'phone', get_lang('Phone'), array('size' => 20));
-
     if (api_get_setting('registration', 'phone') == 'true') {
         $form->addRule('phone', get_lang('ThisFieldIsRequired'), 'required');
     }

+ 122 - 224
main/auth/profile.php

@@ -1,13 +1,13 @@
 <?php
 /* For licensing terms, see /license.txt */
 /**
- * This file displays the user's profile,
- * optionally it allows users to modify their profile as well.
- *
- * See inc/conf/profile.conf.php to modify settings
- *
- * @package chamilo.auth
- */
+* This file displays the user's profile,
+* optionally it allows users to modify their profile as well.
+*
+* See inc/conf/profile.conf.php to modify settings
+*
+* @package chamilo.auth
+*/
 /**
  * Code
  */
@@ -42,23 +42,23 @@ function confirmation(name) {
     }
 }
 function show_image(image,width,height) {
-	width = parseInt(width) + 20;
-	height = parseInt(height) + 20;
-	window_x = window.open(image,\'windowX\',\'width=\'+ width + \', height=\'+ height + \'\');
+    width = parseInt(width) + 20;
+    height = parseInt(height) + 20;
+    window_x = window.open(image,\'windowX\',\'width=\'+ width + \', height=\'+ height + \'\');
 
 }
 function generate_open_id_form() {
-	$.ajax({
-		contentType: "application/x-www-form-urlencoded",
-		beforeSend: function(objeto) {
-		/*$("#div_api_key").html("Loading...");*/ },
-		type: "POST",
-		url: "'.api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php?a=generate_api_key",
-		data: "num_key_id="+"",
-		success: function(datos) {
-		 $("#div_api_key").html(datos);
-		}
-	});
+    $.ajax({
+        contentType: "application/x-www-form-urlencoded",
+        beforeSend: function(objeto) {
+        /*$("#div_api_key").html("Loading...");*/ },
+        type: "POST",
+        url: "'.api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php?a=generate_api_key",
+        data: "num_key_id="+"",
+        success: function(datos) {
+         $("#div_api_key").html(datos);
+        }
+    });
 }
 
 function hide_icon_edit(element_html)  {
@@ -86,18 +86,20 @@ if (!empty($_GET['fe'])) {
 $jquery_ready_content = '';
 if (api_get_setting('allow_message_tool') == 'true') {
     $jquery_ready_content = <<<EOF
-			$(".message-content .message-delete").click(function(){
-				$(this).parents(".message-content").animate({ opacity: "hide" }, "slow");
-				$(".message-view").animate({ opacity: "show" }, "slow");
-			});
+            $(".message-content .message-delete").click(function(){
+                $(this).parents(".message-content").animate({ opacity: "hide" }, "slow");
+                $(".message-view").animate({ opacity: "show" }, "slow");
+            });
 EOF;
 }
 
+
 // Libraries
+
 $tool_name = is_profile_editable() ? get_lang('ModifProfile') : get_lang('ViewProfile');
 $table_user = Database :: get_main_table(TABLE_MAIN_USER);
 
-/*	Form	*/
+/*    Form    */
 
 /*
  * Get initial values for all fields.
@@ -117,19 +119,15 @@ if ($user_data !== false) {
 /*
  * Initialize the form.
  */
-$form = new FormValidator('profile', 'post', api_get_self()."?".str_replace(
-    '&fe=1',
-    '',
-    $_SERVER['QUERY_STRING']
-), null, array('style' => 'width: 70%; float: '.($text_dir == 'rtl' ? 'right;' : 'left;')));
+$form = new FormValidator('profile', 'post', api_get_self()."?".str_replace('&fe=1', '', $_SERVER['QUERY_STRING']), null, array('style' => 'width: 70%; float: '.($text_dir == 'rtl' ? 'right;' : 'left;')));
 
 if (api_is_western_name_order()) {
-    //	FIRST NAME and LAST NAME
+    //    FIRST NAME and LAST NAME
     $form->addElement('text', 'firstname', get_lang('FirstName'), array('size' => 40));
-    $form->addElement('text', 'lastname', get_lang('LastName'), array('size' => 40));
+    $form->addElement('text', 'lastname',  get_lang('LastName'),  array('size' => 40));
 } else {
-    //	LAST NAME and FIRST NAME
-    $form->addElement('text', 'lastname', get_lang('LastName'), array('size' => 40));
+    //    LAST NAME and FIRST NAME
+    $form->addElement('text', 'lastname',  get_lang('LastName'),  array('size' => 40));
     $form->addElement('text', 'firstname', get_lang('FirstName'), array('size' => 40));
 }
 if (api_get_setting('profile', 'name') !== 'true') {
@@ -137,16 +135,11 @@ if (api_get_setting('profile', 'name') !== 'true') {
 }
 $form->applyFilter(array('lastname', 'firstname'), 'stripslashes');
 $form->applyFilter(array('lastname', 'firstname'), 'trim');
-$form->addRule('lastname', get_lang('ThisFieldIsRequired'), 'required');
+$form->addRule('lastname' , get_lang('ThisFieldIsRequired'), 'required');
 $form->addRule('firstname', get_lang('ThisFieldIsRequired'), 'required');
 
-//	USERNAME
-$form->addElement(
-    'text',
-    'username',
-    get_lang('UserName'),
-    array('id' => 'username', 'maxlength' => USERNAME_MAX_LENGTH, 'size' => USERNAME_MAX_LENGTH)
-);
+//    USERNAME
+$form->addElement('text', 'username', get_lang('UserName'), array('id' => 'username', 'maxlength' => USERNAME_MAX_LENGTH, 'size' => USERNAME_MAX_LENGTH));
 if (api_get_setting('profile', 'login') !== 'true') {
     $form->freeze('username');
 }
@@ -156,7 +149,7 @@ $form->addRule('username', get_lang('ThisFieldIsRequired'), 'required');
 $form->addRule('username', get_lang('UsernameWrong'), 'username');
 $form->addRule('username', get_lang('UserTaken'), 'username_available', $user_data['username']);
 
-//	OFFICIAL CODE
+//    OFFICIAL CODE
 if (CONFVAL_ASK_FOR_OFFICIAL_CODE) {
     $form->addElement('text', 'official_code', get_lang('OfficialCode'), array('size' => 40));
     if (api_get_setting('profile', 'officialcode') !== 'true') {
@@ -164,22 +157,18 @@ if (CONFVAL_ASK_FOR_OFFICIAL_CODE) {
     }
     $form->applyFilter('official_code', 'stripslashes');
     $form->applyFilter('official_code', 'trim');
-    if (api_get_setting('registration', 'officialcode') == 'true' && api_get_setting(
-        'profile',
-        'officialcode'
-    ) == 'true'
-    ) {
+    if (api_get_setting('registration', 'officialcode') == 'true' && api_get_setting('profile', 'officialcode') == 'true') {
         $form->addRule('official_code', get_lang('ThisFieldIsRequired'), 'required');
     }
 }
 
-//	EMAIL
+//    EMAIL
 $form->addElement('email', 'email', get_lang('Email'), array('size' => 40));
 if (api_get_setting('profile', 'email') !== 'true') {
     $form->freeze('email');
 }
 
-if (api_get_setting('registration', 'email') == 'true' && api_get_setting('profile', 'email') == 'true') {
+if (api_get_setting('registration', 'email') == 'true' &&  api_get_setting('profile', 'email') == 'true') {
     $form->applyFilter('email', 'stripslashes');
     $form->applyFilter('email', 'trim');
     $form->addRule('email', get_lang('ThisFieldIsRequired'), 'required');
@@ -194,11 +183,11 @@ if (is_profile_editable() && api_get_setting('openid_authentication') == 'true')
     }
     $form->applyFilter('openid', 'trim');
     //if (api_get_setting('registration', 'openid') == 'true') {
-    //	$form->addRule('openid', get_lang('ThisFieldIsRequired'), 'required');
+    //    $form->addRule('openid', get_lang('ThisFieldIsRequired'), 'required');
     //}
 }
 
-//	PHONE
+//    PHONE
 $form->addElement('text', 'phone', get_lang('phone'), array('size' => 20));
 if (api_get_setting('profile', 'phone') !== 'true') {
     $form->freeze('phone');
@@ -206,31 +195,22 @@ if (api_get_setting('profile', 'phone') !== 'true') {
 $form->applyFilter('phone', 'stripslashes');
 $form->applyFilter('phone', 'trim');
 /*if (api_get_setting('registration', 'phone') == 'true') {
-	$form->addRule('phone', get_lang('ThisFieldIsRequired'), 'required');
+    $form->addRule('phone', get_lang('ThisFieldIsRequired'), 'required');
 }
 $form->addRule('phone', get_lang('EmailWrong'), 'email');*/
 
-//	PICTURE
+//    PICTURE
 if (is_profile_editable() && api_get_setting('profile', 'picture') == 'true') {
-    $form->addElement(
-        'file',
-        'picture',
-        ($user_data['picture_uri'] != '' ? get_lang('UpdateImage') : get_lang('AddImage'))
-    );
+    $form->addElement('file', 'picture', ($user_data['picture_uri'] != '' ? get_lang('UpdateImage') : get_lang('AddImage')));
     $form->add_progress_bar();
     if (!empty($user_data['picture_uri'])) {
         $form->addElement('checkbox', 'remove_picture', null, get_lang('DelImage'));
     }
-    $allowed_picture_types = array('jpg', 'jpeg', 'png', 'gif');
-    $form->addRule(
-        'picture',
-        get_lang('OnlyImagesAllowed').' ('.implode(',', $allowed_picture_types).')',
-        'filetype',
-        $allowed_picture_types
-    );
+    $allowed_picture_types = array ('jpg', 'jpeg', 'png', 'gif');
+    $form->addRule('picture', get_lang('OnlyImagesAllowed').' ('.implode(',', $allowed_picture_types).')', 'filetype', $allowed_picture_types);
 }
 
-//	LANGUAGE
+//    LANGUAGE
 $form->addElement('select_language', 'language', get_lang('Language'));
 if (api_get_setting('profile', 'language') !== 'true') {
     $form->freeze('language');
@@ -244,59 +224,34 @@ if (is_profile_editable() && api_get_setting('user_selected_theme') == 'true') {
     }
     $form->applyFilter('theme', 'trim');
 }
-//	EXTENDED PROFILE  this make the page very slow!
+
+
+//    EXTENDED PROFILE  this make the page very slow!
 if (api_get_setting('extended_profile') == 'true') {
     if (!isset($_GET['type']) || (isset($_GET['type']) && $_GET['type'] == 'extended')) {
         $width_extended_profile = 500;
         //$form->addElement('html', '<a href="javascript: void(0);" onclick="javascript: show_extend();"> show_extend_profile</a>');
         //$form->addElement('static', null, '<em>'.get_lang('OptionalTextFields').'</em>');
-        //	MY COMPETENCES
-        $form->add_html_editor(
-            'competences',
-            get_lang('MyCompetences'),
-            false,
-            false,
-            array('ToolbarSet' => 'Profile', 'Width' => $width_extended_profile, 'Height' => '130')
-        );
-        //	MY DIPLOMAS
-        $form->add_html_editor(
-            'diplomas',
-            get_lang('MyDiplomas'),
-            false,
-            false,
-            array('ToolbarSet' => 'Profile', 'Width' => $width_extended_profile, 'Height' => '130')
-        );
-        //	WHAT I AM ABLE TO TEACH
-        $form->add_html_editor(
-            'teach',
-            get_lang('MyTeach'),
-            false,
-            false,
-            array('ToolbarSet' => 'Profile', 'Width' => $width_extended_profile, 'Height' => '130')
-        );
-
-        //	MY PRODUCTIONS
+        //    MY COMPETENCES
+        $form->add_html_editor('competences', get_lang('MyCompetences'), false, false, array('ToolbarSet' => 'Profile', 'Width' => $width_extended_profile, 'Height' => '130'));
+        //    MY DIPLOMAS
+        $form->add_html_editor('diplomas', get_lang('MyDiplomas'), false, false, array('ToolbarSet' => 'Profile', 'Width' => $width_extended_profile, 'Height' => '130'));
+        //    WHAT I AM ABLE TO TEACH
+        $form->add_html_editor('teach', get_lang('MyTeach'), false, false, array('ToolbarSet' => 'Profile', 'Width' => $width_extended_profile, 'Height' => '130'));
+
+        //    MY PRODUCTIONS
         $form->addElement('file', 'production', get_lang('MyProductions'));
         if ($production_list = UserManager::build_production_list(api_get_user_id(), '', true)) {
             $form->addElement('static', 'productions_list', null, $production_list);
         }
-        //	MY PERSONAL OPEN AREA
-        $form->add_html_editor(
-            'openarea',
-            get_lang('MyPersonalOpenArea'),
-            false,
-            false,
-            array('ToolbarSet' => 'Profile', 'Width' => $width_extended_profile, 'Height' => '350')
-        );
+        //    MY PERSONAL OPEN AREA
+        $form->add_html_editor('openarea', get_lang('MyPersonalOpenArea'), false, false, array('ToolbarSet' => 'Profile', 'Width' => $width_extended_profile, 'Height' => '350'));
         $form->applyFilter(array('competences', 'diplomas', 'teach', 'openarea'), 'stripslashes');
-        $form->applyFilter(
-            array('competences', 'diplomas', 'teach'),
-            'trim'
-        ); // openarea is untrimmed for maximum openness
+        $form->applyFilter(array('competences', 'diplomas', 'teach'), 'trim'); // openarea is untrimmed for maximum openness
     }
 }
 
-//	PASSWORD, if auth_source is platform
+//    PASSWORD, if auth_source is platform
 if (is_platform_authentication() && is_profile_editable() && api_get_setting('profile', 'password') == 'true') {
     $form->addElement(
         'password',
@@ -310,7 +265,7 @@ if (is_platform_authentication() && is_profile_editable() && api_get_setting('pr
     }
     $form->addElement('password', 'password1', get_lang('NewPass'), array('size' => 40));
     $form->addElement('password', 'password2', get_lang('Confirmation'), array('size' => 40));
-    //	user must enter identical password twice so we can prevent some user errors
+    //    user must enter identical password twice so we can prevent some user errors
     $form->addRule(array('password1', 'password2'), get_lang('PassTwo'), 'compare');
     if (CHECK_PASS_EASY_TO_FIND) {
         $form->addRule('password1', get_lang('CurrentPasswordEmptyOrIncorrect'), 'callback', 'api_check_password');
@@ -324,29 +279,19 @@ $return_params = $extraField->set_extra_fields_in_form($form, $extra_data, 'prof
 $jquery_ready_content = $return_params['jquery_ready_content'];
 
 // the $jquery_ready_content variable collects all functions that will be load in the $(document).ready javascript function
-$htmlHeadXtra[] = '<script>
+$htmlHeadXtra[] ='<script>
 $(document).ready(function(){
-	'.$jquery_ready_content.'
+    '.$jquery_ready_content.'
 });
 </script>';
 
 if (api_get_setting('profile', 'apikeys') == 'true') {
     $form->addElement('html', '<div id="div_api_key">');
-    $form->addElement(
-        'text',
-        'api_key_generate',
-        get_lang('MyApiKey'),
-        array('size' => 40, 'id' => 'id_api_key_generate')
-    );
+    $form->addElement('text', 'api_key_generate', get_lang('MyApiKey'), array('size' => 40, 'id' => 'id_api_key_generate'));
     $form->addElement('html', '</div>');
-    $form->addElement(
-        'button',
-        'generate_api_key',
-        get_lang('GenerateApiKey'),
-        array('id' => 'id_generate_api_key', 'onclick' => 'generate_open_id_form()')
-    ); //generate_open_id_form()
+    $form->addElement('button', 'generate_api_key', get_lang('GenerateApiKey'), array('id' => 'id_generate_api_key', 'onclick' => 'generate_open_id_form(); return false;')); //generate_open_id_form()
 }
-//	SUBMIT
+//    SUBMIT
 if (is_profile_editable()) {
     $form->addElement('style_submit_button', 'apply_change', get_lang('SaveSettings'), 'class="save"');
 } else {
@@ -356,7 +301,7 @@ if (is_profile_editable()) {
 $user_data = array_merge($user_data, $extra_data);
 $form->setDefaults($user_data);
 
-/*		FUNCTIONS   */
+/*        FUNCTIONS   */
 
 
 /**
@@ -367,7 +312,6 @@ $form->setDefaults($user_data);
 function is_platform_authentication()
 {
     $tab_user_info = api_get_user_info();
-
     return $tab_user_info['auth_source'] == PLATFORM_AUTH_SOURCE;
 }
 
@@ -383,7 +327,7 @@ function is_profile_editable()
 }
 
 /*
-	PRODUCTIONS FUNCTIONS
+    PRODUCTIONS FUNCTIONS
 */
 
 /**
@@ -409,7 +353,6 @@ function upload_user_production($user_id)
             return $filename;
         }
     }
-
     return false; // this should be returned if anything went wrong with the upload
 }
 
@@ -430,10 +373,8 @@ function check_user_password($password)
     $password = api_get_encrypted_password($password);
     $sql_password = "SELECT * FROM $table_user WHERE user_id='".$user_id."' AND password='".$password."'";
     $result = Database::query($sql_password);
-
     return Database::num_rows($result) != 0;
 }
-
 /**
  * Check current user's current password
  * @param    char    email
@@ -450,21 +391,20 @@ function check_user_email($email)
     $email = Database::escape_string($email);
     $sql_password = "SELECT * FROM $table_user WHERE user_id='".$user_id."' AND email='".$email."'";
     $result = Database::query($sql_password);
-
     return Database::num_rows($result) != 0;
 }
 
-/*		MAIN CODE */
-$filtered_extension = false;
-$update_success = false;
-$upload_picture_success = false;
-$upload_production_success = false;
-$msg_fail_changue_email = false;
-$msg_is_not_password = false;
+/*        MAIN CODE */
+$filtered_extension         = false;
+$update_success             = false;
+$upload_picture_success     = false;
+$upload_production_success  = false;
+$msg_fail_changue_email     = false;
+$msg_is_not_password        = false;
 
 if (is_platform_authentication()) {
     if (!empty($_SESSION['change_email'])) {
-        $msg_fail_changue_email = ($_SESSION['change_email'] == 'success');
+        $msg_fail_changue_email= ($_SESSION['change_email'] == 'success');
         unset($_SESSION['change_email']);
     } elseif (!empty($_SESSION['is_not_password'])) {
         $msg_is_not_password = ($_SESSION['is_not_password'] == 'success');
@@ -484,7 +424,7 @@ if (is_platform_authentication()) {
 if ($form->validate()) {
 
     $wrong_current_password = false;
-//	$user_data = $form->exportValues();
+//    $user_data = $form->exportValues();
     $user_data = $form->getSubmitValues();
 
     // set password if a new one was provided
@@ -508,21 +448,24 @@ if ($form->validate()) {
         $allow_users_to_change_email_with_no_password = false;
     }
 
+
+
+
     //If user sending the email to be changed (input available and not frozen )
     if (api_get_setting('profile', 'email') == 'true') {
-
         if ($allow_users_to_change_email_with_no_password) {
             if (!check_user_email($user_data['email'])) {
                 $changeemail = $user_data['email'];
                 //$_SESSION['change_email'] = 'success';
             }
+
         } else {
             //Normal behaviour
             if (!check_user_email($user_data['email']) && !empty($user_data['password0']) && !$wrong_current_password) {
                 $changeemail = $user_data['email'];
             }
 
-            if (!check_user_email($user_data['email']) && empty($user_data['password0'])) {
+            if (!check_user_email($user_data['email']) && empty($user_data['password0'])){
                 $_SESSION['change_email'] = 'success';
             }
         }
@@ -531,12 +474,7 @@ if ($form->validate()) {
 
     // Upload picture if a new one is provided
     if ($_FILES['picture']['size']) {
-        if ($new_picture = UserManager::update_user_picture(
-            api_get_user_id(),
-            $_FILES['picture']['name'],
-            $_FILES['picture']['tmp_name']
-        )
-        ) {
+        if ($new_picture = UserManager::update_user_picture(api_get_user_id(), $_FILES['picture']['name'], $_FILES['picture']['tmp_name'])) {
             $user_data['picture_uri'] = $new_picture;
             $_SESSION['image_uploaded'] = 'success';
         }
@@ -552,10 +490,7 @@ if ($form->validate()) {
             UserManager::remove_user_production(api_get_user_id(), urldecode($production));
         }
         if ($production_list = UserManager::build_production_list(api_get_user_id(), true, true)) {
-            $form->insertElementBefore(
-                $form->createElement('static', null, null, $production_list),
-                'productions_list'
-            );
+            $form->insertElementBefore($form->createElement('static', null, null, $production_list), 'productions_list');
         }
         $form->removeElement('productions_list');
         $file_deleted = true;
@@ -573,8 +508,8 @@ if ($form->validate()) {
     }
 
     // remove values that shouldn't go in the database
-    unset($user_data['password0'], $user_data['password1'], $user_data['password2'], $user_data['MAX_FILE_SIZE'],
-    $user_data['remove_picture'], $user_data['apply_change'], $user_data['email']);
+    unset($user_data['password0'],$user_data['password1'], $user_data['password2'], $user_data['MAX_FILE_SIZE'],
+    $user_data['remove_picture'], $user_data['apply_change'],$user_data['email'] );
 
     // Following RFC2396 (http://www.faqs.org/rfcs/rfc2396.html), a URI uses ':' as a reserved character
     // we can thus ensure the URL doesn't contain any scheme name by searching for ':' in the string
@@ -596,9 +531,9 @@ if ($form->validate()) {
     //Adding missing variables
 
     $available_values_to_modify = array();
-    foreach ($profile_list as $key => $status) {
+    foreach($profile_list as $key => $status) {
         if ($status == 'true') {
-            switch ($key) {
+            switch($key) {
                 case 'login':
                     $available_values_to_modify[] = 'username';
                     break;
@@ -617,10 +552,7 @@ if ($form->validate()) {
     }
 
     //Fixing missing variables
-    $available_values_to_modify = array_merge(
-        $available_values_to_modify,
-        array('competences', 'diplomas', 'openarea', 'teach', 'openid')
-    );
+    $available_values_to_modify = array_merge($available_values_to_modify, array('competences', 'diplomas', 'openarea', 'teach', 'openid'));
 
     // build SQL query
     $sql = "UPDATE $table_user SET";
@@ -632,12 +564,12 @@ if ($form->validate()) {
             if (is_array($value) && isset($value['Y']) && isset($value['F']) && isset($value['d'])) {
                 if (isset($value['H']) && isset($value['i'])) {
                     // extra field date time
-                    $time = mktime($value['H'], $value['i'], 0, $value['F'], $value['d'], $value['Y']);
-                    $extras[$new_key] = date('Y-m-d H:i:s', $time);
+                    $time = mktime($value['H'],$value['i'],0,$value['F'],$value['d'],$value['Y']);
+                    $extras[$new_key] = date('Y-m-d H:i:s',$time);
                 } else {
                     // extra field date
-                    $time = mktime(0, 0, 0, $value['F'], $value['d'], $value['Y']);
-                    $extras[$new_key] = date('Y-m-d', $time);
+                    $time = mktime(0,0,0,$value['F'],$value['d'],$value['Y']);
+                    $extras[$new_key] = date('Y-m-d',$time);
                 }
             } else {
                 $extras[$new_key] = $value;
@@ -662,21 +594,13 @@ if ($form->validate()) {
             $sql = rtrim($sql, ',');
         }
     } else {
-        //normal behaviour
-        if (empty($changeemail) && isset($password)) {
-            $sql .= " email = y@u.com";
-        }
         if (isset($changeemail) && !isset($password) && in_array('email', $available_values_to_modify)) {
             $sql .= " email = '".Database::escape_string($changeemail)."'";
-        } elseif (isset($password) && isset($changeemail) && in_array('email', $available_values_to_modify) && in_array(
-            'password',
-            $available_values_to_modify
-        )
-        ) {
+        } else {
+            if (isset($password) && in_array('password', $available_values_to_modify)) {
+                if (isset($changeemail) && in_array('email', $available_values_to_modify)) {
             $sql .= " email = '".Database::escape_string($changeemail)."',";
-            $password = api_get_encrypted_password($password);
-            $sql .= " password = '".Database::escape_string($password)."'";
-        } elseif (isset($password) && in_array('password', $available_values_to_modify)) {
+                }
             $password = api_get_encrypted_password($password);
             $sql .= " password = '".Database::escape_string($password)."'";
         } else {
@@ -687,6 +611,7 @@ if ($form->validate()) {
     if (api_get_setting('profile', 'officialcode') == 'true' && isset($user_data['official_code'])) {
         $sql .= ", official_code = '".Database::escape_string($user_data['official_code'])."'";
     }
+
     $sql .= " WHERE user_id  = '".api_get_user_id()."'";
     Database::query($sql);
 
@@ -695,7 +620,7 @@ if ($form->validate()) {
     //1. Deleting all user tags
     $list_extra_field_type_tag = UserManager::get_all_extra_field_by_type(ExtraField::FIELD_TYPE_TAG);
 
-    if (is_array($list_extra_field_type_tag) && count($list_extra_field_type_tag) > 0) {
+    if (is_array($list_extra_field_type_tag) && count($list_extra_field_type_tag)>0) {
         foreach ($list_extra_field_type_tag as $id) {
             UserManager::delete_user_tags(api_get_user_id(), $id);
         }
@@ -703,7 +628,7 @@ if ($form->validate()) {
 
     //2. Update the extra fields and user tags if available
 
-    if (is_array($extras) && count($extras) > 0) {
+    if (is_array($extras) && count($extras)> 0) {
         foreach ($extras as $key => $value) {
             //3. Tags are process in the UserManager::update_extra_field_value by the UserManager::process_tags function
             UserManager::update_extra_field_value(api_get_user_id(), $key, $value);
@@ -714,16 +639,13 @@ if ($form->validate()) {
     $_SESSION['_user']['uidReset'] = true;
     $_SESSION['noredirection'] = true;
     $_SESSION['profile_update'] = 'success';
-    $url = api_get_self()."?{$_SERVER['QUERY_STRING']}".($filtered_extension && strpos(
-        $_SERVER['QUERY_STRING'],
-        '&fe=1'
-    ) === false ? '&fe=1' : '');
+    $url = api_get_self()."?{$_SERVER['QUERY_STRING']}".($filtered_extension && strpos($_SERVER['QUERY_STRING'], '&fe=1') === false ? '&fe=1' : '');
     header("Location: ".$url);
     exit;
 }
 
 
-/*  		MAIN DISPLAY SECTION  */
+/*          MAIN DISPLAY SECTION  */
 // the header
 Display::display_header(get_lang('ModifyProfile'));
 
@@ -733,33 +655,17 @@ if (api_get_setting('allow_social_tool') != 'true') {
         echo '<div class="actions">';
 
         if (api_get_setting('allow_social_tool') == 'true' && api_get_setting('allow_message_tool') == 'true') {
-            echo '<a href="'.api_get_path(WEB_PATH).'main/social/profile.php">'.Display::return_icon(
-                'shared_profile.png',
-                get_lang('ViewSharedProfile')
-            ).'</a>';
+            echo '<a href="'.api_get_path(WEB_PATH).'main/social/profile.php">'.Display::return_icon('shared_profile.png', get_lang('ViewSharedProfile')).'</a>';
         }
         if (api_get_setting('allow_message_tool') == 'true') {
-            echo '<a href="'.api_get_path(WEB_PATH).'main/messages/inbox.php">'.Display::return_icon(
-                'inbox.png',
-                get_lang('Messages')
-            ).'</a>';
+            echo '<a href="'.api_get_path(WEB_PATH).'main/messages/inbox.php">'.Display::return_icon('inbox.png', get_lang('Messages')).'</a>';
         }
         $show = isset($_GET['show']) ? '&amp;show='.Security::remove_XSS($_GET['show']) : '';
 
         if (isset($_GET['type']) && $_GET['type'] == 'extended') {
-            echo '<a href="profile.php?type=reduced'.$show.'">'.Display::return_icon(
-                'edit.png',
-                get_lang('EditNormalProfile'),
-                '',
-                16
-            ).'</a>';
+            echo '<a href="profile.php?type=reduced'.$show.'">'.Display::return_icon('edit.png', get_lang('EditNormalProfile'),'',16).'</a>';
         } else {
-            echo '<a href="profile.php?type=extended'.$show.'">'.Display::return_icon(
-                'edit.png',
-                get_lang('EditExtendProfile'),
-                '',
-                16
-            ).'</a>';
+            echo '<a href="profile.php?type=extended'.$show.'">'.Display::return_icon('edit.png', get_lang('EditExtendProfile'),'',16).'</a>';
         }
         echo '</div>';
     }
@@ -775,18 +681,18 @@ if (!empty($file_deleted)) {
     }
 
     if ($upload_production_success) {
-        $message .= '<br />'.get_lang('ProductionUploaded');
+        $message.='<br />'.get_lang('ProductionUploaded');
     }
     Display :: display_confirmation_message($message, false);
 }
 
 
-if (!empty($msg_fail_changue_email)) {
-    $errormail = get_lang('ToChangeYourEmailMustTypeYourPassword');
+if (!empty($msg_fail_changue_email)){
+    $errormail=get_lang('ToChangeYourEmailMustTypeYourPassword');
     Display :: display_error_message($errormail, false);
 }
 
-if (!empty($msg_is_not_password)) {
+if (!empty($msg_is_not_password)){
     $warning_msg = get_lang('CurrentPasswordEmptyOrIncorrect');
     Display :: display_warning_message($warning_msg, false);
 }
@@ -795,8 +701,6 @@ if (!empty($msg_is_not_password)) {
 $image_syspath = UserManager::get_user_picture_path_by_id(api_get_user_id(), 'system', false, true);
 $image_syspath['dir'].$image_syspath['file'];
 
-//$image_size = api_getimagesize($image_syspath['dir'].$image_syspath['file']);
-
 //Web path
 $image_path = UserManager::get_user_picture_path_by_id(api_get_user_id(), 'web', false, true);
 $image_dir = $image_path['dir'];
@@ -805,33 +709,27 @@ $image_file = $image_dir.$image;
 $img_attributes = 'src="'.$image_file.'?rand='.time().'" '
     .'alt="'.api_get_person_name($user_data['firstname'], $user_data['lastname']).'" '
     .'style="float:'.($text_dir == 'rtl' ? 'left' : 'right').'; margin-top:0px;padding:5px;" ';
-/*
-if ($image_size['width'] > 300) {
-	//limit display width to 300px
-	$img_attributes .= 'width="300" ';
-}*/
 
 // get the path,width and height from original picture
 $big_image = $image_dir.'big_'.$image;
 
-$big_image_size = api_getimagesize($big_image);
-$big_image_width = $big_image_size['width'];
-$big_image_height = $big_image_size['height'];
-$url_big_image = $big_image.'?rnd='.time();
+$big_image_size     = api_getimagesize($big_image);
+$big_image_width    = $big_image_size['width'];
+$big_image_height   = $big_image_size['height'];
+$url_big_image      = $big_image.'?rnd='.time();
 
 $show_delete_account_button = api_get_setting('platform_unsubscribe_allowed') == 'true' ? true : false;
 
 if (api_get_setting('allow_social_tool') == 'true') {
     echo '<div class="row-fluid">';
-    echo '<div class="span3">';
-    echo SocialManager::show_social_menu('home', null, api_get_user_id(), false, $show_delete_account_button);
-    echo '</div>';
-    echo '<div class="span9">';
-    $form->display();
+        echo '<div class="span3">';
+        echo SocialManager::show_social_menu('home', null, api_get_user_id(), false, $show_delete_account_button);
+        echo '</div>';
+        echo '<div class="span9">';
+        $form->display();
     echo '</div>';
 } else {
     // Style position:absolute has been removed for Opera-compatibility.
-    //echo '<div id="image-message-container" style="float:right;display:inline;position:absolute;padding:3px;width:250px;" >';
     echo '<div id="image-message-container" style="float:right;display:inline;padding:3px;width:230px;" >';
 
     if ($image == 'unknown.jpg') {

Файлын зөрүү хэтэрхий том тул дарагдсан байна
+ 192 - 354
main/calendar/agenda.inc.php


+ 945 - 0
main/calendar/agenda.lib.php

@@ -0,0 +1,945 @@
+<?php
+/* For licensing terms, see /license.txt */
+
+/**
+ *  @author: Julio Montoya <gugli100@gmail.com> Implementing a real agenda lib
+ */
+class Agenda
+{
+    var $events = array();
+    var $type = 'personal'; // personal, admin or course
+
+    function __construct()
+    {
+        //Table definitions
+        $this->tbl_global_agenda = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
+        $this->tbl_personal_agenda = Database::get_user_personal_table(TABLE_PERSONAL_AGENDA);
+        $this->tbl_course_agenda = Database::get_course_table(TABLE_AGENDA);
+
+        //Setting the course object if we are in a course
+        $this->course = null;
+        $course_info = api_get_course_info();
+        if (!empty($course_info)) {
+            $this->course = $course_info;
+        }
+
+        $this->events = array();
+
+        //Event colors
+        $this->event_platform_color = 'red'; //red
+        $this->event_course_color = '#458B00'; //green
+        $this->event_group_color = '#A0522D'; //siena
+        $this->event_session_color = '#00496D'; // kind of green
+        $this->event_personal_color = 'steel blue'; //steel blue
+    }
+
+    function set_course($course_info)
+    {
+        $this->course = $course_info;
+    }
+
+    /**
+     *
+     * Adds an event to the calendar
+     *
+     * @param   string  start datetime format: 2012-06-14 09:00:00
+     * @param   string  end datetime format: 2012-06-14 09:00:00
+     * @param   string  all day (true, false)
+     * @param   string  view agendaDay, agendaWeek, month @todo seems not to be used
+     * @param   string  title
+     * @param   string  content
+     * @param   array   users to send array('everyone') or a list of user ids
+     * @param   bool    add event as a *course* announcement
+     *
+     */
+    function add_event($start, $end, $all_day, $view, $title, $content, $users_to_send = array(), $add_as_announcement = false)
+    {
+        $start = api_get_utc_datetime($start);
+        $end = api_get_utc_datetime($end);
+        $all_day = isset($all_day) && $all_day == 'true' ? 1 : 0;
+
+        $attributes = array();
+        $id = null;
+        switch ($this->type) {
+            case 'personal':
+                $attributes['user'] = api_get_user_id();
+                $attributes['title'] = $title;
+                $attributes['text'] = $content;
+                $attributes['date'] = $start;
+                $attributes['enddate'] = $end;
+                $attributes['all_day'] = $all_day;
+                $id = Database::insert($this->tbl_personal_agenda, $attributes);
+                break;
+            case 'course':
+                $attributes['title'] = $title;
+                $attributes['content'] = $content;
+                $attributes['start_date'] = $start;
+                $attributes['end_date'] = $end;
+                $attributes['all_day'] = $all_day;
+                $attributes['session_id'] = api_get_session_id();
+                $attributes['c_id'] = $this->course['real_id'];
+
+                //simple course event
+                $id = Database::insert($this->tbl_course_agenda, $attributes);
+
+                if ($id) {
+                    $group_id = api_get_group_id();
+
+                    if ((!is_null($users_to_send)) or (!empty($group_id))) {
+                        $send_to = self::separate_users_groups($users_to_send);
+                        if (isset($send_to['everyone']) && $send_to['everyone']) {
+                            api_item_property_update($this->course, TOOL_CALENDAR_EVENT, $id, "AgendaAdded", api_get_user_id(), $group_id, '', $start, $end);
+                        } else {
+                            // storing the selected groups
+                            if (isset($send_to['groups']) && is_array($send_to['groups'])) {
+                                foreach ($send_to['groups'] as $group) {
+                                    api_item_property_update($this->course, TOOL_CALENDAR_EVENT, $id, "AgendaAdded", api_get_user_id(), $group, 0, $start, $end);
+                                }
+                            }
+
+                            // storing the selected users
+                            if (isset($send_to['groups']) && is_array($send_to['users'])) {
+                                foreach ($send_to['users'] as $to_user_id) {
+                                    api_item_property_update($this->course, TOOL_CALENDAR_EVENT, $id, "AgendaAdded", api_get_user_id(), $group_id, $to_user_id, $start, $end);
+                                }
+                            }
+                        }
+                    }
+
+                    if (isset($add_as_announcement) && !empty($add_as_announcement)) {
+                        self::store_agenda_item_as_announcement($id, $users_to_send);
+                    }
+                }
+                break;
+            case 'admin':
+                if (api_is_platform_admin()) {
+                    $attributes['title'] = $title;
+                    $attributes['content'] = $content;
+                    $attributes['start_date'] = $start;
+                    $attributes['end_date'] = $end;
+                    $attributes['all_day'] = $all_day;
+                    $attributes['access_url_id'] = api_get_current_access_url_id();
+                    $id = Database::insert($this->tbl_global_agenda, $attributes);
+                }
+                break;
+        }
+        return $id;
+    }
+
+    /**
+     * @param agenda_id
+     * @sent agenda event to
+     * */
+    function store_agenda_item_as_announcement($item_id, $sent_to = array())
+    {
+        $table_agenda = Database::get_course_table(TABLE_AGENDA);
+        $course_id = api_get_course_int_id();
+
+        //check params
+        if (empty($item_id) or $item_id != strval(intval($item_id))) {
+            return -1;
+        }
+        //get the agenda item
+
+        $item_id = Database::escape_string($item_id);
+        $sql = "SELECT * FROM $table_agenda WHERE c_id = $course_id AND id = ".$item_id;
+        $res = Database::query($sql);
+
+        if (Database::num_rows($res) > 0) {
+            $row = Database::fetch_array($res, 'ASSOC');
+
+            //Sending announcement
+            if (!empty($sent_to)) {
+                $id = AnnouncementManager::add_announcement($row['title'], $row['content'], $sent_to, null, null, $row['end_date']);
+                AnnouncementManager::send_email($id);
+            }
+            return $id;
+        }
+        return -1;
+    }
+
+    /**
+     * Edits an event
+     *
+     * @param int       event id
+     * @param string    start datetime format: 2012-06-14 09:00:00
+     * @param string    end datetime format: 2012-06-14 09:00:00
+     * @param int       event is all day? 1|0
+     * @param string    view
+     * @param string    event title
+     * @param string    event content
+     */
+    function edit_event($id, $start, $end, $all_day, $view, $title, $content)
+    {
+        $start = api_get_utc_datetime($start);
+
+        if ($all_day == '0') {
+            $end = api_get_utc_datetime($end);
+        }
+        $all_day = isset($all_day) && $all_day == '1' ? 1 : 0;
+
+        $attributes = array();
+
+        switch ($this->type) {
+            case 'personal':
+                $eventInfo = $this->get_event($id);
+                if ($eventInfo['user'] != api_get_user_id()) {
+                    break;
+                }
+                $attributes['title'] = $title;
+                $attributes['text'] = $content;
+                $attributes['date'] = $start;
+                $attributes['enddate'] = $end;
+                Database::update($this->tbl_personal_agenda, $attributes, array('id = ?' => $id));
+                break;
+            case 'course':
+                $course_id = api_get_course_int_id();
+                if (!empty($course_id) && api_is_allowed_to_edit(null, true)) {
+                    $attributes['title'] = $title;
+                    $attributes['content'] = $content;
+                    $attributes['start_date'] = $start;
+                    $attributes['end_date'] = $end;
+                    $attributes['all_day'] = $all_day;
+                    Database::update($this->tbl_course_agenda, $attributes, array('id = ? AND c_id = ?' => array($id, $course_id)));
+                }
+                break;
+            case 'admin':
+                if (api_is_platform_admin()) {
+                    $attributes['title'] = $title;
+                    $attributes['content'] = $content;
+                    $attributes['start_date'] = $start;
+                    $attributes['end_date'] = $end;
+                    Database::update($this->tbl_global_agenda, $attributes, array('id = ?' => $id));
+                }
+                break;
+        }
+    }
+
+    function delete_event($id)
+    {
+        switch ($this->type) {
+            case 'personal':
+                $eventInfo = $this->get_event($id);
+                if ($eventInfo['user'] == api_get_user_id()) {
+                    Database::delete($this->tbl_personal_agenda, array('id = ?' => $id));
+                }
+                break;
+            case 'course':
+                $course_id = api_get_course_int_id();
+                if (!empty($course_id) && api_is_allowed_to_edit(null, true)) {
+                    Database::delete($this->tbl_course_agenda, array('id = ? AND c_id = ?' => array($id, $course_id)));
+                }
+                break;
+            case 'admin':
+                if (api_is_platform_admin()) {
+                    Database::delete($this->tbl_global_agenda, array('id = ?' => $id));
+                }
+                break;
+        }
+    }
+
+    /**
+     *
+     * Get agenda events
+     * @param	int		start tms
+     * @param	int		end tms
+     * @param	int		course id *integer* not the course code
+     * @param   int     user id
+     *
+     */
+    function get_events($start, $end, $course_id = null, $group_id = null, $user_id = 0)
+    {
+
+        switch ($this->type) {
+            case 'admin':
+                $this->get_platform_events($start, $end);
+                break;
+            case 'course':
+                $session_id = api_get_session_id();
+                $course_info = api_get_course_info_by_id($course_id);
+                $this->get_course_events($start, $end, $course_info, $group_id, $session_id, $user_id);
+                break;
+            case 'personal':
+            default:
+                //Getting personal events
+                $this->get_personal_events($start, $end);
+
+                //Getting platform/admin events
+                $this->get_platform_events($start, $end);
+
+                //Getting course events
+                $my_course_list = array();
+
+                if (!api_is_anonymous()) {
+                    $session_list = SessionManager::get_sessions_by_user(api_get_user_id());
+                    $my_course_list = CourseManager::get_courses_list_by_user_id(api_get_user_id(), true);
+                }
+
+                if (!empty($session_list)) {
+                    foreach ($session_list as $session_item) {
+                        $my_courses = $session_item['courses'];
+                        $my_session_id = $session_item['session_id'];
+                        if (!empty($my_courses)) {
+                            foreach ($my_courses as $course_item) {
+                                $course_info = api_get_course_info($course_item['code']);
+                                $this->get_course_events($start, $end, $course_info, 0, $my_session_id);
+                            }
+                        }
+                    }
+                }
+
+                if (!empty($my_course_list)) {
+                    foreach ($my_course_list as $course_info_item) {
+                        if (isset($course_id) && !empty($course_id)) {
+                            if ($course_info_item['real_id'] == $course_id) {
+                                $this->get_course_events($start, $end, $course_info_item);
+                            }
+                        } else {
+                            $this->get_course_events($start, $end, $course_info_item);
+                        }
+                    }
+                }
+                break;
+        }
+        if (!empty($this->events)) {
+            return json_encode($this->events);
+        }
+        return '';
+    }
+
+    function resize_event($id, $day_delta, $minute_delta)
+    {
+        // we convert the hour delta into minutes and add the minute delta
+        $delta = ($day_delta * 60 * 24) + $minute_delta;
+        $delta = intval($delta);
+
+        $event = $this->get_event($id);
+        if (!empty($event)) {
+            switch ($this->type) {
+                case 'personal':
+                    $sql = "UPDATE $this->tbl_personal_agenda SET all_day = 0, enddate = DATE_ADD(enddate, INTERVAL $delta MINUTE)
+							WHERE id=".intval($id);
+                    $result = Database::query($sql);
+                    break;
+                case 'course':
+                    $sql = "UPDATE $this->tbl_course_agenda SET all_day = 0,  end_date = DATE_ADD(end_date, INTERVAL $delta MINUTE)
+							WHERE c_id = ".$this->course['real_id']." AND id=".intval($id);
+                    $result = Database::query($sql);
+                    break;
+                case 'admin':
+                    $sql = "UPDATE $this->tbl_global_agenda SET all_day = 0, end_date = DATE_ADD(end_date, INTERVAL $delta MINUTE)
+							WHERE id=".intval($id);
+                    $result = Database::query($sql);
+                    break;
+            }
+        }
+        return 1;
+    }
+
+    function move_event($id, $day_delta, $minute_delta)
+    {
+        // we convert the hour delta into minutes and add the minute delta
+        $delta = ($day_delta * 60 * 24) + $minute_delta;
+        $delta = intval($delta);
+
+        $event = $this->get_event($id);
+
+        $all_day = 0;
+        if ($day_delta == 0 && $minute_delta == 0) {
+            $all_day = 1;
+        }
+
+        if (!empty($event)) {
+            switch ($this->type) {
+                case 'personal':
+                    $sql = "UPDATE $this->tbl_personal_agenda SET all_day = $all_day, date = DATE_ADD(date, INTERVAL $delta MINUTE), enddate = DATE_ADD(enddate, INTERVAL $delta MINUTE)
+							WHERE id=".intval($id);
+                    $result = Database::query($sql);
+                    break;
+                case 'course':
+                    $sql = "UPDATE $this->tbl_course_agenda SET all_day = $all_day, start_date = DATE_ADD(start_date,INTERVAL $delta MINUTE), end_date = DATE_ADD(end_date, INTERVAL $delta MINUTE)
+							WHERE c_id = ".$this->course['real_id']." AND id=".intval($id);
+                    $result = Database::query($sql);
+                    break;
+                case 'admin':
+                    $sql = "UPDATE $this->tbl_global_agenda SET all_day = $all_day, start_date = DATE_ADD(start_date,INTERVAL $delta MINUTE), end_date = DATE_ADD(end_date, INTERVAL $delta MINUTE)
+							WHERE id=".intval($id);
+                    $result = Database::query($sql);
+                    break;
+            }
+        }
+        return 1;
+    }
+
+    /**
+     * Gets a single event
+     *
+     * @param int event id
+     * @return array
+     */
+    function get_event($id)
+    {
+        // make sure events of the personal agenda can only be seen by the user himself
+        $id = intval($id);
+        $event = null;
+        switch ($this->type) {
+            case 'personal':
+                $sql = " SELECT * FROM ".$this->tbl_personal_agenda." WHERE id = $id AND user = ".api_get_user_id();
+                $result = Database::query($sql);
+                if (Database::num_rows($result)) {
+                    $event = Database::fetch_array($result, 'ASSOC');
+                    $event['description'] = $event['text'];
+                    $event['start_date'] = $event['date'];
+                    $event['end_date'] = $event['enddate'];
+                }
+                break;
+            case 'course':
+                if (!empty($this->course['real_id'])) {
+                    $sql = " SELECT * FROM ".$this->tbl_course_agenda." WHERE c_id = ".$this->course['real_id']." AND id = ".$id;
+                    $result = Database::query($sql);
+                    if (Database::num_rows($result)) {
+                        $event = Database::fetch_array($result, 'ASSOC');
+                        $event['description'] = $event['content'];
+                    }
+                }
+                break;
+            case 'admin':
+            case 'platform':
+                $sql = " SELECT * FROM ".$this->tbl_global_agenda." WHERE id=".$id;
+                $result = Database::query($sql);
+                if (Database::num_rows($result)) {
+                    $event = Database::fetch_array($result, 'ASSOC');
+                    $event['description'] = $event['content'];
+                }
+                break;
+        }
+        return $event;
+    }
+
+    /**
+     *
+     * Gets personal events
+     * @param int 	start date tms
+     * @param int	end   date tms
+     */
+    function get_personal_events($start, $end)
+    {
+        $start = intval($start);
+        $end = intval($end);
+        $start = api_get_utc_datetime($start);
+        $end = api_get_utc_datetime($end);
+        $user_id = api_get_user_id();
+
+        $sql = "SELECT * FROM ".$this->tbl_personal_agenda."
+				   WHERE date >= '".$start."' AND (enddate <='".$end."' OR enddate IS NULL) AND user = $user_id";
+
+        $result = Database::query($sql);
+        $my_events = array();
+        if (Database::num_rows($result)) {
+            while ($row = Database::fetch_array($result, 'ASSOC')) {
+                $event = array();
+                $event['id'] = 'personal_'.$row['id'];
+                $event['title'] = $row['title'];
+                $event['className'] = 'personal';
+                $event['borderColor'] = $event['backgroundColor'] = $this->event_personal_color;
+                $event['editable'] = true;
+
+                $event['sent_to'] = get_lang('Me');
+                $event['type'] = 'personal';
+
+                if (!empty($row['date']) && $row['date'] != '0000-00-00 00:00:00') {
+                    $event['start'] = $this->format_event_date($row['date']);
+                }
+
+                if (!empty($row['enddate']) && $row['enddate'] != '0000-00-00 00:00:00') {
+                    $event['end'] = $this->format_event_date($row['enddate']);
+                }
+                $event['description'] = $row['text'];
+                $event['allDay'] = isset($row['all_day']) && $row['all_day'] == 1 ? $row['all_day'] : 0;
+                $my_events[] = $event;
+                $this->events[] = $event;
+            }
+        }
+        return $my_events;
+    }
+
+    function get_course_events($start, $end, $course_info, $group_id = 0, $session_id = 0, $user_id = 0)
+    {
+        $course_id = $course_info['real_id'];
+        $user_id = intval($user_id);
+
+        $group_list = GroupManager::get_group_list(null, $course_info['code']);
+
+        $group_name_list = array();
+        if (!empty($group_list)) {
+            foreach ($group_list as $group) {
+                $group_name_list[$group['id']] = $group['name'];
+            }
+        }
+
+        if (!api_is_allowed_to_edit()) {
+            $group_memberships = GroupManager::get_group_ids($course_id, api_get_user_id());
+            $user_id = api_get_user_id();
+        } else {
+            $group_memberships = GroupManager::get_group_ids($course_id, $user_id);
+        }
+
+        $tlb_course_agenda = Database::get_course_table(TABLE_AGENDA);
+        $tbl_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
+
+        if (!empty($group_id)) {
+            $group_memberships = array($group_id);
+        }
+
+        $session_id = intval($session_id);
+       
+        if (is_array($group_memberships) && count($group_memberships) > 0) {
+            if (api_is_allowed_to_edit()) {
+                if (!empty($group_id)){
+                    $where_condition = "( ip.to_group_id IN (0, ".implode(", ", $group_memberships).") ) "; 
+                } else {
+                    if (!empty($user_id)) {
+                        $where_condition = "( ip.to_user_id = $user_id OR ip.to_group_id IN (0, ".implode(", ", $group_memberships).") ) ";
+                    } else {
+                        $where_condition = "( ip.to_group_id is null OR ip.to_group_id IN (0, ".implode(", ", $group_memberships).") ) ";
+                    }
+                }
+            } else {
+                $where_condition = "( ip.to_user_id = $user_id OR ip.to_group_id IN (0, ".implode(", ", $group_memberships).") ) ";
+            }
+
+            $sql = "SELECT DISTINCT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref, to_user_id
+                    FROM ".$tlb_course_agenda." agenda, ".$tbl_property." ip
+                    WHERE   agenda.id       = ip.ref  AND
+                            ip.tool         ='".TOOL_CALENDAR_EVENT."' AND
+                            $where_condition AND
+                            ip.visibility   = '1' AND
+                            agenda.c_id     = $course_id AND
+                            ip.c_id         = $course_id
+
+                    GROUP BY id";
+        } else {
+            if (api_is_allowed_to_edit()) {
+                if ($user_id == 0) {
+                    $where_condition = "";
+                } else {
+                    $where_condition = "( ip.to_user_id=".$user_id. ") AND ";
+                }
+            } else {
+                $where_condition = "( ip.to_user_id=$user_id OR ip.to_group_id='0') AND ";
+            }
+
+            $sql = "SELECT DISTINCT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref, to_user_id
+                    FROM ".$tlb_course_agenda." agenda, ".$tbl_property." ip
+                    WHERE   agenda.id = ip.ref AND
+                            ip.tool='".TOOL_CALENDAR_EVENT."' AND
+                            $where_condition
+                            ip.visibility='1' AND
+                            agenda.c_id = $course_id AND
+                            ip.c_id = $course_id AND
+                            agenda.session_id = $session_id AND
+                            ip.id_session = $session_id
+                    ";
+        }
+
+        $result = Database::query($sql);
+        $events = array();
+        if (Database::num_rows($result)) {
+            $events_added = array();
+            while ($row = Database::fetch_array($result, 'ASSOC')) {
+                //to gather sent_tos
+                $sql = "SELECT to_user_id, to_group_id
+                    FROM ".$tbl_property." ip
+                    WHERE   ip.tool         = '".TOOL_CALENDAR_EVENT."' AND
+                            ref             = {$row['ref']} AND
+                            ip.visibility   = '1' AND
+                            ip.c_id         = $course_id";
+                $sent_to_result = Database::query($sql);
+                $user_to_array = array();
+                $group_to_array = array();
+                while ($row_send_to = Database::fetch_array($sent_to_result, 'ASSOC')) {
+                    if (!empty($row_send_to['to_group_id'])) {
+                        $group_to_array[] = $row_send_to['to_group_id'];
+                    }
+                    if (!empty($row_send_to['to_user_id'])) {
+                        $user_to_array[] = $row_send_to['to_user_id'];
+                    }
+                }
+
+                //Only show events from the session
+                /* if (api_get_course_int_id()) {
+                  if ($row['session_id'] != api_get_session_id()) {
+                  continue;
+                  }
+                  } */
+
+                $event = array();
+
+                $event['id'] = 'course_'.$row['id'];
+
+                //To avoid doubles
+                if (in_array($row['id'], $events_added)) {
+                    continue;
+                }
+
+                $events_added[] = $row['id'];
+
+                $attachment = get_attachment($row['id'], $course_id);
+
+                $has_attachment = '';
+
+                if (!empty($attachment)) {
+                    $has_attachment = Display::return_icon('attachment.gif', get_lang('Attachment'));
+                    $user_filename = $attachment['filename'];
+                    $full_file_name = 'download.php?file='.$attachment['path'].'&course_id='.$course_id;
+                    $event['attachment'] = $has_attachment.Display::url($user_filename, $full_file_name);
+                } else {
+                    $event['attachment'] = '';
+                }
+
+                $event['title'] = $row['title'];
+                $event['className'] = 'course';
+                $event['allDay'] = 'false';
+
+                $event['course_id'] = $course_id;
+
+                $event['borderColor'] = $event['backgroundColor'] = $this->event_course_color;
+                if (isset($row['session_id']) && !empty($row['session_id'])) {
+                    $event['borderColor'] = $event['backgroundColor'] = $this->event_session_color;
+                }
+
+                if (isset($row['to_group_id']) && !empty($row['to_group_id'])) {
+                    $event['borderColor'] = $event['backgroundColor'] = $this->event_group_color;
+                }
+
+                $event['editable'] = false;
+
+                if (api_is_allowed_to_edit() && $this->type == 'course') {
+                    $event['editable'] = true;
+                }
+
+                if (!empty($row['start_date']) && $row['start_date'] != '0000-00-00 00:00:00') {
+                    $event['start'] = $this->format_event_date($row['start_date']);
+                }
+                if (!empty($row['end_date']) && $row['end_date'] != '0000-00-00 00:00:00') {
+                    $event['end'] = $this->format_event_date($row['end_date']);
+                }
+
+                $event['sent_to'] = '';
+                //$event['type']    = $this->type;
+                $event['type'] = 'course';
+                if ($row['session_id'] != 0) {
+                    $event['type'] = 'session';
+                }
+
+                //Event Sent to a group?
+                if (isset($row['to_group_id']) && !empty($row['to_group_id'])) {
+                    $sent_to = array();
+                    if (!empty($group_to_array)) {
+                        foreach ($group_to_array as $group_item) {
+                            $sent_to[] = $group_name_list[$group_item];
+                        }
+                    }
+                    $sent_to = implode('@@', $sent_to);
+                    $sent_to = str_replace('@@', '</div><div class="label_tag notice">', $sent_to);
+                    $event['sent_to'] = '<div class="label_tag notice">'.$sent_to.'</div>';
+                    $event['type'] = 'group';
+                }
+
+                //Event sent to a user?
+                if (isset($row['to_user_id'])) {
+                    $sent_to = array();
+                    if (!empty($user_to_array)) {
+                        foreach ($user_to_array as $item) {
+                            $user_info = api_get_user_info($item);
+                            // add username as tooltip for $event['sent_to'] - ref #4226
+                            $username = api_htmlentities(sprintf(get_lang('LoginX'), $user_info['username']), ENT_QUOTES);
+                            $sent_to[] = "<span title='".$username."'>".$user_info['complete_name']."</span>";
+                        }
+                    }
+                    $sent_to = implode('@@', $sent_to);
+                    $sent_to = str_replace('@@', '</div><div class="label_tag notice">', $sent_to);
+                    $event['sent_to'] = '<div class="label_tag notice">'.$sent_to.'</div>';
+                }
+
+                //Event sent to everyone!
+                if (empty($event['sent_to'])) {
+                    $event['sent_to'] = '<div class="label_tag notice">'.get_lang('Everyone').'</div>';
+                }
+
+                $event['description'] = $row['content'];
+                $event['allDay'] = isset($row['all_day']) && $row['all_day'] == 1 ? $row['all_day'] : 0;
+
+                $this->events[] = $event;
+            }
+        }
+        return $this->events;
+    }
+
+    function get_platform_events($start, $end)
+    {
+        $start = intval($start);
+        $end = intval($end);
+
+        $start = api_get_utc_datetime($start);
+        $end = api_get_utc_datetime($end);
+
+        $access_url_id = api_get_current_access_url_id();
+
+        $sql = "SELECT * FROM ".$this->tbl_global_agenda."
+				   WHERE start_date >= '".$start."' AND end_date <= '".$end."' AND access_url_id = $access_url_id ";
+
+        $result = Database::query($sql);
+        $my_events = array();
+        if (Database::num_rows($result)) {
+            while ($row = Database::fetch_array($result, 'ASSOC')) {
+                $event = array();
+                $event['id'] = 'platform_'.$row['id'];
+                $event['title'] = $row['title'];
+                $event['className'] = 'platform';
+                $event['allDay'] = 'false';
+                $event['borderColor'] = $event['backgroundColor'] = $this->event_platform_color;
+                $event['editable'] = false;
+
+                $event['type'] = 'admin';
+
+                if (api_is_platform_admin() && $this->type == 'admin') {
+                    $event['editable'] = true;
+                }
+
+                if (!empty($row['start_date']) && $row['start_date'] != '0000-00-00 00:00:00') {
+                    $event['start'] = $this->format_event_date($row['start_date']);
+                }
+                if (!empty($row['end_date']) && $row['end_date'] != '0000-00-00 00:00:00') {
+                    $event['end'] = $this->format_event_date($row['end_date']);
+                }
+
+                $event['description'] = $row['content'];
+                $event['allDay'] = isset($row['all_day']) && $row['all_day'] == 1 ? $row['all_day'] : 0;
+
+                $my_events[] = $event;
+                $this->events[] = $event;
+            }
+        }
+        return $my_events;
+    }
+
+    /**
+     * Format needed for the Fullcalendar js lib
+     *  @param string UTC time
+     */
+    function format_event_date($utc_time)
+    {
+        return date('c', api_strtotime(api_get_local_time($utc_time)));
+    }
+
+    /**
+     * this function shows the form with the user that were not selected
+     * @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
+     * @return html code
+     */
+    static function construct_not_selected_select_form($group_list = null, $user_list = null, $to_already_selected = array())
+    {
+        $html = '<select id="users_to_send_id" data-placeholder="'.get_lang('Select').'" name="users_to_send[]" multiple="multiple" style="width:250px" class="chzn-select">';
+
+
+        if ($to_already_selected == 'everyone') {
+            $html .= '<option value="everyone" checked="checked">'.get_lang('Everyone').'</option>';
+        } else {
+            $html .= '<option value="everyone">'.get_lang('Everyone').'</option>';
+        }
+
+        if (is_array($group_list)) {
+            $html .= '<optgroup label="'.get_lang('Groups').'">';
+            foreach ($group_list as $this_group) {
+                if (!is_array($to_already_selected) || !in_array("GROUP:".$this_group['id'], $to_already_selected)) {
+                    // $to_already_selected is the array containing the groups (and users) that are already selected
+                    $count_users = isset($this_group['count_users']) ? $this_group['count_users'] : $this_group['userNb'];
+                    $count_users = " &ndash; $count_users ".get_lang('Users');
+
+                    $html .= '<option value="GROUP:'.$this_group['id'].'"> '.$this_group['name'].$count_users.'</option>';
+                }
+            }
+            $html .= '</optgroup>';
+        }
+
+        // adding the individual users to the select form
+        if (is_array($group_list)) {
+            $html .= '<optgroup label="'.get_lang('Users').'">';
+        }
+        foreach ($user_list as $this_user) {
+            // $to_already_selected is the array containing the users (and groups) that are already selected
+            if (!is_array($to_already_selected) || !in_array("USER:".$this_user['user_id'], $to_already_selected)) {
+                $username = api_htmlentities(sprintf(get_lang('LoginX'), $this_user['username']), ENT_QUOTES);
+                // @todo : add title attribute $username in the jqdialog window. wait for a chosen version to inherit title attribute
+                $html .= '<option title="'.$username.'" value="USER:'.$this_user['user_id'].'">'.api_get_person_name($this_user['firstname'], $this_user['lastname']).' ('.$this_user['username'].') </option>';
+            }
+        }
+        if (is_array($group_list)) {
+            $html .= '</optgroup>';
+            $html .= "</select>";
+        }
+        return $html;
+    }
+
+    static function construct_not_selected_select_form_validator($form, $group_list = null, $user_list = null, $to_already_selected = array())
+    {
+
+        $params = array(
+            'id' => 'users_to_send_id',
+            'data-placeholder' => get_lang('Select'),
+            'multiple' => 'multiple',
+            'style' => 'width:250px',
+            'class' => 'chzn-select'
+        );
+
+        $select = $form->addElement('select', 'users_to_send', get_lang('To'), null, $params);
+
+        $select->addOption(get_lang('Everyone'), 'everyone');
+
+        $options = array();
+        if (is_array($group_list)) {
+            foreach ($group_list as $this_group) {
+                if (!is_array($to_already_selected) || !in_array("GROUP:".$this_group['id'], $to_already_selected)) {
+                    // $to_already_selected is the array containing the groups (and users) that are already selected
+                    $count_users = isset($this_group['count_users']) ? $this_group['count_users'] : $this_group['userNb'];
+                    $count_users = " &ndash; $count_users ".get_lang('Users');
+                    $options[] = array('text' => $this_group['name'].$count_users, 'value' => "GROUP:".$this_group['id']);
+                }
+            }
+            $select->addOptGroup($options, get_lang('Groups'));
+            $html .= '</optgroup>';
+        }
+
+        // adding the individual users to the select form
+        if (is_array($group_list)) {
+            $options = array();
+            foreach ($user_list as $this_user) {
+                // $to_already_selected is the array containing the users (and groups) that are already selected
+                if (!is_array($to_already_selected) || !in_array("USER:".$this_user['user_id'], $to_already_selected)) {
+                    //$username = api_htmlentities(sprintf(get_lang('LoginX'), $this_user['username']), ENT_QUOTES);
+                    // @todo : add title attribute $username in the jqdialog window. wait for a chosen version to inherit title attribute
+                    // from <option> to <li>
+                    //$html .= '<option title="'.$username.'" value="USER:'.$this_user['user_id'].'">'.api_get_person_name($this_user['firstname'], $this_user['lastname']).' ('.$this_user['username'].') </option>';
+                    $options[] = array('text' => api_get_person_name($this_user['firstname'], $this_user['lastname']).' ('.$this_user['username'].')',
+                        'value' => "USER:".$this_user['user_id']);
+                }
+            }
+            $select->addOptGroup($options, get_lang('Users'));
+        }
+    }
+
+    /**
+     * This function separates the users from the groups
+     * users have a value USER:XXX (with XXX the dokeos id
+     * groups have a value GROUP:YYY (with YYY the group id)
+     * @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
+     * @return array
+     */
+    function separate_users_groups($to)
+    {
+        $grouplist = array();
+        $userlist = array();
+        $send_to = null;
+
+        $send_to['everyone'] = false;
+        if (is_array($to) && count($to) > 0) {
+            foreach ($to as $to_item) {
+                if ($to_item == 'everyone') {
+                    $send_to['everyone'] = true;
+                } else {
+                    list($type, $id) = explode(':', $to_item);
+                    switch ($type) {
+                        case 'GROUP':
+                            $grouplist[] = $id;
+                            break;
+                        case 'USER':
+                            $userlist[] = $id;
+                            break;
+                    }
+                }
+            }
+            $send_to['groups'] = $grouplist;
+            $send_to['users'] = $userlist;
+        }
+        return $send_to;
+    }
+
+    static function show_form($params = array())
+    {
+        $form = new FormValidator('add_event', 'POST', api_get_self().'?'.api_get_cidreq(), null, array('enctype' => 'multipart/form-data'));
+        $id = isset($params['id']) ? $params['id'] : null;
+
+        if ($id) {
+            $form_title = get_lang('ModifyCalendarItem');
+            $button = get_lang('ModifyEvent');
+        } else {
+            $form_title = get_lang('AddCalendarItem');
+            $button = get_lang('AgendaAdd');
+        }
+
+        $form->addElement('header', $form_title);
+        $form->addElement('hidden', 'id', $id);
+        $form->addElement('hidden', 'action', $params['action']);
+        $form->addElement('hidden', 'id_attach', $params['id_attach']);
+
+        $form->addElement('text', 'title', get_lang('ItemTitle'));
+
+        $group_id = api_get_group_id();
+
+        if (isset($group_id) && !empty($group_id)) {
+            $form->addElement('hidden', 'selected_form[0]', "GROUP:'.$group_id.'");
+            $form->addElement('hidden', 'to', 'true');
+        } else {
+            self::show_to_form($form, $to);
+        }
+
+        $form->addElement('text', 'start_date', get_lang('StartDate'));
+        $form->addElement('text', 'end_date', get_lang('EndDate'));
+
+        if (empty($id)) {
+            $form->addElement('advanced_settings', '<a href="javascript://" onclick="return plus_repeated_event();"><span id="plus2">
+                                   <img style="vertical-align:middle;" src="../img/div_show.gif" alt="" />&nbsp;'.get_lang('RepeatEvent').'</span>
+                                </a>');
+            $form->addElement('html', '<div style="display:block">');
+
+            $form->addElement('checkbox', 'repeat', null, get_lang('RepeatEvent'));
+
+            $repeat_events = array(
+                'daily' => get_lang('RepeatDaily'),
+                'weekly' => get_lang('RepeatWeekly'),
+                'monthlyByDate' => get_lang('RepeatMonthlyByDate'),
+                'yearly' => get_lang('RepeatYearly')
+            );
+
+            $form->addElement('select', 'repeat_type', get_lang('RepeatType'), $repeat_events);
+            $form->addElement('text', 'repeat_end_day', get_lang('RepeatEnd'));
+            $form->addElement('html', '</div>');
+
+            if (!api_is_allowed_to_edit(null, true)) {
+                $toolbar = 'AgendaStudent';
+            } else {
+                $toolbar = 'Agenda';
+            }
+            //$form->addElement('html_editor', 'content', get_lang('Description'), null, array('ToolbarSet' => $toolbar, 'Width' => '100%', 'Height' => '200'));
+
+            $form->addElement('file', 'user_upload', get_lang('AddAnAttachment'));
+            $form->addElement('text', 'file_comment', get_lang('Comment'));
+        }
+
+        $form->addElement('button', 'submit', $button);
+        $form->display();
+    }
+
+    static function show_to_form($form, $to_already_selected)
+    {
+        $order = 'lastname';
+        if (api_is_western_name_order()) {
+            $order = 'firstname';
+        }
+        $user_list = CourseManager::get_user_list_from_course_code(api_get_course_id(), api_get_session_id(), null, $order);
+        $group_list = CourseManager::get_group_list_of_course(api_get_course_id(), api_get_session_id());
+
+        self::construct_not_selected_select_form_validator($form, $group_list, $user_list, $to_already_selected);
+    }
+}

+ 2 - 1
main/course_home/activity.php

@@ -54,7 +54,8 @@ if (api_is_platform_admin()) {
 //	COURSE ADMIN ONLY VIEW
 
 // Start of tools for CourseAdmins (teachers/tutors)
-if (api_is_allowed_to_edit(null, true) && !api_is_coach()) {
+
+if ($session_id == 0 && api_is_course_admin() && api_is_allowed_to_edit(null, true)) {
 	$content .=  '<div class="courseadminview" style="border:0px; margin-top: 0px;padding:0px;">
 		<div class="normal-message" id="id_normal_message" style="display:none">';
 			$content .=  '<img src="'.api_get_path(WEB_PATH).'main/inc/lib/javascript/indicator.gif"/>&nbsp;&nbsp;';

+ 3 - 1
main/course_info/infocours.php

@@ -136,7 +136,7 @@ $form->addElement('html', $image_html);
 
 
 $form->add_textfield('title', get_lang('Title'), true, array('class' => 'span6'));
-//$form->applyFilter('title', 'html_filter');
+$form->applyFilter('title', 'html_filter');
 $form->applyFilter('title', 'trim');
 
 //$form->add_textfield('tutor_name', get_lang('Professors'), true, array ('size' => '60'));
@@ -156,9 +156,11 @@ $form->addElement('select', 'category_code', get_lang('Fac'), $categories, array
 $form->addElement('select_language', 'course_language', array(get_lang('Ln'), get_lang('TipLang')));
 
 $form->add_textfield('department_name', get_lang('Department'), false, array('class' => 'span5'));
+$form->applyFilter('department_name', 'html_filter');
 $form->applyFilter('department_name', 'trim');
 
 $form->add_textfield('department_url', get_lang('DepartmentUrl'), false, array('class' => 'span5'));
+$form->applyFilter('department_url', 'html_filter');
 //$form->addRule('tutor_name', get_lang('ThisFieldIsRequired'), 'required');
 
 // Picture

+ 50 - 50
main/coursecopy/classes/Announcement.class.php

@@ -10,65 +10,65 @@ require_once 'Resource.class.php';
  */
 class Announcement extends Resource
 {
-    /**
-     * The title of the announcement
-     */
+	/**
+	 * The title of the announcement
+	 */
     public $title;
-    /**
-     * The content of the announcement
-     */
+	/**
+	 * The content of the announcement
+	 */
     public $content;
-    /**
-     * The date on which this announcement was made
-     */
+	/**
+	 * The date on which this announcement was made
+	 */
     public $date;
-    /**
-     * The display order of this announcement
-     */
+	/**
+	 * The display order of this announcement
+	 */
     public $display_order;
-    /**
-     * Has the e-mail been sent?
-     */
+	/**
+	 * Has the e-mail been sent?
+	 */
     public $email_sent;
-
+	
     public $attachment_path;
-
+	
     public $attachment_filename;
-
+	
     public $attachment_size;
-
+	
     public $attachment_comment;
-
-    /**
-     * Create a new announcement
-     * @param int $id
-     * @param string $title
-     * @param string $content
-     * @param string $date
-     * @param int display_order
-     */
+	
+	/**
+	 * Create a new announcement
+	 * @param int $id
+	 * @param string $title
+	 * @param string $content
+	 * @param string $date
+	 * @param int display_order
+	 */
     function Announcement($id, $title, $content, $date, $display_order, $email_sent, $path, $filename, $size, $comment)
     {
-        parent::Resource($id, RESOURCE_ANNOUNCEMENT);
-
-        $this->content       = $content;
-        $this->title         = $title;
-        $this->date          = $date;
-        $this->display_order = $display_order;
-        $this->email_sent    = $email_sent;
-
-        $this->attachment_path     = $path;
-        $this->attachment_filename = $filename;
-        $this->attachment_size     = $size;
-        $this->attachment_comment  = $comment;
-    }
-
-    /**
-     * Show this announcement
-     */
-    function show()
-    {
-        parent::show();
-        echo $this->date.': '.$this->title;
-    }
+		parent::Resource($id,RESOURCE_ANNOUNCEMENT);
+		
+		$this->content	= $content;
+		$this->title 	= $title;
+		$this->date 	= $date;
+		$this->display_order	= $display_order;
+		$this->email_sent	 	= $email_sent;		
+		
+		$this->attachment_path 	= $path;
+		$this->attachment_filename = $filename;
+		$this->attachment_size 	= $size;
+		$this->attachment_comment 	= $comment;		
+	}
+	
+	/**
+	 * Show this announcement
+	 */
+	function show()
+	{
+		parent::show();
+		echo $this->date.': '.$this->title;
+	}
 }

+ 18 - 17
main/coursecopy/classes/Attendance.class.php

@@ -8,29 +8,30 @@ require_once 'Resource.class.php';
 
 class CourseCopyAttendance extends Resource
 {
-
+		
     public $params = array();
     public $attendance_calendar = array();
-
-    /**
-     * Create a new Thematic
-     *
-     * @param array parameters
-     */
+	
+	
+	/**
+	 * Create a new Thematic
+	 * 
+	 * @param array parameters	
+	 */
     public function __construct($params)
     {
-        parent::Resource($params['id'], RESOURCE_ATTENDANCE);
-        $this->params = $params;
-    }
+		parent::Resource($params['id'], RESOURCE_ATTENDANCE);
+		$this->params = $params;
+	}
 
     public function show()
     {
-        parent::show();
-        echo $this->params['name'];
-    }
-
+		parent::show();
+		echo $this->params['name'];
+	}
+	
     public function add_attendance_calendar($data)
     {
-        $this->attendance_calendar[] = $data;
-    }
-}
+		$this->attendance_calendar[] = $data;
+	}	
+}

+ 299 - 297
main/coursecopy/classes/Course.class.php

@@ -19,345 +19,347 @@ class Course
     public $destination_db;
     public $encoding;
 
-    /**
-     * Create a new Course-object
-     */
+	/**
+	 * Create a new Course-object
+	 */
     function __construct()
     {
-        $this->resources   = array();
-        $this->code        = '';
-        $this->path        = '';
-        $this->backup_path = '';
-        $this->encoding    = api_get_system_encoding();
-    }
+		$this->resources    = array();
+		$this->code         = '';
+		$this->path         = '';
+		$this->backup_path  = '';
+		$this->encoding     = api_get_system_encoding();
+	}
 
-    /**
-     * Check if a resource links to the given resource
-     */
+	/**
+	 * Check if a resource links to the given resource
+	 */
     function is_linked_resource(& $resource_to_check)
     {
-        foreach ($this->resources as $type => $resources) {
-            if (is_array($resources)) {
-                foreach ($resources as $id => $resource) {
-                    if ($resource->links_to($resource_to_check)) {
-
-                        return true;
-                    }
-                    if ($type == RESOURCE_LEARNPATH && get_class($resource) == 'CourseCopyLearnpath') {
-                        if ($resource->has_item($resource_to_check)) {
-
-                            return true;
-                        }
-                    }
-                }
-            }
-        }
+		foreach($this->resources as $type => $resources) {
+			if (is_array($resources)) {
+				foreach($resources as $id => $resource) {
+					if( $resource->links_to($resource_to_check) ) {
+						return true;
+					}
+					if ($type == RESOURCE_LEARNPATH && get_class($resource)=='CourseCopyLearnpath') {
+						if($resource->has_item($resource_to_check)) {
+							return true;
+						}
+					}
+				}
+			}
+		}
+		return false;
+	}
 
-        return false;
-    }
-
-    /**
-     * Add a resource from a given type to this course
-     */
+	/**
+	 * Add a resource from a given type to this course
+	 */
     function add_resource(& $resource)
     {
-        $this->resources[$resource->get_type()][$resource->get_id()] = $resource;
-    }
+		$this->resources[$resource->get_type()][$resource->get_id()] = $resource;
+	}
 
-    /**
-     * Does this course has resources?
-     * @param const $resource_type Check if this course has resources of the
-     * given type. If no type is given, check if course has resources of any
-     * type.
-     */
+	/**
+	 * Does this course has resources?
+	 * @param const $resource_type Check if this course has resources of the
+	 * given type. If no type is given, check if course has resources of any
+	 * type.
+	 */
     function has_resources($resource_type = null)
     {
-        if ($resource_type != null) {
+		if( $resource_type != null) {
             return isset($this->resources[$resource_type]) && is_array($this->resources[$resource_type]) && (count(
                     $this->resources[$resource_type]
                 ) > 0);
-        }
-
-        return (count($this->resources) > 0);
-    }
-
-    /**
-     * Show this course resources
-     */
+		}
+		return (count($this->resources) > 0);
+	}
+	/**
+	 * Show this course resources
+	 */
     function show()
     { /*
 		echo '<pre>';
 		print_r($this);
 		echo '</pre>';*/
-    }
+	}
 
-    /**
-     * Returns sample text based on the imported course content.
-     * This sample text is to be used for course language or encoding detection if there is missing (meta)data in the archive.
-     * @return string    The resulting sample text extracted from some common resources' data fields.
-     */
+	/**
+	 * Returns sample text based on the imported course content.
+	 * This sample text is to be used for course language or encoding detection if there is missing (meta)data in the archive.
+	 * @return string	The resulting sample text extracted from some common resources' data fields.
+	 */
     public function get_sample_text()
     {
 
-        $sample_text = '';
-        foreach ($this->resources as $type => & $resources) {
-            if (count($resources) > 0) {
-                foreach ($resources as $id => & $resource) {
-                    $title       = '';
-                    $description = '';
-
-                    switch ($type) {
-                        case RESOURCE_ANNOUNCEMENT:
-                            $title       = $resource->title;
-                            $description = $resource->content;
-                            break;
-                        case RESOURCE_DOCUMENT:
-                            $title       = $resource->title;
-                            $description = $resource->comment;
-                            break;
-                        case RESOURCE_EVENT:
-                            $title       = $resource->title;
-                            $description = $resource->content;
-                            break;
-                        case RESOURCE_FORUM:
-                            $title       = $resource->title;
-                            $description = $resource->description;
-                            break;
-                        case RESOURCE_FORUMCATEGORY:
-                            $title       = $resource->title;
-                            $description = $resource->description;
-                            break;
-                        case RESOURCE_FORUMPOST:
-                            $title       = $resource->title;
-                            $description = $resource->text;
-                            break;
-                        case RESOURCE_FORUMTOPIC:
+		$sample_text = '';
+		foreach ($this->resources as $type => & $resources) {
+			if (count($resources) > 0) {
+				foreach ($resources as $id => & $resource) {
+					$title = '';
+					$description = '';
+
+					switch ($type) {
+						case RESOURCE_ANNOUNCEMENT:
+							$title = $resource->title;
+							$description = $resource->content;
+							break;
+						case RESOURCE_DOCUMENT:
+							$title = $resource->title;
+							$description = $resource->comment;
+							break;
+						case RESOURCE_EVENT:
+							$title = $resource->title;
+							$description = $resource->content;
+							break;
+						case RESOURCE_FORUM:
+							$title = $resource->title;
+							$description = $resource->description;
+							break;
+
+						case RESOURCE_FORUMCATEGORY:
+							$title = $resource->title;
+							$description = $resource->description;
+							break;
+						case RESOURCE_FORUMPOST:
+							$title = $resource->title;
+							$description = $resource->text;
+							break;
+						case RESOURCE_FORUMTOPIC:
+							$title = $resource->title;
+							break;
+						case RESOURCE_GLOSSARY:
+							$title = $resource->name;
+							$description = $resource->description;
+							break;
+						case RESOURCE_LEARNPATH:
+							$title = $resource->name;
+							$description = $resource->description;
+							break;
+						case RESOURCE_LINK:
+							$title = $resource->title;
+							$description = $resource->description;
+							break;
+						case RESOURCE_LINKCATEGORY:
+							$title = $resource->title;
+							$description = $resource->description;
+							break;
+						case RESOURCE_QUIZ:
+							$title = $resource->title;
+							$description = $resource->description;
+							break;
+						case RESOURCE_QUIZQUESTION:
+							$title = $resource->question;
+							$description = $resource->description;
+							break;
+						case RESOURCE_SCORM:
+							$title = $resource->title;
+							break;
+						case RESOURCE_SURVEY:
+							$title = $resource->title;
+							$description = $resource->subtitle;
+							break;
+						case RESOURCE_SURVEYQUESTION:
+							$title = $resource->survey_question;
+							$description = $resource->survey_question_comment;
+							break;
+						case RESOURCE_TOOL_INTRO:
+							$description = $resource->intro_text;
+							break;
+						case RESOURCE_WIKI:
+							$title = $resource->title;
+							$description = $resource->content;
+							break;
+						case RESOURCE_THEMATIC:
+							$title 			= $resource->title;
+							$description 	= $resource->content;
+							break;
+						case RESOURCE_ATTENDANCE:
+							$title 			= $resource->params['name'];
+							$description 	= $resource->params['description'];
+							break;
+                        case RESOURCE_WORK:
                             $title = $resource->title;
-                            break;
-                        case RESOURCE_GLOSSARY:
-                            $title       = $resource->name;
-                            $description = $resource->description;
-                            break;
-                        case RESOURCE_LEARNPATH:
-                            $title       = $resource->name;
                             $description = $resource->description;
-                            break;
-                        case RESOURCE_LINK:
-                            $title       = $resource->title;
-                            $description = $resource->description;
-                            break;
-                        case RESOURCE_LINKCATEGORY:
-                            $title       = $resource->title;
-                            $description = $resource->description;
-                            break;
-                        case RESOURCE_QUIZ:
-                            $title       = $resource->title;
-                            $description = $resource->description;
-                            break;
-                        case RESOURCE_QUIZQUESTION:
-                            $title       = $resource->question;
-                            $description = $resource->description;
-                            break;
-                        case RESOURCE_SCORM:
-                            $title = $resource->title;
-                            break;
-                        case RESOURCE_SURVEY:
-                            $title       = $resource->title;
-                            $description = $resource->subtitle;
-                            break;
-                        case RESOURCE_SURVEYQUESTION:
-                            $title       = $resource->survey_question;
-                            $description = $resource->survey_question_comment;
-                            break;
-                        case RESOURCE_TOOL_INTRO:
-                            $description = $resource->intro_text;
-                            break;
-                        case RESOURCE_WIKI:
-                            $title       = $resource->title;
-                            $description = $resource->content;
-                            break;
-                        case RESOURCE_THEMATIC:
-                            $title       = $resource->title;
-                            $description = $resource->content;
-                            break;
-                        case RESOURCE_ATTENDANCE:
-                            $title       = $resource->params['name'];
-                            $description = $resource->params['description'];
-                            break;
-                        default:
-                            break;
-                    }
+							break;
+						default:
+							break;
+					}
 
                     $title       = Text::api_html_to_text($title);
                     $description = Text::api_html_to_text($description);
 
-                    if (!empty($title)) {
-                        $sample_text .= $title."\n";
-                    }
-                    if (!empty($description)) {
-                        $sample_text .= $description."\n";
-                    }
-                    if (!empty($title) || !empty($description)) {
-                        $sample_text .= "\n";
-                    }
-                }
-            }
-        }
-
-        return $sample_text;
-    }
+					if (!empty($title)) {
+						$sample_text .= $title."\n";
+					}
+					if (!empty($description)) {
+						$sample_text .= $description."\n";
+					}
+					if (!empty($title) || !empty($description)) {
+						$sample_text .= "\n";
+					}
+				}
+			}
+		}
+		return $sample_text;
+	}
 
-    /**
-     * Converts to the system encoding all the language-sensitive fields in the imported course.
-     */
+	/**
+	 * Converts to the system encoding all the language-sensitive fields in the imported course.
+	 */
     public function to_system_encoding()
     {
 
-        if (api_equal_encodings($this->encoding, api_get_system_encoding())) {
-            return;
-        }
+		if (api_equal_encodings($this->encoding, api_get_system_encoding())) {
+			return;
+		}
 
-        foreach ($this->resources as $type => & $resources) {
-            if (count($resources) > 0) {
-                foreach ($resources as $id => & $resource) {
+		foreach ($this->resources as $type => & $resources) {
+			if (count($resources) > 0) {
+				foreach ($resources as $id => & $resource) {
 
-                    switch ($type) {
-                        case RESOURCE_ANNOUNCEMENT:
-                            $resource->title   = api_to_system_encoding($resource->title, $this->encoding);
-                            $resource->content = api_to_system_encoding($resource->content, $this->encoding);
-                            break;
-                        case RESOURCE_DOCUMENT:
-                            $resource->title   = api_to_system_encoding($resource->title, $this->encoding);
-                            $resource->comment = api_to_system_encoding($resource->comment, $this->encoding);
-                            break;
-                        case RESOURCE_EVENT:
-                            $resource->title   = api_to_system_encoding($resource->title, $this->encoding);
-                            $resource->content = api_to_system_encoding($resource->content, $this->encoding);
-                            break;
-                        case RESOURCE_FORUM:
-                            $resource->title       = api_to_system_encoding($resource->title, $this->encoding);
-                            $resource->description = api_to_system_encoding($resource->description, $this->encoding);
-                            break;
-                        case RESOURCE_FORUMCATEGORY:
-                            $resource->title       = api_to_system_encoding($resource->title, $this->encoding);
-                            $resource->description = api_to_system_encoding($resource->description, $this->encoding);
-                            break;
-                        case RESOURCE_FORUMPOST:
-                            $resource->title       = api_to_system_encoding($resource->title, $this->encoding);
-                            $resource->text        = api_to_system_encoding($resource->text, $this->encoding);
-                            $resource->poster_name = api_to_system_encoding($resource->poster_name, $this->encoding);
-                            break;
-                        case RESOURCE_FORUMTOPIC:
-                            $resource->title             = api_to_system_encoding($resource->title, $this->encoding);
-                            $resource->topic_poster_name = api_to_system_encoding(
-                                $resource->topic_poster_name,
-                                $this->encoding
-                            );
-                            $resource->title_qualify     = api_to_system_encoding(
-                                $resource->title_qualify,
-                                $this->encoding
-                            );
-                            break;
-                        case RESOURCE_GLOSSARY:
-                            $resource->name        = api_to_system_encoding($resource->name, $this->encoding);
-                            $resource->description = api_to_system_encoding($resource->description, $this->encoding);
-                            break;
-                        case RESOURCE_LEARNPATH:
-                            $resource->name            = api_to_system_encoding($resource->name, $this->encoding);
-                            $resource->description     = api_to_system_encoding(
-                                $resource->description,
-                                $this->encoding
-                            );
-                            $resource->content_maker   = api_to_system_encoding(
-                                $resource->content_maker,
-                                $this->encoding
-                            );
-                            $resource->content_license = api_to_system_encoding(
-                                $resource->content_license,
-                                $this->encoding
-                            );
-                            //$resource->author = api_to_system_encoding($resource->author, $this->encoding);  // Needs implamantation.
-                            break;
-                        case RESOURCE_LINK:
-                            $resource->title       = api_to_system_encoding($resource->title, $this->encoding);
-                            $resource->description = api_to_system_encoding($resource->description, $this->encoding);
-                            break;
-                        case RESOURCE_LINKCATEGORY:
-                            $resource->title       = api_to_system_encoding($resource->title, $this->encoding);
-                            $resource->description = api_to_system_encoding($resource->description, $this->encoding);
-                            break;
-                        case RESOURCE_QUIZ:
-                            $resource->title       = api_to_system_encoding($resource->title, $this->encoding);
-                            $resource->description = api_to_system_encoding($resource->description, $this->encoding);
-                            break;
-                        case RESOURCE_QUIZQUESTION:
-                            $resource->question    = api_to_system_encoding($resource->question, $this->encoding);
-                            $resource->description = api_to_system_encoding($resource->description, $this->encoding);
-                            if (is_array($resource->answers) && count($resource->answers) > 0) {
-                                foreach ($resource->answers as $index => & $answer) {
-                                    $answer['answer']  = api_to_system_encoding($answer['answer'], $this->encoding);
-                                    $answer['comment'] = api_to_system_encoding($answer['comment'], $this->encoding);
-                                }
-                            }
-                            break;
-                        case RESOURCE_SCORM:
+					switch ($type) {
+
+						case RESOURCE_ANNOUNCEMENT:
+							$resource->title = api_to_system_encoding($resource->title, $this->encoding);
+							$resource->content = api_to_system_encoding($resource->content, $this->encoding);
+							break;
+
+						case RESOURCE_DOCUMENT:
+							$resource->title = api_to_system_encoding($resource->title, $this->encoding);
+							$resource->comment = api_to_system_encoding($resource->comment, $this->encoding);
+							break;
+
+						case RESOURCE_EVENT:
+							$resource->title = api_to_system_encoding($resource->title, $this->encoding);
+							$resource->content = api_to_system_encoding($resource->content, $this->encoding);
+							break;
+
+						case RESOURCE_FORUM:
+							$resource->title = api_to_system_encoding($resource->title, $this->encoding);
+							$resource->description = api_to_system_encoding($resource->description, $this->encoding);
+							break;
+
+						case RESOURCE_FORUMCATEGORY:
+							$resource->title = api_to_system_encoding($resource->title, $this->encoding);
+							$resource->description = api_to_system_encoding($resource->description, $this->encoding);
+							break;
+
+						case RESOURCE_FORUMPOST:
+							$resource->title = api_to_system_encoding($resource->title, $this->encoding);
+							$resource->text = api_to_system_encoding($resource->text, $this->encoding);
+							$resource->poster_name = api_to_system_encoding($resource->poster_name, $this->encoding);
+							break;
+
+						case RESOURCE_FORUMTOPIC:
+							$resource->title = api_to_system_encoding($resource->title, $this->encoding);
+							$resource->topic_poster_name = api_to_system_encoding($resource->topic_poster_name, $this->encoding);
+							$resource->title_qualify = api_to_system_encoding($resource->title_qualify, $this->encoding);
+							break;
+
+						case RESOURCE_GLOSSARY:
+							$resource->name = api_to_system_encoding($resource->name, $this->encoding);
+							$resource->description = api_to_system_encoding($resource->description, $this->encoding);
+							break;
+
+						case RESOURCE_LEARNPATH:
+							$resource->name = api_to_system_encoding($resource->name, $this->encoding);
+							$resource->description = api_to_system_encoding($resource->description, $this->encoding);
+							$resource->content_maker = api_to_system_encoding($resource->content_maker, $this->encoding);
+							$resource->content_license = api_to_system_encoding($resource->content_license, $this->encoding);
+							//$resource->author = api_to_system_encoding($resource->author, $this->encoding);  // Needs implamantation.
+							break;
+
+						case RESOURCE_LINK:
+							$resource->title = api_to_system_encoding($resource->title, $this->encoding);
+							$resource->description = api_to_system_encoding($resource->description, $this->encoding);
+							break;
+
+						case RESOURCE_LINKCATEGORY:
+							$resource->title = api_to_system_encoding($resource->title, $this->encoding);
+							$resource->description = api_to_system_encoding($resource->description, $this->encoding);
+							break;
+
+						case RESOURCE_QUIZ:
+							$resource->title = api_to_system_encoding($resource->title, $this->encoding);
+							$resource->description = api_to_system_encoding($resource->description, $this->encoding);
+							break;
+
+						case RESOURCE_QUIZQUESTION:
+							$resource->question = api_to_system_encoding($resource->question, $this->encoding);
+							$resource->description = api_to_system_encoding($resource->description, $this->encoding);
+							if (is_array($resource->answers) && count($resource->answers) > 0) {
+								foreach ($resource->answers as $index => & $answer) {
+									$answer['answer'] = api_to_system_encoding($answer['answer'], $this->encoding);
+									$answer['comment'] = api_to_system_encoding($answer['comment'], $this->encoding);
+								}
+							}
+							break;
+
+						case RESOURCE_SCORM:
+							$resource->title = api_to_system_encoding($resource->title, $this->encoding);
+							break;
+
+						case RESOURCE_SURVEY:
+							$resource->title = api_to_system_encoding($resource->title, $this->encoding);
+							$resource->subtitle = api_to_system_encoding($resource->subtitle, $this->encoding);
+							$resource->author = api_to_system_encoding($resource->author, $this->encoding);
+							$resource->intro = api_to_system_encoding($resource->intro, $this->encoding);
+							$resource->surveythanks = api_to_system_encoding($resource->surveythanks, $this->encoding);
+							break;
+
+						case RESOURCE_SURVEYQUESTION:
+							$resource->survey_question = api_to_system_encoding($resource->survey_question, $this->encoding);
+							$resource->survey_question_comment = api_to_system_encoding($resource->survey_question_comment, $this->encoding);
+							break;
+
+						case RESOURCE_TOOL_INTRO:
+							$resource->intro_text = api_to_system_encoding($resource->intro_text, $this->encoding);
+							break;
+
+						case RESOURCE_WIKI:
+							$resource->title = api_to_system_encoding($resource->title, $this->encoding);
+							$resource->content = api_to_system_encoding($resource->content, $this->encoding);
+							$resource->reflink = api_to_system_encoding($resource->reflink, $this->encoding);
+							break;
+
+                        case RESOURCE_WORK:
+                            $resource->url = api_to_system_encoding($resource->url, $this->encoding);
                             $resource->title = api_to_system_encoding($resource->title, $this->encoding);
+                            $resource->description = api_to_system_encoding($resource->description, $this->encoding);
                             break;
-                        case RESOURCE_SURVEY:
-                            $resource->title        = api_to_system_encoding($resource->title, $this->encoding);
-                            $resource->subtitle     = api_to_system_encoding($resource->subtitle, $this->encoding);
-                            $resource->author       = api_to_system_encoding($resource->author, $this->encoding);
-                            $resource->intro        = api_to_system_encoding($resource->intro, $this->encoding);
-                            $resource->surveythanks = api_to_system_encoding($resource->surveythanks, $this->encoding);
-                            break;
-                        case RESOURCE_SURVEYQUESTION:
-                            $resource->survey_question         = api_to_system_encoding(
-                                $resource->survey_question,
-                                $this->encoding
-                            );
-                            $resource->survey_question_comment = api_to_system_encoding(
-                                $resource->survey_question_comment,
-                                $this->encoding
-                            );
-                            break;
-                        case RESOURCE_TOOL_INTRO:
-                            $resource->intro_text = api_to_system_encoding($resource->intro_text, $this->encoding);
-                            break;
-                        case RESOURCE_WIKI:
-                            $resource->title   = api_to_system_encoding($resource->title, $this->encoding);
-                            $resource->content = api_to_system_encoding($resource->content, $this->encoding);
-                            $resource->reflink = api_to_system_encoding($resource->reflink, $this->encoding);
-                            break;
-                        default:
-                            break;
-                    }
-                }
-            }
-        }
-        $this->encoding = api_get_system_encoding();
-    }
+						default:
+							break;
+					}
+				}
+			}
+		}
+		$this->encoding = api_get_system_encoding();
+	}
 
     /**
-     * Serialize the course with the best serializer available
-     */
+	* Serialize the course with the best serializer available
+	*/
     public static function serialize($course)
     {
-        if (extension_loaded('igbinary')) {
-            return igbinary_serialize($course);
-        } else {
-            return serialize($course);
+		if (extension_loaded('igbinary')) {
+			return igbinary_serialize($course);
+		} else {
+			return serialize($course);
         }
-    }
+	}
 
-    /**
-     * Unserialize the course with the best serializer available
-     */
+	/**
+	* Unserialize the course with the best serializer available
+	*/
     public static function unserialize($course)
     {
-        if (extension_loaded('igbinary')) {
-            return igbinary_unserialize($course);
-        } else {
-            return unserialize($course);
-        }
-    }
-}
+		if (extension_loaded('igbinary')) {
+			return igbinary_unserialize($course);
+		} else {
+			return unserialize($course);
+		}
+	}
+}

+ 19 - 13
main/coursecopy/classes/CourseArchiver.class.php

@@ -41,11 +41,11 @@ class CourseArchiver
         CourseArchiver::clean_backup_dir();
 
         // Create a temp directory
-        $tmp_dir_name = 'CourseArchiver_'.api_get_unique_id();
-        $backup_dir = api_get_path(SYS_ARCHIVE_PATH).$tmp_dir_name . '/';
+        $tmp_dir_name = 'CourseArchiver_' . api_get_unique_id();
+        $backup_dir = api_get_path(SYS_ARCHIVE_PATH) . $tmp_dir_name . '/';
 
         // All course-information will be stored in course_info.dat
-        $course_info_file = $backup_dir.'course_info.dat';
+        $course_info_file = $backup_dir . 'course_info.dat';
         $zip_dir = api_get_path(SYS_ARCHIVE_PATH);
         $user = api_get_user_info();
         $date = new DateTime(api_get_local_time());
@@ -71,8 +71,9 @@ class CourseArchiver
         if ($res === false) {
             error_log(__FILE__ . ' line ' . __LINE__ . ': ' . (ini_get('track_errors') != false ? $php_errormsg : 'error not recorded because track_errors is off in your php.ini'), 0);
         }
-
-        // Copy all documents to the temp-dir
+        
+        
+        // Copy all documents to the temp-dir        
         if (isset($course->resources[RESOURCE_DOCUMENT]) && is_array($course->resources[RESOURCE_DOCUMENT])) {
             foreach ($course->resources[RESOURCE_DOCUMENT] as $document) {
                 if ($document->file_type == DOCUMENT) {
@@ -101,7 +102,7 @@ class CourseArchiver
         if (isset($course->resources[RESOURCE_EVENT]) && is_array($course->resources[RESOURCE_EVENT])) {
             $doc_dir = dirname($backup_dir . '/upload/calendar/');
             @mkdir($doc_dir, $perm_dirs, true);
-            FileManager::copyDirTo($course->path . 'upload/calendar/', $doc_dir, false);
+            copyDirTo($course->path . 'upload/calendar/', $doc_dir, false);
         }
 
         // Copy Learning path author image.
@@ -119,6 +120,14 @@ class CourseArchiver
             FileManager::copyDirTo($course->path . 'upload/announcements/', $doc_dir, false);
         }
 
+        // Copy work folders (only folders)
+        if (isset($course->resources[RESOURCE_WORK]) && is_array($course->resources[RESOURCE_WORK])) {
+            $doc_dir = dirname($backup_dir . '/upload/work/');
+            @mkdir($doc_dir, $perm_dirs, true);
+            // @todo: adjust to only create subdirs, but not copy files
+            FileManager::copyDirTo($course->path . 'upload/work/', $doc_dir, false);
+        }
+
         // Zip the course-contents
         $zip = new PclZip($zip_dir . $zip_file);
         $zip->create($zip_dir . $tmp_dir_name, PCLZIP_OPT_REMOVE_PATH, $zip_dir . $tmp_dir_name . '/');
@@ -173,8 +182,7 @@ class CourseArchiver
      * @param boolean $delete Delete the file after reading the course?
      * @todo Check if the archive is a correct Chamilo-export
      */
-    static function read_course($filename, $delete = false)
-    {
+    static function read_course($filename, $delete = false) {
         CourseArchiver::clean_backup_dir();
         // Create a temp directory
         $tmp_dir_name = 'CourseArchiver_' . uniqid('');
@@ -182,8 +190,7 @@ class CourseArchiver
         mkdir($unzip_dir, api_get_permissions_for_new_directories(), true);
         copy(api_get_path(SYS_ARCHIVE_PATH).$filename, $unzip_dir.'/backup.zip');
         // unzip the archive
-
-        $zip = new PclZip($unzip_dir.'/backup.zip');
+        $zip = new PclZip($unzip_dir . '/backup.zip');
         chdir($unzip_dir);
         $list = $zip->extract(PCLZIP_OPT_TEMP_FILE_ON);
 
@@ -192,19 +199,17 @@ class CourseArchiver
             $errorMessage = $zip->errorInfo(true);
             $app['session']->getFlashBag()->add('warning', $errorMessage);*/
         }
-
         // remove the archive-file
         if ($delete) {
             if (file_exists(api_get_path(SYS_ARCHIVE_PATH).$filename)) {
                 unlink(api_get_path(SYS_ARCHIVE_PATH).$filename);
-            }
+        }
         }
 
         // Read the course
         if (!is_file('course_info.dat')) {
             return new Course();
         }
-
         $contents = file_get_contents('course_info.dat');
         // CourseCopyLearnpath class appeared in Chamilo 1.8.7, it is the former Learnpath class in the "Copy course" tool.
         // For backward comaptibility with archives created on Chamilo 1.8.6.2 or older systems, we have to do the following:
@@ -216,4 +221,5 @@ class CourseArchiver
         $course->backup_path = $unzip_dir;
         return $course;
     }
+
 }

Файлын зөрүү хэтэрхий том тул дарагдсан байна
+ 619 - 659
main/coursecopy/classes/CourseBuilder.class.php


+ 36 - 21
main/coursecopy/classes/CourseRecycler.class.php

@@ -56,6 +56,7 @@ class CourseRecycler
         $this->recycle_glossary();
         $this->recycle_thematic();
         $this->recycle_attendance();
+        $this->recycle_work();
 
         foreach ($this->course->resources as $type => $resources) {
             foreach ($resources as $id => $resource) {
@@ -311,7 +312,7 @@ class CourseRecycler
             $table_qui 	   = Database :: get_course_table(TABLE_QUIZ_TEST);
             $table_rel 	   = Database :: get_course_table(TABLE_QUIZ_TEST_QUESTION);
             $table_qui_que_opt = Database :: get_course_table(TABLE_QUIZ_QUESTION_OPTION);
-            $table_qui_que_cat = Database :: get_course_table(TABLE_QUIZ_CATEGORY);
+            $table_qui_que_cat = Database :: get_course_table(TABLE_QUIZ_QUESTION_CATEGORY);
             $table_qui_que_rel_cat = Database :: get_course_table(TABLE_QUIZ_QUESTION_REL_CATEGORY);
 
             $ids = array_keys($this->course->resources[RESOURCE_QUIZ]);
@@ -321,7 +322,7 @@ class CourseRecycler
             // This value is set in CourseBuilder::quiz_build_questions()
             $delete_orphan_questions = in_array(-1, $ids);
             $ids = implode(',', $ids);
-
+            
             if (!empty($ids)) {
                 // Deletion of the tests first. Questions in these tests are
                 //   not deleted and become orphan at this point
@@ -333,21 +334,7 @@ class CourseRecycler
 
             // Identifying again and deletion of the orphan questions, if it was desired.
             if ($delete_orphan_questions) {
-
-                /*$sql = 'SELECT questions.id '.
-                       ' FROM '.$table_qui_que.' as questions '.
-                       ' LEFT JOIN '.$table_rel.' as quizz_questions '.
-                       '   ON questions.id=quizz_questions.question_id '.
-                       ' LEFT JOIN '.$table_qui.' as exercices '.
-                       '   ON exercice_id=exercices.id '.
-                       ' WHERE '.
-                       '   questions.c_id = '.$this->course_id.' AND '.
-                       '   quizz_questions.c_id = '.$this->course_id.' AND '.
-                       '   exercices.c_id = '.$this->course_id.' AND '.
-                       '   quizz_questions.exercice_id IS NULL OR '.
-                       '   exercices.active = -1';
-                       // active = -1 means "deleted" test.
-                */
+               
 
                 //@todo fix query in order to use iid
                 $sql = " (
@@ -372,7 +359,6 @@ class CourseRecycler
                     ON (q.c_id = r.c_id AND q.iid = r.question_id)
                     WHERE r.c_id = ".$this->course_id." AND (r.exercice_id = '-1' OR r.exercice_id = '0')
                 )";
-
                 $db_result = Database::query($sql);
                 if (Database::num_rows($db_result) > 0) {
                     $orphan_ids = array();
@@ -405,7 +391,8 @@ class CourseRecycler
     /**
      * Recycle surveys - removes everything
      */
-    function recycle_surveys() {
+    function recycle_surveys() 
+    {
         if ($this->course->has_resources(RESOURCE_SURVEY)) {
             $table_survey = Database :: get_course_table(TABLE_SURVEY);
             $table_survey_q = Database :: get_course_table(TABLE_SURVEY_QUESTION);
@@ -428,7 +415,8 @@ class CourseRecycler
     /**
      * Recycle learnpaths
      */
-    function recycle_learnpaths() {
+    function recycle_learnpaths() 
+    {
         if ($this->course->has_resources(RESOURCE_LEARNPATH)) {
             $table_main = Database :: get_course_table(TABLE_LP_MAIN);
             $table_item = Database :: get_course_table(TABLE_LP_ITEM);
@@ -527,7 +515,8 @@ class CourseRecycler
     /**
     * Recycle Attendances
     */
-    function recycle_attendance($session_id = 0) {
+    function recycle_attendance($session_id = 0) 
+    {
         if ($this->course->has_resources(RESOURCE_ATTENDANCE)) {
             $table_attendance          = Database :: get_course_table(TABLE_ATTENDANCE);
             $table_attendance_calendar = Database :: get_course_table(TABLE_ATTENDANCE_CALENDAR);
@@ -546,4 +535,30 @@ class CourseRecycler
             }
         }
     }
+
+    /**
+     * Recycle Works
+     */
+    function recycle_work($session_id = 0) 
+    {
+        if ($this->course->has_resources(RESOURCE_WORK)) {
+            $table_work          = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);
+            $table_work_assignment = Database :: get_course_table(TABLE_STUDENT_PUBLICATION_ASSIGNMENT);
+
+            $resources = $this->course->resources;
+            foreach ($resources[RESOURCE_WORK] as $last_id => $obj) {
+                if (is_numeric($last_id)) {
+                    $cond = array('publication_id = ? AND c_id = ? '=>array($last_id, $this->course_id));
+                    Database::delete($table_work_assignment, $cond);
+                    // The following also deletes student tasks
+                    $cond = array('parent_id = ? AND c_id = ?'=>array($last_id, $this->course_id));
+                    Database::delete($table_work, $cond);
+                    // Finally, delete the main task registry
+                    $cond = array('id = ? AND c_id = ?'=>array($last_id, $this->course_id));
+                    Database::delete($table_work, $cond);
+                    api_item_property_update($this->course_info, TOOL_STUDENTPUBLICATION, $last_id,'StudentPublicationDeleted', api_get_user_id());
+                }
+            }
+        }
+    }
 }

Файлын зөрүү хэтэрхий том тул дарагдсан байна
+ 337 - 453
main/coursecopy/classes/CourseRestorer.class.php


+ 4 - 3
main/coursecopy/classes/CourseSelectForm.class.php

@@ -35,9 +35,10 @@ class CourseSelectForm
 		$resource_titles[RESOURCE_WIKI]                 = get_lang('Wiki');
 		$resource_titles[RESOURCE_THEMATIC]             = get_lang('Thematic');
 		$resource_titles[RESOURCE_ATTENDANCE]           = get_lang('Attendance');
+        $resource_titles[RESOURCE_WORK]                 = get_lang('ToolStudentPublication');
 
         $iconPath = api_get_path(WEB_IMG_PATH);
-        ?>
+?>
 		<script>
 			function exp(item) {
 				el = document.getElementById('div_'+item);
@@ -489,7 +490,7 @@ class CourseSelectForm
 							}
 					default :
 						if (!empty($resources) && is_array($resources)) {
-							foreach($resources as $id => $obj) {
+							foreach ($resources as $id => $obj) {
 								$resource_is_used_elsewhere = $course->is_linked_resource($obj);
                                 //var_dump($obj, $resource_is_used_elsewhere);
 								// check if document is in a quiz (audio/video)
@@ -563,7 +564,7 @@ class CourseSelectForm
 		<?php
 
 		//get destination course title
-		if (!empty($hidden_fields['destination_course'])) {
+		if(!empty($hidden_fields['destination_course'])) {
 			$course_infos = CourseManager::get_course_information($hidden_fields['destination_course']);
 			echo '<h3>';
 				echo get_lang('DestinationCourse').' : '.$course_infos['title'];

+ 3 - 0
main/coursecopy/classes/Resource.class.php

@@ -30,6 +30,7 @@ define('RESOURCE_SURVEYINVITATION', 'survey_invitation');
 define('RESOURCE_WIKI', 'wiki');
 define('RESOURCE_THEMATIC', 'thematic');
 define('RESOURCE_ATTENDANCE', 'attendance');
+define('RESOURCE_WORK', 'work');
 
 /**
  * Representation of a resource in a Chamilo-course.
@@ -192,6 +193,8 @@ class Resource
                 return TOOL_COURSE_PROGRESS;
             case RESOURCE_ATTENDANCE:
                 return TOOL_ATTENDANCE;
+            case RESOURCE_WORK:
+                return TOOL_STUDENTPUBLICATION;
             default:
                 return null;
         }

+ 36 - 0
main/coursecopy/classes/Work.class.php

@@ -0,0 +1,36 @@
+<?php
+/* For licensing terms, see /license.txt */
+/**
+ * Work/Assignment/Student publication backup script
+ * @package chamilo.backup
+ */
+/**
+ * Code
+ */
+require_once 'Resource.class.php';
+/**
+ * An event
+ * @author Yannick Warnier <yannick.warnier@beeznest.com>
+ * @package chamilo.backup
+ */
+class Work extends Resource
+{
+    public $params = array();
+
+    /**
+     * Create a new Work
+     *
+     * @param array parameters
+     */
+    public function __construct($params)
+    {
+        parent::Resource($params['id'], RESOURCE_WORK);
+        $this->params = $params;
+    }
+
+    public function show()
+    {
+        parent::show();
+        echo $this->params['title'];
+    }
+}

+ 680 - 0
main/cron/import_csv.php

@@ -0,0 +1,680 @@
+<?php
+
+if (PHP_SAPI !='cli') {
+    die('Run this script through the command line or comment this line in the code');
+}
+
+//$_SERVER['SERVER_NAME'] = '';
+//$_SERVER['HTTP_HOST'] = '';
+
+require_once __DIR__.'/../inc/global.inc.php';
+require_once api_get_path(LIBRARY_PATH).'log.class.php';
+
+/**
+ * Class ImportCsv
+ */
+class ImportCsv
+{
+    private $logger;
+    private $dumpValues;
+    public $test;
+    public $defaultLanguage = 'dutch';
+    public $extraFieldIdNameList = array(
+        'session' => 'external_session_id',
+        'course' => 'external_course_id',
+        'user' => 'external_user_id',
+    );
+    public $defaultAdminId = 1;
+    public $defaultSessionVisibility = 1;
+
+    /**
+     * When creating a user the expiration date is set to registration date + this value
+     * @var int number of years
+     */
+    public $expirationDateInUserCreation = 1;
+
+    /**
+     * When updating a user the expiration date is set to update date + this value
+     * @var int number of years
+     */
+    public $expirationDateInUserUpdate = 1;
+    public $daysCoachAccessBeforeBeginning = 30;
+    public $daysCoachAccessAfterBeginning = 60;
+    public $conditions;
+
+    /**
+     * @param Logger $logger
+     */
+    public function __construct($logger, $conditions)
+    {
+        $this->logger = $logger;
+        $this->conditions = $conditions;
+    }
+
+    /**
+     * @param bool $dump
+     */
+    function setDumpValues($dump)
+    {
+        $this->dumpValues = $dump;
+    }
+
+    /**
+     * @return mixed
+     */
+    function getDumpValues()
+    {
+        return $this->dumpValues;
+    }
+
+    /**
+     * Runs the import process
+     */
+    public function run()
+    {
+        $path = api_get_path(SYS_CODE_PATH).'cron/incoming/';
+        if (!is_dir($path)) {
+            echo "The folder! $path does not exits";
+            exit;
+        }
+
+        if ($this->getDumpValues()) {
+            $this->dumpDatabaseTables();
+        }
+
+        echo "Starting with reading the files: ".PHP_EOL.PHP_EOL;
+
+        $files = scandir($path);
+        $fileToProcess = array();
+
+        if (!empty($files)) {
+            foreach ($files as $file) {
+                $fileInfo = pathinfo($file);
+                if ($fileInfo['extension'] == 'csv') {
+                    // teachers_yyyymmdd.csv, courses_yyyymmdd.csv, students_yyyymmdd.csv and sessions_yyyymmdd.csv
+                    $parts = explode('_', $fileInfo['filename']);
+                    $method = 'import'.ucwords($parts[1]);
+
+                    if (method_exists($this, $method)) {
+                         $fileToProcess[$parts[1]][] = array(
+                            'method' => $method,
+                            'file' => $path.$fileInfo['basename']
+                        );
+                        //$this->$method($path.$fileInfo['basename']);
+                    } else {
+                        echo "Error - This file '$file' can't be processed.".PHP_EOL;
+                        echo "The file have to has this format:".PHP_EOL;
+                        echo "prefix_students_ddmmyyyy.csv, prefix_teachers_ddmmyyyy.csv, prefix_courses_ddmmyyyy.csv, prefix_sessions_ddmmyyyy.csv ".PHP_EOL;
+                        exit;
+                    }
+                }
+            }
+
+            if (empty($fileToProcess)) {
+                echo 'Error - no files to process.';
+                exit;
+            }
+
+            $sections = array('students', 'teachers', 'courses', 'sessions');
+
+            $this->prepareImport();
+
+            foreach ($sections as $section) {
+                $this->logger->addInfo("-- Import $section --");
+
+                if (isset($fileToProcess[$section]) && !empty($fileToProcess[$section])) {
+                    $files = $fileToProcess[$section];
+                    foreach ($files as $fileInfo) {
+                        $method = $fileInfo['method'];
+                        $file = $fileInfo['file'];
+
+                        echo 'Reading file: '.$file.PHP_EOL;
+                        $this->logger->addInfo("Reading file: $file");
+
+                        $this->$method($file);
+                    }
+
+                }
+            }
+        }
+    }
+
+    private function prepareImport()
+    {
+        // Create user extra field: extra_external_user_id
+        UserManager::create_extra_field($this->extraFieldIdNameList['user'], 1, 'External user id', null);
+
+        // Create course extra field: extra_external_course_id
+        CourseManager::create_course_extra_field($this->extraFieldIdNameList['course'], 1, 'External course id');
+        // Create session extra field extra_external_session_id
+        SessionManager::create_session_extra_field($this->extraFieldIdNameList['session'], 1, 'External session id');
+    }
+
+    /**
+     * @param string $file
+     */
+    function moveFile($file)
+    {
+        $moved = str_replace('incoming', 'treated', $file);
+
+        if ($this->test) {
+            $result = 1;
+        } else {
+            $result = rename($file, $moved);
+        }
+
+        if ($result) {
+            $this->logger->addInfo("Moving file to the treated folder: $file");
+        } else {
+            $this->logger->addError("Error - Cant move file to the treated folder: $file");
+        }
+    }
+
+    /**
+     * @param array $row
+     *
+     * @return array
+     */
+    private function cleanUserRow($row)
+    {
+        $row['lastname'] = $row['LastName'];
+        $row['firstname'] = $row['FirstName'];
+        $row['email'] = $row['Email'];
+        $row['username'] = $row['UserName'];
+        $row['password'] = $row['Password'];
+        $row['auth_source'] = $row['AuthSource'];
+        $row['official_code'] = $row['OfficialCode'];
+        $row['phone'] = $row['PhoneNumber'];
+
+        if (isset($row['StudentID'])) {
+            $row['extra_'.$this->extraFieldIdNameList['user']] = $row['StudentID'];
+        }
+
+        if (isset($row['TeacherID'])) {
+            $row['extra_'.$this->extraFieldIdNameList['user']] = $row['TeacherID'];
+        }
+
+        //$row['lastname'] =  Status
+        return $row;
+    }
+
+    /**
+     * @param array $row
+     * @return array
+     */
+    private function cleanCourseRow($row)
+    {
+        $row['title'] = $row['Title'];
+        $row['course_code'] = $row['Code'];
+        $row['course_category'] = $row['CourseCategory'];
+        $row['email'] = $row['Teacher'];
+        $row['language'] = $row['Language'];
+
+        $row['teachers'] = array();
+        if (isset($row['Teacher']) && !empty($row['Teacher'])) {
+            $userInfo = api_get_user_info_from_username($row['Teacher']);
+            if (!empty($userInfo)) {
+                $row['teachers'] = $userInfo['user_id'];
+            }
+        }
+
+        if (isset($row['CourseID'])) {
+            $row['extra_'.$this->extraFieldIdNameList['course']] = $row['CourseID'];
+        }
+        return $row;
+    }
+
+    /**
+     * File to import
+     * @param string $file
+     */
+    private function importTeachers($file)
+    {
+        $data = Import::csv_to_array($file);
+
+        /* Unique identifier: official-code username.
+        Email address and password should never get updated. *ok
+        The only fields that I can think of that should update if the data changes in the csv file are FirstName and LastName. *ok
+        A slight edit of these fields should be taken into account. ???
+        Adding teachers is no problem, but deleting them shouldn’t be automated, but we should get a log of “to delete teachers”.
+        We’ll handle that manually if applicable.
+        No delete!
+        */
+        $language = $this->defaultLanguage;
+
+        if (!empty($data)) {
+            $this->logger->addInfo(count($data)." records found.");
+            foreach ($data as $row) {
+                $row = $this->cleanUserRow($row);
+
+                $user_id = UserManager::get_user_id_from_original_id($row['extra_'.$this->extraFieldIdNameList['user']], $this->extraFieldIdNameList['user']);
+                $userInfo  = array();
+                $userInfoByOfficialCode  = null;
+
+                if (!empty($user_id)) {
+                    $userInfo = api_get_user_info($user_id);
+                    //$userInfo = api_get_user_info_from_username($row['username']);
+                    $userInfoByOfficialCode = api_get_user_info_from_official_code($row['official_code']);
+                }
+
+                $expirationDate = api_get_utc_datetime(strtotime("+".intval($this->expirationDateInUserCreation)."years"));
+
+                if (empty($userInfo) && empty($userInfoByOfficialCode)) {
+                    // Create user
+                    $userId = UserManager::create_user(
+                        $row['firstname'],
+                        $row['lastname'],
+                        COURSEMANAGER,
+                        $row['email'],
+                        $row['username'],
+                        $row['password'],
+                        $row['official_code'],
+                        $language, //$row['language'],
+                        $row['phone'],
+                        null, //$row['picture'], //picture
+                        PLATFORM_AUTH_SOURCE, // ?
+                        $expirationDate, //'0000-00-00 00:00:00', //$row['expiration_date'], //$expiration_date = '0000-00-00 00:00:00',
+                        1, //active
+                        0,
+                        null, // extra
+                        null, //$encrypt_method = '',
+                        false //$send_mail = false
+                    );
+
+                    if ($userId) {
+                        foreach ($row as $key => $value) {
+                            if (substr($key, 0, 6) == 'extra_') { //an extra field
+                                UserManager::update_extra_field_value($userId, substr($key, 6), $value);
+                            }
+                        }
+                        $this->logger->addInfo("Teachers - User created: ".$row['username']);
+                    } else {
+                        $this->logger->addError("Teachers - User NOT created: ".$row['username']." ".$row['firstname']." ".$row['lastname']);
+                    }
+                } else {
+                    if (empty($userInfo)) {
+                        $this->logger->addError("Teachers - Can't update user :".$row['username']);
+                        continue;
+                    }
+
+                    $expirationDate = api_get_utc_datetime(strtotime("+".intval($this->expirationDateInUserUpdate)."years"));
+
+                    // Update user
+                    $result = UserManager::update_user(
+                        $userInfo['user_id'],
+                        $row['firstname'], // <<-- changed
+                        $row['lastname'],  // <<-- changed
+                        $userInfo['username'],
+                        null, //$password = null,
+                        $auth_source = null,
+                        $userInfo['email'],
+                        COURSEMANAGER,
+                        $userInfo['official_code'],
+                        $userInfo['phone'],
+                        $userInfo['picture_uri'],
+                        $expirationDate,
+                        $userInfo['active'],
+                        null, //$creator_id = null,
+                        0, //$hr_dept_id = 0,
+                        null, // $extra = null,
+                        null, //$language = 'english',
+                        null, //$encrypt_method = '',
+                        false, //$send_email = false,
+                        0 //$reset_password = 0
+                    );
+
+                    if ($result) {
+                        foreach ($row as $key => $value) {
+                            if (substr($key, 0, 6) == 'extra_') { //an extra field
+                                UserManager::update_extra_field_value($userInfo['user_id'], substr($key, 6), $value);
+                            }
+                        }
+                        $this->logger->addInfo("Teachers - User updated: ".$row['username']);
+                    } else {
+                        $this->logger->addError("Teachers - User not updated: ".$row['username']);
+                    }
+                }
+            }
+        }
+        $this->moveFile($file);
+    }
+
+    /**
+     * @param string $file
+     */
+    private function importStudents($file)
+    {
+        $data = Import::csv_to_array($file);
+
+        /*
+         * Another users import.
+        Unique identifier: official code and username . ok
+        Username and password should never get updated. ok
+        If an update should need to occur (because it changed in the .csv), we’ll want that logged. We will handle this manually in that case.
+        All other fields should be updateable, though passwords should of course not get updated. ok
+        If a user gets deleted (not there anymore),
+        He should be set inactive one year after the current date. So I presume you’ll just update the expiration date. We want to grant access to courses up to a year after deletion.
+         */
+
+        if (!empty($data)) {
+            $language = $this->defaultLanguage;
+            $this->logger->addInfo(count($data)." records found.");
+            foreach ($data as $row) {
+                $row = $this->cleanUserRow($row);
+                //$userInfo = api_get_user_info_from_username($row['username']);
+                $user_id = UserManager::get_user_id_from_original_id($row['extra_'.$this->extraFieldIdNameList['user']], $this->extraFieldIdNameList['user']);
+
+                $userInfo = array();
+                $userInfoByOfficialCode = null;
+                if (!empty($user_id)) {
+                    $userInfo = api_get_user_info($user_id);
+                    $userInfoByOfficialCode = api_get_user_info_from_official_code($row['official_code']);
+                }
+
+                $expirationDate = api_get_utc_datetime(strtotime("+".intval($this->expirationDateInUserCreation)."years"));
+
+                if (empty($userInfo) && empty($userInfoByOfficialCode)) {
+                    // Create user
+                    $result = UserManager::create_user(
+                        $row['firstname'],
+                        $row['lastname'],
+                        STUDENT,
+                        $row['email'],
+                        $row['username'],
+                        $row['password'],
+                        $row['official_code'],
+                        $language, //$row['language'],
+                        $row['phone'],
+                        null, //$row['picture'], //picture
+                        PLATFORM_AUTH_SOURCE, // ?
+                        $expirationDate, //'0000-00-00 00:00:00', //$row['expiration_date'], //$expiration_date = '0000-00-00 00:00:00',
+                        1, //active
+                        0,
+                        null, // extra
+                        null, //$encrypt_method = '',
+                        false //$send_mail = false
+                    );
+
+                    if ($result) {
+                        foreach ($row as $key => $value) {
+                            if (substr($key, 0, 6) == 'extra_') { //an extra field
+                                UserManager::update_extra_field_value($result, substr($key, 6), $value);
+                            }
+                        }
+                        $this->logger->addInfo("Students - User created: ".$row['username']);
+                    } else {
+                        $this->logger->addError("Students - User NOT created: ".$row['username']." ".$row['firstname']." ".$row['lastname']);
+                    }
+                } else {
+                    if (empty($userInfo)) {
+                        $this->logger->addError("Students - Can't update user :".$row['username']);
+                        continue;
+                    }
+
+                    if ($row['action'] == 'delete') {
+                        // INactive one year later
+                        $userInfo['expiration_date'] = api_get_utc_datetime(api_strtotime(time() + 365*24*60*60));
+                    }
+
+                    if (isset($this->conditions['importStudents'])) {
+                        if (isset($this->conditions['importStudents']['update']) && isset($this->conditions['importStudents']['update']['avoid'])) {
+                            $avoidUsersWithEmail = $this->conditions['importStudents']['update']['avoid']['email'];
+                            if ($userInfo['email'] != $row['email'] && in_array($row['email'], $avoidUsersWithEmail)) {
+                                $this->logger->addInfo("Students - User skipped: ".$row['username']." because the avoid conditions (email).");
+                                continue;
+                            }
+
+                            $avoidUsersWithPassword = $this->conditions['importStudents']['update']['avoid']['password'];
+
+                            if ($userInfo['password'] != api_get_encrypted_password($row['password']) && in_array($row['password'], $avoidUsersWithPassword)) {
+                                $this->logger->addInfo("Students - User skipped: ".$row['username']." because the avoid conditions (password).");
+                                continue;
+                            }
+                        }
+                    }
+
+                    $expirationDate = api_get_utc_datetime(strtotime("+".intval($this->expirationDateInUserUpdate)."years"));
+
+                    // Update user
+                    $result = UserManager::update_user(
+                        $userInfo['user_id'],
+                        $row['firstname'], // <<-- changed
+                        $row['lastname'],  // <<-- changed
+                        $userInfo['username'],
+                        null, //$password = null,
+                        $auth_source = null,
+                        $userInfo['email'],
+                        STUDENT,
+                        $userInfo['official_code'],
+                        $userInfo['phone'],
+                        $userInfo['picture_uri'],
+                        $expirationDate,
+                        $userInfo['active'],
+                        null, //$creator_id = null,
+                        0, //$hr_dept_id = 0,
+                        null, // $extra = null,
+                        null, //$language = 'english',
+                        null, //$encrypt_method = '',
+                        false, //$send_email = false,
+                        0 //$reset_password = 0
+                    );
+
+                    if ($result) {
+                        foreach ($row as $key => $value) {
+                            if (substr($key, 0, 6) == 'extra_') { //an extra field
+                                UserManager::update_extra_field_value($userInfo['user_id'], substr($key, 6), $value);
+                            }
+                        }
+
+                        $this->logger->addInfo("Students - User updated: ".$row['username']);
+                    } else {
+                        $this->logger->addError("Students - User NOT updated: ".$row['username']." ".$row['firstname']." ".$row['lastname']);
+                    }
+                }
+            }
+        }
+
+        $this->moveFile($file);
+    }
+
+    /**
+     * @param string $file
+     */
+    private function importCourses($file)
+    {
+        $data = Import::csv_to_array($file);
+
+        //$language = $this->defaultLanguage;
+
+        if (!empty($data)) {
+            $this->logger->addInfo(count($data)." records found.");
+
+            foreach ($data as $row) {
+                $row = $this->cleanCourseRow($row);
+                $courseCode = CourseManager::get_course_id_from_original_id($row['extra_'.$this->extraFieldIdNameList['course']], $this->extraFieldIdNameList['course']);
+
+                //$courseInfo = api_get_course_info($row['course_code']);
+                $courseInfo = api_get_course_info($courseCode);
+                if (empty($courseInfo)) {
+                    // Create
+                    $params = array();
+                    $params['title']                = $row['title'];
+                    $params['exemplary_content']    = false;
+                    $params['wanted_code']          = $row['course_code'];
+                    $params['course_category']      = $row['course_category'];
+                    $params['course_language']      = $row['language'];
+                    $params['teachers']             = $row['teachers'];
+
+                    $courseInfo = CourseManager::create_course($params);
+
+                    if (!empty($courseInfo)) {
+                        CourseManager::update_course_extra_field_value($courseInfo['code'], 'external_course_id', $row['extra_'.$this->extraFieldIdNameList['course']]);
+                        $this->logger->addInfo("Courses - Course created ".$courseInfo['code']);
+                    } else {
+                        $this->logger->addError("Courses - Can't create course:".$row['title']);
+                    }
+                } else {
+                    // Update
+                    $params = array(
+                        'title' => $row['title'],
+                    );
+                    $result = CourseManager::update_attributes($courseInfo['real_id'], $params);
+
+                    //CourseManager::updateTeachers($courseInfo['id'], $row['teachers']);
+
+                    if ($result) {
+                        $this->logger->addInfo("Courses - Course updated ".$courseInfo['code']);
+                    } else {
+                        $this->logger->addError("Courses - Course NOT updated ".$courseInfo['code']);
+                    }
+                }
+            }
+        }
+        $this->moveFile($file);
+    }
+
+    /**
+     * @param string $file
+     */
+    private function importSessions($file)
+    {
+        $result = SessionManager::importCSV(
+            $file,
+            true,
+            $this->defaultAdminId,
+            $this->logger,
+            array('SessionID' => 'extra_'.$this->extraFieldIdNameList['session']),
+            $this->extraFieldIdNameList['session'],
+            $this->daysCoachAccessBeforeBeginning,
+            $this->daysCoachAccessAfterBeginning,
+            $this->defaultSessionVisibility
+        );
+
+        if (!empty($result['error_message'])) {
+            $this->logger->addError($result['error_message']);
+        }
+        $this->logger->addInfo("Sessions - Sessions parsed: ".$result['session_counter']);
+        $this->moveFile($file);
+    }
+
+    private function dumpDatabaseTables()
+    {
+        echo 'Dumping tables'.PHP_EOL;
+
+        // User
+        $table = Database::get_main_table(TABLE_MAIN_USER);
+        $tableAdmin = Database::get_main_table(TABLE_MAIN_ADMIN);
+        //$sql = "DELETE FROM $table WHERE username NOT IN ('admin') AND lastname <> 'Anonymous' ";
+        $sql = "DELETE FROM $table WHERE user_id not in (select user_id from $tableAdmin) and status <> ".ANONYMOUS;
+        Database::query($sql);
+        echo $sql.PHP_EOL;
+
+        // Course
+        $table = Database::get_main_table(TABLE_MAIN_COURSE);
+        $sql = "DELETE FROM $table";
+        Database::query($sql);
+        echo $sql.PHP_EOL;
+
+        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
+        $sql = "DELETE FROM $table";
+        Database::query($sql);
+        echo $sql.PHP_EOL;
+
+        $table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
+        $sql = "DELETE FROM $table";
+        Database::query($sql);
+        echo $sql.PHP_EOL;
+
+        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
+        $sql = "DELETE FROM $table";
+        Database::query($sql);
+        echo $sql.PHP_EOL;
+
+        // Sessions
+        $table = Database::get_main_table(TABLE_MAIN_SESSION);
+        $sql = "DELETE FROM $table";
+        Database::query($sql);
+        echo $sql.PHP_EOL;
+
+        $table = Database::get_main_table(TABLE_MAIN_SESSION_CATEGORY);
+        $sql = "DELETE FROM $table";
+        Database::query($sql);
+        echo $sql.PHP_EOL;
+
+        $table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
+        $sql = "DELETE FROM $table";
+        Database::query($sql);
+        echo $sql.PHP_EOL;
+
+        $table = Database::get_main_table(TABLE_MAIN_SESSION_USER);
+        $sql = "DELETE FROM $table";
+        Database::query($sql);
+        echo $sql.PHP_EOL;
+
+        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
+        $sql = "DELETE FROM $table";
+        Database::query($sql);
+        echo $sql.PHP_EOL;
+
+        // Extra fields
+        $table = Database::get_main_table(TABLE_MAIN_SESSION_FIELD_VALUES);
+        $sql = "DELETE FROM $table";
+        Database::query($sql);
+        echo $sql.PHP_EOL;
+
+        $table = Database::get_main_table(TABLE_MAIN_COURSE_FIELD_VALUES);
+        $sql = "DELETE FROM $table";
+        Database::query($sql);
+        echo $sql.PHP_EOL;
+
+        $table = Database::get_main_table(TABLE_MAIN_USER_FIELD_VALUES);
+        $sql = "DELETE FROM $table";
+        Database::query($sql);
+        echo $sql.PHP_EOL;
+    }
+}
+
+use Monolog\Logger;
+use Monolog\Handler\StreamHandler;
+use Monolog\Handler\NativeMailerHandler;
+use Monolog\Handler\RotatingFileHandler;
+use Monolog\Handler\BufferHandler;
+
+$logger = new Logger('cron');
+$emails = isset($_configuration['cron_notification_mails']) ? $_configuration['cron_notification_mails'] : null;
+
+$minLevel = Logger::DEBUG;
+
+if (!is_array($emails)) {
+    $emails = array($emails);
+}
+$subject = "Cron main/cron/import_csv.php ".date('Y-m-d h:i:s');
+$from = api_get_setting('emailAdministrator');
+
+if (!empty($emails)) {
+    foreach ($emails as $email) {
+        $stream = new NativeMailerHandler($email, $subject, $from, $minLevel);
+        $logger->pushHandler(new BufferHandler($stream, 0, $minLevel));
+    }
+}
+
+$stream = new StreamHandler(api_get_path(SYS_ARCHIVE_PATH).'import_csv.log', $minLevel);
+$logger->pushHandler(new BufferHandler($stream, 0, $minLevel));
+$logger->pushHandler(new RotatingFileHandler('import_csv', 5, $minLevel));
+
+$import = new ImportCsv($logger, $_configuration['cron_import_csv_conditions']);
+
+if (isset($_configuration['default_admin_user_id_for_cron'])) {
+    $import->defaultAdminId = $_configuration['default_admin_user_id_for_cron'];
+}
+// @todo in production disable the dump option
+$dump = false;
+
+if (isset($argv[1]) && $argv[1] = '--dump') {
+    $dump = true;
+}
+
+$import->setDumpValues($dump);
+// Do not moves the files to treated
+$import->test = true;
+$import->run();

Файлын зөрүү хэтэрхий том тул дарагдсан байна
+ 151 - 184
main/css/base.css


BIN
main/css/chamilo_electric_blue/images/header-logo.png


BIN
main/css/chamilo_green/images/header-logo.png


BIN
main/css/chamilo_orange/images/header-logo.png


BIN
main/css/chamilo_red/images/header-logo.png


+ 0 - 2
main/css/journal/bootstrap.css

@@ -1484,7 +1484,6 @@ table .span24 {
   *margin-right: .3em;
   line-height: 14px;
   vertical-align: text-top;
-  background-image: url("../img/glyphicons-halflings.png");
   background-position: 14px 14px;
   background-repeat: no-repeat;
 }
@@ -1493,7 +1492,6 @@ table .span24 {
   *margin-left: 0;
 }
 .icon-white {
-  background-image: url("../img/glyphicons-halflings-white.png");
 }
 .icon-glass {
   background-position: 0      0;

+ 0 - 2
main/css/readable/bootstrap.css

@@ -1483,7 +1483,6 @@ table .span24 {
   *margin-right: .3em;
   line-height: 14px;
   vertical-align: text-top;
-  background-image: url("../img/glyphicons-halflings.png");
   background-position: 14px 14px;
   background-repeat: no-repeat;
 }
@@ -1492,7 +1491,6 @@ table .span24 {
   *margin-left: 0;
 }
 .icon-white {
-  background-image: url("../img/glyphicons-halflings-white.png");
 }
 .icon-glass {
   background-position: 0      0;

+ 14 - 0
main/css/responsive.css

@@ -578,6 +578,20 @@ The more frequent ones have been marked with *
     .course-tool {
         width: 260px;
     }
+    .btn-invitations {
+        margin-left: 120px;
 }
 
+    .btn-msg {
+        padding-left: 27px;
+    }
+    .btn-inv {
+        padding-left: 27px;
+        padding-right:5px;
+    }
+    .btn-inv-off {
+        padding-left: 27px;
+        padding-right:5px;
+    }
+}
 

BIN
main/css/send_inv.png


BIN
main/css/send_inv_off.png


BIN
main/css/send_msg.png


+ 0 - 2
main/css/simplex/bootstrap.css

@@ -1484,7 +1484,6 @@ table .span24 {
   *margin-right: .3em;
   line-height: 14px;
   vertical-align: text-top;
-  background-image: url("../img/glyphicons-halflings.png");
   background-position: 14px 14px;
   background-repeat: no-repeat;
 }
@@ -1493,7 +1492,6 @@ table .span24 {
   *margin-left: 0;
 }
 .icon-white {
-  background-image: url("../img/glyphicons-halflings-white.png");
 }
 .icon-glass {
   background-position: 0      0;

+ 0 - 2
main/css/spacelab/bootstrap.css

@@ -1483,7 +1483,6 @@ table .span24 {
   *margin-right: .3em;
   line-height: 14px;
   vertical-align: text-top;
-  background-image: url("../img/glyphicons-halflings.png");
   background-position: 14px 14px;
   background-repeat: no-repeat;
 }
@@ -1492,7 +1491,6 @@ table .span24 {
   *margin-left: 0;
 }
 .icon-white {
-  background-image: url("../img/glyphicons-halflings-white.png");
 }
 .icon-glass {
   background-position: 0      0;

+ 402 - 445
main/document/create_audio.php

@@ -2,14 +2,14 @@
 /* For licensing terms, see /license.txt */
 
 /**
- *    This file allows creating audio files from a text.
+ *	This file allows creating audio files from a text.
  *
- * @package chamilo.document
+ *	@package chamilo.document
  *
  * @author Juan Carlos Raña Trabado
  * @since 8/January/2011
  * TODO:clean all file
- */
+*/
 /**
  * Code
  */
@@ -27,17 +27,16 @@ $nameTools = get_lang('CreateAudio');
 
 api_protect_course_script();
 api_block_anonymous_users();
-
-if (api_get_setting('enabled_text2audio') == 'false') {
-    api_not_allowed(true);
+if (api_get_setting('enabled_text2audio') == 'false'){
+	api_not_allowed(true);
 }
 
 $document_data = DocumentManager::get_document_data_by_id($_GET['id'], api_get_course_id());
 if (empty($document_data)) {
     if (api_is_in_group()) {
-        $group_properties = GroupManager::get_group_properties(api_get_group_id());
-        $document_id = DocumentManager::get_document_id(api_get_course_info(), $group_properties['directory']);
-        $document_data = DocumentManager::get_document_data_by_id($document_id, api_get_course_id());
+        $group_properties   = GroupManager::get_group_properties(api_get_group_id());        
+        $document_id        = DocumentManager::get_document_id(api_get_course_info(), $group_properties['directory']);
+        $document_data      = DocumentManager::get_document_data_by_id($document_id, api_get_course_id());
     }
 }
 $document_id = $document_data['id'];
@@ -50,42 +49,39 @@ $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
 // Please, do not modify this dirname formatting
 
 if (strstr($dir, '..')) {
-    $dir = '/';
+	$dir = '/';
 }
 
 if ($dir[0] == '.') {
-    $dir = substr($dir, 1);
+	$dir = substr($dir, 1);
 }
 
 if ($dir[0] != '/') {
-    $dir = '/'.$dir;
+	$dir = '/'.$dir;
 }
 
 if ($dir[strlen($dir) - 1] != '/') {
-    $dir .= '/';
+	$dir .= '/';
 }
 
 $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document'.$dir;
 
 if (!is_dir($filepath)) {
-    $filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
-    $dir = '/';
+	$filepath = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document/';
+	$dir = '/';
 }
 
 //groups //TODO: clean
 if (isset ($_SESSION['_gid']) && $_SESSION['_gid'] != 0) {
-    $req_gid = '&amp;gidReq='.$_SESSION['_gid'];
-    $interbreadcrumb[] = array(
-        "url" => "../group/group_space.php?gidReq=".$_SESSION['_gid'],
-        "name" => get_lang('GroupSpace')
-    );
-    $noPHP_SELF = true;
-    $to_group_id = $_SESSION['_gid'];
-    $group = GroupManager :: get_group_properties($to_group_id);
-    $path = explode('/', $dir);
-    if ('/'.$path[1] != $group['directory']) {
-        api_not_allowed(true);
-    }
+	$req_gid = '&amp;gidReq='.$_SESSION['_gid'];
+	$interbreadcrumb[] = array ("url" => "../group/group_space.php?gidReq=".$_SESSION['_gid'], "name" => get_lang('GroupSpace'));
+	$noPHP_SELF = true;
+	$to_group_id = $_SESSION['_gid'];
+	$group = GroupManager :: get_group_properties($to_group_id);
+	$path = explode('/', $dir);
+	if ('/'.$path[1] != $group['directory']) {
+		api_not_allowed(true);
+	}
 }
 
 $interbreadcrumb[] = array(
@@ -99,7 +95,7 @@ if (!($is_allowed_to_edit || $_SESSION['group_member_with_upload_rights'] || is_
     api_get_session_id()
 ))
 ) {
-    api_not_allowed(true);
+	api_not_allowed(true);
 }
 
 
@@ -108,213 +104,178 @@ event_access_tool(TOOL_DOCUMENT);
 
 $display_dir = $dir;
 if (isset ($group)) {
-    $display_dir = explode('/', $dir);
-    unset ($display_dir[0]);
-    unset ($display_dir[1]);
-    $display_dir = implode('/', $display_dir);
+	$display_dir = explode('/', $dir);
+	unset ($display_dir[0]);
+	unset ($display_dir[1]);
+	$display_dir = implode('/', $display_dir);
 }
 
 // Interbreadcrumb for the current directory root path
-// Copied from document.php
-$dir_array = explode('/', $dir);
-$array_len = count($dir_array);
-
-$dir_acum = '';
-for ($i = 0; $i < $array_len; $i++) {
-    $url_dir = 'document.php?&curdirpath='.$dir_acum.$dir_array[$i];
-    //Max char 80
-    $url_to_who = Text::cut($dir_array[$i], 80);
-    if ($is_certificate_mode) {
-        $interbreadcrumb[] = array(
-            'url' => $url_dir.'&selectcat='.Security::remove_XSS($_GET['selectcat']),
-            'name' => $url_to_who
-        );
-    } else {
-        $interbreadcrumb[] = array('url' => $url_dir, 'name' => $url_to_who);
-    }
-    $dir_acum .= $dir_array[$i].'/';
-}
+	// Copied from document.php
+	$dir_array = explode('/', $dir);
+	$array_len = count($dir_array);
+	
+	$dir_acum = '';
+	for ($i = 0; $i < $array_len; $i++) {
+		$url_dir = 'document.php?&curdirpath='.$dir_acum.$dir_array[$i];
+		//Max char 80
+        $url_to_who = Text::cut($dir_array[$i], 80);
+		if ($is_certificate_mode) {
+			$interbreadcrumb[] = array('url' => $url_dir.'&selectcat='.Security::remove_XSS($_GET['selectcat']), 'name' => $url_to_who);
+		} else {
+			$interbreadcrumb[] = array('url' => $url_dir, 'name' => $url_to_who);
+		}
+		$dir_acum .= $dir_array[$i].'/';
+	}
 
 Display :: display_header($nameTools, 'Doc');
 
 echo '<div class="actions">';
-echo '<a href="document.php?id='.$document_id.'">'.Display::return_icon(
-    'back.png',
-    get_lang('BackTo').' '.get_lang('DocumentsOverview'),
-    '',
-    ICON_SIZE_MEDIUM
-).'</a>';
-
-echo '<a href="create_audio.php?'.api_get_cidreq().'&amp;id='.$document_id.'&amp;dt2a=google">'.Display::return_icon(
-    'google.png',
-    get_lang('GoogleAudio'),
-    '',
-    ICON_SIZE_MEDIUM
-).'</a>';
-
-echo '<a href="create_audio.php?'.api_get_cidreq().'&amp;id='.$document_id.'&amp;dt2a=pediaphon">'.Display::return_icon(
-    'pediaphon.png',
-    get_lang('Pediaphon'),
-    '',
-    ICON_SIZE_MEDIUM
-).'</a>';
-
+		echo '<a href="document.php?id='.$document_id.'">'.Display::return_icon('back.png',get_lang('BackTo').' '.get_lang('DocumentsOverview'),'',ICON_SIZE_MEDIUM).'</a>';
+		
+		echo '<a href="create_audio.php?'.api_get_cidreq().'&amp;id='.$document_id.'&amp;dt2a=google">'.Display::return_icon('google.png',get_lang('GoogleAudio'),'',ICON_SIZE_MEDIUM).'</a>';
+		
+		echo '<a href="create_audio.php?'.api_get_cidreq().'&amp;id='.$document_id.'&amp;dt2a=pediaphon">'.Display::return_icon('pediaphon.png', get_lang('Pediaphon'),'',ICON_SIZE_MEDIUM).'</a>';
 
+		
 echo '</div>';
 
 ?>
 <!-- javascript and styles for textareaCounter-->
 <script type="text/javascript">
-    var info;
-    $(document).ready(function () {
-        var options = {
-            'maxCharacterSize':100,
-            'originalStyle':'originalTextareaInfo',
-            'warningStyle':'warningTextareaInfo',
-            'warningNumber':20,
-            'displayFormat':'#input/#max'
-        };
-        $('#textarea_google').textareaCount(options, function (data) {
-            $('#textareaCallBack').html(data);
-        });
-    });
-
-</script>
+var info;
+$(document).ready(function(){
+	var options = {
+		'maxCharacterSize': 100,
+		'originalStyle': 'originalTextareaInfo',
+		'warningStyle' : 'warningTextareaInfo',
+		'warningNumber': 20,
+		'displayFormat' : '#input/#max'
+	};
+	$('#textarea_google').textareaCount(options, function(data){
+		$('#textareaCallBack').html(data);				
+	});    
+});
+
+</script>		        
 <style>
-    .overview {
-        background: #FFEC9D;
-        padding: 10px;
-        width: 90%;
-        border: 1px solid #CCCCCC;
-    }
+.overview {
+	background: #FFEC9D;
+	padding: 10px;
+	width: 90%;
+	border: 1px solid #CCCCCC;
+}
 
-    .originalTextareaInfo {
-        font-size: 12px;
-        color: #000000;
-        text-align: right;
-    }
+.originalTextareaInfo {
+	font-size: 12px;
+	color: #000000;
+	text-align: right;
+}
 
-    .warningTextareaInfo {
-        color: #FF0000;
-        font-weight: bold;
-        text-align: right;
-    }
+.warningTextareaInfo {
+	color: #FF0000;
+	font-weight:bold;
+	text-align: right;	
+}
 
-    #showData {
-        height: 70px;
-        width: 200px;
-        border: 1px solid #CCCCCC;
-        padding: 10px;
-        margin: 10px;
-    }
+#showData {
+	height: 70px;
+	width: 200px;
+	border: 1px solid #CCCCCC;
+	padding: 10px;
+	margin: 10px;
+}
 </style>
 <div id="textareaCallBack"></div>
 <?php
-if (Security::remove_XSS($_POST['text2voice_mode']) == 'google') {
-    downloadMP3_google($filepath, $dir);
-} elseif (Security::remove_XSS($_POST['text2voice_mode']) == 'pediaphon') {
-    downloadMP3_pediaphon($filepath, $dir);
-}
-
-$tbl_admin_languages = Database :: get_main_table(TABLE_MAIN_LANGUAGE);
-$sql_select = "SELECT * FROM $tbl_admin_languages";
-$result_select = Database::query($sql_select);
-
-$options = $options_pedia = array();
-$selected_language = null;
-$options_pedia['defaultmessage'] = get_lang('FirstSelectALanguage'); //need read before platform languages
-
-while ($row = Database::fetch_array($result_select)) {
-    if (api_get_setting('platformLanguage') == $row['english_name']) {
-        //$selected_language = $row['isocode'];//lang default is the default platform language
-    }
-
-    $options[$row['isocode']] = $row['original_name'].' ('.$row['english_name'].')';
+	if(Security::remove_XSS($_POST['text2voice_mode'])=='google'){  
+    	downloadMP3_google($filepath, $dir);
+    } elseif (Security::remove_XSS($_POST['text2voice_mode']) == 'pediaphon') {
+    	downloadMP3_pediaphon($filepath, $dir);
+	}
+    
+    $tbl_admin_languages    = Database :: get_main_table(TABLE_MAIN_LANGUAGE);
+    $sql_select = "SELECT * FROM $tbl_admin_languages";
+    $result_select = Database::query($sql_select);              
+
+    $options = $options_pedia = array();
+    $selected_language = null;
+    $options_pedia['defaultmessage'] = get_lang('FirstSelectALanguage'); //need read before platform languages
+	
+    while ($row = Database::fetch_array($result_select)) {       
+        if (api_get_setting('platformLanguage')==$row['english_name']) {        
+            //$selected_language = $row['isocode'];//lang default is the default platform language
+        }
+		
+        $options[$row['isocode']] =$row['original_name'].' ('.$row['english_name'].')';
 
-    if (in_array($row['isocode'], array('de', 'en', 'es', 'fr'))) {
-        $options_pedia[$row['isocode']] = $row['original_name'].' ('.$row['english_name'].')';
+        if (in_array($row['isocode'], array('de', 'en', 'es', 'fr'))){		
+            $options_pedia[$row['isocode']] =$row['original_name'].' ('.$row['english_name'].')';
+        }        
     }
-}
-
-$icon = Display::return_icon('text2audio.png', get_lang('HelpText2Audio'), '', ICON_SIZE_MEDIUM);
-echo '<div class="page-header"><h2>'.$icon.get_lang('HelpText2Audio').'</h2></div>';
-
-
-if (Security::remove_XSS($_GET['dt2a']) == 'google') {
-    $selected_language = api_get_language_isocode(); //lang default is the course language
-    echo '<div>';
-    $form = new FormValidator('form1', 'post', null, '', array('id' => 'form1'));
-    $form->addElement('hidden', 'text2voice_mode', 'google');
-    $form->addElement('hidden', 'document_id', $document_id);
-    $form->addElement('text', 'title', get_lang('Title'));
-    $form->addElement('select', 'lang', get_lang('Language'), $options);
-    $form->addElement(
-        'textarea',
-        'text',
-        get_lang('InsertText2Audio'),
-        array('id' => 'textarea_google', 'class' => 'span6')
-    );
-    //echo Display :: return_icon('info3.gif', get_lang('HelpGoogleAudio'), array('align' => 'absmiddle', 'hspace' => '3px'), false);
-    $form->addElement('style_submit_button', 'submit', get_lang('SaveMP3'), 'class="save"');
-    $defaults = array();
-    $defaults['lang'] = $selected_language;
-    $form->setDefaults($defaults);
-    $form->display();
-
-    echo '</div>';
-}
-
-if (Security::remove_XSS($_GET['dt2a']) == 'pediaphon') {
-    //lang default is a default message
-    $selected_language = "defaultmessage";
-
-    $options['defaultmessage'] = get_lang('FirstSelectALanguage');
-    echo '<div>';
-
-    $form = new FormValidator('form2', 'post', null, '', array('id' => 'form2'));
-    $form->addElement('hidden', 'text2voice_mode', 'pediaphon');
-    $form->addElement('hidden', 'document_id', $document_id);
-    $form->addElement('text', 'title', get_lang('Title'));
-    $form->addElement(
-        'select',
-        'lang',
-        get_lang('Language'),
-        $options_pedia,
-        array('onclick' => 'update_voices(this.selectedIndex);')
-    );
-    $form->addElement('select', 'voices', get_lang('Voice'), array(get_lang('FirstSelectALanguage')), array());
-    $speed_options = array();
-    $speed_options['1'] = get_lang('Normal');
-    $speed_options['0.75'] = get_lang('GoFaster');
-    $speed_options['0.8'] = get_lang('Fast');
-    $speed_options['1.2'] = get_lang('Slow');
-    $speed_options['1.6'] = get_lang('SlowDown');
-
-    $form->addElement('select', 'speed', get_lang('Speed'), $speed_options, array());
-    $form->addElement(
-        'textarea',
-        'text',
-        get_lang('InsertText2Audio'),
-        array('id' => 'textarea_pediaphon', 'class' => 'span6')
-    );
-    //echo Display :: return_icon('info3.gif', get_lang('HelpPediaphon'), array('align' => 'absmiddle', 'hspace' => '3px'), false);
-
-    $form->addElement('style_submit_button', 'submit', get_lang('SaveMP3'), 'class="save"');
-    $defaults = array();
-    $defaults['lang'] = $selected_language;
-    $form->setDefaults($defaults);
-    $form->display();
-    echo '</div>';
-
-    ?>
-
+	
+	$icon = Display::return_icon('text2audio.png', get_lang('HelpText2Audio'),'',ICON_SIZE_MEDIUM);
+	echo '<div class="page-header"><h2>'.$icon.get_lang('HelpText2Audio').'</h2></div>'; 
+	
+  
+    if(Security::remove_XSS($_GET['dt2a'])=='google'){
+		$selected_language = api_get_language_isocode();//lang default is the course language
+		echo '<div>';
+		$form = new FormValidator('form1', 'post', null, '', array('id' => 'form1'));
+		$form->addElement('hidden', 'text2voice_mode', 'google');
+		$form->addElement('hidden', 'document_id', $document_id);
+		$form->addElement('text', 'title', get_lang('Title'));
+		$form->addElement('select', 'lang', get_lang('Language'), $options);    
+		$form->addElement('textarea', 'text', get_lang('InsertText2Audio'), array('id' => 'textarea_google', 'class' =>'span6' ));
+		//echo Display :: return_icon('info3.gif', get_lang('HelpGoogleAudio'), array('align' => 'absmiddle', 'hspace' => '3px'), false);
+		$form->addElement('style_submit_button', 'submit', get_lang('SaveMP3'), 'class="save"');
+		$defaults = array();
+		$defaults['lang'] = $selected_language;   
+		$form->setDefaults($defaults);        
+		$form->display();
+
+		echo '</div>';
+	}
+	
+	if(Security::remove_XSS($_GET['dt2a'])=='pediaphon'){
+		//lang default is a default message
+		$selected_language = "defaultmessage";
+		$options['defaultmessage'] =get_lang('FirstSelectALanguage'); 
+		echo '<div>';
+		
+		$form = new FormValidator('form2', 'post', null, '', array('id' => 'form2'));
+		$form->addElement('hidden', 'text2voice_mode','pediaphon');
+		$form->addElement('hidden', 'document_id', $document_id);
+		$form->addElement('text', 'title', get_lang('Title'));
+		$form->addElement('select', 'lang', get_lang('Language'), $options_pedia, array('onclick' => 'update_voices(this.selectedIndex);'));
+		$form->addElement('select', 'voices', get_lang('Voice'), array(get_lang('FirstSelectALanguage')), array());            
+		$speed_options = array();
+		$speed_options['1']     = get_lang('Normal');
+		$speed_options['0.75']  = get_lang('GoFaster');
+		$speed_options['0.8']   = get_lang('Fast');
+		$speed_options['1.2']   = get_lang('Slow');
+		$speed_options['1.6']   = get_lang('SlowDown');
+		
+		$form->addElement('select', 'speed', get_lang('Speed'), $speed_options, array());        
+		$form->addElement('textarea', 'text', get_lang('InsertText2Audio'), array('id' => 'textarea_pediaphon', 'class' =>'span6'));
+		//echo Display :: return_icon('info3.gif', get_lang('HelpPediaphon'), array('align' => 'absmiddle', 'hspace' => '3px'), false);
+		    
+		$form->addElement('style_submit_button', 'submit', get_lang('SaveMP3'), 'class="save"');
+		$defaults = array();
+		$defaults['lang'] = $selected_language;    
+		$form->setDefaults($defaults);        
+		$form->display();
+		echo '</div>';
+		
+		?>
+		
 <!-- javascript form name form2 update voices -->
 <script>
-    var langslist = document.form2.lang
-    var voiceslist = document.form2.voices
+    var langslist=document.form2.lang
+	var voiceslist=document.form2.voices     
     var voices = new Array();
-
-            voices[0] = ["<?php echo get_lang('FirstSelectALanguage'); ?>"]
+		
+   voices[0] = ["<?php echo get_lang('FirstSelectALanguage'); ?>"]
 
             // German
             voices[1] = ["<?php echo get_lang('Female').' (de1)'; ?>|de1", "<?php echo get_lang(
@@ -326,7 +287,7 @@ if (Security::remove_XSS($_GET['dt2a']) == 'pediaphon') {
     ).' (de6)'; ?>|de6", "<?php echo get_lang('Female').' (de7)'; ?>|de7", "<?php echo get_lang(
         'Female'
     ).' (de8 HQ)'; ?>|de8"]
-
+		
             // English
             voices[2] = ["<?php echo get_lang('Male').' (en1)'; ?>|en1", "<?php echo get_lang(
         'Male'
@@ -335,70 +296,72 @@ if (Security::remove_XSS($_GET['dt2a']) == 'pediaphon') {
     ).' (us2)'; ?>|us2", "<?php echo get_lang('Male').' (us3)'; ?>|us3", "<?php echo get_lang(
         'Female'
     ).'(us4 HQ)'; ?>|us4"]
-
+		
             //Spanish
-            voices[3] = ["<?php echo get_lang('Male').' (es5 HQ)'; ?>|es5"]
-
+		voices[3]=["<?php echo get_lang('Male').' (es5 HQ)'; ?>|es5"]
+		
             //French
-            voices[4] = ["<?php echo get_lang('Female').' (fr8 HQ)'; ?>|fr8"]
-
-
-    function update_voices(selectedvoicegroup) {
-        voiceslist.options.length = 0
-        for (i = 0; i < voices[selectedvoicegroup].length; i++)
-            voiceslist.options[voiceslist.options.length] = new Option(voices[selectedvoicegroup][i].split("|")[0], voices[selectedvoicegroup][i].split("|")[1])
-    }
-</script>
-<?php
+		voices[4]=["<?php echo get_lang('Female').' (fr8 HQ)'; ?>|fr8"]
+			
+			 
+		function update_voices(selectedvoicegroup){
+		voiceslist.options.length=0
+		for (i=0; i<voices[selectedvoicegroup].length; i++)
+			voiceslist.options[voiceslist.options.length]=new Option(voices[selectedvoicegroup][i].split("|")[0], voices[selectedvoicegroup][i].split("|")[1])
+		}
+		</script>    
+
+     
+    <?php
 }
 //end pediaphon
-
-//vozMe services
-//disabled for a time
-/*
-echo '<div>&nbsp;</div><input type="checkbox" value="1" name="checktext2voice" onclick="javascript: if(this.checked){document.getElementById(\'option3\').style.display=\'block\';}else{document.getElementById(\'option3\').style.display=\'none\';}"/>&nbsp;<img src="../img/file_sound.gif" title="'.get_lang('HelpvozMe').'" alt="'.get_lang('vozMe').'"/>&nbsp;'.get_lang('vozMe').'';
-echo '&nbsp;&nbsp;&nbsp;<span id="msg_error3" style="display:none;color:red"></span>';
-echo '<div id="option3" style="padding:4px; margin:5px; border:1px dotted; display:none;">';
-
-echo '<form id="form3" name="form3" method="post" action="http://vozme.com/text2voice.php" target="mymp3" class="formw">';
-    echo '<br/>';
-    echo '<label>'.get_lang('Language').': ';
-    $tbl_admin_languages 	= Database :: get_main_table(TABLE_MAIN_LANGUAGE);
-    $sql_select = "SELECT * FROM $tbl_admin_languages";
-    $result_select = Database::query($sql_select);
-    echo '<select name="lang" id="select">';
-    while ($row = Database::fetch_array($result_select)) {
-
-        if (in_array($row['isocode'], array('ca', 'en', 'es', 'hi', 'it', 'pt'))){
-
-            if (api_get_setting('platformLanguage')==$row['english_name']){
-                echo '<option value="'.$row['isocode'].'" selected="selected">'.$row['original_name'].' ('.$row['english_name'].')</option>';
-            }
-            else{
-                echo '<option value="'.$row['isocode'].'">'.$row['original_name'].' ('.$row['english_name'].')</option>';
-            }
-        }
-    }
-    echo '</select>';
-    echo '</label>';
-    echo '<label>&nbsp;&nbsp;'.get_lang('Voice').': ';
-    echo '<select name="gn" id="select1">';
-    echo '<option value="ml">'.get_lang('Male').'</option>';
-    echo '<option value="fm">'.get_lang('Female').'</option>';
-    echo '</select>';
-    echo '</label>';
-    echo '<br/><br/>';
-    echo '<div>'.get_lang('InsertText2Audio').'</div>';
-    echo '<br/>';
-    echo '<label>';
-    echo '<textarea name="text" id="textarea" cols="70" rows="10"></textarea>';
-    echo '</label>';
-    echo '<br/><br/>';
-    echo '<button class="save" type="submit" name="SendText2Audio">'.get_lang('BuildMP3').'</button>';
-    echo '<br/>';
-echo '</form>';
-echo '</div>';
-*/
+	
+	//vozMe services
+		//disabled for a time
+	/*
+	echo '<div>&nbsp;</div><input type="checkbox" value="1" name="checktext2voice" onclick="javascript: if(this.checked){document.getElementById(\'option3\').style.display=\'block\';}else{document.getElementById(\'option3\').style.display=\'none\';}"/>&nbsp;<img src="../img/file_sound.gif" title="'.get_lang('HelpvozMe').'" alt="'.get_lang('vozMe').'"/>&nbsp;'.get_lang('vozMe').'';
+	echo '&nbsp;&nbsp;&nbsp;<span id="msg_error3" style="display:none;color:red"></span>';
+	echo '<div id="option3" style="padding:4px; margin:5px; border:1px dotted; display:none;">';
+	
+	echo '<form id="form3" name="form3" method="post" action="http://vozme.com/text2voice.php" target="mymp3" class="formw">';
+		echo '<br/>';
+		echo '<label>'.get_lang('Language').': ';
+		$tbl_admin_languages 	= Database :: get_main_table(TABLE_MAIN_LANGUAGE);
+		$sql_select = "SELECT * FROM $tbl_admin_languages";
+		$result_select = Database::query($sql_select);		
+		echo '<select name="lang" id="select">';
+		while ($row = Database::fetch_array($result_select)) {
+			
+			if (in_array($row['isocode'], array('ca', 'en', 'es', 'hi', 'it', 'pt'))){
+			
+				if (api_get_setting('platformLanguage')==$row['english_name']){
+					echo '<option value="'.$row['isocode'].'" selected="selected">'.$row['original_name'].' ('.$row['english_name'].')</option>';
+				}
+				else{					
+					echo '<option value="'.$row['isocode'].'">'.$row['original_name'].' ('.$row['english_name'].')</option>';
+				}
+			}
+		}
+		echo '</select>';
+		echo '</label>';
+		echo '<label>&nbsp;&nbsp;'.get_lang('Voice').': ';
+		echo '<select name="gn" id="select1">';
+		echo '<option value="ml">'.get_lang('Male').'</option>';
+		echo '<option value="fm">'.get_lang('Female').'</option>';
+		echo '</select>';
+		echo '</label>';
+		echo '<br/><br/>';
+		echo '<div>'.get_lang('InsertText2Audio').'</div>';
+		echo '<br/>';
+		echo '<label>';
+		echo '<textarea name="text" id="textarea" cols="70" rows="10"></textarea>';
+		echo '</label>';  
+		echo '<br/><br/>';  
+		echo '<button class="save" type="submit" name="SendText2Audio">'.get_lang('BuildMP3').'</button>';
+		echo '<br/>';
+	echo '</form>';
+	echo '</div>';
+	*/
 echo '</div>';
 
 Display :: display_footer();
@@ -415,51 +378,48 @@ Display :: display_footer();
  */
 function downloadMP3_google($filepath, $dir)
 {
-    $location = 'create_audio.php?'.api_get_cidreq().'&id='.Security::remove_XSS($_POST['document_id']).'&dt2a=google';
-
-    //security
-    if (!isset($_POST['lang']) && !isset($_POST['text']) && !isset($_POST['title']) && !isset($filepath) && !isset($dir)) {
-        echo '<script>window.location.href="'.$location.'"</script>';
+	$location='create_audio.php?'.api_get_cidreq().'&id='.Security::remove_XSS($_POST['document_id']).'&dt2a=google';
 
-        return;
-    }
+	//security
+	if (!isset($_POST['lang']) && !isset($_POST['text']) && !isset($_POST['title']) && !isset($filepath) && !isset($dir)) {
+		echo '<script>window.location.href="'.$location.'"</script>';
+		return;	
+	}
     global $_user;
     $_course = api_get_course_info();
-
-    $clean_title = trim($_POST['title']);
-    $clean_text = trim($_POST['text']);
-    if (empty($clean_title) || empty($clean_text)) {
-        echo '<script>window.location.href="'.$location.'"</script>';
-
-        return;
-    }
-    $clean_title = Security::remove_XSS($clean_title);
-    $clean_title = Database::escape_string($clean_title);
-    $clean_title = str_replace(' ', '_', $clean_title); //compound file names
-
-    $clean_text = Security::remove_XSS($clean_text);
-    $clean_lang = Security::remove_XSS($_POST['lang']);
-
-    $extension = 'mp3';
-    $audio_filename = $clean_title.'.'.$extension;
-    $audio_title = str_replace('_', ' ', $clean_title);
-
-    //prevent duplicates
-    if (file_exists($filepath.'/'.$clean_title.'.'.$extension)) {
-        $i = 1;
+	$clean_title=trim($_POST['title']);
+	$clean_text=trim($_POST['text']);
+	if(empty($clean_title) || empty($clean_text)){ 
+		echo '<script>window.location.href="'.$location.'"</script>';
+		return;
+	}
+	$clean_title=Security::remove_XSS($clean_title);
+	$clean_title=Database::escape_string($clean_title);	
+	$clean_title=str_replace(' ','_', $clean_title);//compound file names
+	
+	$clean_text=Security::remove_XSS($clean_text);
+	$clean_lang=Security::remove_XSS($_POST['lang']);	
+	
+	$extension='mp3';
+	$audio_filename=$clean_title.'.'.$extension;	
+	$audio_title = str_replace('_',' ',$clean_title);
+	
+	//prevent duplicates
+	if (file_exists($filepath.'/'.$clean_title.'.'.$extension)){ 
+		$i = 1;		
         while (file_exists($filepath.'/'.$clean_title.'_'.$i.'.'.$extension)) {
             $i++;
         }
-        $audio_filename = $clean_title.'_'.$i.'.'.$extension;
-        $audio_title = $clean_title.'_'.$i.'.'.$extension;
-        $audio_title = str_replace('_', ' ', $audio_title);
-    }
-
-    $documentPath = $filepath.'/'.$audio_filename;
-
-
-    //prev for a fine unicode, borrowed from main api TODO:clean
-    // Safe replacements for some non-letter characters (whitout blank spaces)
+		$audio_filename = $clean_title . '_' . $i . '.'.$extension;
+		$audio_title = $clean_title . '_' . $i . '.'.$extension;
+		$audio_title = str_replace('_',' ',$audio_title);
+	}
+
+	$documentPath = $filepath.'/'.$audio_filename;
+	
+	
+	//prev for a fine unicode, borrowed from main api TODO:clean
+	// Safe replacements for some non-letter characters (whitout blank spaces)
     $search = array(
         "\0",
         "\t",
@@ -514,16 +474,15 @@ function downloadMP3_google($filepath, $dir)
         '-',
         '-'
     );
-    $filename = $clean_text;
-    // Encoding detection.
-    $encoding = api_detect_encoding($filename);
-    // Converting html-entities into encoded characters.
-    $filename = api_html_entity_decode($filename, ENT_QUOTES, $encoding);
-    // Transliteration to ASCII letters, they are not dangerous for filesystems.
-    $filename = api_transliterate($filename, 'x', $encoding);
+	$filename=$clean_text;
+	// Encoding detection.
+	$encoding = api_detect_encoding($filename);
+	// Converting html-entities into encoded characters.
+	$filename = api_html_entity_decode($filename, ENT_QUOTES, $encoding);
+	// Transliteration to ASCII letters, they are not dangerous for filesystems.
+	$filename = api_transliterate($filename, 'x', $encoding);
     // Replacing remaining dangerous non-letter characters.
     $clean_text = str_replace($search, $replace, $filename);
-
     $returntext2voice = file_get_contents(
         "http://translate.google.com/translate_tts?tl=".$clean_lang."&q=".urlencode($clean_text).""
     );
@@ -540,16 +499,15 @@ function downloadMP3_google($filepath, $dir)
     }
     //erase temporal file
     unlink($tmpfname);
-
-
-    //adding the file
-    //add new file to disk
+	
+	//adding the file
+		//add new file to disk
     file_put_contents($documentPath, $returntext2voice);
-    //add document to database
-    $current_session_id = api_get_session_id();
-    $groupId = $_SESSION['_gid'];
-    $file_size = filesize($documentPath);
-    $relativeUrlPath = $dir;
+		//add document to database
+		$current_session_id = api_get_session_id();
+		$groupId=$_SESSION['_gid'];
+		$file_size = filesize($documentPath);
+		$relativeUrlPath=$dir;
     $doc_id = FileManager::add_document(
         $_course,
         $relativeUrlPath.$audio_filename,
@@ -569,9 +527,9 @@ function downloadMP3_google($filepath, $dir)
         null,
         $current_session_id
     );
-    Display::display_confirmation_message(get_lang('DocumentCreated'));
-    //return to location
-    echo '<script>window.location.href="'.$location.'"</script>';
+        Display::display_confirmation_message(get_lang('DocumentCreated'));
+	//return to location
+	echo '<script>window.location.href="'.$location.'"</script>';
 }
 
 /**
@@ -587,50 +545,50 @@ function downloadMP3_pediaphon($filepath, $dir)
     $location = 'create_audio.php?'.api_get_cidreq().'&id='.Security::remove_XSS(
         $_POST['document_id']
     ).'&dt2a=pediaphon';
-    //security
-    if (!isset($_POST['lang']) && !isset($_POST['text']) && !isset($_POST['title']) && !isset($filepath) && !isset($dir)) {
-        echo '<script>window.location.href="'.$location.'"</script>';
-
-        return;
-    }
+	//security
+	if(!isset($_POST['lang']) && !isset($_POST['text']) && !isset($_POST['title']) && !isset($filepath) && !isset($dir)) {
+		echo '<script>window.location.href="'.$location.'"</script>';
+		return;	
+	}
     global $_user;
     $_course = api_get_course_info();
-    $clean_title = trim($_POST['title']);
-    $clean_title = Database::escape_string($clean_title);
-    $clean_text = trim($_POST['text']);
-    $clean_voices = Security::remove_XSS($_POST['voices']);
-    if (empty($clean_title) || empty($clean_text) || empty($clean_voices)) {
-        echo '<script>window.location.href="'.$location.'"</script>';
-
-        return;
-    }
-    $clean_title = Security::remove_XSS($clean_title);
-    $clean_title = Database::escape_string($clean_title);
-    $clean_title = str_replace(' ', '_', $clean_title); //compound file names
-    $clean_text = Security::remove_XSS($clean_text);
-    $clean_lang = Security::remove_XSS($_POST['lang']);
-    $clean_speed = Security::remove_XSS($_POST['speed']);
-
-    $extension = 'mp3';
-    $audio_filename = $clean_title.'.'.$extension;
-    $audio_title = str_replace('_', ' ', $clean_title);
-
-    //prevent duplicates
-    if (file_exists($filepath.'/'.$clean_title.'.'.$extension)) {
-        $i = 1;
+	$clean_title=trim($_POST['title']);
+	$clean_title= Database::escape_string($clean_title);
+	$clean_text=trim($_POST['text']);
+	$clean_voices=Security::remove_XSS($_POST['voices']);
+	if(empty($clean_title) || empty($clean_text) || empty($clean_voices)){
+		echo '<script>window.location.href="'.$location.'"</script>';
+		return;
+	}
+	$clean_title=Security::remove_XSS($clean_title);
+	$clean_title=Database::escape_string($clean_title);	
+	$clean_title=str_replace(' ','_', $clean_title);//compound file names
+	$clean_text=Security::remove_XSS($clean_text);
+	$clean_lang=Security::remove_XSS($_POST['lang']);
+	$clean_speed=Security::remove_XSS($_POST['speed']);
+	
+	$extension='mp3';
+	$audio_filename=$clean_title.'.'.$extension;
+	$audio_title = str_replace('_',' ',$clean_title);
+	
+	//prevent duplicates
+	if (file_exists($filepath.'/'.$clean_title.'.'.$extension)){ 
+		$i = 1;		
         while (file_exists($filepath.'/'.$clean_title.'_'.$i.'.'.$extension)) {
             $i++;
         }
-        $audio_filename = $clean_title.'_'.$i.'.'.$extension;
-        $audio_title = $clean_title.'_'.$i.'.'.$extension;
-        $audio_title = str_replace('_', ' ', $audio_title);
-    }
+		$audio_filename = $clean_title . '_' . $i . '.'.$extension;
+		$audio_title = $clean_title . '_' . $i . '.'.$extension;
+		$audio_title = str_replace('_',' ',$audio_title);
+	}
+
+	$documentPath = $filepath.'/'.$audio_filename;
+	
 
-    $documentPath = $filepath.'/'.$audio_filename;
 
 
-    //prev for a fine unicode, borrowed from main api TODO:clean
-    // Safe replacements for some non-letter characters (whitout blank spaces)
+	//prev for a fine unicode, borrowed from main api TODO:clean
+	// Safe replacements for some non-letter characters (whitout blank spaces)
     $search = array(
         "\0",
         "\t",
@@ -685,87 +643,86 @@ function downloadMP3_pediaphon($filepath, $dir)
         '-',
         '-'
     );
-    $filename = $clean_text;
-    // Encoding detection.
-    $encoding = api_detect_encoding($filename);
-    // Converting html-entities into encoded characters.
-    $filename = api_html_entity_decode($filename, ENT_QUOTES, $encoding);
-    // Transliteration to ASCII letters, they are not dangerous for filesystems.
-    $filename = api_transliterate($filename, 'x', $encoding);
+	$filename=$clean_text;
+	// Encoding detection.
+	$encoding = api_detect_encoding($filename);
+	// Converting html-entities into encoded characters.
+	$filename = api_html_entity_decode($filename, ENT_QUOTES, $encoding);
+	// Transliteration to ASCII letters, they are not dangerous for filesystems.
+	$filename = api_transliterate($filename, 'x', $encoding);
     // Replacing remaining dangerous non-letter characters.
     $clean_text = str_replace($search, $replace, $filename);
-
-    //adding the file
-
-
-    if ($clean_lang == 'de') {
-        $url_pediaphon = 'http://www.pediaphon.org/~bischoff/radiopedia/sprich_multivoice.cgi';
-        $find_t2v = '/http\:\/\/www\.pediaphon\.org\/\~bischoff\/radiopedia\/mp3\/(.*)\.mp3\"/';
+	
+	//adding the file
+	
+		
+		if($clean_lang=='de'){
+			$url_pediaphon='http://www.pediaphon.org/~bischoff/radiopedia/sprich_multivoice.cgi';
+			$find_t2v = '/http\:\/\/www\.pediaphon\.org\/\~bischoff\/radiopedia\/mp3\/(.*)\.mp3\"/';
     } else {
-        $url_pediaphon = 'http://www.pediaphon.org/~bischoff/radiopedia/sprich_multivoice_'.$clean_lang.'.cgi'; //en, es, fr
-        $find_t2v = '/http\:\/\/www\.pediaphon\.org\/\~bischoff\/radiopedia\/mp3\/'.$clean_lang.'\/(.*)\.mp3\"/';
-    }
-
-    $data = "stimme=".$clean_voices."&inputtext=".$clean_text."&speed=".$clean_speed."&go=go";
-    $opts = array(
-        'http' =>
-        array(
-            'method' => 'POST',
-            'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
-            "Content-Length: ".strlen($data)."\r\n",
-            'content' => $data
-        )
-    );
-    $context = stream_context_create($opts);
-    $previous_returntext2voice = file_get_contents($url_pediaphon, false, $context);
-
-    //clean file contents
-
-    $search_source = preg_match($find_t2v, $previous_returntext2voice, $hits);
-    $souce_end = substr($hits[0], 0, -1);
-    $returntext2voice = file_get_contents($souce_end);
-
-    //make a temporal file for get the file size
-    $tmpfname = tempnam("/tmp", "CTF");
-    $handle = fopen($tmpfname, "w");
-    fwrite($handle, $returntext2voice);
-    fclose($handle);
-    // Check if there is enough space in the course to save the file
-    if (!DocumentManager::enough_space(filesize($tmpfname), DocumentManager::get_course_quota())) {
+			$url_pediaphon='http://www.pediaphon.org/~bischoff/radiopedia/sprich_multivoice_'.$clean_lang.'.cgi';//en, es, fr
+			$find_t2v = '/http\:\/\/www\.pediaphon\.org\/\~bischoff\/radiopedia\/mp3\/'.$clean_lang.'\/(.*)\.mp3\"/';
+		}
+
+		$data="stimme=".$clean_voices."&inputtext=".$clean_text."&speed=".$clean_speed."&go=go";
+        $opts = array(
+            'http' =>
+			    array(
+			         'method'  => 'POST',
+			         'header'  =>"Content-Type: application/x-www-form-urlencoded\r\n",
+			         "Content-Length: " . strlen($data) . "\r\n",
+			         'content' => $data
+			    )
+		);                   
+		$context  = stream_context_create($opts);
+		$previous_returntext2voice = file_get_contents($url_pediaphon,false,$context);
+		
+		//clean file contents
+		
+		$search_source=preg_match($find_t2v, $previous_returntext2voice, $hits);
+		$souce_end=substr($hits[0], 0,-1);
+		$returntext2voice = file_get_contents($souce_end);
+        //make a temporal file for get the file size
+        $tmpfname = tempnam("/tmp", "CTF");
+        $handle = fopen($tmpfname, "w");
+        fwrite($handle, $returntext2voice);
+        fclose($handle);
+        // Check if there is enough space in the course to save the file
+        if (!DocumentManager::enough_space(filesize($tmpfname), DocumentManager::get_course_quota())) {
+            unlink($tmpfname);
+            die(get_lang('UplNotEnoughSpace'));
+        }
+        //erase temporal file
         unlink($tmpfname);
-        die(get_lang('UplNotEnoughSpace'));
-    }
-    //erase temporal file
-    unlink($tmpfname);
-
-    //save file
-    file_put_contents($documentPath, $returntext2voice);
-
-    //add document to database
-    $current_session_id = api_get_session_id();
-    $groupId = $_SESSION['_gid'];
-    $file_size = filesize($documentPath);
-    $relativeUrlPath = $dir;
-    $doc_id = FileManager::add_document(
-        $_course,
-        $relativeUrlPath.$audio_filename,
-        'file',
-        filesize($documentPath),
-        $audio_title
-    );
-    api_item_property_update(
-        $_course,
-        TOOL_DOCUMENT,
-        $doc_id,
-        'DocumentAdded',
-        $_user['user_id'],
-        $groupId,
-        null,
-        null,
-        null,
-        $current_session_id
-    );
-    Display::display_confirmation_message(get_lang('DocumentCreated'));
-    //return to location
-    echo '<script>window.location.href="'.$location.'"</script>';
+				
+		//save file
+		file_put_contents($documentPath, $returntext2voice);
+		
+		//add document to database
+		$current_session_id = api_get_session_id();
+		$groupId=$_SESSION['_gid'];
+		$file_size = filesize($documentPath);
+		$relativeUrlPath=$dir;
+        $doc_id = FileManager::add_document(
+            $_course,
+            $relativeUrlPath.$audio_filename,
+            'file',
+            filesize($documentPath),
+            $audio_title
+        );
+        api_item_property_update(
+            $_course,
+            TOOL_DOCUMENT,
+            $doc_id,
+            'DocumentAdded',
+            $_user['user_id'],
+            $groupId,
+            null,
+            null,
+            null,
+            $current_session_id
+        );
+        Display::display_confirmation_message(get_lang('DocumentCreated'));
+	//return to location
+	echo '<script>window.location.href="'.$location.'"</script>';
 }

+ 61 - 182
main/document/document.php

@@ -6,19 +6,19 @@
  * This script allows the user to manage files and directories on a remote http
  * server.
  * The user can : - navigate through files and directories.
- *                  - upload a file
- *                  - delete, copy a file or a directory
- *                  - edit properties & content (name, comments, html content)
+ * 				 - upload a file
+ * 				 - delete, copy a file or a directory
+ * 				 - edit properties & content (name, comments, html content)
  * The script is organised in four sections.
  *
  * 1) Execute the command called by the user
- *                 Note: somme commands of this section are organised in two steps.
- *                 The script always begins with the second step,
- *                 so it allows to return more easily to the first step.
+ * 				Note: somme commands of this section are organised in two steps.
+ * 			    The script always begins with the second step,
+ * 			    so it allows to return more easily to the first step.
  *
- *                 Note (March 2004) some editing functions (renaming, commenting)
- *                 are moved to a separate page, edit_document.php. This is also
- *                 where xml and other stuff should be added.
+ * 				Note (March 2004) some editing functions (renaming, commenting)
+ * 				are moved to a separate page, edit_document.php. This is also
+ * 				where xml and other stuff should be added.
  * 2) Define the directory to display
  * 3) Read files and directories from the directory defined in part 2
  * 4) Display all of that on an HTML page
@@ -29,14 +29,10 @@
 /**
  * Code
  */
-
 // Language files that need to be included
 $language_file = array('document', 'slideshow', 'gradebook', 'create_course');
-
 require_once '../inc/global.inc.php';
-
 $parent_id = null;
-
 $current_course_tool = TOOL_DOCUMENT;
 $this_section = SECTION_COURSES;
 
@@ -124,10 +120,7 @@ if (api_get_group_id()) {
         // Documents are public
         $to_group_id = api_get_group_id();
         $interbreadcrumb[] = array('url' => '../group/group.php', 'name' => get_lang('Groups'));
-        $interbreadcrumb[] = array(
-            'url' => '../group/group_space.php?gidReq='.api_get_group_id(),
-            'name' => get_lang('GroupSpace').' '.$group_properties['name']
-        );
+        $interbreadcrumb[] = array('url' => '../group/group_space.php?gidReq='.api_get_group_id(), 'name' => get_lang('GroupSpace').' '.$group_properties['name']);
         //allowed to upload?
         if ($is_allowed_to_edit || GroupManager::is_subscribed(api_get_user_id(), api_get_group_id())) {
             // Only courseadmin or group members can upload
@@ -178,19 +171,12 @@ switch ($action) {
         exit;
         break;
     case 'downloadfolder' :
-        if (api_get_setting('students_download_folders') == 'true' || api_is_allowed_to_edit() || api_is_platform_admin(
-        )
-        ) {
+        if (api_get_setting('students_download_folders') == 'true' || api_is_allowed_to_edit() || api_is_platform_admin()) {
             $document_data = DocumentManager::get_document_data_by_id($document_id, api_get_course_id());
 
             //filter when I am into shared folder, I can donwload only my shared folder
             if (is_any_user_shared_folder($document_data['path'], $session_id)) {
-                if (is_my_shared_folder(
-                    api_get_user_id(),
-                    $document_data['path'],
-                    $session_id
-                ) || api_is_allowed_to_edit() || api_is_platform_admin()
-                ) {
+                if (is_my_shared_folder(api_get_user_id(), $document_data['path'], $session_id) || api_is_allowed_to_edit() || api_is_platform_admin()) {
                     require 'downloadfolder.inc.php';
                 }
             } else {
@@ -228,19 +214,12 @@ switch ($action) {
             if (empty($parent_id)) {
                 $parent_id = 0;
             }
-            $file_link = Display::url(
-                get_lang('SeeFile'),
-                api_get_path(
-                    WEB_CODE_PATH
-                ).'social/myfiles.php?cidReq='.$cidReq.'&amp;id_session='.$id_session.'&amp;gidReq='.$gidReq.'&amp;parent_id='.$parent_id
-            );
+            $file_link = Display::url(get_lang('SeeFile'), api_get_path(WEB_CODE_PATH).'social/myfiles.php?cidReq='.$cidReq.'&amp;id_session='.$id_session.'&amp;gidReq='.$gidReq.'&amp;parent_id='.$parent_id);
 
             if (file_exists($copyfile)) {
                 $message = get_lang('CopyAlreadyDone').'</p><p>';
-                $message .= '<a class = "btn" href="'.api_get_self().'?'.api_get_cidreq(
-                ).'&amp;id='.$parent_id.'">'.get_lang("No").'</a>&nbsp;&nbsp;|&nbsp;&nbsp;
-                    <a class = "btn" href="'.api_get_self().'?'.api_get_cidreq(
-                ).'&amp;action=copytomyfiles&amp;id='.$document_info['id'].'&amp;copy=yes">'.get_lang('Yes').'</a></p>';
+                $message .= '<a class = "btn" href="'.api_get_self().'?'.api_get_cidreq().'&amp;id='.$parent_id.'">'.get_lang("No").'</a>&nbsp;&nbsp;|&nbsp;&nbsp;
+                    <a class = "btn" href="'.api_get_self().'?'.api_get_cidreq().'&amp;action=copytomyfiles&amp;id='.$document_info['id'].'&amp;copy=yes">'.get_lang('Yes').'</a></p>';
                 if (!isset($_GET['copy'])) {
                     $message = Display::return_message($message, 'warning', false);
                 }
@@ -248,15 +227,10 @@ switch ($action) {
                     if (!copy($file, $copyfile)) {
                         $message = Display::return_message(get_lang('CopyFailed'), 'error');
                     } else {
-                        $message = Display::return_message(
-                            get_lang('OverwritenFile').' '.$file_link,
-                            'confirmation',
-                            false
-                        );
+                        $message = Display::return_message(get_lang('OverwritenFile').' '.$file_link, 'confirmation', false);
                     }
                 }
             } else {
-
                 if (!copy($file, $copyfile)) {
                     $message = Display::return_message(get_lang('CopyFailed'), 'error');
                 } else {
@@ -285,18 +259,11 @@ if (isset($document_id) && empty($action)) {
         $parent_id = $document_data['parent_id'];
 
         //$visibility = DocumentManager::is_visible_by_id($document_id, $course_info, api_get_session_id(), api_get_user_id());
-        $visibility = DocumentManager::check_visibility_tree(
-            $document_id,
-            api_get_course_id(),
-            api_get_session_id(),
-            api_get_user_id()
-        );
+        $visibility = DocumentManager::check_visibility_tree($document_id, api_get_course_id(), api_get_session_id(), api_get_user_id());
 
         if (!empty($document_data['filetype']) && $document_data['filetype'] == 'file') {
             if ($visibility && api_is_allowed_to_session_edit()) {
-                $url = api_get_path(
-                    WEB_COURSE_PATH
-                ).$course_info['path'].'/document'.$document_data['path'].'?'.api_get_cidreq();
+                $url = api_get_path(WEB_COURSE_PATH).$course_info['path'].'/document'.$document_data['path'].'?'.api_get_cidreq();
                 header("Location: $url");
             }
             exit;
@@ -383,25 +350,15 @@ if (isset($_GET['curdirpath']) && $_GET['curdirpath'] == '/certificates' && isse
         $new_content_html = str_replace('../images/gallery', $path_image, $new_content_html);
 
         $path_image_in_default_course = api_get_path(WEB_CODE_PATH).'default_course_document';
-        $new_content_html = str_replace(
-            '/main/default_course_document',
-            $path_image_in_default_course,
-            $new_content_html
-        );
+        $new_content_html = str_replace('/main/default_course_document', $path_image_in_default_course, $new_content_html);
         $new_content_html = str_replace('/main/img/', api_get_path(WEB_IMG_PATH), $new_content_html);
 
         Display::display_reduced_header();
 
         echo '<style>body {background:none;}</style><style media="print" type="text/css"> #print_div { visibility:hidden; } </style>';
-        echo '<a href="javascript:window.print();" style="float:right; padding:4px;" id="print_div"><img src="../img/printmgr.gif" alt="'.get_lang(
-            'Print'
-        ).'"/>'.get_lang('Print').'</a>';
+        echo '<a href="javascript:window.print();" style="float:right; padding:4px;" id="print_div"><img src="../img/printmgr.gif" alt="'.get_lang('Print').'"/>'.get_lang('Print').'</a>';
         if (is_file($qr_code_filename) && is_readable($qr_code_filename)) {
-            $new_content_html = str_replace(
-                '((certificate_barcode))',
-                Display::img($qr_code_web_filename),
-                $new_content_html
-            );
+            $new_content_html = str_replace('((certificate_barcode))', Display::img($qr_code_web_filename), $new_content_html);
         }
         print_r($new_content_html);
         exit;
@@ -578,6 +535,7 @@ $htmlHeadXtra[] = '<link rel="stylesheet" href="'.$js_path.'jquery-jplayer/skins
 $htmlHeadXtra[] = '<script type="text/javascript" src="'.$js_path.'jquery-jplayer/jquery.jplayer.min.js"></script>';
 //$htmlHeadXtra[] = '<script type="text/javascript" src="'.$js_path.'jquery-jplayer/jquery.jplayer.inspector.js"></script>';
 
+$to_group_id = api_get_group_id();
 $mediaplayer_path = api_get_path(WEB_LIBRARY_PATH).'mediaplayer/player.swf';
 $docs_and_folders = DocumentManager::get_all_document_data(
     $course_info,
@@ -625,7 +583,6 @@ $(document).ready( function() {
 
 Display::display_header('', 'Doc');
 
-
 // Lib for event log, stats & tracking & record of the access
 event_access_tool(TOOL_DOCUMENT);
 
@@ -852,11 +809,7 @@ if ($is_allowed_to_edit || $group_member_with_upload_rights || is_my_shared_fold
                 }
 
                 foreach ($_POST['path'] as $index => & $path) {
-                    if (in_array(
-                        $path,
-                        array('/audio', '/flash', '/images', '/shared_folder', '/video', '/chat_files', '/certificates')
-                    )
-                    ) {
+                    if (in_array($path, array('/audio', '/flash', '/images', '/shared_folder', '/video', '/chat_files', '/certificates'))) {
                         continue;
                     } else {
                         $delete_document = DocumentManager::delete_document($_course, $path, $base_work_dir);
@@ -872,12 +825,7 @@ if ($is_allowed_to_edit || $group_member_with_upload_rights || is_my_shared_fold
 
 /* 	CREATE DIRECTORY */
 //Only teacher and all users into their group and any user into his/her shared folder
-if ($is_allowed_to_edit || $group_member_with_upload_rights || is_my_shared_folder(
-    api_get_user_id(),
-    $curdirpath,
-    $session_id
-)
-) {
+if ($is_allowed_to_edit || $group_member_with_upload_rights || is_my_shared_folder(api_get_user_id(), $curdirpath, $session_id)) {
     // Create directory with $_POST data
 
     if (isset($_POST['create_dir']) && $_POST['dirname'] != '') {
@@ -981,12 +929,7 @@ if ($is_allowed_to_edit) {
 
 /* 	TEMPLATE ACTION */
 //Only teacher and all users into their group
-if ($is_allowed_to_edit || $group_member_with_upload_rights || is_my_shared_folder(
-    api_get_user_id(),
-    $curdirpath,
-    $session_id
-)
-) {
+if ($is_allowed_to_edit || $group_member_with_upload_rights || is_my_shared_folder(api_get_user_id(), $curdirpath, $session_id)) {
     if (isset($_GET['add_as_template']) && !isset($_POST['create_template'])) {
 
         $document_id_for_template = intval($_GET['add_as_template']);
@@ -1025,6 +968,7 @@ if ($is_allowed_to_edit || $group_member_with_upload_rights || is_my_shared_fold
         }
         // Upload the file
         if (!empty($_FILES['template_image']['name'])) {
+
             $upload_ok = FileManager::process_uploaded_file($_FILES['template_image']);
 
             if ($upload_ok) {
@@ -1076,10 +1020,7 @@ if ($is_allowed_to_edit || $group_member_with_upload_rights || is_my_shared_fold
 
 // END ACTION MENU
 // Attach certificate in the gradebook
-if (isset($_GET['curdirpath']) && $_GET['curdirpath'] == '/certificates' && isset($_GET['set_certificate']) && $_GET['set_certificate'] == strval(
-    intval($_GET['set_certificate'])
-)
-) {
+if (isset($_GET['curdirpath']) && $_GET['curdirpath'] == '/certificates' && isset($_GET['set_certificate']) && $_GET['set_certificate'] == strval(intval($_GET['set_certificate']))) {
     if (isset($_GET['cidReq'])) {
         $course_id = Security::remove_XSS($_GET['cidReq']); // course id
         $document_id = Security::remove_XSS($_GET['set_certificate']); // document id
@@ -1090,42 +1031,17 @@ if (isset($_GET['curdirpath']) && $_GET['curdirpath'] == '/certificates' && isse
 
 /* 	GET ALL DOCUMENT DATA FOR CURDIRPATH */
 if (isset($_GET['keyword']) && !empty($_GET['keyword'])) {
-    $docs_and_folders = DocumentManager::get_all_document_data(
-        $_course,
-        $curdirpath,
-        $to_group_id,
-        null,
-        $is_allowed_to_edit || $group_member_with_upload_rights,
-        true
-    );
+    $docs_and_folders = DocumentManager::get_all_document_data($_course, $curdirpath, $to_group_id, null, $is_allowed_to_edit || $group_member_with_upload_rights, true);
 } else {
-    $docs_and_folders = DocumentManager::get_all_document_data(
-        $_course,
-        $curdirpath,
-        $to_group_id,
-        null,
-        $is_allowed_to_edit || $group_member_with_upload_rights,
-        false
-    );
+    $docs_and_folders = DocumentManager::get_all_document_data($_course, $curdirpath, $to_group_id, null, $is_allowed_to_edit || $group_member_with_upload_rights, false);
 }
 if (api_get_group_id() != 0) {
-    if (api_is_allowed_to_edit() || GroupManager::is_subscribed(api_get_user_id(), api_get_group_id()) || GroupManager :: is_tutor_of_group(
-        api_get_user_id(),
-        api_get_group_id()
-    ) || UserManager::is_admin(api_get_user_id())
-    ) {
-        $folders = DocumentManager::get_all_document_folders(
-            $_course,
-            api_get_group_id(),
-            $is_allowed_to_edit || $group_member_with_upload_rights
-        );
+
+    if (api_is_allowed_to_edit() || GroupManager::is_subscribed(api_get_user_id(), api_get_group_id()) || GroupManager :: is_tutor_of_group(api_get_user_id(), api_get_group_id())) {
+        $folders = DocumentManager::get_all_document_folders($_course, api_get_group_id(), $is_allowed_to_edit || $group_member_with_upload_rights);
     }
 } else {
-    $folders = DocumentManager::get_all_document_folders(
-        $_course,
-        api_get_group_id(),
-        $is_allowed_to_edit || $group_member_with_upload_rights
-    );
+    $folders = DocumentManager::get_all_document_folders($_course, api_get_group_id(), $is_allowed_to_edit || $group_member_with_upload_rights);
 }
 
 
@@ -1156,22 +1072,15 @@ if ($curdirpath != '/' && $curdirpath != $group_properties['directory'] && !$is_
 
 if ($is_certificate_mode && $curdirpath != '/certificates') {
     ?>
-    <a href="<?php echo api_get_self(); ?>?<?php echo api_get_cidreq(); ?>&amp;curdirpath=<?php echo urlencode(
-        (dirname($curdirpath) == '\\') ? '/' : dirname($curdirpath)
-    ); ?>">
-        <?php Display::display_icon('folder_up.png', get_lang('Up'), '', ICON_SIZE_MEDIUM); ?></a>
-<?php
+    <a href="<?php echo api_get_self(); ?>?<?php echo api_get_cidreq(); ?>&amp;curdirpath=<?php echo urlencode((dirname($curdirpath) == '\\') ? '/' : dirname($curdirpath)); ?>">
+    <?php Display::display_icon('folder_up.png', get_lang('Up'), '', ICON_SIZE_MEDIUM); ?></a>
+    <?php
 }
 
 
 $column_show = array();
 
-if ($is_allowed_to_edit || $group_member_with_upload_rights || is_my_shared_folder(
-    api_get_user_id(),
-    $curdirpath,
-    $session_id
-)
-) {
+if ($is_allowed_to_edit || $group_member_with_upload_rights || is_my_shared_folder(api_get_user_id(), $curdirpath, $session_id)) {
 
     // TODO:check enable more options for shared folders
     /* CREATE NEW DOCUMENT OR NEW DIRECTORY / GO TO UPLOAD / DOWNLOAD ZIPPED FOLDER */
@@ -1180,15 +1089,15 @@ if ($is_allowed_to_edit || $group_member_with_upload_rights || is_my_shared_fold
     if (!$is_certificate_mode) {
         ?>
         <a href="create_document.php?<?php echo api_get_cidreq(); ?>&id=<?php echo $document_id; ?>">
-            <?php Display::display_icon('new_document.png', get_lang('CreateDoc'), '', ICON_SIZE_MEDIUM); ?></a>
+        <?php Display::display_icon('new_document.png', get_lang('CreateDoc'), '', ICON_SIZE_MEDIUM); ?></a>
         <?php
         // Create new draw
         if (api_get_setting('enabled_support_svg') == 'true') {
             if (api_browser_support('svg')) {
                 ?>
                 <a href="create_draw.php?<?php echo api_get_cidreq(); ?>&id=<?php echo $document_id; ?>">
-                    <?php Display::display_icon('new_draw.png', get_lang('Draw'), '', ICON_SIZE_MEDIUM); ?></a>&nbsp;
-            <?php
+                <?php Display::display_icon('new_draw.png', get_lang('Draw'), '', ICON_SIZE_MEDIUM); ?></a>&nbsp;
+                <?php
             } else {
                 Display::display_icon('new_draw_na.png', get_lang('BrowserDontSupportsSVG'), '', ICON_SIZE_MEDIUM);
             }
@@ -1198,8 +1107,8 @@ if ($is_allowed_to_edit || $group_member_with_upload_rights || is_my_shared_fold
         if (api_get_setting('enabled_support_pixlr') == 'true') {
             ?>
             <a href="create_paint.php?<?php echo api_get_cidreq(); ?>&id=<?php echo $document_id; ?>">
-                <?php Display::display_icon('new_paint.png', get_lang('PhotoRetouching'), '', ICON_SIZE_MEDIUM); ?></a>
-        <?php
+            <?php Display::display_icon('new_paint.png', get_lang('PhotoRetouching'), '', ICON_SIZE_MEDIUM); ?></a>
+            <?php
         }
 
 
@@ -1207,24 +1116,24 @@ if ($is_allowed_to_edit || $group_member_with_upload_rights || is_my_shared_fold
         if (api_get_setting('enable_webcam_clip') == 'true') {
             ?>
             <a href="webcam_clip.php?<?php echo api_get_cidreq(); ?>&id=<?php echo $document_id; ?>">
-                <?php Display::display_icon('webcam.png', get_lang('WebCamClip'), '', ICON_SIZE_MEDIUM); ?></a>
-        <?php
+            <?php Display::display_icon('webcam.png', get_lang('WebCamClip'), '', ICON_SIZE_MEDIUM); ?></a>
+            <?php
         }
 
         // Record audio (nanogong)
         if (api_get_setting('enable_nanogong') == 'true') {
             ?>
             <a href="record_audio.php?<?php echo api_get_cidreq(); ?>&id=<?php echo $document_id; ?>">
-                <?php Display::display_icon('new_recording.png', get_lang('RecordMyVoice'), '', ICON_SIZE_MEDIUM); ?></a>
-        <?php
+            <?php Display::display_icon('new_recording.png', get_lang('RecordMyVoice'), '', ICON_SIZE_MEDIUM); ?></a>
+            <?php
         }
 
         // Record  audio (wami record)
         if (api_get_setting('enable_wami_record') == 'true') {
             ?>
             <a href="record_audio_wami.php?<?php echo api_get_cidreq(); ?>&id=<?php echo $document_id; ?>">
-                <?php Display::display_icon('new_recording.png', get_lang('RecordMyVoice'), '', ICON_SIZE_MEDIUM); ?></a>
-        <?php
+            <?php Display::display_icon('new_recording.png', get_lang('RecordMyVoice'), '', ICON_SIZE_MEDIUM); ?></a>
+            <?php
         }
 
         // Create new audio from text
@@ -1233,18 +1142,17 @@ if ($is_allowed_to_edit || $group_member_with_upload_rights || is_my_shared_fold
             $req_dt2a = '&amp;dt2a='.$dt2a;
             ?>
             <a href="create_audio.php?<?php echo api_get_cidreq(); ?>&amp;id=<?php echo $document_id.$req_dt2a; ?>">
-                <?php Display::display_icon('new_sound.png', get_lang('CreateAudio'), '', ICON_SIZE_MEDIUM); ?></a>
-        <?php
+            <?php Display::display_icon('new_sound.png', get_lang('CreateAudio'), '', ICON_SIZE_MEDIUM); ?></a>
+            <?php
         }
     }
 
     // Create new certificate
     if ($is_certificate_mode) {
         ?>
-        <a href="create_document.php?<?php echo api_get_cidreq(
-        ); ?>&id=<?php echo $document_id; ?>&certificate=true&selectcat=<?php echo $selectcat; ?>">
-            <?php Display::display_icon('new_certificate.png', get_lang('CreateCertificate'), '', ICON_SIZE_MEDIUM); ?></a>
-    <?php
+        <a href="create_document.php?<?php echo api_get_cidreq(); ?>&id=<?php echo $document_id; ?>&certificate=true&selectcat=<?php echo $selectcat; ?>">
+        <?php Display::display_icon('new_certificate.png', get_lang('CreateCertificate'), '', ICON_SIZE_MEDIUM); ?></a>
+        <?php
     }
     // File upload link
     if ($is_certificate_mode) {
@@ -1263,8 +1171,8 @@ if ($is_allowed_to_edit || $group_member_with_upload_rights || is_my_shared_fold
     if (!$is_certificate_mode) {
         ?>
         <a href="<?php echo api_get_self(); ?>?<?php echo api_get_cidreq(); ?>&id=<?php echo $document_id; ?>&createdir=1">
-            <?php Display::display_icon('new_folder.png', get_lang('CreateDir'), '', ICON_SIZE_MEDIUM); ?></a>
-    <?php
+        <?php Display::display_icon('new_folder.png', get_lang('CreateDir'), '', ICON_SIZE_MEDIUM); ?></a>
+        <?php
     }
 }
 
@@ -1417,25 +1325,11 @@ if (!is_null($docs_and_folders)) {
 
     // Show download zipped folder icon
     global $total_size;
-    if (!$is_certificate_mode && $total_size != 0 && (api_get_setting(
-        'students_download_folders'
-    ) == 'true' || api_is_allowed_to_edit() || api_is_platform_admin())
-    ) {
+    if (!$is_certificate_mode && $total_size != 0 && (api_get_setting('students_download_folders') == 'true' || api_is_allowed_to_edit() || api_is_platform_admin())) {
 
         //for student does not show icon into other shared folder, and does not show into main path (root)
-        if (is_my_shared_folder(
-            api_get_user_id(),
-            $curdirpath,
-            $session_id
-        ) && $curdirpath != '/' || api_is_allowed_to_edit() || api_is_platform_admin()
-        ) {
-            echo '<a href="'.api_get_self().'?'.api_get_cidreq(
-            ).'&amp;action=downloadfolder&amp;id='.$document_id.'">'.Display::return_icon(
-                'save_pack.png',
-                get_lang('Save').' (ZIP)',
-                '',
-                ICON_SIZE_MEDIUM
-            ).'</a>';
+        if (is_my_shared_folder(api_get_user_id(), $curdirpath, $session_id) && $curdirpath != '/' || api_is_allowed_to_edit() || api_is_platform_admin()) {
+            echo '<a href="'.api_get_self().'?'.api_get_cidreq().'&amp;action=downloadfolder&amp;id='.$document_id.'">'.Display::return_icon('save_pack.png', get_lang('Save').' (ZIP)', '', ICON_SIZE_MEDIUM).'</a>';
         }
     }
 }
@@ -1443,21 +1337,11 @@ if (!is_null($docs_and_folders)) {
 // Slideshow by Patrick Cool, May 2004
 require 'document_slideshow.inc.php';
 if ($image_present && !isset($_GET['keyword'])) {
-    echo '<a href="slideshow.php?'.api_get_cidreq().'&amp;curdirpath='.$curdirpathurl.'">'.Display::return_icon(
-        'slideshow.png',
-        get_lang('ViewSlideshow'),
-        '',
-        ICON_SIZE_MEDIUM
-    ).'</a>';
+    echo '<a href="slideshow.php?'.api_get_cidreq().'&amp;curdirpath='.$curdirpathurl.'">'.Display::return_icon('slideshow.png', get_lang('ViewSlideshow'), '', ICON_SIZE_MEDIUM).'</a>';
 }
 
 if (api_is_allowed_to_edit(null, true)) {
-    echo '<a href="document_quota.php?'.api_get_cidreq().'">'.Display::return_icon(
-        'percentage.png',
-        get_lang('DocumentQuota'),
-        '',
-        ICON_SIZE_MEDIUM
-    ).'</a>';
+    echo '<a href="document_quota.php?'.api_get_cidreq().'">'.Display::return_icon('percentage.png', get_lang('DocumentQuota'), '', ICON_SIZE_MEDIUM).'</a>';
 }
 
 echo '</div>'; //end actions
@@ -1546,12 +1430,7 @@ $table->set_header($column++, get_lang('Name'));
 $table->set_header($column++, get_lang('Size'), true, array('style' => 'width:50px;'));
 $table->set_header($column++, get_lang('Date'), true, array('style' => 'width:150px;'));
 // Admins get an edit column
-if ($is_allowed_to_edit || $group_member_with_upload_rights || is_my_shared_folder(
-    api_get_user_id(),
-    $curdirpath,
-    $session_id
-)
-) {
+if ($is_allowed_to_edit || $group_member_with_upload_rights || is_my_shared_folder(api_get_user_id(), $curdirpath, $session_id)) {
     $table->set_header($column++, get_lang('Actions'), false, array('class' => 'td_actions'));
 }
 

+ 10 - 10
main/document/download.php

@@ -37,8 +37,7 @@ if (strpos($doc_url,'../') OR strpos($doc_url,'/..')) {
 // survey while not being authenticated on the plateform.
 // The administrator should probably be able to disable this code through admin
 // inteface.
-
-$refer_script = isset($_SERVER["HTTP_REFERER"]) ? strrchr($_SERVER["HTTP_REFERER"], '/') : null;
+$refer_script = strrchr($_SERVER["HTTP_REFERER"], '/');
 
 $sys_course_path = api_get_path(SYS_COURSE_PATH).$_course['path'].'/document';
 
@@ -63,11 +62,11 @@ if (substr($refer_script, 0, 15) == '/fillsurvey.php') {
 		$document_explorer = api_get_path(WEB_CODE_PATH).'document/document.php?curdirpath='.urlencode($doc_url).'&cidReq='.Security::remove_XSS($_GET['cidReq']).$gid_req;
 		// Redirect
 		header('Location: '.$document_explorer);
-	}
+	}	
 }
 
-
-//Fixes swf upload problem in chamilo 1.8.x. When uploading a file with
+        
+//Fixes swf upload problem in chamilo 1.8.x. When uploading a file with 
 //the character "-" the filename was changed from "-" to "_" in the DB for no reason
 $path_info = pathinfo($doc_url);
 
@@ -80,21 +79,22 @@ if (isset($path_info['extension']) && $path_info['extension'] == 'swf') {
     }
 }
 
+
 if (Security::check_abs_path($sys_course_path.$doc_url, $sys_course_path.'/')) {
-    $full_file_name = $sys_course_path.$doc_url;
+    $full_file_name = $sys_course_path.$doc_url;    
     if ($fix_file_name) {
         $doc_url = $fixed_url;
     }
     // Check visibility of document and paths
     $is_visible = DocumentManager::is_visible($doc_url, $_course, api_get_session_id());
-
-	//Documents' slideshow thumbnails
+    
+    //Document's slideshow thumbnails
 	//correct $is_visible used in below and ??. Now the students can view the thumbnails too
-	if ( preg_match('/\.thumbs\/\./',  $doc_url)){
+	if ( preg_match('/\.thumbs\/\./',  $doc_url)){ 
 		$doc_url_thumbs = str_replace('.thumbs/.', '', $doc_url);
 		$is_visible = DocumentManager::is_visible($doc_url_thumbs, $_course, api_get_session_id());
 	}
-
+	
     if (!api_is_allowed_to_edit() && !$is_visible) {
     	Display::display_error_message(get_lang('ProtectedDocument'));//api_not_allowed backbutton won't work.
     	exit; // You shouldn't be here anyway.

+ 1 - 1
main/document/upload.php

@@ -228,7 +228,7 @@ $course_quota = Text::format_file_size(DocumentManager::get_course_quota() - Doc
 
 $label = get_lang('MaxFileSize').': '.ini_get('upload_max_filesize').'<br/>'.get_lang('DocumentQuota').': '.$course_quota;
 
-$form->addElement('file', 'file', array(get_lang('File'), $label), 'id="user_upload" size="45"');
+$form->addElement('file', 'file', array(get_lang('File'), $label), 'style="width: 250px" id="user_upload"');
 
 $form->addElement('text', 'title', get_lang('Title'), array('size' => '20', 'style' => 'width:300px', 'id' => 'title_file'));
 $form->addElement('textarea', 'comment', get_lang('Comment'), 'wrap="virtual" style="width:300px;"');

+ 4 - 3
main/dropbox/dropbox_class.inc.php

@@ -252,7 +252,7 @@ class Dropbox_SentWork extends Dropbox_Work
 	 * @param unknown_type $recipient_ids
 	 */
 	function _createNewSentWork($uploader_id, $title, $description, $author, $filename, $filesize, $recipient_ids) {
-		global $dropbox_cnf;
+			global $dropbox_cnf;
 		// Call constructor of Dropbox_Work object
 		$this->Dropbox_Work($uploader_id, $title, $description, $author, $filename, $filesize);
 
@@ -284,6 +284,7 @@ class Dropbox_SentWork extends Dropbox_Work
         $table_person = $dropbox_cnf['tbl_person'];
         $session_id = api_get_session_id();
         $uploader_id = $this->uploader_id;
+        $user  = api_get_user_id();
 		// Insert data in dropbox_post and dropbox_person table for each recipient
 		foreach ($this->recipients as $rec) {
             $file_id = (int)$this->id;
@@ -296,7 +297,7 @@ class Dropbox_SentWork extends Dropbox_Work
             /**
              * Poster is already added when work is created - not so good to split logic
              */
-            //if ($user_id != $user_id) {
+            if ($user_id != $user) {
                 // Insert entries into person table
                 $sql = "INSERT INTO $table_person (c_id, file_id, user_id)
                         VALUES ($course_id, $file_id, $user_id)";
@@ -305,7 +306,7 @@ class Dropbox_SentWork extends Dropbox_Work
                 if (!$justSubmit) {
                     $result = Database::query($sql);	// If work already exists no error is generated
                 }
-            //}
+            }
 
 			// Update item_property table for each recipient
 			global $dropbox_cnf;

+ 4 - 1
main/exercice/admin.php

@@ -304,7 +304,10 @@ function multiple_answer_true_false_onchange(variable) {
     var result = variable.checked;
     var id = variable.id;
     var weight_id = "weighting_" + id;
-    var array_result=new Array(); array_result[1]="1"; array_result[0]= "-0.50"; array_result[-1]= "0";
+    var array_result=new Array();
+    array_result[1]="1";
+    array_result[0]= "-0.50";
+    array_result[-1]= "0";
     if (result) {
         result = 1;
     } else {

Файлын зөрүү хэтэрхий том тул дарагдсан байна
+ 423 - 434
main/exercice/answer.class.php


+ 2350 - 0
main/exercice/exercise.lib.php

@@ -0,0 +1,2350 @@
+<?php
+/* For licensing terms, see /license.txt */
+/**
+ * Exercise library
+ * @todo convert this lib into a static class
+ *
+ * shows a question and its answers
+ * @package chamilo.exercise
+ * @author Olivier Brouckaert <oli.brouckaert@skynet.be>
+ * @version $Id: exercise.lib.php 22247 2009-07-20 15:57:25Z ivantcholakov $
+ * Modified by Hubert Borderiou 2011-10-21 Question Category
+ */
+/**
+ * Code
+ */
+// The initialization class for the online editor is needed here.
+require_once dirname(__FILE__).'/../inc/lib/fckeditor/fckeditor.php';
+
+/**
+ * Shows a question
+ *
+ * @param int   question id
+ * @param bool  if true only show the questions, no exercise title
+ * @param bool  origin i.e = learnpath
+ * @param int   current item from the list of questions
+ * @param int   number of total questions
+ * */
+function showQuestion($questionId, $only_questions = false, $origin = false, $current_item = '', $show_title = true, $freeze = false, $user_choice = array(), $show_comment = false, $exercise_feedback = null, $show_answers = false) {
+
+    // Text direction for the current language
+    $is_ltr_text_direction = api_get_text_direction() != 'rtl';
+
+    // Change false to true in the following line to enable answer hinting
+    $debug_mark_answer = $show_answers; //api_is_allowed_to_edit() && false;
+
+    // Reads question information
+    if (!$objQuestionTmp = Question::read($questionId)) {
+    	// Question not found
+    	return false;
+    }
+
+    if ($exercise_feedback != EXERCISE_FEEDBACK_TYPE_END) {
+        $show_comment = false;
+    }
+
+    $answerType    = $objQuestionTmp->selectType();
+    $pictureName   = $objQuestionTmp->selectPicture();
+
+    if ($answerType != HOT_SPOT && $answerType != HOT_SPOT_DELINEATION) {
+    	// Question is not a hotspot
+
+    	if (!$only_questions) {
+    		$questionDescription = $objQuestionTmp->selectDescription();
+    		if ($show_title) {
+    			Testcategory::displayCategoryAndTitle($objQuestionTmp->id);	//
+    			echo Display::div($current_item.'. '.$objQuestionTmp->selectTitle(), array('class'=>'question_title'));
+    		}
+    		if (!empty($questionDescription)) {
+                echo Display::div($questionDescription, array('class'=>'question_description'));
+            }
+        }
+
+        if (in_array($answerType, array(FREE_ANSWER, ORAL_EXPRESSION)) && $freeze) {
+            return '';
+        }
+
+        echo '<div class="question_options">';
+
+    	$s = '';
+
+    	// construction of the Answer object (also gets all answers details)
+    	$objAnswerTmp = new Answer($questionId);
+
+    	$nbrAnswers     = $objAnswerTmp->selectNbrAnswers();
+        $course_id      = api_get_course_int_id();
+        $quiz_question_options = Question::readQuestionOption($questionId, $course_id);
+
+    	// For "matching" type here, we need something a little bit special
+    	// because the match between the suggestions and the answers cannot be
+    	// done easily (suggestions and answers are in the same table), so we
+    	// have to go through answers first (elems with "correct" value to 0).
+    	$select_items = array();
+    	//This will contain the number of answers on the left side. We call them
+    	// suggestions here, for the sake of comprehensions, while the ones
+    	// on the right side are called answers
+    	$num_suggestions = 0;
+
+    	if ($answerType == MATCHING) {
+            $s .= '<table class="data_table">';
+            // Iterate through answers
+    		$x = 1;
+            //mark letters for each answer
+    		$letter = 'A';
+    		$answer_matching = array();
+            $cpt1 = array();
+            for ($answerId = 1; $answerId <= $nbrAnswers; $answerId++) {
+                $answerCorrect = $objAnswerTmp->isCorrect($answerId);
+                $numAnswer = $objAnswerTmp->selectAutoId($answerId);
+
+                $answer = $objAnswerTmp->selectAnswer($answerId);
+                if ($answerCorrect == 0) {
+                    // options (A, B, C, ...) that will be put into the list-box
+                    // have the "correct" field set to 0 because they are answer
+                    $cpt1[$x] = $letter;
+    				$answer_matching[$x] = $objAnswerTmp->selectAnswerByAutoId($numAnswer);
+                    $x++;
+                    $letter++;
+                }
+            }
+
+            $i = 1;
+
+            $select_items[0]['id'] = 0;
+            $select_items[0]['letter'] = '--';
+            $select_items[0]['answer'] = '';
+            foreach ($answer_matching as $id => $value) {
+                $select_items[$i]['id'] 	= $value['id'];
+                $select_items[$i]['letter'] = $cpt1[$id];
+                $select_items[$i]['answer'] = $value['answer'];
+                $i++;
+            }
+
+            $user_choice_array_position = array();
+            if (!empty($user_choice)) {
+                foreach ($user_choice as $item) {
+                    $user_choice_array_position[$item['position']] = $item['answer'];
+                }
+            }
+
+    		$num_suggestions = ($nbrAnswers - $x) + 1;
+
+    	} elseif ($answerType == FREE_ANSWER) {
+    		$fck_content = isset($user_choice[0]) && !empty($user_choice[0]['answer']) ? $user_choice[0]['answer']:null;
+
+    		$oFCKeditor = new FCKeditor("choice[".$questionId."]") ;
+
+    		$oFCKeditor->ToolbarSet = 'TestFreeAnswer';
+    		$oFCKeditor->Width      = '100%';
+    		$oFCKeditor->Height     = '200';
+    		$oFCKeditor->Value      = $fck_content;
+            $s .= $oFCKeditor->CreateHtml();
+    	} elseif ($answerType == ORAL_EXPRESSION) {
+    		//Add nanog
+    		if (api_get_setting('enable_nanogong') == 'true') {
+    			require_once api_get_path(LIBRARY_PATH).'nanogong.lib.php';
+    			//@todo pass this as a parameter
+    			global $exercise_stat_info, $exerciseId, $exe_id;
+
+    			if (!empty($exercise_stat_info)) {
+    				$params = array(
+    					'exercise_id' 	=> $exercise_stat_info['exe_exo_id'],
+    					'exe_id' 		=> $exercise_stat_info['exe_id'],
+    					'question_id'   => $questionId
+    				);
+    			} else {
+    				$params = array(
+    					'exercise_id' 	=> $exerciseId,
+    					'exe_id' 		=> 'temp_exe',
+    					'question_id'   => $questionId
+    				);
+    			}
+    			$nano = new Nanogong($params);
+    			echo $nano->show_button();
+    		}
+
+    		$oFCKeditor = new FCKeditor("choice[".$questionId."]") ;
+    		$oFCKeditor->ToolbarSet = 'TestFreeAnswer';
+    		$oFCKeditor->Width  = '100%';
+    		$oFCKeditor->Height = '150';
+    		$oFCKeditor->ToolbarStartExpanded = false;
+    		$oFCKeditor->Value	= '' ;
+    		$s .= $oFCKeditor->CreateHtml();
+    	}
+
+    	// Now navigate through the possible answers, using the max number of
+    	// answers for the question as a limiter
+    	$lines_count = 1; // a counter for matching-type answers
+
+        if ($answerType == MULTIPLE_ANSWER_TRUE_FALSE || $answerType ==  MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE) {
+            $header = Display::tag('th', get_lang('Options'));
+            foreach ($objQuestionTmp->options as $key=>$item) {
+                $header .= Display::tag('th', $item);
+            }
+            if ($show_comment) {
+                $header .= Display::tag('th', get_lang('Feedback'));
+            }
+            $s .= '<table class="data_table">';
+            $s .= Display::tag('tr', $header, array('style'=>'text-align:left;'));
+        }
+
+        if ($show_comment) {
+            if (in_array($answerType, array(MULTIPLE_ANSWER, MULTIPLE_ANSWER_COMBINATION, UNIQUE_ANSWER, UNIQUE_ANSWER_NO_OPTION, GLOBAL_MULTIPLE_ANSWER))) {
+                $header = Display::tag('th', get_lang('Options'));
+                if ($exercise_feedback == EXERCISE_FEEDBACK_TYPE_END) {
+                    $header .= Display::tag('th', get_lang('Feedback'));
+                }
+                $s .= '<table class="data_table">';
+                $s.= Display::tag('tr',$header, array('style'=>'text-align:left;'));
+            }
+        }
+
+        $matching_correct_answer = 0;
+        $user_choice_array = array();
+        if (!empty($user_choice)) {
+        	foreach($user_choice as $item) {
+        		$user_choice_array[] = $item['answer'];
+        	}
+        }
+
+
+    	for ($answerId=1; $answerId <= $nbrAnswers; $answerId++) {
+    		$answer          = $objAnswerTmp->selectAnswer($answerId);
+    		$answerCorrect   = $objAnswerTmp->isCorrect($answerId);
+    		$numAnswer       = $objAnswerTmp->selectAutoId($answerId);
+            $comment         = $objAnswerTmp->selectComment($answerId);
+
+            $attributes = array();
+
+    		// Unique answer
+    		if ($answerType == UNIQUE_ANSWER || $answerType == UNIQUE_ANSWER_NO_OPTION) {
+    			$input_id = 'choice-'.$questionId.'-'.$answerId;
+    			if (isset($user_choice[0]['answer']) && $user_choice[0]['answer'] == $numAnswer ) {
+    				$attributes = array('id' =>$input_id, 'checked'=>1, 'selected'=>1);
+    			} else {
+    				$attributes = array('id' =>$input_id);
+    			}
+
+                if ($debug_mark_answer) {
+    				if ($answerCorrect) {
+    					$attributes['checked'] = 1;
+                        $attributes['selected'] = 1;
+    				}
+    			}
+
+    			$answer = Security::remove_XSS($answer, STUDENT);
+
+    			$s .= Display::input('hidden','choice2['.$questionId.']','0');
+
+    			$answer_input = '<label class="radio">';
+    			$answer_input .= Display::input('radio', 'choice['.$questionId.']', $numAnswer, $attributes);
+    			$answer_input .= $answer;
+    			$answer_input .= '</label>';
+
+                if ($show_comment) {
+                    $s .= '<tr><td>';
+                    $s .= $answer_input;
+                    $s .= '</td>';
+                    $s .= '<td>';
+                    $s .= $comment;
+                    $s .= '</td>';
+                    $s .= '</tr>';
+                } else {
+                    $s .= $answer_input;
+                }
+
+    		} elseif ($answerType == MULTIPLE_ANSWER || $answerType == MULTIPLE_ANSWER_TRUE_FALSE || $answerType == GLOBAL_MULTIPLE_ANSWER) {
+    			$input_id = 'choice-'.$questionId.'-'.$answerId;
+    			$answer = Security::remove_XSS($answer, STUDENT);
+
+    			if (in_array($numAnswer, $user_choice_array)) {
+    				$attributes = array('id' =>$input_id, 'checked'=>1, 'selected'=>1);
+    			} else {
+    				$attributes = array('id' =>$input_id);
+    			}
+
+                if ($debug_mark_answer) {
+    				if ($answerCorrect) {
+    					$attributes['checked'] = 1;
+                        $attributes['selected'] = 1;
+    				}
+    			}
+
+                if ($answerType == MULTIPLE_ANSWER || $answerType == GLOBAL_MULTIPLE_ANSWER) {
+                    $s .= '<input type="hidden" name="choice2['.$questionId.']" value="0" />';
+
+                    $answer_input = '<label class="checkbox">';
+                    $answer_input .= Display::input('checkbox', 'choice['.$questionId.']['.$numAnswer.']', $numAnswer, $attributes);
+                    $answer_input .= $answer;
+                    $answer_input .= '</label>';
+
+                    if ($show_comment) {
+                        $s .= '<tr><td>';
+                        $s .= $answer_input;
+                        $s .= '</td>';
+                        $s .= '<td>';
+                        $s .= $comment;
+                        $s .= '</td>';
+                        $s .='</tr>';
+                    } else {
+                        $s .= $answer_input;
+                    }
+                } elseif ($answerType == MULTIPLE_ANSWER_TRUE_FALSE) {
+
+                	$my_choice = array();
+                    if (!empty($user_choice_array)) {
+                        foreach ($user_choice_array as $item) {
+                            $item = explode(':', $item);
+                            $my_choice[$item[0]] = $item[1];
+                        }
+                    }
+
+                    $s .= '<tr>';
+                    $s .= Display::tag('td', $answer);
+
+                    if (!empty($quiz_question_options)) {
+                    	foreach ($quiz_question_options as $id => $item) {
+
+                    		if (isset($my_choice[$numAnswer]) && $id == $my_choice[$numAnswer]) {
+                    			$attributes = array('checked'=>1, 'selected'=>1);
+                    		} else {
+                    			$attributes = array();
+                    		}
+
+                            if ($debug_mark_answer) {
+                                if ($id == $answerCorrect) {
+                                    $attributes['checked'] = 1;
+                                    $attributes['selected'] = 1;
+                                }
+                            }
+                    		$s .= Display::tag('td', Display::input('radio', 'choice['.$questionId.']['.$numAnswer.']', $id, $attributes), array('style'=>''));
+                    	}
+                    }
+
+                    if ($show_comment) {
+                        $s .= '<td>';
+                        $s .= $comment;
+                        $s .= '</td>';
+                    }
+                    $s.='</tr>';
+                }
+    		} elseif ($answerType == MULTIPLE_ANSWER_COMBINATION) {
+    			// multiple answers
+    			$input_id = 'choice-'.$questionId.'-'.$answerId;
+
+    			if (in_array($numAnswer, $user_choice_array)) {
+    			    $attributes = array('id'=>$input_id, 'checked'=>1, 'selected'=>1);
+    			} else {
+    			    $attributes = array('id'=>$input_id);
+    			}
+
+                if ($debug_mark_answer) {
+    				if ($answerCorrect) {
+    					$attributes['checked'] = 1;
+                        $attributes['selected'] = 1;
+    				}
+    			}
+
+    			$answer = Security::remove_XSS($answer, STUDENT);
+    			$answer_input = '<input type="hidden" name="choice2['.$questionId.']" value="0" />';
+    			$answer_input .= '<label class="checkbox">';
+    			$answer_input .= Display::input('checkbox', 'choice['.$questionId.']['.$numAnswer.']', 1, $attributes);
+    		    $answer_input .= $answer;
+                $answer_input .= '</label>';
+
+                if ($show_comment) {
+                    $s.= '<tr>';
+                    $s .= '<td>';
+                    $s.= $answer_input;
+                    $s .= '</td>';
+                    $s .= '<td>';
+                    $s .= $comment;
+                    $s .= '</td>';
+                    $s.= '</tr>';
+                } else {
+                    $s.= $answer_input;
+                }
+
+            } elseif ($answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE) {
+            	$s .= '<input type="hidden" name="choice2['.$questionId.']" value="0" />';
+
+            	$my_choice = array();
+            	if (!empty($user_choice_array)) {
+            		foreach ($user_choice_array as $item) {
+            			$item = explode(':', $item);
+            			$my_choice[$item[0]] = $item[1];
+            		}
+            	}
+            	$answer = Security::remove_XSS($answer, STUDENT);
+            	$s .='<tr>';
+            	$s .= Display::tag('td', $answer);
+
+            	foreach ($objQuestionTmp->options as $key => $item) {
+            		if (isset($my_choice[$numAnswer]) && $key == $my_choice[$numAnswer]) {
+            			$attributes = array('checked' => 1, 'selected' => 1);
+            		} else {
+            			$attributes = array();
+            		}
+
+                    if ($debug_mark_answer) {
+                        if ($key == $answerCorrect) {
+                            $attributes['checked']  = 1;
+                            $attributes['selected'] = 1;
+                        }
+                    }
+            		$s .= Display::tag('td', Display::input('radio', 'choice['.$questionId.']['.$numAnswer.']', $key, $attributes));
+            	}
+
+                if ($show_comment) {
+                    $s .= '<td>';
+                    $s .= $comment;
+                    $s .= '</td>';
+                }
+            	$s.='</tr>';
+
+    		} elseif ($answerType == FILL_IN_BLANKS) {
+    			list($answer) = explode('::', $answer);
+
+                //Correct answer
+    			api_preg_match_all('/\[[^]]+\]/', $answer, $correct_answer_list);
+
+                //Student's answezr
+    			if (isset($user_choice[0]['answer'])) {
+    				api_preg_match_all('/\[[^]]+\]/', $user_choice[0]['answer'], $student_answer_list);
+    				$student_answer_list = $student_answer_list[0];
+    			}
+
+                //If debug
+                if ($debug_mark_answer) {
+    				$student_answer_list = $correct_answer_list[0];
+                }
+
+    			if (!empty($correct_answer_list) && !empty($student_answer_list)) {
+    			    $correct_answer_list = $correct_answer_list[0];
+    			    $i = 0;
+
+    			    foreach ($correct_answer_list as $correct_item) {
+    			        $value = null;
+    			        if (isset($student_answer_list[$i]) && !empty($student_answer_list[$i])) {
+
+    			        	//Cleaning student answer list
+    			            $value = strip_tags($student_answer_list[$i]);
+    			            $value = api_substr($value, 1, api_strlen($value)-2);
+    			            $value = explode('/', $value);
+
+    			            if (!empty($value[0])) {
+    			            	$value = str_replace('&nbsp;', '',  trim($value[0]));
+    			            }
+                            //var_dump($correct_item);
+                            //$correct_item = preg_quote($correct_item);
+                            // to prevent error if there is a / in the text to find
+                            //$correct_item = api_preg_replace('|/|', '\/', $correct_item);
+
+                            $size = strlen($correct_item);
+                            $attributes['class'] = detectInputAppropriateClass($size);
+
+    			            //$answer = api_preg_replace('/'.$correct_item.'/', Display::input('text', "choice[$questionId][]", $value, $attributes), $answer, 1);
+                            $answer = str_replace($correct_item, Display::input('text', "choice[$questionId][]", $value, $attributes), $answer);
+    			        }
+    			        $i++;
+    			    }
+    			} else {
+
+                    foreach ($correct_answer_list[0] as $item) {
+                        $size = strlen($item);
+                        $attributes['class'] = detectInputAppropriateClass($size);
+
+                        //$pattern = '/\['.$item.'+\]/';
+                        //$answer = api_preg_replace($pattern, Display::input('text', "choice[$questionId][]", '', $attributes), $answer);
+                        $answer = str_replace($item, Display::input('text', "choice[$questionId][]", '', $attributes), $answer);
+                    }
+                    //$answer = api_preg_replace('/\[[^]]+\]/', Display::input('text', "choice[$questionId][]", '', $attributes), $answer);
+    			}
+
+    			$s .= $answer;
+            } elseif ($answerType == MATCHING) {
+    			// matching type, showing suggestions and answers
+    			// TODO: replace $answerId by $numAnswer
+
+    			if ($answerCorrect != 0) {
+    				// only show elements to be answered (not the contents of
+    				// the select boxes, who are corrrect = 0)
+    				$s .= '<tr><td width="45%" valign="top">';
+    				$parsed_answer = $answer;
+    				//left part questions
+    				$s .= ' <span style="float:left; width:8%;"><b>'.$lines_count.'</b>.&nbsp;</span>
+    					 	<span style="float:left; width:92%;">'.$parsed_answer.'</span></td>';
+    				//middle part (matches selects)
+
+    				$s .= '<td width="10%" valign="top" align="center">&nbsp;&nbsp;
+    			            <select name="choice['.$questionId.']['.$numAnswer.']">';
+
+    				// fills the list-box
+    				foreach ($select_items as $key => $val) {
+    					// set $debug_mark_answer to true at function start to
+    					// show the correct answer with a suffix '-x'
+    					$selected = '';
+    					if ($debug_mark_answer) {
+    						if ($val['id'] == $answerCorrect) {
+    							$selected = 'selected="selected"';
+    						}
+    					}
+                        //$user_choice_array_position
+                        if (isset($user_choice_array_position[$numAnswer]) && $val['id'] == $user_choice_array_position[$numAnswer]) {
+    					    $selected = 'selected="selected"';
+    					}
+    					/*if (isset($user_choice_array[$matching_correct_answer]) && $val['id'] == $user_choice_array[$matching_correct_answer]['answer']) {
+    					    $selected = 'selected="selected"';
+    					}*/
+    					$s .= '<option value="'.$val['id'].'" '.$selected.'>'.$val['letter'].'</option>';
+
+    				}  // end foreach()
+
+    				$s .= '</select></td>';
+    				$s.='<td width="45%" valign="top" >';
+    				if (isset($select_items[$lines_count])) {
+    					$s.='<span style="float:left; width:5%;"><b>'.$select_items[$lines_count]['letter'].'.</b></span>'.
+    						 '<span style="float:left; width:95%;">'.$select_items[$lines_count]['answer'].'</span>';
+    				} else {
+    					$s.='&nbsp;';
+    				}
+    				$s .= '</td>';
+    				$s .= '</tr>';
+    				$lines_count++;
+    				//if the left side of the "matching" has been completely
+    				// shown but the right side still has values to show...
+    				if (($lines_count -1) == $num_suggestions) {
+    					// if it remains answers to shown at the right side
+    					while (isset($select_items[$lines_count])) {
+    						$s .= '<tr>
+    							  <td colspan="2"></td>
+    							  <td valign="top">';
+    						$s.='<b>'.$select_items[$lines_count]['letter'].'.</b> '.$select_items[$lines_count]['answer'];
+    						$s.="</td>
+    						</tr>";
+    						$lines_count++;
+    					}	// end while()
+    				}  // end if()
+    				$matching_correct_answer++;
+    			}
+    		}
+    	}	// end for()
+
+        if ($show_comment) {
+            $s .= '</table>';
+        } else {
+            if ($answerType == MATCHING || $answerType == UNIQUE_ANSWER_NO_OPTION || $answerType == MULTIPLE_ANSWER_TRUE_FALSE ||
+                $answerType == MULTIPLE_ANSWER_COMBINATION_TRUE_FALSE) {
+                $s .= '</table>';
+            }
+        }
+
+
+
+    	$s .= '</div>';
+
+    	// destruction of the Answer object
+    	unset($objAnswerTmp);
+
+    	// destruction of the Question object
+    	unset($objQuestionTmp);
+
+    	if ($origin != 'export') {
+    		echo $s;
+    	} else {
+    		return $s;
+    	}
+    } elseif ($answerType == HOT_SPOT || $answerType == HOT_SPOT_DELINEATION) {
+    	// Question is a HOT_SPOT
+        //checking document/images visibility
+        if (api_is_platform_admin() || api_is_course_admin()) {
+            require_once api_get_path(LIBRARY_PATH).'document.lib.php';
+            $course = api_get_course_info();
+            $doc_id = DocumentManager::get_document_id($course, '/images/'.$pictureName);
+            if (is_numeric($doc_id)) {
+                $images_folder_visibility = api_get_item_visibility($course,'document', $doc_id, api_get_session_id());
+                if (!$images_folder_visibility) {
+                    //This message is shown only to the course/platform admin if the image is set to visibility = false
+                    Display::display_warning_message(get_lang('ChangeTheVisibilityOfTheCurrentImage'));
+                }
+            }
+        }
+    	$questionName         = $objQuestionTmp->selectTitle();
+    	$questionDescription  = $objQuestionTmp->selectDescription();
+
+        if ($freeze) {
+            echo Display::img($objQuestionTmp->selectPicturePath());
+            return;
+        }
+
+    	// Get the answers, make a list
+    	$objAnswerTmp         = new Answer($questionId);
+    	$nbrAnswers           = $objAnswerTmp->selectNbrAnswers();
+
+    	// get answers of hotpost
+    	$answers_hotspot = array();
+    	for ($answerId=1;$answerId <= $nbrAnswers;$answerId++) {
+    		$answers = $objAnswerTmp->selectAnswerByAutoId($objAnswerTmp->selectAutoId($answerId));
+    		$answers_hotspot[$answers['id']] = $objAnswerTmp->selectAnswer($answerId);
+    	}
+
+    	// display answers of hotpost order by id
+    	$answer_list = '<div style="padding: 10px; margin-left: 0px; border: 1px solid #A4A4A4; height: 408px; width: 200px;"><b>'.get_lang('HotspotZones').'</b><dl>';
+    	if (!empty($answers_hotspot)) {
+    		ksort($answers_hotspot);
+    		foreach ($answers_hotspot as $key => $value) {
+    			$answer_list .= '<dt>'.$key.'.- '.$value.'</dt><br />';
+    		}
+    	}
+    	$answer_list .= '</dl></div>';
+
+    	if ($answerType == HOT_SPOT_DELINEATION) {
+    		$answer_list='';
+    		$swf_file = 'hotspot_delineation_user';
+    		$swf_height = 405;
+    	} else {
+    		$swf_file = 'hotspot_user';
+    		$swf_height = 436;
+    	}
+
+    	if (!$only_questions) {
+            if ($show_title) {
+    			Testcategory::displayCategoryAndTitle($objQuestionTmp->id);
+                echo '<div class="question_title">'.$current_item.'. '.$questionName.'</div>';
+            }
+    		//@todo I need to the get the feedback type
+    		echo '<input type="hidden" name="hidden_hotspot_id" value="'.$questionId.'" />';
+    		echo '<table class="exercise_questions" >
+    			  <tr>
+    		  		<td valign="top" colspan="2">';
+    		echo $questionDescription;
+    		echo '</td></tr>';
+    	}
+    	$canClick = isset($_GET['editQuestion']) ? '0' : (isset($_GET['modifyAnswers']) ? '0' : '1');
+
+    	$s .= '<script type="text/javascript" src="../plugin/hotspot/JavaScriptFlashGateway.js"></script>
+    					<script src="../plugin/hotspot/hotspot.js" type="text/javascript" ></script>
+    					<script type="text/javascript">
+    					<!--
+    					// Globals
+    					// Major version of Flash required
+    					var requiredMajorVersion = 7;
+    					// Minor version of Flash required
+    					var requiredMinorVersion = 0;
+    					// Minor version of Flash required
+    					var requiredRevision = 0;
+    					// the version of javascript supported
+    					var jsVersion = 1.0;
+    					// -->
+    					</script>
+    					<script language="VBScript" type="text/vbscript">
+    					<!-- // Visual basic helper required to detect Flash Player ActiveX control version information
+    					Function VBGetSwfVer(i)
+    					  on error resume next
+    					  Dim swControl, swVersion
+    					  swVersion = 0
+
+    					  set swControl = CreateObject("ShockwaveFlash.ShockwaveFlash." + CStr(i))
+    					  if (IsObject(swControl)) then
+    					    swVersion = swControl.GetVariable("$version")
+    					  end if
+    					  VBGetSwfVer = swVersion
+    					End Function
+    					// -->
+    					</script>
+
+    					<script language="JavaScript1.1" type="text/javascript">
+    					<!-- // Detect Client Browser type
+    					var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
+    					var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
+    					var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;
+    					jsVersion = 1.1;
+    					// JavaScript helper required to detect Flash Player PlugIn version information
+    					function JSGetSwfVer(i) {
+    						// NS/Opera version >= 3 check for Flash plugin in plugin array
+    						if (navigator.plugins != null && navigator.plugins.length > 0) {
+    							if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
+    								var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
+    					      		var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
+    								descArray = flashDescription.split(" ");
+    								tempArrayMajor = descArray[2].split(".");
+    								versionMajor = tempArrayMajor[0];
+    								versionMinor = tempArrayMajor[1];
+    								if ( descArray[3] != "" ) {
+    									tempArrayMinor = descArray[3].split("r");
+    								} else {
+    									tempArrayMinor = descArray[4].split("r");
+    								}
+    					      		versionRevision = tempArrayMinor[1] > 0 ? tempArrayMinor[1] : 0;
+    					            flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
+    					      	} else {
+    								flashVer = -1;
+    							}
+    						}
+    						// MSN/WebTV 2.6 supports Flash 4
+    						else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
+    						// WebTV 2.5 supports Flash 3
+    						else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
+    						// older WebTV supports Flash 2
+    						else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
+    						// Can\'t detect in all other cases
+    						else
+    						{
+    							flashVer = -1;
+    						}
+    						return flashVer;
+    					}
+    					// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
+
+    					function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision) {
+    					 	reqVer = parseFloat(reqMajorVer + "." + reqRevision);
+    					   	// loop backwards through the versions until we find the newest version
+    						for (i=25;i>0;i--) {
+    							if (isIE && isWin && !isOpera) {
+    								versionStr = VBGetSwfVer(i);
+    							} else {
+    								versionStr = JSGetSwfVer(i);
+    							}
+    							if (versionStr == -1 ) {
+    								return false;
+    							} else if (versionStr != 0) {
+    								if(isIE && isWin && !isOpera) {
+    									tempArray         = versionStr.split(" ");
+    									tempString        = tempArray[1];
+    									versionArray      = tempString .split(",");
+    								} else {
+    									versionArray      = versionStr.split(".");
+    								}
+    								versionMajor      = versionArray[0];
+    								versionMinor      = versionArray[1];
+    								versionRevision   = versionArray[2];
+
+    								versionString     = versionMajor + "." + versionRevision;   // 7.0r24 == 7.24
+    								versionNum        = parseFloat(versionString);
+    					        	// is the major.revision >= requested major.revision AND the minor version >= requested minor
+    								if ( (versionMajor > reqMajorVer) && (versionNum >= reqVer) ) {
+    									return true;
+    								} else {
+    									return ((versionNum >= reqVer && versionMinor >= reqMinorVer) ? true : false );
+    								}
+    							}
+    						}
+    					}
+    					// -->
+    					</script>';
+    	$s .= '<tr><td valign="top" colspan="2" width="520"><table><tr><td width="520">
+    				<script>
+    					<!--
+    					// Version check based upon the values entered above in "Globals"
+    					var hasReqestedVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);
+
+    					// Check to see if the version meets the requirements for playback
+    					if (hasReqestedVersion) {  // if we\'ve detected an acceptable version
+    					    var oeTags = \'<object type="application/x-shockwave-flash" data="../plugin/hotspot/'.$swf_file.'.swf?modifyAnswers='.$questionId.'&amp;canClick:'.$canClick.'" width="600" height="'.$swf_height.'">\'
+    					    			+ \'<param name="wmode" value="transparent">\'
+    									+ \'<param name="movie" value="../plugin/hotspot/'.$swf_file.'.swf?modifyAnswers='.$questionId.'&amp;canClick:'.$canClick.'" />\'
+    									+ \'<\/object>\';
+    					    document.write(oeTags);   // embed the Flash Content SWF when all tests are passed
+    					} else {  // flash is too old or we can\'t detect the plugin
+    						var alternateContent = "Error<br \/>"
+    							+ "Hotspots requires Macromedia Flash 7.<br \/>"
+    							+ "<a href=\"http://www.macromedia.com/go/getflash/\">Get Flash<\/a>";
+    						document.write(alternateContent);  // insert non-flash content
+    					}
+    					// -->
+    				</script>
+    				</td>
+    				<td valign="top" align="left">'.$answer_list.'</td></tr>
+    				</table>
+    	</td></tr>';
+    	echo $s;
+        echo '</table>';
+    }
+    return $nbrAnswers;
+}
+
+function get_exercise_track_exercise_info($exe_id) {
+    $TBL_EXERCICES         	= Database::get_course_table(TABLE_QUIZ_TEST);
+    $TBL_TRACK_EXERCICES	= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+    $TBL_COURSE             = Database::get_main_table(TABLE_MAIN_COURSE);
+    $exe_id = intval($exe_id);
+    $result = array();
+    if (!empty($exe_id)) {
+       $sql_fb_type = "SELECT q.*, tee.*
+                        FROM $TBL_EXERCICES as q
+                        INNER JOIN $TBL_TRACK_EXERCICES as tee
+                        ON q.id=tee.exe_exo_id
+                        INNER JOIN $TBL_COURSE c
+                        ON c.code = tee.exe_cours_id
+                        WHERE tee.exe_id=$exe_id
+                        AND q.c_id=c.id";
+
+       $res_fb_type = Database::query($sql_fb_type);
+       $result      = Database::fetch_array($res_fb_type, 'ASSOC');
+    }
+    return $result;
+}
+
+
+/**
+ * Validates the time control key
+ */
+function exercise_time_control_is_valid($exercise_id, $lp_id = 0 , $lp_item_id = 0) {
+    $course_id = api_get_course_int_id();
+    $exercise_id = intval($exercise_id);
+    $TBL_EXERCICES =  Database::get_course_table(TABLE_QUIZ_TEST);
+    $sql 	= "SELECT expired_time FROM $TBL_EXERCICES WHERE c_id = $course_id AND id = $exercise_id";
+    $result = Database::query($sql);
+    $row	= Database::fetch_array($result, 'ASSOC');
+    if (!empty($row['expired_time']) ) {
+    	$current_expired_time_key = get_time_control_key($exercise_id, $lp_id, $lp_item_id);
+    	if (isset($_SESSION['expired_time'][$current_expired_time_key])) {
+            $current_time = time();
+    		$expired_time = api_strtotime($_SESSION['expired_time'][$current_expired_time_key], 'UTC');
+    		$total_time_allowed = $expired_time + 30;
+    		//error_log('expired time converted + 30: '.$total_time_allowed);
+    		//error_log('$current_time: '.$current_time);
+            if ($total_time_allowed < $current_time) {
+            	return false;
+            }
+            return true;
+    	} else {
+    		return false;
+    	}
+    } else {
+    	return true;
+    }
+}
+
+/**
+    Deletes the time control token
+*/
+function exercise_time_control_delete($exercise_id,  $lp_id = 0 , $lp_item_id = 0) {
+    $current_expired_time_key = get_time_control_key($exercise_id, $lp_id, $lp_item_id);
+    unset($_SESSION['expired_time'][$current_expired_time_key]);
+}
+
+/**
+    Generates the time control key
+*/
+function get_time_control_key($exercise_id, $lp_id = 0, $lp_item_id = 0) {
+    $exercise_id = intval($exercise_id);
+    $lp_id = intval($lp_id);
+    $lp_item_id = intval($lp_item_id);
+    return api_get_course_int_id().'_'.api_get_session_id().'_'.$exercise_id.'_'.api_get_user_id().'_'.$lp_id.'_'.$lp_item_id;
+}
+
+/**
+ * Get session time control
+ */
+function get_session_time_control_key($exercise_id, $lp_id = 0, $lp_item_id = 0) {
+    $return_value = 0;
+    $time_control_key = get_time_control_key($exercise_id, $lp_id, $lp_item_id);
+    if (isset($_SESSION['expired_time']) && isset($_SESSION['expired_time'][$time_control_key])) {
+        $return_value = $_SESSION['expired_time'][$time_control_key];
+    }
+    return $return_value;
+}
+
+/**
+ * Gets count of exam results
+ * @todo this function should be moved in a library  + no global calls
+ */
+function get_count_exam_results($exercise_id, $extra_where_conditions) {
+    $count = get_exam_results_data(null, null, null, null, $exercise_id, $extra_where_conditions, true);
+    return $count;
+}
+
+function get_count_exam_hotpotatoes_results($in_hotpot_path) {
+    return get_exam_results_hotpotatoes_data(0, 0, '', '', $in_hotpot_path, true, '');
+}
+
+//function get_exam_results_hotpotatoes_data($from, $number_of_items, $column, $direction, $exercise_id, $extra_where_conditions = null, $get_count = false) {
+function get_exam_results_hotpotatoes_data($in_from, $in_number_of_items, $in_column, $in_direction, $in_hotpot_path, $in_get_count = false, $where_condition = null) {
+
+    $tab_res = array();
+    $course_code = api_get_course_id();
+    // by default in_column = 1 If parameters given, it is the name of the column witch is the bdd field name
+    if ($in_column == 1) {
+        $in_column = 'firstname';
+    }
+
+    $TBL_TRACK_HOTPOTATOES      = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES);
+    $TBL_GROUP_REL_USER         = Database :: get_course_table(TABLE_GROUP_USER);
+    $TBL_GROUP                  = Database :: get_course_table(TABLE_GROUP);
+    $TBL_USER                   = Database :: get_main_table(TABLE_MAIN_USER);
+
+    $sql .= "SELECT * FROM $TBL_TRACK_HOTPOTATOES thp JOIN $TBL_USER u ON thp.exe_user_id = u.user_id WHERE thp.exe_cours_id = '$course_code' AND exe_name LIKE '$in_hotpot_path%'";
+
+    // just count how many answers
+    if ($in_get_count) {
+        $res = Database::query($sql);
+        return Database::num_rows($res);
+    }
+
+    // get a number of sorted results
+    $sql .= " $where_condition ORDER BY $in_column $in_direction  LIMIT $in_from, $in_number_of_items";
+
+    $res = Database::query($sql);
+    while ($data = Database::fetch_array($res)) {
+        $tab_one_res = array();
+        $tab_one_res['firstname'] = $data['firstname'];
+        $tab_one_res['lastname'] = $data['lastname'];
+        $tab_one_res['username'] = $data['username'];
+        $tab_one_res['group_name'] = implode("<br/>",GroupManager::get_user_group_name($data['user_id']));
+        $tab_one_res['exe_date'] = $data['exe_date'];
+        $tab_one_res['score'] = $data['exe_result'].'/'.$data['exe_weighting'];
+        $tab_one_res['actions'] = "";
+        $tab_res[] = $tab_one_res;
+    }
+    return $tab_res;
+}
+
+/**
+ * Gets the exam'data results
+ * @todo this function should be moved in a library  + no global calls
+ */
+function get_exam_results_data($from, $number_of_items, $column, $direction, $exercise_id, $extra_where_conditions = null, $get_count = false) {
+
+    //@todo replace all this globals
+    global $documentPath, $filter;
+
+    if (empty($extra_where_conditions)) {
+    	$extra_where_conditions = "1 = 1 ";
+    }
+
+    $course_id = api_get_course_int_id();
+    $course_code = api_get_course_id();
+
+   	$is_allowedToEdit           = api_is_allowed_to_edit(null,true) || api_is_allowed_to_edit(true) || api_is_drh();
+
+    $TBL_USER                   = Database :: get_main_table(TABLE_MAIN_USER);
+    $TBL_EXERCICES              = Database :: get_course_table(TABLE_QUIZ_TEST);
+    $TBL_GROUP_REL_USER         = Database :: get_course_table(TABLE_GROUP_USER);
+    $TBL_GROUP                  = Database :: get_course_table(TABLE_GROUP);
+
+    $TBL_TRACK_EXERCICES        = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+    $TBL_TRACK_HOTPOTATOES      = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES);
+    $TBL_TRACK_ATTEMPT_RECORDING= Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING);
+
+    $session_id_and = ' AND te.session_id = '.api_get_session_id().' ';
+
+    $exercise_id = intval($exercise_id);
+
+    $exercise_where = '';
+    if (!empty($exercise_id)) {
+        $exercise_where .= ' AND te.exe_exo_id = '.$exercise_id.'  ';
+    }
+
+    $hotpotatoe_where = '';
+    if (!empty($_GET['path'])) {
+        $hotpotatoe_path = Database::escape_string($_GET['path']);
+        $hotpotatoe_where .= ' AND exe_name = "'.$hotpotatoe_path.'"  ';
+    }
+
+    // sql for chamilo-type tests for teacher / tutor view
+    $sql_inner_join_tbl_track_exercices = " (
+                                            SELECT DISTINCT ttte.*, if(tr.exe_id,1, 0) as revised
+                                            FROM $TBL_TRACK_EXERCICES ttte LEFT JOIN $TBL_TRACK_ATTEMPT_RECORDING tr
+                                            ON (ttte.exe_id = tr.exe_id)
+                                            WHERE exe_cours_id = '$course_code' AND
+                                                  exe_exo_id = $exercise_id AND
+                                                  ttte.session_id = ".api_get_session_id()."
+                                            )";
+    if ($is_allowedToEdit) {
+        //Teacher view
+        if (isset($_GET['gradebook']) && $_GET['gradebook'] == 'view') {
+            //$exercise_where_query = ' te.exe_exo_id = ce.id AND ';
+        }
+
+    	$sqlFromOption                      = "";
+    	$sqlWhereOption                     = "";           // for hpsql
+
+        //@todo fix to work with COURSE_RELATION_TYPE_RRHH in both queries
+
+        //Hack in order to filter groups
+        $sql_inner_join_tbl_user = '';
+
+        if (strpos($extra_where_conditions, 'group_id')) {
+            $sql_inner_join_tbl_user = "
+            (
+                SELECT u.user_id, firstname, lastname, email, username, g.name as group_name, g.id as group_id
+                FROM $TBL_USER u
+                INNER JOIN $TBL_GROUP_REL_USER gru ON ( gru.user_id = u.user_id AND gru.c_id=".$course_id.")
+                INNER JOIN $TBL_GROUP g ON (gru.group_id = g.id AND g.c_id=".$course_id.")
+            )";
+
+        }
+
+        if (strpos($extra_where_conditions, 'group_all')) {
+
+            $extra_where_conditions = str_replace("AND (  group_id = 'group_all'  )", '', $extra_where_conditions);
+            $extra_where_conditions = str_replace("AND group_id = 'group_all'", '', $extra_where_conditions);
+            $extra_where_conditions = str_replace("group_id = 'group_all' AND", '', $extra_where_conditions);
+
+            $sql_inner_join_tbl_user = "
+            (
+                SELECT u.user_id, firstname, lastname, email, username, '' as group_name, '' as group_id
+                FROM $TBL_USER u
+            )";
+            $sql_inner_join_tbl_user = null;
+        }
+
+        if (strpos($extra_where_conditions, 'group_none')) {
+            $extra_where_conditions = str_replace("AND (  group_id = 'group_none'  )", "AND (  group_id is null  )", $extra_where_conditions);
+            $extra_where_conditions = str_replace("AND group_id = 'group_none'", "AND (  group_id is null  )", $extra_where_conditions);
+            $sql_inner_join_tbl_user = "
+            (
+                SELECT u.user_id, firstname, lastname, email, username, g.name as group_name, g.id as group_id
+                FROM $TBL_USER u
+                LEFT OUTER JOIN $TBL_GROUP_REL_USER gru ON ( gru.user_id = u.user_id AND gru.c_id=".$course_id." )
+                LEFT OUTER JOIN $TBL_GROUP g ON (gru.group_id = g.id AND g.c_id = ".$course_id.")
+            )";
+        }
+
+        //All
+        $is_empty_sql_inner_join_tbl_user = false;
+
+        if (empty($sql_inner_join_tbl_user)) {
+            $is_empty_sql_inner_join_tbl_user = true;
+             $sql_inner_join_tbl_user = "
+            (
+                SELECT u.user_id, firstname, lastname, email, username, ' ' as group_name, '' as group_id
+                FROM $TBL_USER u
+            )";
+        }
+
+
+        $sqlFromOption = " , $TBL_GROUP_REL_USER AS gru ";
+        $sqlWhereOption = "  AND gru.c_id = ".api_get_course_int_id()." AND gru.user_id = user.user_id ";
+
+        $first_and_last_name = api_is_western_name_order() ? "firstname, lastname" : "lastname, firstname";
+
+        if ($get_count) {
+            $sql_select = "SELECT count(te.exe_id) ";
+        } else {
+            $sql_select = "SELECT DISTINCT
+                    user_id,
+                    $first_and_last_name,
+                    ce.title,
+                    username,
+                    te.exe_result,
+                    te.exe_weighting,
+                    te.exe_date,
+                    te.exe_id,
+                    email as exemail,
+                    te.start_date,
+                    steps_counter,
+                    exe_user_id,
+                    te.exe_duration,
+                    propagate_neg,
+                    revised,
+                    group_name,
+                    group_id,
+                    orig_lp_id";
+        }
+
+        $sql = " $sql_select
+                FROM $TBL_EXERCICES AS ce
+                INNER JOIN $sql_inner_join_tbl_track_exercices AS te ON (te.exe_exo_id = ce.id)
+                INNER JOIN $sql_inner_join_tbl_user  AS user ON (user.user_id = exe_user_id)
+                WHERE $extra_where_conditions AND
+                    te.status != 'incomplete'
+                    AND te.exe_cours_id='" . api_get_course_id() . "' $session_id_and
+                    AND ce.active <>-1
+                    AND ce.c_id=".api_get_course_int_id()."
+                    $exercise_where ";
+
+        // sql for hotpotatoes tests for teacher / tutor view
+
+        if ($get_count) {
+            $hpsql_select = "SELECT count(username)";
+        } else {
+            $hpsql_select = "SELECT
+                    $first_and_last_name ,
+                    username,
+                    tth.exe_name,
+                    tth.exe_result ,
+                    tth.exe_weighting,
+                    tth.exe_date";
+        }
+
+        $hpsql = " $hpsql_select
+                FROM
+                    $TBL_TRACK_HOTPOTATOES tth,
+                    $TBL_USER user
+                    $sqlFromOption
+                WHERE
+                    user.user_id=tth.exe_user_id
+                    AND tth.exe_cours_id = '" . api_get_course_id()."'
+                    $hotpotatoe_where
+                    $sqlWhereOption
+    				AND $where_condition
+                ORDER BY
+                    tth.exe_cours_id ASC,
+                    tth.exe_date DESC";
+    }
+
+    if ($get_count) {
+        $resx = Database::query($sql);
+        $rowx = Database::fetch_row($resx,'ASSOC');
+        return $rowx[0];
+    }
+
+    $teacher_list = CourseManager::get_teacher_list_from_course_code(api_get_course_id());
+    $teacher_id_list = array();
+    foreach ($teacher_list as $teacher) {
+    	$teacher_id_list[] = $teacher['user_id'];
+    }
+
+    //Simple exercises
+    if (empty($hotpotatoe_where)) {
+        $column             = !empty($column) ? Database::escape_string($column) : null;
+        $from               = intval($from);
+        $number_of_items    = intval($number_of_items);
+
+        if (!empty($column)) {
+            $sql .= " ORDER BY $column $direction ";
+        }
+        $sql .= " LIMIT $from, $number_of_items";
+
+        $results = array();
+        $resx = Database::query($sql);
+        while ($rowx = Database::fetch_array($resx,'ASSOC')) {
+            $results[] = $rowx;
+        }
+
+        $list_info = array();
+
+        $group_list = GroupManager::get_group_list();
+        $clean_group_list = array();
+
+        if (!empty($group_list)) {
+            foreach ($group_list as $group) {
+                $clean_group_list[$group['id']] = $group['name'];
+            }
+        }
+
+        $lp_list_obj = new learnpathList(api_get_user_id());
+        $lp_list = $lp_list_obj->get_flat_list();
+
+        if (is_array($results)) {
+
+            $users_array_id = array();
+            if ($_GET['gradebook'] == 'view') {
+                $from_gradebook = true;
+            }
+            $sizeof = count($results);
+
+            $user_list_id = array ();
+
+            $locked = api_resource_is_locked_by_gradebook($exercise_id, LINK_EXERCISE);
+
+            //Looping results
+            for ($i = 0; $i < $sizeof; $i++) {
+                $revised = $results[$i]['revised'];
+
+                if ($from_gradebook && ($is_allowedToEdit)) {
+                    if (in_array($results[$i]['username'] . $results[$i]['firstname'] . $results[$i]['lastname'], $users_array_id)) {
+                        continue;
+                    }
+                    $users_array_id[] = $results[$i]['username'] . $results[$i]['firstname'] . $results[$i]['lastname'];
+                }
+
+                $lp_obj = isset($results[$i]['orig_lp_id']) && isset($lp_list[$results[$i]['orig_lp_id']]) ? $lp_list[$results[$i]['orig_lp_id']] : null;
+                $lp_name = null;
+
+                if ($lp_obj) {
+                    $url = api_get_path(WEB_CODE_PATH).'newscorm/lp_controller.php?'.api_get_cidreq().'&action=view&lp_id='.$results[$i]['orig_lp_id'];
+                    $lp_name =  Display::url($lp_obj['lp_name'], $url, array('target' => '_blank'));
+                }
+
+                //Add all groups by user
+                $group_name_list = null;
+
+                if ($is_empty_sql_inner_join_tbl_user) {
+                    $group_list = GroupManager::get_group_ids(api_get_course_int_id(), $results[$i]['user_id']);
+
+                    foreach ($group_list as $id) {
+                        $group_name_list .= $clean_group_list[$id].'<br/>';
+                    }
+                    $results[$i]['group_name'] = $group_name_list;
+                }
+
+                $results[$i]['exe_duration'] =  !empty($results[$i]['exe_duration']) ? round($results[$i]['exe_duration'] / 60) : 0;
+
+                $user_list_id[] = $results[$i]['exe_user_id'];
+                $id = $results[$i]['exe_id'];
+
+                $dt = api_convert_and_format_date($results[$i]['exe_weighting']);
+
+                // we filter the results if we have the permission to
+                if (isset($results[$i]['results_disabled'])) {
+                    $result_disabled = intval($results[$i]['results_disabled']);
+                }  else {
+                    $result_disabled = 0;
+                }
+
+                if ($result_disabled == 0) {
+
+                    $my_res     = $results[$i]['exe_result'];
+                    $my_total   = $results[$i]['exe_weighting'];
+
+                    $results[$i]['start_date']  =   api_get_local_time($results[$i]['start_date']);
+                    $results[$i]['exe_date']    =   api_get_local_time($results[$i]['exe_date']);
+
+                    if (!$results[$i]['propagate_neg'] && $my_res < 0) {
+                        $my_res = 0;
+                    }
+                    $score = show_score($my_res, $my_total);
+
+                    $actions = '';
+                    if ($is_allowedToEdit) {
+                        if (isset($teacher_id_list)) {
+                            if (in_array($results[$i]['exe_user_id'], $teacher_id_list)) {
+                                $actions .= Display::return_icon('teachers.gif', get_lang('Teacher'));
+                            }
+                        }
+                        if ($revised) {
+                            $actions .= "<a href='exercise_show.php?".api_get_cidreq()."&action=edit&id=$id'>".Display :: return_icon('edit.png', get_lang('Edit'), array(), ICON_SIZE_SMALL);
+                            $actions .= '&nbsp;';
+                        } else {
+                            $actions .="<a href='exercise_show.php?".api_get_cidreq()."&action=qualify&id=$id'>".Display :: return_icon('quiz.gif', get_lang('Qualify'));
+                            $actions .='&nbsp;';
+                        }
+                        $actions .="</a>";
+
+                        if ($filter == 2) {
+                            $actions .=' <a href="exercise_history.php?'.api_get_cidreq().'&exe_id=' . $id . '">' .Display :: return_icon('history.gif', get_lang('ViewHistoryChange')).'</a>';
+                        }
+
+                        //Admin can always delete the attempt
+                        if ($locked == false || api_is_platform_admin()) {
+                            $ip = TrackingUserLog::get_ip_from_user_event($results[$i]['exe_user_id'], $results[$i]['exe_date'], false);
+                            $actions .= '<a href="http://www.whatsmyip.org/ip-geo-location/?ip='.$ip.'" target="_blank"><img src="'.api_get_path(WEB_CODE_PATH).'img/icons/22/info.png" title="'.$ip.'" /></a>';
+
+                            $delete_link = '<a href="exercise_report.php?'.api_get_cidreq().'&filter_by_user='.intval($_GET['filter_by_user']).'&filter=' . $filter . '&exerciseId='.$exercise_id.'&delete=delete&did=' . $id . '"
+                                onclick="javascript:if(!confirm(\'' . sprintf(get_lang('DeleteAttempt'), $results[$i]['username'], $dt) . '\')) return false;">'.Display :: return_icon('delete.png', get_lang('Delete')).'</a>';
+                            $delete_link = utf8_encode($delete_link);
+                            $actions .= $delete_link.'&nbsp;';
+                        }
+
+                    } else {
+                    	$attempt_url 	= api_get_path(WEB_CODE_PATH).'exercice/result.php?'.api_get_cidreq().'&id='.$results[$i]['exe_id'].'&id_session='.api_get_session_id().'&height=500&width=750';
+                    	$attempt_link 	= Display::url(get_lang('Show'), $attempt_url, array('class'=>'ajax btn'));
+                    	$actions .= $attempt_link;
+                    }
+
+                    if ($revised) {
+                        $revised = Display::label(get_lang('Validated'), 'success');
+                    } else {
+                        $revised = Display::label(get_lang('NotValidated'), 'info');
+                    }
+
+                    if ($is_allowedToEdit) {
+    					$results[$i]['status']  =  $revised;
+    					$results[$i]['score']   =  $score;
+                        $results[$i]['lp']      =  $lp_name;
+    					$results[$i]['actions'] =  $actions;
+    					$list_info[] = $results[$i];
+                    } else {
+                        $results[$i]['status']  =  $revised;
+    					$results[$i]['score']   =  $score;
+                        $results[$i]['actions'] =  $actions;
+    					$list_info[] = $results[$i];
+                    }
+                }
+            }
+        }
+    } else {
+        //echo $hpsql; var_dump($hpsql);
+        $hpresults = getManyResultsXCol($hpsql, 6);
+
+        // Print HotPotatoes test results.
+        if (is_array($hpresults)) {
+
+            for ($i = 0; $i < sizeof($hpresults); $i++) {
+                $hp_title = GetQuizName($hpresults[$i][3], $documentPath);
+                if ($hp_title == '') {
+                    $hp_title = basename($hpresults[$i][3]);
+                }
+                //var_dump($hpresults[$i]);
+
+                $hp_date = api_get_local_time($hpresults[$i][6], null, date_default_timezone_get());
+                $hp_result = round(($hpresults[$i][4] / ($hpresults[$i][5] != 0 ? $hpresults[$i][5] : 1)) * 100, 2).'% ('.$hpresults[$i][4].' / '.$hpresults[$i][5].')';
+                if ($is_allowedToEdit) {
+                    $list_info[] = array($hpresults[$i][0], $hpresults[$i][1], $hpresults[$i][2], '',  $hp_title, '-',  $hp_date , $hp_result , '-');
+                } else {
+                    $list_info[] = array($hp_title, '-', $hp_date , $hp_result , '-');
+                }
+            }
+        }
+    }
+
+    return $list_info;
+}
+
+
+/**
+ * Converts the score with the exercise_max_note and exercise_min_score the platform settings + formats the results using the float_format function
+ *
+ * @param   float   score
+ * @param   float   weight
+ * @param   bool    show porcentage or not
+ * @param	bool	use or not the platform settings
+ * @return  string  an html with the score modified
+ */
+function show_score($score, $weight, $show_percentage = true, $use_platform_settings = true, $show_only_percentage = false) {
+    if (is_null($score) && is_null($weight)) {
+        return '-';
+    }
+
+    $max_note =  api_get_setting('exercise_max_score');
+    $min_note =  api_get_setting('exercise_min_score');
+
+    if ($use_platform_settings) {
+        if ($max_note != '' && $min_note != '') {
+            if (!empty($weight) && intval($weight) != 0) {
+    	       $score = $min_note + ($max_note - $min_note) * $score / $weight;
+            } else {
+               $score = $min_note;
+            }
+            $weight = $max_note;
+        }
+    }
+    $percentage = (100 * $score)/ ($weight != 0 ? $weight : 1);
+
+    //Formats values
+    $percentage = float_format($percentage, 1);
+    $score = float_format($score, 1);
+    $weight = float_format($weight, 1);
+
+    $html  = null;
+    if ($show_percentage) {
+        $parent = '(' . $score . ' / ' . $weight . ')';
+        $html = $percentage."%  $parent";
+        if ($show_only_percentage) {
+            $html = $percentage."% ";
+        }
+    } else {
+    	$html = $score . ' / ' . $weight;
+    }
+    $html  = Display::span($html, array('class' => 'score_exercise'));
+    return $html;
+}
+
+function is_success_exercise_result($score, $weight, $pass_percentage) {
+    $percentage = float_format(($score / ($weight != 0 ? $weight : 1)) * 100, 1);
+    if (isset($pass_percentage) && !empty($pass_percentage)) {
+        if ($percentage >= $pass_percentage) {
+            return true;
+        }
+    }
+    return false;
+}
+
+function show_success_message($score, $weight, $pass_percentage) {
+    $res = "";
+    if (is_pass_pourcentage_enabled($pass_percentage)) {
+        $is_success = is_success_exercise_result($score, $weight, $pass_percentage);
+
+        $icon = '';
+        if ($is_success) {
+            $html = get_lang('CongratulationsYouPassedTheTest');
+            $icon = Display::return_icon('completed.png', get_lang('Correct'), array(), ICON_SIZE_MEDIUM);
+        } else {
+            //$html .= Display::return_message(get_lang('YouDidNotReachTheMinimumScore'), 'warning');
+            $html = get_lang('YouDidNotReachTheMinimumScore');
+            $icon = Display::return_icon('warning.png', get_lang('Wrong'), array(), ICON_SIZE_MEDIUM);
+        }
+        $html = Display::tag('h4', $html);
+        $html .= Display::tag('h5', $icon, array('style' => 'width:40px; padding:2px 10px 0px 0px'));
+        $res = $html;
+    }
+    return $res;
+}
+
+/**
+ * Return true if pass_pourcentage activated (we use the pass pourcentage feature
+ * return false if pass_percentage = 0 (we don't use the pass pourcentage feature
+ * @param $in_pass_pourcentage
+ * @return boolean
+ * In this version, pass_percentage and show_success_message are disabled if
+ * pass_percentage is set to 0
+ */
+function is_pass_pourcentage_enabled($in_pass_pourcentage) {
+    return $in_pass_pourcentage > 0;
+}
+
+/**
+ * Converts a numeric value in a percentage example 0.66666 to 66.67 %
+ * @param $value
+ * @return float Converted number
+ */
+function convert_to_percentage($value) {
+    $return = '-';
+    if ($value != '') {
+        $return = float_format($value * 100, 1).' %';
+    }
+    return $return;
+}
+
+/**
+ * Converts a score/weight values to the platform scale
+ * @param   float   score
+ * @param   float   weight
+ * @return  float   the score rounded converted to the new range
+ */
+function convert_score($score, $weight) {
+    $max_note =  api_get_setting('exercise_max_score');
+    $min_note =  api_get_setting('exercise_min_score');
+
+    if ($score != '' && $weight != '') {
+        if ($max_note != '' && $min_note != '') {
+           if (!empty($weight)) {
+               $score   = $min_note + ($max_note - $min_note) * $score / $weight;
+           } else {
+               $score   = $min_note;
+           }
+        }
+    }
+    $score_rounded  = float_format($score, 1);
+    return $score_rounded;
+}
+
+/**
+ * Getting all active exercises from a course from a session (if a session_id is provided we will show all the exercises in the course + all exercises in the session)
+ * @param   array   course data
+ * @param   int     session id
+ * @return  array   array with exercise data
+ */
+function get_all_exercises($course_info = null, $session_id = 0, $check_publication_dates = false) {
+    $TBL_EXERCICES = Database :: get_course_table(TABLE_QUIZ_TEST);
+    $course_id = api_get_course_int_id();
+
+    if (!empty($course_info) && !empty($course_info['real_id'])) {
+    	$course_id = $course_info['real_id'];
+    }
+
+    if ($session_id == -1) {
+    	$session_id  = 0;
+    }
+
+    $now = api_get_utc_datetime();
+    $time_conditions = '';
+
+    if ($check_publication_dates) {
+        $time_conditions = " AND ((start_time <> '0000-00-00 00:00:00' AND start_time < '$now'  AND end_time <> '0000-00-00 00:00:00' AND end_time > '$now' )  OR "; //start and end are set
+        $time_conditions .= " (start_time <> '0000-00-00 00:00:00' AND start_time < '$now'  AND end_time = '0000-00-00 00:00:00') OR "; // only start is set
+        $time_conditions .= " (start_time = '0000-00-00 00:00:00'   AND end_time <> '0000-00-00 00:00:00'  AND end_time > '$now') OR   "; // only end is set
+        $time_conditions .= " (start_time = '0000-00-00 00:00:00'   AND end_time =  '0000-00-00 00:00:00'))  "; // nothing is set
+    }
+
+    if ($session_id == 0) {
+    	$conditions = array('where'=>array('active = ? AND session_id = ? AND c_id = ? '.$time_conditions => array('1', $session_id, $course_id)), 'order'=>'title');
+    } else {
+        //All exercises
+    	$conditions = array('where'=>array('active = ? AND  (session_id = 0 OR session_id = ? ) AND c_id = ? '.$time_conditions => array('1', $session_id, $course_id)), 'order'=>'title');
+    }
+    return Database::select('*',$TBL_EXERCICES, $conditions);
+}
+
+
+/**
+ * Getting all active exercises from a course from a session (if a session_id is provided we will show all the exercises in the course + all exercises in the session)
+ * @param   array   course data
+ * @param   int     session id
+ * @param		int			course c_id
+ * @return  array   array with exercise data
+ * modified by Hubert Borderiou
+ */
+function get_all_exercises_for_course_id($course_info = null, $session_id = 0, $course_id=0) {
+   	$TBL_EXERCICES = Database :: get_course_table(TABLE_QUIZ_TEST);
+    if ($session_id == -1) {
+    	$session_id  = 0;
+    }
+    if ($session_id == 0) {
+    	$conditions = array('where'=>array('active = ? AND session_id = ? AND c_id = ?'=>array('1', $session_id, $course_id)), 'order'=>'title');
+    } else {
+        //All exercises
+    	$conditions = array('where'=>array('active = ? AND (session_id = 0 OR session_id = ? ) AND c_id=?' =>array('1', $session_id, $course_id)), 'order'=>'title');
+    }
+    return Database::select('*',$TBL_EXERCICES, $conditions);
+}
+
+/**
+ * Gets the position of the score based in a given score (result/weight) and the exe_id based in the user list
+ * (NO Exercises in LPs )
+ * @param   float   user score to be compared *attention* $my_score = score/weight and not just the score
+ * @param   int     exe id of the exercise (this is necesary because if 2 students have the same score the one with the minor exe_id will have a best position, just to be fair and FIFO)
+ * @param   int     exercise id
+ * @param   string  course code
+ * @param   int     session id
+ * @return  int     the position of the user between his friends in a course (or course within a session)
+ */
+function get_exercise_result_ranking($my_score, $my_exe_id, $exercise_id, $course_code, $session_id = 0, $user_list = array(), $return_string = true) {
+    //No score given we return
+    if (is_null($my_score)) {
+        return '-';
+    }
+    if (empty($user_list)) {
+        return '-';
+    }
+
+    $best_attempts = array();
+    foreach ($user_list as $user_data) {
+        $user_id = $user_data['user_id'];
+        $best_attempts[$user_id]= get_best_attempt_by_user($user_id, $exercise_id, $course_code, $session_id);
+    }
+
+    if (empty($best_attempts)) {
+    	return 1;
+    } else {
+        $position = 1;
+        $my_ranking = array();
+        foreach($best_attempts as $user_id => $result) {
+            if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) {
+                $my_ranking[$user_id] = $result['exe_result']/$result['exe_weighting'];
+            } else {
+                $my_ranking[$user_id] = 0;
+            }
+        }
+        //if (!empty($my_ranking)) {
+            asort($my_ranking);
+            $position = count($my_ranking);
+            if (!empty($my_ranking)) {
+                foreach ($my_ranking as $user_id => $ranking) {
+                	if ($my_score >= $ranking) {
+                        if ($my_score == $ranking) {
+                            $exe_id = $best_attempts[$user_id]['exe_id'];
+                            if ($my_exe_id < $exe_id) {
+                                $position--;
+                            }
+                        } else {
+                		  $position--;
+                        }
+                	}
+                }
+            }
+        //}
+        $return_value = array('position'=>$position, 'count'=>count($my_ranking));
+        //var_dump($my_score, $my_ranking);
+        if ($return_string) {
+            if (!empty($position) && !empty($my_ranking)) {
+               $return_value = $position.'/'.count($my_ranking);
+            } else {
+                $return_value = '-';
+            }
+        }
+        return $return_value;
+    }
+}
+
+/**
+ * Gets the position of the score based in a given score (result/weight) and the exe_id based in all attempts
+ * (NO Exercises in LPs ) old funcionality by attempt
+ * @param   float   user score to be compared attention => score/weight
+ * @param   int     exe id of the exercise (this is necesary because if 2 students have the same score the one with the minor exe_id will have a best position, just to be fair and FIFO)
+ * @param   int     exercise id
+ * @param   string  course code
+ * @param   int     session id
+ * @return  int     the position of the user between his friends in a course (or course within a session)
+ */
+function get_exercise_result_ranking_by_attempt($my_score, $my_exe_id, $exercise_id, $course_code, $session_id = 0, $return_string = true) {
+    if (empty($session_id)) {
+    	$session_id = 0;
+    }
+    if (is_null($my_score)) {
+        return '-';
+    }
+    $user_results = get_all_exercise_results($exercise_id, $course_code, $session_id, false);
+    $position_data = array();
+    if (empty($user_results)) {
+    	return 1;
+    } else {
+        $position = 1;
+        $my_ranking = array();
+        foreach($user_results as $result) {
+            //print_r($result);
+            if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) {
+                $my_ranking[$result['exe_id']] = $result['exe_result']/$result['exe_weighting'];
+            } else {
+                $my_ranking[$result['exe_id']] = 0;
+            }
+        }
+        asort($my_ranking);
+        $position = count($my_ranking);
+        if (!empty($my_ranking)) {
+            foreach($my_ranking as $exe_id=>$ranking) {
+            	if ($my_score >= $ranking) {
+                    if ($my_score == $ranking) {
+                        if ($my_exe_id < $exe_id) {
+                            $position--;
+                        }
+                    } else {
+            		  $position--;
+                    }
+            	}
+            }
+        }
+        $return_value = array('position'=>$position, 'count'=>count($my_ranking));
+        //var_dump($my_score, $my_ranking);
+        if ($return_string) {
+            if (!empty($position) && !empty($my_ranking)) {
+               return $position.'/'.count($my_ranking);
+            }
+        }
+        return $return_value;
+    }
+}
+
+
+/*
+ *  Get the best attempt in a exercise (NO Exercises in LPs )
+ */
+
+function get_best_attempt_in_course($exercise_id, $course_code, $session_id) {
+    $user_results = get_all_exercise_results($exercise_id, $course_code, $session_id, false);
+    $best_score_data = array();
+    $best_score = 0;
+    if (!empty($user_results)) {
+        foreach($user_results as $result) {
+            if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) {
+                $score = $result['exe_result']/$result['exe_weighting'];
+                if ($score >= $best_score) {
+                    $best_score = $score;
+                    $best_score_data = $result;
+                }
+            }
+        }
+    }
+    return $best_score_data;
+}
+
+/*
+ *  Get the best score in a exercise (NO Exercises in LPs )
+ */
+function get_best_attempt_by_user($user_id, $exercise_id, $course_code, $session_id) {
+    $user_results = get_all_exercise_results($exercise_id, $course_code, $session_id, false, $user_id);
+    $best_score_data = array();
+    $best_score = 0;
+    if (!empty($user_results)) {
+        foreach($user_results as $result) {
+            if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) {
+                $score = $result['exe_result']/$result['exe_weighting'];
+                if ($score >= $best_score) {
+                    $best_score = $score;
+                    $best_score_data = $result;
+                }
+            }
+        }
+    }
+    return $best_score_data;
+}
+
+
+
+
+/**
+ * Get average score (NO Exercises in LPs )
+ * @param 	int	exercise id
+ * @param 	string	course code
+ * @param 	int	session id
+ * @return 	float	Average score
+ */
+function get_average_score($exercise_id, $course_code, $session_id) {
+    $user_results = get_all_exercise_results($exercise_id, $course_code, $session_id);
+    $avg_score = 0;
+    if (!empty($user_results)) {
+        foreach($user_results as $result) {
+            if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) {
+                $score = $result['exe_result']/$result['exe_weighting'];
+                $avg_score +=$score;
+            }
+        }
+        $avg_score = float_format($avg_score / count($user_results), 1);
+    }
+    return $avg_score;
+}
+
+/**
+ * Get average score by score (NO Exercises in LPs )
+ * @param 	int	exercise id
+ * @param 	string	course code
+ * @param 	int	session id
+ * @return 	float	Average score
+ */
+function get_average_score_by_course($course_code, $session_id) {
+    $user_results = get_all_exercise_results_by_course($course_code, $session_id, false);
+    //echo $course_code.' - '.$session_id.'<br />';
+    $avg_score = 0;
+    if (!empty($user_results)) {
+        foreach($user_results as $result) {
+            if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) {
+                $score = $result['exe_result']/$result['exe_weighting'];
+                //var_dump($score);
+                $avg_score +=$score;
+            }
+        }
+        //We asume that all exe_weighting
+        //$avg_score = show_score( $avg_score / count($user_results) , $result['exe_weighting']);
+        $avg_score = ($avg_score / count($user_results));
+    }
+    //var_dump($avg_score);
+    return $avg_score;
+}
+
+function get_average_score_by_course_by_user($user_id, $course_code, $session_id) {
+    $user_results = get_all_exercise_results_by_user($user_id, $course_code, $session_id);
+    $avg_score = 0;
+    if (!empty($user_results)) {
+    	foreach($user_results as $result) {
+    		if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) {
+    			$score = $result['exe_result']/$result['exe_weighting'];
+    			$avg_score +=$score;
+    		}
+    	}
+    	//We asume that all exe_weighting
+    	//$avg_score = show_score( $avg_score / count($user_results) , $result['exe_weighting']);
+    	$avg_score = ($avg_score / count($user_results));
+    }
+    return $avg_score;
+}
+
+
+/**
+ * Get average score by score (NO Exercises in LPs )
+ * @param 	int		exercise id
+ * @param 	string	course code
+ * @param 	int		session id
+ * @return	float	Best average score
+ */
+function get_best_average_score_by_exercise($exercise_id, $course_code, $session_id, $user_count) {
+    $user_results = get_best_exercise_results_by_user($exercise_id, $course_code, $session_id);
+    $avg_score = 0;
+    if (!empty($user_results)) {
+        foreach($user_results as $result) {
+            if (!empty($result['exe_weighting']) && intval($result['exe_weighting']) != 0) {
+                $score = $result['exe_result']/$result['exe_weighting'];
+                $avg_score +=$score;
+            }
+        }
+        //We asume that all exe_weighting
+        //$avg_score = show_score( $avg_score / count($user_results) , $result['exe_weighting']);
+        //$avg_score = ($avg_score / count($user_results));
+        if(!empty($user_count)) {
+            $avg_score = float_format($avg_score / $user_count, 1) * 100;
+        } else {
+            $avg_score = 0;
+        }
+    }
+    return $avg_score;
+}
+
+function get_exercises_to_be_taken($course_code, $session_id) {
+    $course_info = api_get_course_info($course_code);
+    $exercises = get_all_exercises($course_info, $session_id);
+    $result = array();
+    $now = time() + 15*24*60*60;
+    foreach($exercises as $exercise_item) {
+    	if (isset($exercise_item['end_time'])  && !empty($exercise_item['end_time']) && $exercise_item['end_time'] != '0000-00-00 00:00:00' && api_strtotime($exercise_item['end_time'], 'UTC') < $now) {
+    		$result[] = $exercise_item;
+    	}
+    }
+    return $result;
+}
+
+/**
+ * Get student results (only in completed exercises) stats by question
+ * @param 	int		question id
+ * @param 	int		exercise id
+ * @param 	string	course code
+ * @param 	int		session id
+ *
+ * */
+function get_student_stats_by_question($question_id,  $exercise_id, $course_code, $session_id) {
+    $track_exercises	= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+    $track_attempt		= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
+
+    $question_id 		= intval($question_id);
+    $exercise_id 		= intval($exercise_id);
+    $course_code 		= Database::escape_string($course_code);
+    $session_id 		= intval($session_id);
+
+    $sql = "SELECT MAX(marks) as max , MIN(marks) as min, AVG(marks) as average
+    		FROM $track_exercises e INNER JOIN $track_attempt a ON (a.exe_id = e.exe_id)
+    		WHERE 	exe_exo_id 		= $exercise_id AND
+    				course_code 	= '$course_code' AND
+    				e.session_id 	= $session_id AND
+    				question_id 	= $question_id AND status = '' LIMIT 1";
+    $result = Database::query($sql);
+    $return = array();
+    if ($result) {
+    	$return = Database::fetch_array($result, 'ASSOC');
+
+    }
+    return $return;
+}
+
+function get_number_students_question_with_answer_count($question_id, $exercise_id, $course_code, $session_id) {
+    $track_exercises	= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+    $track_attempt		= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
+    $course_user        = Database::get_main_table(TABLE_MAIN_COURSE_USER);
+
+    $question_id 		= intval($question_id);
+    $exercise_id 		= intval($exercise_id);
+    $course_code 		= Database::escape_string($course_code);
+    $session_id 		= intval($session_id);
+
+
+    $sql = "SELECT DISTINCT exe_user_id
+    		FROM $track_exercises e INNER JOIN $track_attempt a ON (a.exe_id = e.exe_id) INNER JOIN $course_user cu
+                ON cu.course_code = a.course_code AND cu.user_id  = exe_user_id
+    		WHERE 	exe_exo_id 		= $exercise_id AND
+    				a.course_code 	= '$course_code' AND
+    				e.session_id 	= $session_id AND
+    				question_id 	= $question_id AND
+                    answer          <> '0' AND
+                    cu.status       = ".STUDENT." AND
+                    relation_type  <> 2 AND
+                    e.status        = ''";
+    $result = Database::query($sql);
+    $return = 0;
+    if ($result) {
+    	$return = Database::num_rows($result);
+    }
+    return $return;
+}
+
+function get_number_students_answer_hotspot_count($answer_id, $question_id,  $exercise_id, $course_code, $session_id) {
+    $track_exercises	= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+    $track_hotspot		= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTSPOT);
+    $course_user        = Database::get_main_table(TABLE_MAIN_COURSE_USER);
+
+    $question_id 		= intval($question_id);
+    $answer_id          = intval($answer_id);
+    $exercise_id 		= intval($exercise_id);
+    $course_code 		= Database::escape_string($course_code);
+    $session_id 		= intval($session_id);
+
+    $sql = "SELECT DISTINCT exe_user_id
+    		FROM $track_exercises e INNER JOIN $track_hotspot a ON (a.hotspot_exe_id = e.exe_id) INNER JOIN $course_user cu
+                ON cu.course_code = a.hotspot_course_code AND cu.user_id  = exe_user_id
+    		WHERE 	exe_exo_id              = $exercise_id AND
+    				a.hotspot_course_code 	= '$course_code' AND
+    				e.session_id            = $session_id AND
+                    hotspot_answer_id       = $answer_id AND
+    				hotspot_question_id     = $question_id AND
+                    cu.status               = ".STUDENT." AND
+                    hotspot_correct         =  1 AND
+                    relation_type           <> 2 AND
+                    e.status                = ''";
+
+    $result = Database::query($sql);
+    $return = 0;
+    if ($result) {
+    	$return = Database::num_rows($result);
+    }
+    return $return;
+}
+
+
+function get_number_students_answer_count($answer_id, $question_id, $exercise_id, $course_code, $session_id, $question_type = null, $correct_answer = null, $current_answer = null) {
+    $track_exercises	= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+    $track_attempt		= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
+    $course_user        = Database::get_main_table(TABLE_MAIN_COURSE_USER);
+
+    $question_id 		= intval($question_id);
+    $answer_id          = intval($answer_id);
+    $exercise_id 		= intval($exercise_id);
+    $course_code 		= Database::escape_string($course_code);
+    $session_id 		= intval($session_id);
+
+    switch ($question_type) {
+        case FILL_IN_BLANKS:
+            $answer_condition = "";
+            $select_condition = " e.exe_id, answer ";
+            break;
+        case MATCHING:
+        default:
+            $answer_condition = " answer = $answer_id AND ";
+            $select_condition = " DISTINCT exe_user_id ";
+    }
+
+    $sql = "SELECT $select_condition
+    		FROM $track_exercises e INNER JOIN $track_attempt a ON (a.exe_id = e.exe_id) INNER JOIN $course_user cu
+                ON cu.course_code = a.course_code AND cu.user_id  = exe_user_id
+    		WHERE 	exe_exo_id 		= $exercise_id AND
+    				a.course_code 	= '$course_code' AND
+    				e.session_id 	= $session_id AND
+                    $answer_condition
+    				question_id 	= $question_id AND
+                    cu.status        = ".STUDENT." AND
+                    relation_type <> 2 AND
+                    e.status = ''";
+    //var_dump($sql);
+    $result = Database::query($sql);
+    $return = 0;
+    if ($result) {
+        $good_answers = 0;
+        switch ($question_type) {
+            case FILL_IN_BLANKS:
+                while ($row = Database::fetch_array($result, 'ASSOC')) {
+                    $fill_blank = check_fill_in_blanks($correct_answer, $row['answer']);
+                    if (isset($fill_blank[$current_answer]) && $fill_blank[$current_answer] == 1 ) {
+                        $good_answers++;
+                    }
+                }
+                return $good_answers;
+                break;
+            case MATCHING:
+            default:
+                $return = Database::num_rows($result);
+        }
+    }
+    return $return;
+}
+
+
+function check_fill_in_blanks($answer, $user_answer) {
+    // the question is encoded like this
+    // [A] B [C] D [E] F::10,10,10@1
+    // number 1 before the "@" means that is a switchable fill in blank question
+    // [A] B [C] D [E] F::10,10,10@ or  [A] B [C] D [E] F::10,10,10
+    // means that is a normal fill blank question
+    // first we explode the "::"
+    $pre_array = explode('::', $answer);
+    // is switchable fill blank or not
+    $last = count($pre_array) - 1;
+    $is_set_switchable = explode('@', $pre_array[$last]);
+    $switchable_answer_set = false;
+    if (isset ($is_set_switchable[1]) && $is_set_switchable[1] == 1) {
+        $switchable_answer_set = true;
+    }
+    $answer = '';
+    for ($k = 0; $k < $last; $k++) {
+        $answer .= $pre_array[$k];
+    }
+    // splits weightings that are joined with a comma
+    $answerWeighting = explode(',', $is_set_switchable[0]);
+
+    // we save the answer because it will be modified
+    //$temp = $answer;
+    $temp = $answer;
+
+    $answer = '';
+    $j = 0;
+    //initialise answer tags
+    $user_tags = $correct_tags = $real_text = array ();
+    // the loop will stop at the end of the text
+    while (1) {
+        // quits the loop if there are no more blanks (detect '[')
+        if (($pos = api_strpos($temp, '[')) === false) {
+            // adds the end of the text
+            $answer = $temp;
+            /* // Deprecated code
+             // TeX parsing - replacement of texcode tags
+            $texstring = api_parse_tex($texstring);
+            $answer = str_replace("{texcode}", $texstring, $answer);
+            */
+            $real_text[] = $answer;
+            break; //no more "blanks", quit the loop
+        }
+        // adds the piece of text that is before the blank
+        //and ends with '[' into a general storage array
+        $real_text[] = api_substr($temp, 0, $pos +1);
+        $answer .= api_substr($temp, 0, $pos +1);
+        //take the string remaining (after the last "[" we found)
+        $temp = api_substr($temp, $pos +1);
+        // quit the loop if there are no more blanks, and update $pos to the position of next ']'
+        if (($pos = api_strpos($temp, ']')) === false) {
+            // adds the end of the text
+            $answer .= $temp;
+            break;
+        }
+
+        $str = $user_answer;
+
+        preg_match_all('#\[([^[]*)\]#', $str, $arr);
+        $str = str_replace('\r\n', '', $str);
+        $choice = $arr[1];
+
+        $tmp = api_strrpos($choice[$j],' / ');
+        $choice[$j] = api_substr($choice[$j],0,$tmp);
+        $choice[$j] = trim($choice[$j]);
+
+        //Needed to let characters ' and " to work as part of an answer
+        $choice[$j] = stripslashes($choice[$j]);
+
+        $user_tags[] = api_strtolower($choice[$j]);
+        //put the contents of the [] answer tag into correct_tags[]
+        $correct_tags[] = api_strtolower(api_substr($temp, 0, $pos));
+        $j++;
+        $temp = api_substr($temp, $pos +1);
+    }
+
+    $answer = '';
+    $real_correct_tags = $correct_tags;
+    $chosen_list = array();
+
+    $good_answer = array();
+
+    for ($i = 0; $i < count($real_correct_tags); $i++) {
+        if (!$switchable_answer_set) {
+            //needed to parse ' and " characters
+            $user_tags[$i] = stripslashes($user_tags[$i]);
+            if ($correct_tags[$i] == $user_tags[$i]) {
+                $good_answer[$correct_tags[$i]] = 1;
+            } elseif (!empty ($user_tags[$i])) {
+                $good_answer[$correct_tags[$i]] = 0;
+            } else {
+                $good_answer[$correct_tags[$i]] = 0;
+            }
+        } else {
+            // switchable fill in the blanks
+            if (in_array($user_tags[$i], $correct_tags)) {
+                $correct_tags = array_diff($correct_tags, $chosen_list);
+                $good_answer[$correct_tags[$i]] = 1;
+            } elseif (!empty ($user_tags[$i])) {
+                $good_answer[$correct_tags[$i]] = 0;
+            } else {
+                $good_answer[$correct_tags[$i]] = 0;
+            }
+        }
+        // adds the correct word, followed by ] to close the blank
+        $answer .= ' / <font color="green"><b>' . $real_correct_tags[$i] . '</b></font>]';
+        if (isset ($real_text[$i +1])) {
+            $answer .= $real_text[$i +1];
+        }
+    }
+    return $good_answer;
+}
+
+
+function get_number_students_finish_exercise($exercise_id, $course_code, $session_id) {
+    $track_exercises	= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+    $track_attempt		= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
+
+    $exercise_id 		= intval($exercise_id);
+    $course_code 		= Database::escape_string($course_code);
+    $session_id 		= intval($session_id);
+
+    $sql = "SELECT DISTINCT exe_user_id
+    		FROM $track_exercises e INNER JOIN $track_attempt a ON (a.exe_id = e.exe_id)
+    		WHERE 	exe_exo_id 		= $exercise_id AND
+    				course_code 	= '$course_code' AND
+    				e.session_id 	= $session_id AND
+    				status = ''";
+    $result = Database::query($sql);
+    $return = 0;
+    if ($result) {
+    	$return = Database::num_rows($result);
+
+    }
+    return $return;
+}
+
+
+
+/**
+// return the HTML code for a menu with students group
+// @input : $in_name : is the name and the id of the <select>
+//          $in_default : default value for option
+// @return : the html code of the <select>
+*/
+function displayGroupMenu($in_name, $in_default, $in_onchange="") {
+    // check the default value of option
+    $tabSelected = array($in_default => " selected='selected' ");
+    $res = "";
+    $res .= "<select name='$in_name' id='$in_name' onchange='".$in_onchange."' >";
+    $res .= "<option value='-1'".$tabSelected["-1"].">-- ".get_lang('AllGroups')." --</option>";
+    $res .= "<option value='0'".$tabSelected["0"].">- ".get_lang('NotInAGroup')." -</option>";
+    $tabGroups = GroupManager::get_group_list();
+    $currentCatId = 0;
+    for ($i=0; $i < count($tabGroups); $i++) {
+        $tabCategory = GroupManager::get_category_from_group($tabGroups[$i]["id"]);
+        if ($tabCategory["id"] != $currentCatId) {
+            $res .= "<option value='-1' disabled='disabled'>".$tabCategory["title"]."</option>";
+            $currentCatId = $tabCategory["id"];
+        }
+        $res .= "<option ".$tabSelected[$tabGroups[$i]["id"]]."style='margin-left:40px' value='".$tabGroups[$i]["id"]."'>".$tabGroups[$i]["name"]."</option>";
+    }
+    $res .= "</select>";
+    return $res;
+}
+
+
+/**
+ * Return a list of group for user with user_id=in_userid separated with in_separator
+ * @deprecated ?
+ */
+function displayGroupsForUser($in_separator, $in_userid) {
+    $res = implode($in_separator, GroupManager::get_user_group_name($in_userid));
+    if ($res == "") {
+        $res = "<div style='text-align:center'>-</div>";
+    }
+    return $res;
+}
+
+function create_chat_exercise_session($exe_id) {
+    if (!isset($_SESSION['current_exercises'])) {
+        $_SESSION['current_exercises'] = array();
+    }
+    $_SESSION['current_exercises'][$exe_id] = true;
+}
+
+function delete_chat_exercise_session($exe_id) {
+    if (isset($_SESSION['current_exercises'])) {
+        $_SESSION['current_exercises'][$exe_id] = false;
+    }
+}
+
+
+/**
+ * Display the exercise results
+ * @param obj   exercise obj
+ * @param int   attempt id (exe_id)
+ * @param bool  save users results (true) or just show the results (false)
+ */
+function display_question_list_by_attempt($objExercise, $exe_id, $save_user_result = false) {
+    global $origin, $debug;
+
+    //Getting attempt info
+    $exercise_stat_info = $objExercise->get_stat_track_exercise_info_by_exe_id($exe_id);
+
+    //Getting question list
+    $question_list = array();
+    if (!empty($exercise_stat_info['data_tracking'])) {
+        $question_list = explode(',', $exercise_stat_info['data_tracking']);
+    } else {
+        //Try getting the question list only if save result is off
+        if ($save_user_result == false) {
+            $question_list = $objExercise->get_validated_question_list();
+        }
+        error_log("Data tracking is empty! exe_id: $exe_id");
+    }
+
+    $counter = 1;
+    $total_score = $total_weight = 0;
+
+    $exercise_content = null;
+
+    //Hide results
+    $show_results     = false;
+    $show_only_score  = false;
+
+    if ($objExercise->results_disabled == RESULT_DISABLE_SHOW_SCORE_AND_EXPECTED_ANSWERS) {
+        $show_results = true;
+    }
+
+    if (in_array($objExercise->results_disabled, array(RESULT_DISABLE_SHOW_SCORE_ONLY, RESULT_DISABLE_SHOW_FINAL_SCORE_ONLY_WITH_CATEGORIES))) {
+        $show_only_score = true;
+    }
+
+    if ($show_results || $show_only_score) {
+        $user_info   = api_get_user_info($exercise_stat_info['exe_user_id']);
+        //Shows exercise header
+        echo $objExercise->show_exercise_result_header($user_info['complete_name'], api_convert_and_format_date($exercise_stat_info['start_date'], DATE_TIME_FORMAT_LONG), $exercise_stat_info['duration']);
+    }
+
+    // Display text when test is finished #4074 and for LP #4227
+    $end_of_message = $objExercise->selectTextWhenFinished();
+    if (!empty($end_of_message)) {
+        Display::display_normal_message($end_of_message, false);
+        echo "<div class='clear'>&nbsp;</div>";
+    }
+
+    $question_list_answers = array();
+    $media_list = array();
+    $category_list = array();
+
+    // Loop over all question to show results for each of them, one by one
+    if (!empty($question_list)) {
+        if ($debug) { error_log('Looping question_list '.print_r($question_list,1));}
+        foreach ($question_list as $questionId) {
+
+            // creates a temporary Question object
+            $objQuestionTmp = Question::read($questionId);
+
+            //this variable commes from exercise_submit_modal.php
+            ob_start();
+
+            // We're inside *one* question. Go through each possible answer for this question
+            $result = $objExercise->manage_answer($exercise_stat_info['exe_id'], $questionId, null, 'exercise_result', array(), $save_user_result, true, $show_results, $objExercise->selectPropagateNeg(), $hotspot_delineation_result);
+
+            if (empty($result)) {
+                continue;
+            }
+
+            $total_score     += $result['score'];
+            $total_weight    += $result['weight'];
+
+            $question_list_answers[] = array(
+                'question' => $result['open_question'],
+                'answer' => $result['open_answer'],
+                'answer_type' => $result['answer_type']
+            );
+
+            $my_total_score  = $result['score'];
+            $my_total_weight = $result['weight'];
+
+
+            //Category report
+            $category_was_added_for_this_test = false;
+
+            if (isset($objQuestionTmp->category) && !empty($objQuestionTmp->category)) {
+                $category_list[$objQuestionTmp->category]['score'] += $my_total_score;
+                $category_list[$objQuestionTmp->category]['total'] += $my_total_weight;
+                $category_was_added_for_this_test = true;
+            }
+
+            if (isset($objQuestionTmp->category_list) && !empty($objQuestionTmp->category_list)) {
+                foreach($objQuestionTmp->category_list as $category_id) {
+                    $category_list[$category_id]['score'] += $my_total_score;
+                    $category_list[$category_id]['total'] += $my_total_weight;
+                    $category_was_added_for_this_test = true;
+                }
+            }
+
+            //No category for this question!
+            if ($category_was_added_for_this_test == false) {
+                $category_list['none']['score'] += $my_total_score;
+                $category_list['none']['total'] += $my_total_weight;
+            }
+
+            if ($objExercise->selectPropagateNeg() == 0 && $my_total_score < 0) {
+                $my_total_score = 0;
+            }
+
+            $comnt = null;
+            if ($show_results) {
+                $comnt = get_comments($exe_id, $questionId);
+                if (!empty($comnt)) {
+                    echo '<b>'.get_lang('Feedback').'</b>';
+                    echo '<div id="question_feedback">'.$comnt.'</div>';
+                }
+            }
+
+            $score = array();
+            if ($show_results) {
+                $score['result']    = get_lang('Score')." : ".show_score($my_total_score, $my_total_weight, false, true);
+                $score['pass']      = $my_total_score >= $my_total_weight ? true : false;
+                $score['score']     = $my_total_score;
+                $score['weight']    = $my_total_weight;
+                $score['comments']  = $comnt;
+            }
+
+            $contents = ob_get_clean();
+
+            $question_content = '<div class="question_row">';
+
+            if ($show_results) {
+                $show_media = false;
+                /*if ($objQuestionTmp->parent_id != 0 && !in_array($objQuestionTmp->parent_id, $media_list)) {
+                    $show_media = true;
+                    $media_list[] = $objQuestionTmp->parent_id;
+                }*/
+                //Shows question title an description
+                $question_content .= $objQuestionTmp->return_header(null, $counter, $score);
+            }
+            $counter++;
+
+            $question_content .= $contents;
+            $question_content .= '</div>';
+
+            $exercise_content .= $question_content;
+
+        } // end foreach() block that loops over all questions
+    }
+
+    $total_score_text = null;
+
+    if ($origin != 'learnpath') {
+        if ($show_results || $show_only_score) {
+            $total_score_text .= '<div class="question_row">';
+            $total_score_text .= get_question_ribbon($objExercise, $total_score, $total_weight, true);
+            $total_score_text .= '</div>';
+        }
+    }
+
+    if (!empty($category_list) && ($show_results || $show_only_score) ) {
+        //Adding total
+        $category_list['total'] = array('score' => $total_score, 'total' => $total_weight);
+        echo Testcategory::get_stats_table_by_attempt($objExercise->id, $category_list);
+    }
+
+    echo $total_score_text;
+    echo $exercise_content;
+    if (!$show_only_score) {
+        echo $total_score_text;
+    }
+
+    if ($save_user_result) {
+
+        // Tracking of results
+        $learnpath_id           = $exercise_stat_info['orig_lp_id'];
+        $learnpath_item_id      = $exercise_stat_info['orig_lp_item_id'];
+        $learnpath_item_view_id = $exercise_stat_info['orig_lp_item_view_id'];
+
+        if (api_is_allowed_to_session_edit()) {
+            update_event_exercice($exercise_stat_info['exe_id'], $objExercise->selectId(), $total_score, $total_weight, api_get_session_id(), $learnpath_id, $learnpath_item_id, $learnpath_item_view_id, $exercise_stat_info['exe_duration'], $question_list, '', array(), $end_date);
+        }
+
+        // Send notification ..
+        if (!api_is_allowed_to_edit(null,true)) {
+            $objExercise->send_notification_for_open_questions($question_list_answers, $origin, $exe_id);
+            $objExercise->send_notification_for_oral_questions($question_list_answers, $origin, $exe_id);
+        }
+    }
+}
+
+
+function get_question_ribbon($objExercise, $score, $weight, $check_pass_percentage = false) {
+    $ribbon = '<div class="ribbon">';
+    if ($check_pass_percentage) {
+        $is_success = is_success_exercise_result($score, $weight, $objExercise->selectPassPercentage());
+        // Color the final test score if pass_percentage activated
+        $ribbon_total_success_or_error = "";
+        if (is_pass_pourcentage_enabled($objExercise->selectPassPercentage())) {
+            if ($is_success) {
+                $ribbon_total_success_or_error = ' ribbon-total-success';
+            } else {
+                $ribbon_total_success_or_error = ' ribbon-total-error';
+            }
+        }
+        $ribbon .= '<div class="rib rib-total '.$ribbon_total_success_or_error.'">';
+    } else {
+        $ribbon .= '<div class="rib rib-total">';
+    }
+    $ribbon .= '<h3>'.get_lang('YourTotalScore').":&nbsp;";
+    $ribbon .= show_score($score, $weight, false, true);
+    $ribbon .= '</h3>';
+    $ribbon .= '</div>';
+    if ($check_pass_percentage) {
+        $ribbon .= show_success_message($score, $weight, $objExercise->selectPassPercentage());
+    }
+
+
+    $ribbon .= '</div>';
+    return $ribbon;
+}
+
+function detectInputAppropriateClass($countLetter)
+{
+    $limits = array(
+        0 => 'input-mini',
+        10 => 'input-mini',
+        15 => 'input-medium',
+        20 => 'input-xlarge',
+        40 => 'input-xlarge',
+        60 => 'input-xxlarge',
+        100  => 'input-xxlarge',
+        200 => 'input-xxlarge',
+    );
+    foreach ($limits as $size => $item) {
+        if ($countLetter <= $size) {
+            return $item;
+        }
+    }
+    return $limits[0];
+}

+ 25 - 12
main/exercice/exercise_result.class.php

@@ -90,6 +90,7 @@ class ExerciseResult
 		$TBL_TRACK_EXERCISES    	= Database::get_main_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
 		$TBL_TRACK_HOTPOTATOES	= Database::get_main_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES);
         $TBL_TRACK_ATTEMPT_RECORDING = Database :: get_main_table(TABLE_STATISTIC_TRACK_E_ATTEMPT_RECORDING);
+        $TBL_TABLE_LP_MAIN = Database::get_course_table(TABLE_LP_MAIN);
 
     	$cid             = api_get_course_id();
         $course_id       = api_get_course_int_id();
@@ -115,8 +116,10 @@ class ExerciseResult
                         steps_counter as exstep,
                         exe_user_id as excruid,
                         te.exe_duration as duration
-                FROM $TBL_EXERCISES  AS ce INNER JOIN $TBL_TRACK_EXERCISES AS te ON (te.exe_exo_id = ce.iid) INNER JOIN
-                     $TBL_USER  AS user ON (user.user_id = exe_user_id)
+                FROM $TBL_EXERCISES  AS ce 
+                INNER JOIN $TBL_TRACK_EXERCISES AS te ON (te.exe_exo_id = ce.iid) 
+                INNER JOIN $TBL_USER  AS user ON (user.user_id = exe_user_id)
+                LEFT JOIN $TBL_TABLE_LP_MAIN AS tlm ON tlm.id = te.orig_lp_id AND tlm.c_id = ce.c_id
                 WHERE   ce.c_id = $course_id AND
                         te.status != 'incomplete' AND
                         te.c_id = '" . $course_id . "' $user_id_and $session_id_and AND
@@ -149,9 +152,13 @@ class ExerciseResult
                     steps_counter as exstep,
                     exe_user_id as excruid,
                     te.exe_duration as duration,
-                    ce.results_disabled as exdisabled
-                        FROM $TBL_EXERCISES  AS ce INNER JOIN $TBL_TRACK_EXERCISES AS te ON (te.exe_exo_id = ce.iid)
-                        INNER JOIN $TBL_USER  AS user ON (user.user_id = exe_user_id)
+                    ce.results_disabled as exdisabled,
+                    te.orig_lp_id as orig_lp_id,
+                    tlm.name as lp_name
+                    FROM $TBL_EXERCISES  AS ce 
+                    INNER JOIN $TBL_TRACK_EXERCISES AS te ON (te.exe_exo_id = ce.id) 
+                    INNER JOIN  $TBL_USER  AS user ON (user.user_id = exe_user_id)
+                    LEFT JOIN $TBL_TABLE_LP_MAIN AS tlm ON tlm.id = te.orig_lp_id AND tlm.c_id = ce.c_id
                         WHERE   ce.c_id = $course_id AND
                                 te.status != 'incomplete' AND
                                 te.c_id ='" . $course_id . "'  $user_id_and $session_id_and AND
@@ -161,10 +168,10 @@ class ExerciseResult
                         ORDER BY userpart2, te.c_id ASC, ce.title ASC, te.exe_date DESC";
 
             $hpsql = "SELECT '', exe_name, exe_result , exe_weighting, exe_date
-                        FROM $TBL_TRACK_HOTPOTATOES
-                        WHERE   exe_user_id = '" . $user_id . "' AND
+                            FROM $TBL_TRACK_HOTPOTATOES
+                            WHERE   exe_user_id = '" . $user_id . "' AND
                                 c_id = '" . $course_id . "' AND
-                                tth.exe_name = '$hotpotato_name'
+                                    tth.exe_name = '$hotpotato_name'
                         ORDER BY c_id ASC, exe_date DESC";
 		}
 
@@ -180,7 +187,6 @@ class ExerciseResult
 	    while ($rowx = Database::fetch_array($resx,'ASSOC')) {
             $hpresults[] = $rowx;
 		}
-
         $filter_by_not_revised = false;
         $filter_by_revised = false;
 
@@ -233,6 +239,8 @@ class ExerciseResult
 				$return[$i]['result']  = $results[$i]['exresult'];
 				$return[$i]['max']     = $results[$i]['exweight'];
                 $return[$i]['status']  = $revised ? get_lang('Validated') : get_lang('NotValidated');
+                $return[$i]['lp_id'] = $results[$i]['orig_lp_id'];
+                $return[$i]['lp_name'] = $results[$i]['lp_name'];
 			}
 		}
 
@@ -312,6 +320,7 @@ class ExerciseResult
 		$data .= get_lang('Score').';';
 		$data .= get_lang('Total').';';
         $data .= get_lang('Status').';';
+        $data .= get_lang('ToolLearnpath').';';
 		$data .= "\n";
 
 		//results
@@ -343,6 +352,7 @@ class ExerciseResult
 			$data .= str_replace("\r\n",'  ',$row['result']).';';
 			$data .= str_replace("\r\n",'  ',$row['max']).';';
             $data .= str_replace("\r\n",'  ',$row['status']).';';
+            $data .= str_replace("\r\n",'  ',$row['lp_name']).';';
 			$data .= "\n";
 		}
 
@@ -416,7 +426,7 @@ class ExerciseResult
 		}
 	    $worksheet->write($line,$column,get_lang('Groups'));
 	    $column++;
-
+        
 		if ($export_user_fields) {
 			//show user fields section with a big th colspan that spans over all fields
 			$extra_user_fields = UserManager::get_extra_fields(0,1000,5,'ASC',false, 1);
@@ -441,13 +451,14 @@ class ExerciseResult
 		$worksheet->write($line,$column, get_lang('Total'));
 		$column++;
         $worksheet->write($line,$column, get_lang('Status'));
+		$column++;
+        $worksheet->write($line,$column, get_lang('ToolLearnpath'));
 		$line++;
 
 		foreach ($this->results as $row) {
 			$column = 0;
 
             if ($with_column_user) {
-
                 if (api_is_western_name_order()) {
                     $worksheet->write($line,$column,api_html_entity_decode(strip_tags($row['first_name']), ENT_QUOTES, $charset));
                     $column++;
@@ -465,7 +476,7 @@ class ExerciseResult
 
             $worksheet->write($line,$column,api_html_entity_decode(strip_tags(implode(", ", GroupManager :: get_user_group_name($row['user_id']))), ENT_QUOTES, $charset));
             $column++;
-
+            
 			if ($export_user_fields) {
 				//show user fields data, if any, for this user
 				$user_fields_values = UserManager::get_extra_user_data($row['user_id'],false,false, false, true);
@@ -488,6 +499,8 @@ class ExerciseResult
 			$worksheet->write($line,$column,$row['max']);
 			$column++;
             $worksheet->write($line,$column,$row['status']);
+			$column++;
+            $worksheet->write($line,$column,$row['lp_name']);
 			$line++;
 		}
 		//output the results

+ 1 - 1
main/exercice/showinframes.php

@@ -104,7 +104,7 @@ if ($origin == 'learnpath') {
     Display::display_header($nameTools, "Exercise");
 }
 $url = $document_web_path.$doc_url.$user_id.'.t.html?time='.Security::remove_XSS($time);
-echo '<iframe style="overflow:hidden" id="hotpotatoe" width="100%" frameborder="0" src="'.$url.'"></iframe>';
+echo '<iframe id="hotpotatoe" width="100%" frameborder="0" src="'.$url.'"></iframe>';
 echo '</body></html>';
 Display::display_footer();
 exit;

+ 67 - 65
main/gradebook/index.php

@@ -36,6 +36,8 @@ require_once 'lib/gradebook_data_generator.class.php';
 require_once 'lib/fe/gradebooktable.class.php';
 require_once 'lib/fe/displaygradebook.php';
 require_once 'lib/fe/userform.class.php';
+require_once api_get_path(LIBRARY_PATH).'ezpdf/class.ezpdf.php';
+require_once api_get_path(LIBRARY_PATH).'gradebook.lib.php';
 
 /*
 $htmlHeadXtra[] = api_get_css(api_get_path(WEB_LIBRARY_PATH).'javascript/jqplot/jquery.jqplot.min.css');
@@ -43,7 +45,7 @@ $htmlHeadXtra[] = api_get_js('jqplot/jquery.jqplot.min.js');
 $htmlHeadXtra[] = api_get_js('jqplot/plugins/jqplot.donutRenderer.min.js');*/
 
 $htmlHeadXtra[] = '<script>
-
+    
 var show_icon = "../img/view_more_stats.gif";
 var hide_icon = "../img/view_less_stats.gif";
 
@@ -51,28 +53,28 @@ $(document).ready(function() {
 
     $(".view_children").live("click", function() {
         var id = $(this).attr("data-cat-id");
-        $(".hidden_"+id).removeClass("hidden");
-        $(this).removeClass("view_children");
-        $(this).find("img").attr("src", hide_icon);
+        $(".hidden_"+id).removeClass("hidden");    
+        $(this).removeClass("view_children");        
+        $(this).find("img").attr("src", hide_icon);        
         $(this).attr("class", "hide_children");
     });
 
-    $(".hide_children").live("click", function(event) {
-        var id = $(this).attr("data-cat-id");
-        $(".hidden_"+id).addClass("hidden");
+    $(".hide_children").live("click", function(event) {    
+        var id = $(this).attr("data-cat-id");        
+        $(".hidden_"+id).addClass("hidden");    
         $(this).removeClass("hide_children");
         $(this).addClass("view_children");
         $(this).find("img").attr("src", show_icon);
     });
-
-
-
+ 
+    
+    
 
 /*
   var s1 = [["a",25]];
   var s2 = [["a", 0], ["a", 10], ["a", 10], ["a", 5]];
-
-  var plot3 = $.jqplot("chart3", [s1, s2], {
+     
+  var plot3 = $.jqplot("chart3", [s1, s2], {        
   colors: ["#000", "#fff"],
     seriesDefaults: {
       // make this a donut chart.
@@ -86,7 +88,7 @@ $(document).ready(function() {
         // By default, data labels show the percentage of the donut/pie.
         // You can show the data "value" or data "label" instead.
         dataLabels: "value"
-
+        
       }
     }
   });*/
@@ -118,7 +120,7 @@ $filter_warning_msg = true;
 
 ///direct access to one evaluation
 $cats = Category :: load(null, null, $course_code, null, null, $session_id, false); //already init
-$first_time = null;
+$first_time = null; 
 if (empty($cats)) {
 	$cats = Category :: load(0, null, $course_code, null, null, $session_id, false);//first time
 	$first_time=1;
@@ -137,8 +139,8 @@ if ( (isset($_GET['selectcat']) && $_GET['selectcat']>0) && (isset($_SESSION['st
 	//Introduction tool: student view
 	Display::display_introduction_section(TOOL_GRADEBOOK, array('ToolbarSet' => 'AssessmentsIntroduction'));
 
-	$category= $_GET['selectcat'];
-
+	$category= $_GET['selectcat'];		
+	
 	$cats = Category :: load ($category, null, null, null, null, null, false);
 	$allcat= $cats[0]->get_subcategories($stud_id, $course_code, $session_id);
 	$alleval= $cats[0]->get_evaluations($stud_id);
@@ -310,7 +312,7 @@ if (isset($_GET['deletecat'])) {
 		}
 	}
 	$confirmation_message = get_lang('CategoryDeleted');
-	$filter_confirm_msg = false;
+	$filter_confirm_msg = false;   
 }
 //parameters for evaluations
 if (isset ($_GET['visibleeval'])) {
@@ -347,8 +349,8 @@ if (isset($_GET['lockedeval'])) {
 	if ($eval[0] != null) {
 		$eval[0]->lock($type_locked);
 	}
-
-	$filter_confirm_msg = false;
+	
+	$filter_confirm_msg = false;	
 
 }
 if (isset ($_GET['deleteeval'])) {
@@ -393,11 +395,11 @@ if (isset ($_GET['deletelink'])) {
 		$link= LinkFactory :: load($get_delete_link);
 		if ($link[0] != null) {
 			// clean forum qualify
-			$sql = 'UPDATE '.$tbl_forum_thread.' SET thread_qualify_max=0,thread_weight=0,thread_title_qualify=""
+			$sql = 'UPDATE '.$tbl_forum_thread.' SET thread_qualify_max=0,thread_weight=0,thread_title_qualify="" 
 					WHERE c_id = '.$course_id.' AND thread_id = (SELECT ref_id FROM '.$tbl_grade_links.' WHERE id='.$get_delete_link.' AND type = '.LINK_FORUM_THREAD.');';
 			Database::query($sql);
 			// clean attendance
-			$sql = 'UPDATE '.$tbl_attendance.' SET attendance_qualify_max=0, attendance_weight = 0, attendance_qualify_title=""
+			$sql = 'UPDATE '.$tbl_attendance.' SET attendance_qualify_max=0, attendance_weight = 0, attendance_qualify_title="" 
 				 	WHERE c_id = '.$course_id.' AND id = (SELECT ref_id FROM '.$tbl_grade_links.' WHERE id='.$get_delete_link.' AND type = '.LINK_ATTENDANCE.');';
 			Database::query($sql);
 			$link[0]->delete();
@@ -439,7 +441,7 @@ switch ($action) {
             $category_to_lock[0]->lock_all_items(0);
             $confirmation_message = get_lang('EvaluationHasBeenUnLocked');
         }
-        break;
+        break;    
 }
 
 //actions on the sortabletable
@@ -452,7 +454,7 @@ if (isset ($_POST['action'])) {
 		$filter_warning_msg = false;
 	} else {
 		switch ($_POST['action']) {
-
+ 
 			case 'deleted' :
 				$number_of_deleted_categories= 0;
 				$number_of_deleted_evaluations= 0;
@@ -618,8 +620,8 @@ if (empty ($_GET['selectcat'])) {
 }
 $simple_search_form='';
 
-if (isset($_GET['studentoverview'])) {
-    //@todo this code also seems to be deprecated ...
+if (isset($_GET['studentoverview'])) {    
+    //@todo this code also seems to be deprecated ...    
 	$cats= Category :: load($category);
 	$stud_id= (api_is_allowed_to_edit() ? null : $stud_id);
 	$allcat= array ();
@@ -633,7 +635,7 @@ if (isset($_GET['studentoverview'])) {
 		foreach ($data_array as $data) {
 			$newarray[] = array_slice($data, 1);
 		}
-		$pdf= new Cezpdf();
+		$pdf= new Cezpdf(); 
 		$pdf->selectFont(api_get_path(LIBRARY_PATH).'ezpdf/fonts/Courier.afm');
 		$pdf->ezSetMargins(30, 30, 50, 30);
 		$pdf->ezSetY(810);
@@ -647,15 +649,15 @@ if (isset($_GET['studentoverview'])) {
     }
 } else {
     //Student view
-
+    
     //in any other case (no search, no pdf), print the available gradebooks
     // Important note: loading a category will actually load the *contents* of
     // this category. This means that, to show the categories of a course,
     // we have to show the root category and show its subcategories that
     // are inside this course. This is done at the time of calling
     // $cats[0]->get_subcategories(), not at the time of doing Category::load()
-    // $category comes from GET['selectcat']
-
+    // $category comes from GET['selectcat']    
+    
     //if $category = 0 (which happens when GET['selectcat'] is undefined)
     // then Category::load() will create a new 'root' category with empty
     // course and session fields in memory (Category::create_root_category())
@@ -674,8 +676,8 @@ if (isset($_GET['studentoverview'])) {
 	    $cats = Category :: load(null, null, $course_code, null, null, $session_id, false);
         if (empty($cats)) {
             // There is no category for this course+session, so create one
-            $cat= new Category();
-            if (!empty($session_id)) {
+            $cat= new Category();     
+            if (!empty($session_id)) {            	
                 $s_name = api_get_session_name($session_id);
             	$cat->set_name($course_code.' - '.get_lang('Session').' '.$s_name);
                 $cat->set_session_id($session_id);
@@ -705,7 +707,7 @@ if (isset($_GET['studentoverview'])) {
     } else {
     	$stud_id = $stud_id;
     }
-
+    
 	$allcat  = $cats[0]->get_subcategories($stud_id, $course_code, $session_id);
 	$alleval = $cats[0]->get_evaluations($stud_id);
 	$alllink = $cats[0]->get_links($stud_id);
@@ -733,14 +735,14 @@ if ($category != '0') {
 	$category_id   = intval($_GET['selectcat']);
 	$course_id     = CourseManager::get_course_by_category($category_id);
 	$show_message  = $cat->show_message_resource_delete($course_id);
-
+    
 	if ($show_message == '') {
 		//student
 		if (!api_is_allowed_to_edit()) {
             $certificate_html = Category::register_user_certificate($category_id, $stud_id);
             if ($certificate_html) {
                 echo $certificate_html;
-            }
+            }            
 		} //end hack
 	}
 }
@@ -749,45 +751,45 @@ if (api_is_allowed_to_edit(null, true)) {
 	// Tool introduction
 	Display::display_introduction_section(TOOL_GRADEBOOK, array('ToolbarSet' => 'AssessmentsIntroduction'));
 
-	if ( (isset ($_GET['selectcat']) && $_GET['selectcat']<>0) ) {
+	if ( (isset ($_GET['selectcat']) && $_GET['selectcat']<>0) ) {	    
 	//
-	} else {
+	} else {	    
         if (((isset ($_GET['selectcat']) && $_GET['selectcat']==0) || ((isset($_GET['cidReq']) && $_GET['cidReq']!==''))) || isset($_GET['isStudentView']) && $_GET['isStudentView']=='false') {
-            $cats = Category :: load(null, null, $course_code, null, null, $session_id, false);
+            $cats = Category :: load(null, null, $course_code, null, null, $session_id, false);		
 		}
 	}
 }
 
 if (isset($first_time) && $first_time==1 && api_is_allowed_to_edit(null,true)) {
 	echo '<meta http-equiv="refresh" content="0;url='.api_get_self().'?cidReq='.$course_code.'" />';
-} else {
+} else {    
     $cats = Category :: load(null, null, $course_code, null, null, $session_id, false); //already init
-
+    
 	if (!empty($cats)) {
-
-        if ( (api_get_setting('gradebook_enable_grade_model') == 'true') &&
+        
+        if ( (api_get_setting('gradebook_enable_grade_model') == 'true') && 
              (api_is_platform_admin() || (api_is_allowed_to_edit(null, true) && api_get_setting('teachers_can_change_grade_model_settings') == 'true'))) {
-
+            
             //Getting grade models
             $obj = new GradeModel();
             $grade_models = $obj->get_all();
             $grade_model_id = $cats[0]->get_grade_model_id();
-
+                                    
             //No children
             if ( (count($cats) == 1 && empty($grade_model_id)) || (count($cats) == 1 && $grade_model_id != -1) ) {
-                if (!empty($grade_models)) {
-                    $form_grade = new FormValidator('grade_model_settings');
+                if (!empty($grade_models)) {                   
+                    $form_grade = new FormValidator('grade_model_settings');                    
                     $obj->fill_grade_model_select_in_form($form_grade, 'grade_model_id', $grade_model_id);
                     $form_grade->addElement('style_submit_button', 'submit', get_lang('Save'), 'class="save"');
-
+                    
                     if ($form_grade->validate()) {
                         $value = $form_grade->exportValue('grade_model_id');
-
+                        
                         $gradebook = new Gradebook();
-                        $gradebook->update(array('id'=> $cats[0]->get_id(), 'grade_model_id' => $value), true);
+                        $gradebook->update(array('id'=> $cats[0]->get_id(), 'grade_model_id' => $value), true);                 
 
-                        //do something
-                        $obj = new GradeModel();
+                        //do something                        
+                        $obj = new GradeModel();                             
                         $components = $obj->get_components($value);
 
                         foreach ($components as $component) {
@@ -808,34 +810,34 @@ if (isset($first_time) && $first_time==1 && api_is_allowed_to_edit(null,true)) {
                         //Reloading cats
                         $cats = Category :: load(null, null, $course_code, null, null, $session_id, false);
                     } else {
-                        $form_grade->display();
+                        $form_grade->display();   
                     }
                 }
             }
         }
-
+        
 		$i = 0;
-
-		foreach ($cats as $cat) {
-			$allcat  = $cat->get_subcategories($stud_id, $course_code, $session_id);
+        
+		foreach ($cats as $cat) {			
+			$allcat  = $cat->get_subcategories($stud_id, $course_code, $session_id);            
 			$alleval = $cat->get_evaluations($stud_id);
-			$alllink = $cat->get_links($stud_id);
-
+			$alllink = $cat->get_links($stud_id, true);
+			
 			if ($cat->get_parent_id() != 0 ) {
 				$i++;
 			} else {
-				//This is the father
+				//This is the father				
 				//Create gradebook/add gradebook links
-                DisplayGradebook::display_header_gradebook($cat, 0, $cat->get_id(), $is_course_admin, $is_platform_admin, $simple_search_form, false, true);
-
+                DisplayGradebook::display_header_gradebook($cat, 0, $cat->get_id(), $is_course_admin, $is_platform_admin, $simple_search_form, false, true);				
+				
 				if (api_is_allowed_to_edit(null,true) && api_get_setting('gradebook_enable_grade_model') == 'true') {
 					//Showing the grading system
-					if (!empty($grade_models[$grade_model_id])) {
+					if (!empty($grade_models[$grade_model_id])) {             
                         Display::display_normal_message(get_lang('GradeModel').': '.$grade_models[$grade_model_id]['name']);
-                    }
-				}
-				$gradebooktable = new GradebookTable($cat, $allcat, $alleval, $alllink, $addparams);
-				$gradebooktable->display();
+                    }					
+				}                                
+				$gradebooktable = new GradebookTable($cat, $allcat, $alleval, $alllink, $addparams);                
+				$gradebooktable->display();				
 			}
 		}
 	}

+ 49 - 51
main/gradebook/lib/be/forumthreadlink.class.php

@@ -113,58 +113,56 @@ class ForumThreadLink extends AbstractLink
     }
 
     public function calc_score($stud_id = null) {    			
-		if (!empty($database_name)) {
-			$thread_qualify = Database :: get_course_table(TABLE_FORUM_THREAD_QUALIFY);
+        $thread_qualify = Database :: get_course_table(TABLE_FORUM_THREAD_QUALIFY);
 
-	  		$sql = 'SELECT thread_qualify_max FROM '.Database :: get_course_table(TABLE_FORUM_THREAD)." 
-	  				WHERE c_id = ".$this->course_id." AND thread_id = '".$this->get_ref_id()."'";
-			$query = Database::query($sql);
-			$assignment = Database::fetch_array($query);
-
-	  	    $sql = "SELECT * FROM $thread_qualify WHERE c_id = ".$this->course_id." AND thread_id = ".$this->get_ref_id();
-	    	if (isset($stud_id)) {
-	    		$sql .= ' AND user_id = '."'".intval($stud_id)."'";
-	    	}
-
-	    	// order by id, that way the student's first attempt is accessed first
-			$sql .= ' ORDER BY qualify_time DESC';
-
-	    	$scores = Database::query($sql);
-
-			// for 1 student
-	    	if (isset($stud_id)) {
-	    	    
-	    		if ($data = Database::fetch_array($scores)) {	    		    
-	    			return array ($data['qualify'], $assignment['thread_qualify_max']);
-	    		} else {
-	    			//We sent the 0/thread_qualify_max instead of null for correct calculations
-	      			//return null;
-	      			return array (0, $assignment['thread_qualify_max']);
-	    		}
-	    	} else {
-	    	    // all students -> get average
-	    		$students=array();  // user list, needed to make sure we only
-	    							// take first attempts into account
-				$rescount = 0;
-				$sum = 0;
-
-				while ($data=Database::fetch_array($scores)) {
-					if (!(array_key_exists($data['user_id'],$students))) {
-						if ($assignment['thread_qualify_max'] != 0) {
-							$students[$data['user_id']] = $data['qualify'];
-							$rescount++;
-							$sum += ($data['qualify'] / $assignment['thread_qualify_max']);
-						}
-					 }
-				}
-
-				if ($rescount == 0) {
-					return null;
-				  } else {
-					return array ($sum , $rescount);
-				 }    
-	    	}
-        }
+  		$sql = 'SELECT thread_qualify_max FROM '.Database :: get_course_table(TABLE_FORUM_THREAD)." 
+  				WHERE c_id = ".$this->course_id." AND thread_id = '".$this->get_ref_id()."'";
+		$query = Database::query($sql);
+		$assignment = Database::fetch_array($query);
+
+  	    $sql = "SELECT * FROM $thread_qualify WHERE c_id = ".$this->course_id." AND thread_id = ".$this->get_ref_id();
+    	if (isset($stud_id)) {
+    		$sql .= ' AND user_id = '."'".intval($stud_id)."'";
+    	}
+
+    	// order by id, that way the student's first attempt is accessed first
+		$sql .= ' ORDER BY qualify_time DESC';
+
+    	$scores = Database::query($sql);
+
+		// for 1 student
+    	if (isset($stud_id)) {
+    	    
+    		if ($data = Database::fetch_array($scores)) {	    		    
+    			return array ($data['qualify'], $assignment['thread_qualify_max']);
+			} else {
+    			//We sent the 0/thread_qualify_max instead of null for correct calculations
+      			//return null;
+      			return array (0, $assignment['thread_qualify_max']);
+    		}
+    	} else {
+    	    // all students -> get average
+    		$students=array();  // user list, needed to make sure we only
+    							// take first attempts into account
+			$rescount = 0;
+			$sum = 0;
+
+			while ($data=Database::fetch_array($scores)) {
+				if (!(array_key_exists($data['user_id'],$students))) {
+					if ($assignment['thread_qualify_max'] != 0) {
+						$students[$data['user_id']] = $data['qualify'];
+						$rescount++;
+						$sum += ($data['qualify'] / $assignment['thread_qualify_max']);
+					}
+				 }
+			}
+
+			if ($rescount == 0) {
+			    return null;
+		    } else {
+                return array ($sum , $rescount);
+   		    }    
+    	}
     }
 
 // INTERNAL FUNCTIONS

+ 497 - 492
main/gradebook/lib/fe/flatviewtable.class.php

@@ -20,499 +20,504 @@ set_time_limit(0);
  */
 class FlatViewTable extends SortableTable
 {
-	private $selectcat;
-	public  $datagen;
-	private $limit_enabled;
-	private $offset;
-
-	/**
-	 * Constructor
-	 */
-	function FlatViewTable ($selectcat, $users= array (), $evals= array (), $links= array (), $limit_enabled = false, $offset = 0, $addparams = null) {
-		parent :: __construct ('flatviewlist', null, null, (api_is_western_name_order() xor api_sort_by_first_name()) ? 1 : 0);
+    private $selectcat;
+    public  $datagen;
+    private $limit_enabled;
+    private $offset;
+
+    /**
+     * Constructor
+     */
+    function FlatViewTable ($selectcat, $users= array (), $evals= array (), $links= array (), $limit_enabled = false, $offset = 0, $addparams = null) {
+        parent :: __construct ('flatviewlist', null, null, (api_is_western_name_order() xor api_sort_by_first_name()) ? 1 : 0);
         $this->selectcat = $selectcat;
         $this->datagen = new FlatViewDataGenerator($users, $evals, $links, array('only_subcat'=>$this->selectcat->get_id()));
-
-		$this->limit_enabled = $limit_enabled;
-		$this->offset = $offset;
-		if (isset ($addparams)) {
-			$this->set_additional_parameters($addparams);
-		}
-
-		// step 2: generate rows: students
-		$this->datagen->category = $this->selectcat;
-	}
-
-	/**
-	 * Display the graph of the total results of all students
-	 * */
-	function display_graph() {
-		include_once api_get_path(LIBRARY_PATH).'pchart/pData.class.php';
-		include_once api_get_path(LIBRARY_PATH).'pchart/pChart.class.php';
-		include_once api_get_path(LIBRARY_PATH).'pchart/pCache.class.php';
-
-		$header_name = $this->datagen->get_header_names();
-		$total_users = $this->datagen->get_total_users_count();
-
-		$img_file = '';
-
-		if ($this->datagen->get_total_items_count()>0 && $total_users > 0 ) {
-		    //Removing user names and total
-			array_shift($header_name);
-			array_shift($header_name);
-			array_pop($header_name);
-
-			$user_results = $this->datagen->get_data_to_graph();
-
-			$pre_result = $new_result = array();
-			$DataSet = new pData();
-
-			//$pre_result total score of students
-			//filling the Dataset
-			foreach($user_results as $result) {
-				for($i=0; $i < count($header_name); $i++) {
-					$pre_result[$i+3]+= $result[$i+1];
-				}
-			}
-			$i = 1;
-			$show_draw = false;
-			if ($total_users >0 ) {
-				foreach($pre_result as $res) {
-					$total =  $res / ($total_users);
-					if ($total != 0) {
-						$show_draw  = true;
-					}
-					$DataSet->AddPoint($total, "Serie".$i);
-					$DataSet->SetSerieName(strip_tags($header_name[$i-1]),"Serie".$i);
-
-					// Dataset definition
-					$DataSet->AddAllSeries();
-					$DataSet->SetAbsciseLabelSerie();
-					$i++;
-				}
-			}
-
-			// Cache definition
-			$Cache = new pCache();
-			// the graph id
-			$gradebook_id = intval($_GET['selectcat']);
-			$graph_id = api_get_user_id().'AverageResultsVsResource'.$gradebook_id.api_get_course_id();
-			$data = $DataSet->GetData();
-
-			if ($show_draw) {
-				if ($Cache->IsInCache($graph_id, $DataSet->GetData())) {
-				//if (0) {
-					//if we already created the img
-					//echo 'in cache';
-					$img_file = $Cache->GetHash($graph_id,$DataSet->GetData());
-				} else  {
-					// if the image does not exist in the archive/ folder
-
-					// Initialise the graph
-					$Test = new pChart(760, 360);
-
-					//which schema of color will be used
-					$quant_resources = count($data[0])-1;
-					// Adding the color schemma
-					if ($quant_resources < 8) {
-						$Test->loadColorPalette(api_get_path(LIBRARY_PATH)."pchart/palette/reduced.txt");
-					} else {
-						$Test->loadColorPalette(api_get_path(LIBRARY_PATH)."pchart/palette/default.txt");
-					}
-
-					// set font of the axes
-					$Test->setFontProperties(api_get_path(LIBRARY_PATH)."pchart/fonts/tahoma.ttf",8);
-					$Test->setGraphArea(50,30,610,300);
-
-					$Test->drawFilledRoundedRectangle(7,7,780,330,5,240,240,240);
-					//$Test->drawRoundedRectangle(5,5,790,330,5,230,230,230);
-
-					//background color area & stripe or not
-					$Test->drawGraphArea(255,255,255,TRUE);
-					$Test->drawScale($DataSet->GetData(), $DataSet->GetDataDescription(), SCALE_START0 ,150,150,150,TRUE,0,1, FALSE);
-
-					//background grid
-					$Test->drawGrid(4,TRUE,230,230,230,50);
-
-					// Draw the 0 line
-					//$Test->setFontProperties(api_get_path(LIBRARY_PATH)."pchart/fonts/tahoma.ttf",6);
-					//$Test->drawTreshold(0,143,55,72,TRUE,TRUE);
-
-					// Draw the bar graph
-					$Test->drawBarGraph($DataSet->GetData(),$DataSet->GetDataDescription(),TRUE);
-
-					//Set legend properties: width, height and text color and font
-					$Test->setFontProperties(api_get_path(LIBRARY_PATH)."pchart/fonts/tahoma.ttf",9);
-					$Test->drawLegend(620, 70,$DataSet->GetDataDescription(),255,255,255);
-
-					//Set title properties
-					$Test->setFontProperties(api_get_path(LIBRARY_PATH)."pchart/fonts/tahoma.ttf",10);
-					$Test->drawTitle(50,22,get_lang('AverageResultsVsResource'),50,50,80,620);
-
-					//------------------
-					//echo 'not in cache';
-					$Cache->WriteToCache($graph_id,$DataSet->GetData(),$Test);
-					ob_start();
-					$Test->Stroke();
-					ob_end_clean();
-					$img_file = $Cache->GetHash($graph_id,$DataSet->GetData());
-				}
-			}
-		}
-		return api_get_path(WEB_ARCHIVE_PATH).$img_file;
-	}
-
-	function display_graph_by_resource() {
-
-		$header_name = $this->datagen->get_header_names();
-		$total_users = $this->datagen->get_total_users_count();
-		$img_file = '';
-
-		if ($this->datagen->get_total_items_count() > 0 && $total_users > 0 ) {
+                
+        $this->limit_enabled = $limit_enabled;
+        $this->offset = $offset;
+        if (isset ($addparams)) {
+            $this->set_additional_parameters($addparams);
+        }
+        
+        // step 2: generate rows: students
+        $this->datagen->category = $this->selectcat;
+    }
+
+    /**
+     * Display the graph of the total results of all students
+     * */
+    function display_graph() {
+        include_once api_get_path(LIBRARY_PATH).'pchart/pData.class.php';
+        include_once api_get_path(LIBRARY_PATH).'pchart/pChart.class.php';
+        include_once api_get_path(LIBRARY_PATH).'pchart/pCache.class.php';
+
+        $header_name = $this->datagen->get_header_names();
+        $total_users = $this->datagen->get_total_users_count();
+        
+        $img_file = '';
+        
+        if ($this->datagen->get_total_items_count()>0 && $total_users > 0 ) {
+            //Removing user names and total
+            array_shift($header_name);
+            array_shift($header_name);
+            array_pop($header_name);
+            
+            $user_results = $this->datagen->get_data_to_graph();
+                        
+            $pre_result = $new_result = array();
+            $DataSet = new pData();
+            
+            //$pre_result total score of students
+            //filling the Dataset
+            foreach($user_results as $result) {
+                for($i=0; $i < count($header_name); $i++) {
+                    $pre_result[$i+3]+= $result[$i+1];
+                }
+            }
+            $i = 1;
+            $show_draw = false;
+            if ($total_users >0 ) {                
+                foreach($pre_result as $res) {
+                    $total =  $res / ($total_users);                                        
+                    if ($total != 0) {
+                        $show_draw  = true;
+                    }
+                    $DataSet->AddPoint($total, "Serie".$i);
+                    $DataSet->SetSerieName(strip_tags($header_name[$i-1]),"Serie".$i);
+                    
+                    // Dataset definition
+                    $DataSet->AddAllSeries();
+                    $DataSet->SetAbsciseLabelSerie();
+                    $i++;
+                }
+            }
+
+            // Cache definition
+            $Cache = new pCache();
+            // the graph id
+            $gradebook_id = intval($_GET['selectcat']);
+            $graph_id = api_get_user_id().'AverageResultsVsResource'.$gradebook_id.api_get_course_id();
+            $data = $DataSet->GetData();
+            
+            if ($show_draw) {
+                if ($Cache->IsInCache($graph_id, $DataSet->GetData())) {
+                //if (0) {
+                    //if we already created the img
+                    //echo 'in cache';
+                    $img_file = $Cache->GetHash($graph_id,$DataSet->GetData());
+                } else  {
+                    // if the image does not exist in the archive/ folder
+
+                    // Initialise the graph
+                    $Test = new pChart(760, 360);
+
+                    //which schema of color will be used
+                    $quant_resources = count($data[0])-1;
+                    // Adding the color schemma
+                    if ($quant_resources < 8) {
+                        $Test->loadColorPalette(api_get_path(LIBRARY_PATH)."pchart/palette/reduced.txt");
+                    } else {
+                        $Test->loadColorPalette(api_get_path(LIBRARY_PATH)."pchart/palette/default.txt");
+                    }
+
+                    // set font of the axes
+                    $Test->setFontProperties(api_get_path(LIBRARY_PATH)."pchart/fonts/tahoma.ttf",8);
+                    $Test->setGraphArea(50,30,610,300);
+
+                    $Test->drawFilledRoundedRectangle(7,7,780,330,5,240,240,240);
+                    //$Test->drawRoundedRectangle(5,5,790,330,5,230,230,230);
+
+                    //background color area & stripe or not
+                    $Test->drawGraphArea(255,255,255,TRUE);
+                    $Test->drawScale($DataSet->GetData(), $DataSet->GetDataDescription(), SCALE_START0 ,150,150,150,TRUE,0,1, FALSE);
+                    
+                    //background grid
+                    $Test->drawGrid(4,TRUE,230,230,230,50);
+
+                    // Draw the 0 line
+                    //$Test->setFontProperties(api_get_path(LIBRARY_PATH)."pchart/fonts/tahoma.ttf",6);
+                    //$Test->drawTreshold(0,143,55,72,TRUE,TRUE);
+
+                    // Draw the bar graph
+                    $Test->drawBarGraph($DataSet->GetData(),$DataSet->GetDataDescription(),TRUE);
+
+                    //Set legend properties: width, height and text color and font
+                    $Test->setFontProperties(api_get_path(LIBRARY_PATH)."pchart/fonts/tahoma.ttf",9);
+                    $Test->drawLegend(620, 70,$DataSet->GetDataDescription(),255,255,255);
+
+                    //Set title properties
+                    $Test->setFontProperties(api_get_path(LIBRARY_PATH)."pchart/fonts/tahoma.ttf",10);
+                    $Test->drawTitle(50,22,get_lang('AverageResultsVsResource'),50,50,80,620);
+
+                    //------------------
+                    //echo 'not in cache';
+                    $Cache->WriteToCache($graph_id,$DataSet->GetData(),$Test);
+                    ob_start();
+                    $Test->Stroke();
+                    ob_end_clean();
+                    $img_file = $Cache->GetHash($graph_id,$DataSet->GetData());
+                }
+            }
+        }
+        return api_get_path(WEB_ARCHIVE_PATH).$img_file;
+    }
+
+    function display_graph_by_resource() {
+        require_once api_get_path(LIBRARY_PATH).'pchart/pData.class.php';
+        require_once api_get_path(LIBRARY_PATH).'pchart/pChart.class.php';
+        require_once api_get_path(LIBRARY_PATH).'pchart/pCache.class.php';
+
+        $header_name = $this->datagen->get_header_names();
+        $total_users = $this->datagen->get_total_users_count();
+        $img_file = '';
+
+        if ($this->datagen->get_total_items_count() > 0 && $total_users > 0 ) {
             //Removing first name
-			array_shift($header_name);
-			//Removing last name
-			array_shift($header_name);
-
-			$displayscore = ScoreDisplay :: instance();
-			$customdisplays = $displayscore->get_custom_score_display_settings();
-
-			if (is_array($customdisplays) && count(($customdisplays))) {
-
-				$user_results = $this->datagen->get_data_to_graph2();
-				$pre_result = $new_result = array();
-				$DataSet = new pData();
-				//filling the Dataset
-				foreach ($user_results as $result) {
-					//print_r($result);
-					for($i=0; $i< count($header_name); $i++) {
-						$pre_result[$i+3][]= $result[$i+1];
-					}
-				}
-
-				$i=0;
-				$show_draw = false;
-				$resource_list = array();
-				$pre_result2 = array();
-
-				foreach($pre_result as $key=>$res_array) {
-					rsort($res_array);
-					$pre_result2[] = $res_array;
-				}
-
-				//@todo when a display custom does not exist the order of the color does not match
-				//filling all the answer that are not responded with 0
-				rsort($customdisplays);
-
-				if ($total_users > 0) {
-					foreach($pre_result2 as $key=>$res_array) {
-						$key_list = array();
-						foreach($res_array as $user_result) {
-							$resource_list[$key][$user_result[1]] += 1;
-							$key_list[] = $user_result[1];
-						}
-
-						foreach ($customdisplays as $display) {
-							if (!in_array($display['display'], $key_list))
-								$resource_list[$key][$display['display']] = 0;
-						}
-						$i++;
-					}
-				}
-
-				//fixing $resource_list
-				$max = 0;
-				$new_list = array();
-				foreach($resource_list as $key=>$value) {
-				    $new_value = array();
-
-				    foreach($customdisplays as $item) {
-				        if ($value[$item['display']] > $max) {
-				            $max = $value[$item['display']];
-				        }
-				        $new_value[$item['display']] = strip_tags($value[$item['display']]);
-				    }
-				    $new_list[] = $new_value;
-				}
-				$resource_list = $new_list;
-
-				$i = 1;
-				$j = 0;
-
-				foreach($resource_list as $key=>$resource) {
-					$new_resource_list = $new_resource_list_name = array();
-					$DataSet = new pData();
-					foreach ($resource as $name=>$cant) {
-						$DataSet->AddPoint($cant,"Serie".$j);
-						$DataSet->SetSerieName(strip_tags($name),"Serie".$j);
-						$j++;
-					}
-					//print_r($pre_result); print_r($header_name);
-					// Dataset definition
-					$DataSet->AddAllSeries();
-					$DataSet->SetAbsciseLabelSerie('');
-					$DataSet->SetXAxisName(get_lang('GradebookSkillsRanking'));
-					$DataSet->SetYAxisName(get_lang('Students'));
-					$show_draw = true;
-					// Cache definition
-					$Cache = new pCache();
-					// the graph id
-					$gradebook_id = intval($_GET['selectcat']);
-					$graph_id = api_get_user_id().'ByResource'.$gradebook_id.api_get_course_id().api_get_session_id();
-
-					if ($show_draw) {
-						//if ($Cache->IsInCache($graph_id, $DataSet->GetData())) {
-						if (0) {
-							//if we already created the img we get the img file id
-							//echo 'in cache';
-							$img_file = $Cache->GetHash($graph_id,$DataSet->GetData());
-						} else  {
-							// if the image does not exist in the archive/ folder
-							// Initialise the graph
-							$chart_size_w= 480;
-							$chart_size_h= 250;
-
-							$Test = new pChart($chart_size_w, $chart_size_h);
-
-							// Adding the color schemma
-							$Test->loadColorPalette(api_get_path(LIBRARY_PATH)."pchart/palette/pastel.txt");
-
-							// set font of the axes
-							$Test->setFontProperties(api_get_path(LIBRARY_PATH)."pchart/fonts/tahoma.ttf",8);
-							$area_graph_w = $chart_size_w-130;
-							$Test->setGraphArea(50,30,$area_graph_w ,$chart_size_h-50);
-
-							$Test->drawFilledRoundedRectangle(5,5,$chart_size_w-1,$chart_size_h-20,5,240,240,240);
-							//$Test->drawRoundedRectangle(5,5,790,330,5,230,230,230);
-
-							//background color area & stripe or not
-							$Test->drawGraphArea(255,255,255,TRUE);
-
-							//Setting max height by default see #3296
-						    if (!empty($max)) {
-                                $Test->setFixedScale(0, $max);
-						    }
-
-							$Test->drawScale($DataSet->GetData(),$DataSet->GetDataDescription(), SCALE_ADDALLSTART0, 150,150,150, TRUE, 0, 0, FALSE);
-
-							//background grid
-							$Test->drawGrid(4, TRUE,230,230,230,50);
-
-							// Draw the 0 line
-							//$Test->setFontProperties(api_get_path(LIBRARY_PATH)."pchart/fonts/tahoma.ttf",6);
-							//$Test->drawTreshold(0,143,55,72,TRUE,TRUE);
-
-							// Draw the bar graph
-							$Test->drawBarGraph($DataSet->GetData(),$DataSet->GetDataDescription(),TRUE);
-
-							//Set legend properties: width, height and text color and font
-							$Test->setFontProperties(api_get_path(LIBRARY_PATH)."pchart/fonts/tahoma.ttf",9);
-							$Test->drawLegend($area_graph_w+10, 50,$DataSet->GetDataDescription(),255,255,255);
-
-							//Set title properties
-							$Test->setFontProperties(api_get_path(LIBRARY_PATH)."pchart/fonts/tahoma.ttf",10);
-							$Test->drawTitle(50,22,  strip_tags($header_name[$i-1]),50,50,80,$chart_size_w-50);
-
-							//------------------
-							//echo 'not in cache';
-							$Cache->WriteToCache($graph_id,$DataSet->GetData(),$Test);
-							ob_start();
-							$Test->Stroke();
-							ob_end_clean();
-							$img_file = $Cache->GetHash($graph_id,$DataSet->GetData());
-						}
-						echo '<img src="'.api_get_path(WEB_ARCHIVE_PATH).$img_file.'" >';
-						if ($i % 2 == 0 && $i!=0) {
-							echo '<br />';
-						}
-						$i++;
-					}
-				} //end foreach
-			} else {
-				echo get_lang('ToViewGraphScoreRuleMustBeEnabled');
-			}
-			// Pie charts
-			/*
-			$show_draw = false;
-			$resource_list = array();
-			//print_r($pre_result_pie);
-
-			if ($total_users>0) {
-				foreach($pre_result_pie as $key=>$res_array) {
-					//$resource_list
-					foreach($res_array as $user_result) {
-						$total+=  $user_result / ($total_users*100);
-					}
-					echo $total;
-					//echo $total =  $res / ($total_users*100);
-					echo '<br>';
-					//$DataSet->AddPoint($total,"Serie".$i);
-					//$DataSet->SetSerieName($header_name[$i-1],"Serie".$i);
-
-				}
-			}
-			//here--------------
-			foreach($resource_list as $key=>$resource) {
-				$new_resource_list = $new_resource_list_name = array();
-
-				foreach($resource as $name=>$cant) {
-					$new_resource_list[]=$cant;
-					$new_resource_list_name[]=$name;
-				}
-				//Pie chart
-				$DataSet = new pData;
-				$DataSet->AddPoint($new_resource_list,"Serie1");
-				$DataSet->AddPoint($new_resource_list_name,"Serie2");
-				$DataSet->AddAllSeries();
-				$DataSet->SetAbsciseLabelSerie("Serie2");
-
-				$Test = new pChart(400,300);
-				$Test->loadColorPalette(api_get_path(LIBRARY_PATH)."pchart/palette/soft_tones.txt");
-				// background
-				//$Test->drawFilledRoundedRectangle(7,7,293,193,5,240,240,240);
-				// border color
-				$Test->drawRoundedRectangle(5,5,295,195,5,230,230,230);
-
-			    // This will draw a shadow under the pie chart
-				//$Test->drawFilledCircle(122,102,70,200,200,200);
-
-				 //Draw the pie chart
-				$Test->setFontProperties(api_get_path(LIBRARY_PATH)."pchart/fonts/tahoma.ttf",8);
-
-				$Test->drawBarGraph($DataSet->GetData(),$DataSet->GetDataDescription(),TRUE);
-				$tmp_path = api_get_path(SYS_ARCHIVE_PATH);
-
-				$Test->drawBasicPieGraph($DataSet->GetData(),$DataSet->GetDataDescription(),120,100,70,PIE_PERCENTAGE,255,255,218);
-				$Test->drawPieLegend(230,15,$DataSet->GetData(),$DataSet->GetDataDescription(),250,250,250);
-				$user_id = api_get_user_id();
-				$img_file_generated_name = $key.uniqid('').'gradebook.png';
-				$Test->Render($tmp_path.$img_file_generated_name);
-				chmod($tmp_path.$img_file_generated_name, api_get_permissions_for_new_files());
-
-				if ($i % 2 == 0 && $i!= 0) {
-					echo '<br>';
-				}
-				echo '<img src="'.api_get_path(WEB_ARCHIVE_PATH).$img_file_generated_name.'">';
-			}
-			*/
-		}
-	}
-	/**
-	 * Function used by SortableTable to get total number of items in the table
-	 */
-	function get_total_number_of_items() {
-		return $this->datagen->get_total_users_count();
-	}
-
-	/**
-	 * Function used by SortableTable to generate the data to display
-	 */
-	function get_table_data ($from = 1, $per_page = null, $column = null, $direction = null, $sort = null) {
-		$is_western_name_order = api_is_western_name_order();
-
-		// create page navigation if needed
-		$totalitems = $this->datagen->get_total_items_count();
-		if ($this->limit_enabled && $totalitems > LIMIT) {
-			$selectlimit = LIMIT;
-		} else {
-			$selectlimit = $totalitems;
-		}
-		if ($this->limit_enabled && $totalitems > LIMIT) {
-	      	$calcprevious = LIMIT;
-			$header .= '<table style="width: 100%; text-align: right; margin-left: auto; margin-right: auto;" border="0" cellpadding="2">'
-						.'<tbody>'
-						.'<tr>';
-
-			// previous X
-	      	$header .= '<td style="width:100%;">';
-	      	if ($this->offset >= LIMIT) {
-	      		$header .= '<a href="'.api_get_self()
-	      							.'?selectcat='.Security::remove_XSS($_GET['selectcat'])
-	      							.'&offset='.(($this->offset)-LIMIT)
-									.(isset($_GET['search'])?'&search='.Security::remove_XSS($_GET['search']):'').'">'
-	      					.Display::return_icon('action_prev.png', get_lang('PreviousPage'), array(), 32)
-	      					.'</a>';
-	      	} else {
-	      		$header .= Display::return_icon('action_prev_na.png', get_lang('PreviousPage'), array(), 32);
-	      	}
-	      	$header .= ' ';
-			// next X
-	      	$calcnext = (($this->offset+(2*LIMIT)) > $totalitems) ?
-	      					($totalitems-(LIMIT+$this->offset)) : LIMIT;
-
-      		if ($calcnext > 0) {
-	      		$header .= '<a href="'.api_get_self()
-	      							.'?selectcat='.Security::remove_XSS($_GET['selectcat'])
-	      							.'&offset='.($this->offset+LIMIT)
-	      							.(isset($_GET['search'])?'&search='.Security::remove_XSS($_GET['search']):'').'">'
-	      					.Display::return_icon('action_next.png', get_lang('NextPage'), array(), 32)
-	      					.'</a>';
-      		} else {
-      		    $header .= Display::return_icon('action_next_na.png', get_lang('NextPage'), array(), 32);
-      		}
-      		$header .= '</td>';
-	      	$header .= '</tbody></table>';
-			echo $header;
-		}
-
-		// retrieve sorting type
-		if ($is_western_name_order) {
-			$users_sorting = ($this->column == 0 ? FlatViewDataGenerator :: FVDG_SORT_FIRSTNAME : FlatViewDataGenerator :: FVDG_SORT_LASTNAME);
-		} else {
-			$users_sorting = ($this->column == 0 ? FlatViewDataGenerator :: FVDG_SORT_LASTNAME : FlatViewDataGenerator :: FVDG_SORT_FIRSTNAME);
-		}
-		if ($this->direction == 'DESC') {
-			$users_sorting |= FlatViewDataGenerator :: FVDG_SORT_DESC;
-		} else {
-			$users_sorting |= FlatViewDataGenerator :: FVDG_SORT_ASC;
-		}
-		// step 1: generate columns: evaluations and links
-
-		$header_names = $this->datagen->get_header_names($this->offset, $selectlimit);
-
-		$column = 0;
-
-		if ($is_western_name_order) {
-			$this->set_header($column++, $header_names[1]);
-			$this->set_header($column++, $header_names[0]);
-		} else {
-			$this->set_header($column++, $header_names[0]);
-			$this->set_header($column++, $header_names[1]);
-		}
-
-		while ($column < count($header_names)) {
-			$this->set_header($column, $header_names[$column], false);
-			$column++;
-		}
-
-		$data_array = $this->datagen->get_data($users_sorting, $from, $this->per_page, $this->offset, $selectlimit);
-
-		$table_data = array();
-		foreach ($data_array as $user_row) {
-			$table_row = array ();
-			$count = 0;
-			$user_id = $user_row[$count++];
-			$lastname = $user_row[$count++];
-			$firstname = $user_row[$count++];
-			if ($is_western_name_order) {
-				$table_row[] = $this->build_name_link($user_id, $firstname);
-				$table_row[] = $this->build_name_link($user_id, $lastname);
-			} else {
-				$table_row[] = $this->build_name_link($user_id, $lastname);
-				$table_row[] = $this->build_name_link($user_id, $firstname);
-			}
-			while ($count < count($user_row)) {
-				$table_row[] = $user_row[$count++];
-			}
-			$table_data[]= $table_row;
-		}
-		return $table_data;
-	}
-
-
-	// Other functions
-
-	private function build_name_link ($user_id, $name) {
-		return '<a href="user_stats.php?userid='.$user_id.'&selectcat='.$this->selectcat->get_id().'">'.$name.'</a>';
-	}
+            array_shift($header_name);
+            //Removing last name
+            array_shift($header_name);
+            
+            $displayscore = ScoreDisplay :: instance();
+            $customdisplays = $displayscore->get_custom_score_display_settings();        
+            
+            if (is_array($customdisplays) && count(($customdisplays))) {
+                
+                $user_results = $this->datagen->get_data_to_graph2();                
+                $pre_result = $new_result = array();
+                $DataSet = new pData();
+                //filling the Dataset
+                foreach ($user_results as $result) {
+                    //print_r($result);
+                    for($i=0; $i< count($header_name); $i++) {
+                        $pre_result[$i+3][]= $result[$i+1];
+                    }
+                }
+    
+                $i=0;
+                $show_draw = false;
+                $resource_list = array();
+                $pre_result2 = array();
+
+                foreach($pre_result as $key=>$res_array) {
+                    rsort($res_array);
+                    $pre_result2[] = $res_array;
+                }
+                
+                //@todo when a display custom does not exist the order of the color does not match
+                //filling all the answer that are not responded with 0
+                rsort($customdisplays);
+                
+                if ($total_users > 0) {
+                    foreach($pre_result2 as $key=>$res_array) {
+                        $key_list = array();
+                        foreach($res_array as $user_result) {
+                            $resource_list[$key][$user_result[1]] += 1;
+                            $key_list[] = $user_result[1];
+                        }
+                
+                        foreach ($customdisplays as $display) {
+                            if (!in_array($display['display'], $key_list))
+                                $resource_list[$key][$display['display']] = 0;
+                        }
+                        $i++;
+                    }
+                }                
+                
+                //fixing $resource_list        
+                $max = 0;        
+                $new_list = array();
+                foreach($resource_list as $key=>$value) {
+                    $new_value = array();
+                    
+                    foreach($customdisplays as $item) {                        
+                        if ($value[$item['display']] > $max) {
+                            $max = $value[$item['display']];
+                        }
+                        $new_value[$item['display']] = strip_tags($value[$item['display']]);
+                    }
+                    $new_list[] = $new_value;
+                }
+                $resource_list = $new_list;                
+                
+                $i = 1;
+                $j = 0;
+
+                foreach($resource_list as $key=>$resource) {
+                    $new_resource_list = $new_resource_list_name = array();
+                    $DataSet = new pData();
+                    // Reverse array, otherwise we get highest values first
+                    $resource = array_reverse($resource,true);
+                    foreach ($resource as $name=>$cant) {
+                        $DataSet->AddPoint($cant,"Serie".$j);
+                        $DataSet->SetSerieName(strip_tags($name),"Serie".$j);
+                        $j++;
+                    }
+                    //print_r($pre_result); print_r($header_name);
+                    // Dataset definition
+                    $DataSet->AddAllSeries();
+                    $DataSet->SetAbsciseLabelSerie('');
+                    $DataSet->SetXAxisName(get_lang('GradebookSkillsRanking'));
+                    $DataSet->SetYAxisName(get_lang('Students'));
+                    $show_draw = true;
+                    // Cache definition
+                    $Cache = new pCache();
+                    // the graph id
+                    $gradebook_id = intval($_GET['selectcat']);
+                    $graph_id = api_get_user_id().'ByResource'.$gradebook_id.api_get_course_id().api_get_session_id();
+
+                    if ($show_draw) {
+                        //if ($Cache->IsInCache($graph_id, $DataSet->GetData())) {
+                        if (0) {
+                            //if we already created the img we get the img file id
+                            //echo 'in cache';
+                            $img_file = $Cache->GetHash($graph_id,$DataSet->GetData());
+                        } else  {
+                            // if the image does not exist in the archive/ folder
+                            // Initialise the graph
+                            $chart_size_w= 480;
+                            $chart_size_h= 250;
+
+                            $Test = new pChart($chart_size_w, $chart_size_h);
+
+                            // Adding the color schemma
+                            $Test->loadColorPalette(api_get_path(LIBRARY_PATH)."pchart/palette/pastel.txt");
+
+                            // set font of the axes
+                            $Test->setFontProperties(api_get_path(LIBRARY_PATH)."pchart/fonts/tahoma.ttf",8);
+                            $area_graph_w = $chart_size_w-130;
+                            $Test->setGraphArea(50,30,$area_graph_w ,$chart_size_h-50);
+
+                            $Test->drawFilledRoundedRectangle(5,5,$chart_size_w-1,$chart_size_h-20,5,240,240,240);
+                            //$Test->drawRoundedRectangle(5,5,790,330,5,230,230,230);
+
+                            //background color area & stripe or not
+                            $Test->drawGraphArea(255,255,255,TRUE);
+                            
+                            //Setting max height by default see #3296
+                            if (!empty($max)) {
+                                $Test->setFixedScale(0, $max);    
+                            }
+                            
+                            $Test->drawScale($DataSet->GetData(),$DataSet->GetDataDescription(), SCALE_ADDALLSTART0, 150,150,150, TRUE, 0, 0, FALSE);
+
+                            //background grid
+                            $Test->drawGrid(4, TRUE,230,230,230,50);
+
+                            // Draw the 0 line
+                            //$Test->setFontProperties(api_get_path(LIBRARY_PATH)."pchart/fonts/tahoma.ttf",6);
+                            //$Test->drawTreshold(0,143,55,72,TRUE,TRUE);
+
+                            // Draw the bar graph
+                            $Test->drawBarGraph($DataSet->GetData(),$DataSet->GetDataDescription(),TRUE);
+
+                            //Set legend properties: width, height and text color and font
+                            $Test->setFontProperties(api_get_path(LIBRARY_PATH)."pchart/fonts/tahoma.ttf",9);
+                            $Test->drawLegend($area_graph_w+10, 50,$DataSet->GetDataDescription(),255,255,255);
+
+                            //Set title properties
+                            $Test->setFontProperties(api_get_path(LIBRARY_PATH)."pchart/fonts/tahoma.ttf",10);
+                            $Test->drawTitle(50,22,  strip_tags($header_name[$i-1]),50,50,80,$chart_size_w-50);
+
+                            //------------------
+                            //echo 'not in cache';
+                            $Cache->WriteToCache($graph_id,$DataSet->GetData(),$Test);
+                            //ob_start();
+                            //$Test->Stroke();
+                            //ob_end_clean();
+                            $img_file = $Cache->GetHash($graph_id,$DataSet->GetData());
+                        }
+                        echo '<img src="'.api_get_path(WEB_ARCHIVE_PATH).$img_file.'" >';
+                        if ($i % 2 == 0 && $i!=0) {
+                            echo '<br />';
+                        }
+                        $i++;
+                    }
+                } //end foreach
+            } else {
+                echo get_lang('ToViewGraphScoreRuleMustBeEnabled');
+            }
+            // Pie charts
+            /*
+            $show_draw = false;
+            $resource_list = array();
+            //print_r($pre_result_pie);
+
+            if ($total_users>0) {
+                foreach($pre_result_pie as $key=>$res_array) {
+                    //$resource_list
+                    foreach($res_array as $user_result) {
+                        $total+=  $user_result / ($total_users*100);
+                    }
+                    echo $total;
+                    //echo $total =  $res / ($total_users*100);
+                    echo '<br>';
+                    //$DataSet->AddPoint($total,"Serie".$i);
+                    //$DataSet->SetSerieName($header_name[$i-1],"Serie".$i);
+
+                }
+            }
+            //here--------------
+            foreach($resource_list as $key=>$resource) {
+                $new_resource_list = $new_resource_list_name = array();
+
+                foreach($resource as $name=>$cant) {
+                    $new_resource_list[]=$cant;
+                    $new_resource_list_name[]=$name;
+                }
+                //Pie chart
+                $DataSet = new pData;
+                $DataSet->AddPoint($new_resource_list,"Serie1");
+                $DataSet->AddPoint($new_resource_list_name,"Serie2");
+                $DataSet->AddAllSeries();
+                $DataSet->SetAbsciseLabelSerie("Serie2");
+
+                $Test = new pChart(400,300);
+                $Test->loadColorPalette(api_get_path(LIBRARY_PATH)."pchart/palette/soft_tones.txt");
+                // background
+                //$Test->drawFilledRoundedRectangle(7,7,293,193,5,240,240,240);
+                // border color
+                $Test->drawRoundedRectangle(5,5,295,195,5,230,230,230);
+
+                // This will draw a shadow under the pie chart
+                //$Test->drawFilledCircle(122,102,70,200,200,200);
+
+                 //Draw the pie chart
+                $Test->setFontProperties(api_get_path(LIBRARY_PATH)."pchart/fonts/tahoma.ttf",8);
+
+                $Test->drawBarGraph($DataSet->GetData(),$DataSet->GetDataDescription(),TRUE);
+                $tmp_path = api_get_path(SYS_ARCHIVE_PATH);
+
+                $Test->drawBasicPieGraph($DataSet->GetData(),$DataSet->GetDataDescription(),120,100,70,PIE_PERCENTAGE,255,255,218);
+                $Test->drawPieLegend(230,15,$DataSet->GetData(),$DataSet->GetDataDescription(),250,250,250);
+                $user_id = api_get_user_id();
+                $img_file_generated_name = $key.uniqid('').'gradebook.png';
+                $Test->Render($tmp_path.$img_file_generated_name);
+                chmod($tmp_path.$img_file_generated_name, api_get_permissions_for_new_files());
+
+                if ($i % 2 == 0 && $i!= 0) {
+                    echo '<br>';
+                }
+                echo '<img src="'.api_get_path(WEB_ARCHIVE_PATH).$img_file_generated_name.'">';
+            }
+            */
+        }
+    }
+    /**
+     * Function used by SortableTable to get total number of items in the table
+     */
+    function get_total_number_of_items() {
+        return $this->datagen->get_total_users_count();
+    }
+
+    /**
+     * Function used by SortableTable to generate the data to display
+     */
+    function get_table_data ($from = 1, $per_page = null, $column = null, $direction = null, $sort = null) {
+        $is_western_name_order = api_is_western_name_order();
+
+        // create page navigation if needed
+        $totalitems = $this->datagen->get_total_items_count();
+        if ($this->limit_enabled && $totalitems > LIMIT) {
+            $selectlimit = LIMIT;
+        } else {
+            $selectlimit = $totalitems;
+        }
+        if ($this->limit_enabled && $totalitems > LIMIT) {
+              $calcprevious = LIMIT;
+            $header .= '<table style="width: 100%; text-align: right; margin-left: auto; margin-right: auto;" border="0" cellpadding="2">'
+                        .'<tbody>'
+                        .'<tr>';
+
+            // previous X
+              $header .= '<td style="width:100%;">';
+              if ($this->offset >= LIMIT) {
+                  $header .= '<a href="'.api_get_self()
+                                      .'?selectcat='.Security::remove_XSS($_GET['selectcat'])
+                                      .'&offset='.(($this->offset)-LIMIT)
+                                    .(isset($_GET['search'])?'&search='.Security::remove_XSS($_GET['search']):'').'">'
+                              .Display::return_icon('action_prev.png', get_lang('PreviousPage'), array(), 32)                              
+                              .'</a>';
+              } else {
+                  $header .= Display::return_icon('action_prev_na.png', get_lang('PreviousPage'), array(), 32);
+              }
+              $header .= ' ';
+            // next X
+              $calcnext = (($this->offset+(2*LIMIT)) > $totalitems) ?
+                              ($totalitems-(LIMIT+$this->offset)) : LIMIT;
+              
+              if ($calcnext > 0) {
+                  $header .= '<a href="'.api_get_self()
+                                      .'?selectcat='.Security::remove_XSS($_GET['selectcat'])
+                                      .'&offset='.($this->offset+LIMIT)
+                                      .(isset($_GET['search'])?'&search='.Security::remove_XSS($_GET['search']):'').'">'
+                              .Display::return_icon('action_next.png', get_lang('NextPage'), array(), 32)
+                              .'</a>';
+              } else {
+                  $header .= Display::return_icon('action_next_na.png', get_lang('NextPage'), array(), 32);
+              }
+              $header .= '</td>';
+              $header .= '</tbody></table>';
+            echo $header;
+        }
+
+        // retrieve sorting type
+        if ($is_western_name_order) {
+            $users_sorting = ($this->column == 0 ? FlatViewDataGenerator :: FVDG_SORT_FIRSTNAME : FlatViewDataGenerator :: FVDG_SORT_LASTNAME);
+        } else {
+            $users_sorting = ($this->column == 0 ? FlatViewDataGenerator :: FVDG_SORT_LASTNAME : FlatViewDataGenerator :: FVDG_SORT_FIRSTNAME);
+        }
+        if ($this->direction == 'DESC') {
+            $users_sorting |= FlatViewDataGenerator :: FVDG_SORT_DESC;
+        } else {
+            $users_sorting |= FlatViewDataGenerator :: FVDG_SORT_ASC;
+        }
+        // step 1: generate columns: evaluations and links
+
+        $header_names = $this->datagen->get_header_names($this->offset, $selectlimit);
+
+        $column = 0;
+        
+        if ($is_western_name_order) {
+            $this->set_header($column++, $header_names[1]);
+            $this->set_header($column++, $header_names[0]);
+        } else {
+            $this->set_header($column++, $header_names[0]);
+            $this->set_header($column++, $header_names[1]);
+        }        
+
+        while ($column < count($header_names)) {
+            $this->set_header($column, $header_names[$column], false);
+            $column++;
+        }
+
+        $data_array = $this->datagen->get_data($users_sorting, $from, $this->per_page, $this->offset, $selectlimit);
+
+        $table_data = array();
+        foreach ($data_array as $user_row) {
+            $table_row = array ();
+            $count = 0;
+            $user_id = $user_row[$count++];
+            $lastname = $user_row[$count++];
+            $firstname = $user_row[$count++];
+            if ($is_western_name_order) {
+                $table_row[] = $this->build_name_link($user_id, $firstname);
+                $table_row[] = $this->build_name_link($user_id, $lastname);
+            } else {
+                $table_row[] = $this->build_name_link($user_id, $lastname);
+                $table_row[] = $this->build_name_link($user_id, $firstname);
+            }
+            while ($count < count($user_row)) {
+                $table_row[] = $user_row[$count++];
+            }
+            $table_data[]= $table_row;
+        }
+        return $table_data;
+    }
+
+
+    // Other functions
+
+    private function build_name_link ($user_id, $name) {
+        return '<a href="user_stats.php?userid='.$user_id.'&selectcat='.$this->selectcat->get_id().'">'.$name.'</a>';
+    }
 }

+ 2 - 2
main/gradebook/lib/fe/scoredisplayform.class.php

@@ -88,7 +88,7 @@ class ScoreDisplayForm extends FormValidator
 				<p><!-- BEGIN required --><span class="form_required">*</span> <!-- END required -->
                 
                 <label class="control-label">{label}</label>
-				<div class="controls"><!-- BEGIN error --><span class="form_error">{error}</span><br /><!-- END error -->	<br /><b>'.get_lang('And').'</b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp{element} % =';
+				<div class="controls"><!-- BEGIN error --><span class="form_error">{error}</span><br /><!-- END error -->	<br/>&nbsp<b>'.get_lang('And').'</b>&nbsp&nbsp&nbsp&nbsp&nbsp{element}&nbsp%&nbsp&nbsp=';
 
 				$elementTemplateTwoLabel2 =
 				'<!-- BEGIN error --><span class="form_error">{error}</span><br /><!-- END error -->&nbsp{element}
@@ -107,7 +107,7 @@ class ScoreDisplayForm extends FormValidator
 					'size' => 40,
 					'maxlength' => 40,
 					'id' => 'txtb-'.$counter,
-                    'class' => 'span3',
+                    'class' => 'span',
 				));
 				$renderer->setElementTemplate($elementTemplateTwoLabel,'endscore[' . $counter . ']');
 				$renderer->setElementTemplate($elementTemplateTwoLabel2,'displaytext[' . $counter . ']');

+ 2 - 1
main/gradebook/lib/gradebook_data_generator.class.php

@@ -96,7 +96,8 @@ class GradebookDataGenerator
 			$row = array ();
 			$row[] = $item;
 			$row[] = $item->get_name();
-			$row[] = $item->get_description();
+            // display the 2 first line of description, and all description on mouseover (https://support.chamilo.org/issues/6588)
+			$row[] = '<span title="'.api_remove_tags_with_space($item->get_description()).'">'.api_get_short_text_from_html($item->get_description(), 160).'</span>';
 			$row[] = $item->get_weight();
 			/*if (api_is_allowed_to_edit(null, true)) {
 				$row[] = $this->build_date_column($item);

+ 246 - 248
main/gradebook/lib/scoredisplay.class.php

@@ -41,51 +41,51 @@ class ScoreDisplay
 {
     // Singleton stuff
 
-	/**
-	 * Get the instance of this class
-	 */
-	public static function instance($category_id = 0) {
-		static $instance;
-		if (!isset ($instance)) {
-			$instance = new ScoreDisplay($category_id);
-		}
-		return $instance;
-	}
+    /**
+     * Get the instance of this class
+     */
+    public static function instance($category_id = 0) {
+        static $instance;
+        if (!isset ($instance)) {
+            $instance = new ScoreDisplay($category_id);
+        }
+        return $instance;
+    }
 
 
     // Static methods
 
-	/**
-	 * Compare the custom display of 2 scores, can be useful in sorting
-	 */
-	public static function compare_scores_by_custom_display ($score1, $score2) {
-		if (!isset($score1)) {
-			return (isset($score2) ? 1 : 0);
-		} elseif (!isset($score2)) {
-			return -1;
-		} else {
-			$scoredisplay = ScoreDisplay :: instance();
-			$custom1 = $scoredisplay->display_custom($score1);
-			$custom2 = $scoredisplay->display_custom($score2);
-			if ($custom1 == $custom2) {
-				return 0;
-			} else {
-				return (($score1[0]/$score1[1]) < ($score2[0]/$score2[1]) ? -1 : 1);
-			}
+    /**
+     * Compare the custom display of 2 scores, can be useful in sorting
+     */
+    public static function compare_scores_by_custom_display ($score1, $score2) {
+        if (!isset($score1)) {
+            return (isset($score2) ? 1 : 0);
+        } elseif (!isset($score2)) {
+            return -1;
+        } else {
+            $scoredisplay = ScoreDisplay :: instance();
+            $custom1 = $scoredisplay->display_custom($score1);
+            $custom2 = $scoredisplay->display_custom($score2);
+            if ($custom1 == $custom2) {
+                return 0;
+            } else {
+                return (($score1[0]/$score1[1]) < ($score2[0]/$score2[1]) ? -1 : 1);
+            }
 
-		}
-	}
-	
-	private $coloring_enabled;
-	private $color_split_value;
-	private $custom_enabled;
-	private $upperlimit_included;
-	private $custom_display;
-	private $custom_display_conv;
+        }
+    }
+    
+    private $coloring_enabled;
+    private $color_split_value;
+    private $custom_enabled;
+    private $upperlimit_included;
+    private $custom_display;
+    private $custom_display_conv;
 
-	/**
-	 * Protected constructor - call instance() to instantiate
-	 */
+    /**
+     * Protected constructor - call instance() to instantiate
+     */
     protected function ScoreDisplay($category_id = 0) {
         if (!empty($category_id)) {
             $this->category_id = $category_id;
@@ -101,7 +101,7 @@ class ScoreDisplay
 
         if ($this->coloring_enabled) {
             $value = api_get_setting('gradebook_score_display_colorsplit');
-            if (isset($value)) {  		
+            if (isset($value)) {          
                 $this->color_split_value = $value;
             }
         }
@@ -111,8 +111,7 @@ class ScoreDisplay
         $value = $value['my_display_custom'];   
         $this->custom_enabled  = $value == 'true' ? true : false;
         
-        if ($this->custom_enabled) {             
-            
+        if ($this->custom_enabled) {
             $params = array('category = ? AND subkey = ?' =>  array('Gradebook', 'ranking'));
             $displays = api_get_settings_params($params);
             $portal_displays = array();
@@ -122,16 +121,15 @@ class ScoreDisplay
                     $portal_displays[$data[0]] = array('score' => $data[0], 'display' =>$data[1]);
                 }
                 sort($portal_displays);
-            }            
+            }
             $this->custom_display = $portal_displays;
-            
             if (count($this->custom_display)>0) {
                 $value = api_get_setting('gradebook_score_display_upperlimit');
                 $value = $value['my_display_upperlimit'];        
                 $this->upperlimit_included  = $value == 'true' ? true : false;    
                 $this->custom_display_conv = $this->convert_displays($this->custom_display);                
             }
-    	}
+        }
         
         //If teachers can override the portal parameters
         
@@ -150,43 +148,43 @@ class ScoreDisplay
         }
     }
     
-	/**
-	 * Is coloring enabled ?
-	 */
-	public function is_coloring_enabled () {
-		return $this->coloring_enabled;
-	}
+    /**
+     * Is coloring enabled ?
+     */
+    public function is_coloring_enabled () {
+        return $this->coloring_enabled;
+    }
     
-	/**
-	 * Is custom score display enabled ?
-	 */
-	public function is_custom() {
-		return $this->custom_enabled;
-	}
+    /**
+     * Is custom score display enabled ?
+     */
+    public function is_custom() {
+        return $this->custom_enabled;
+    }
     
-	/**
-	 * Is upperlimit included ?
-	 */
-	public function is_upperlimit_included () {
-		return $this->upperlimit_included;
-	}
+    /**
+     * Is upperlimit included ?
+     */
+    public function is_upperlimit_included () {
+        return $this->upperlimit_included;
+    }
 
-	/**
-	 * If custom score display is enabled, this will return the current settings.
-	 * See also update_custom_score_display_settings
-	 * @return array current settings (or null if feature not enabled)
-	 */
-	public function get_custom_score_display_settings() {
-		return $this->custom_display;
-	}
+    /**
+     * If custom score display is enabled, this will return the current settings.
+     * See also update_custom_score_display_settings
+     * @return array current settings (or null if feature not enabled)
+     */
+    public function get_custom_score_display_settings() {
+        return $this->custom_display;
+    }
 
-	/**
-	 * If coloring is enabled, scores below this value will be displayed in red.
-	 * @return int color split value, in percent (or null if feature not enabled)
-	 */
-	public function get_color_split_value() {
-		return $this->color_split_value;
-	}
+    /**
+     * If coloring is enabled, scores below this value will be displayed in red.
+     * @return int color split value, in percent (or null if feature not enabled)
+     */
+    public function get_color_split_value() {
+        return $this->color_split_value;
+    }
 
     /**
      * Get current gradebook category id
@@ -215,15 +213,15 @@ class ScoreDisplay
         return $category_id;
     }
 
-	/**
-	 * Update custom score display settings
-	 * @param array $displays 2-dimensional array - every subarray must have keys (score, display)
+    /**
+     * Update custom score display settings
+     * @param array $displays 2-dimensional array - every subarray must have keys (score, display)
          * @param int   score color percent (optional)
          * @param int   gradebook category id (optional)
-	 */
-	public function update_custom_score_display_settings ($displays, $scorecolpercent = 0, $category_id = null) {
-		$this->custom_display = $displays;
-   		$this->custom_display_conv = $this->convert_displays($this->custom_display);
+     */
+    public function update_custom_score_display_settings ($displays, $scorecolpercent = 0, $category_id = null) {
+        $this->custom_display = $displays;
+           $this->custom_display_conv = $this->convert_displays($this->custom_display);
 
         if (isset($category_id)) {
             $category_id = intval($category_id);
@@ -231,23 +229,23 @@ class ScoreDisplay
             $category_id = $this->get_current_gradebook_category_id();
         }
 
-		// remove previous settings
+        // remove previous settings
         $tbl_display = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_SCORE_DISPLAY);
-		$sql = 'DELETE FROM '.$tbl_display.' WHERE category_id = '.$category_id;
-		Database::query($sql);
+        $sql = 'DELETE FROM '.$tbl_display.' WHERE category_id = '.$category_id;
+        Database::query($sql);
 
-		// add new settings
-		$sql = 'INSERT INTO '.$tbl_display.' (id, score, display, category_id, score_color_percent) VALUES ';
-		$count = 0;
-		foreach ($displays as $display) {
-			if ($count > 0) {
-				$sql .= ',';
-			}
-			$sql .= "(NULL, '".$display['score']."', '".Database::escape_string($display['display'])."', ".$category_id.", ".intval($scorecolpercent).")";
-			$count++;
-		}        
-		Database::query($sql);
-	}
+        // add new settings
+        $sql = 'INSERT INTO '.$tbl_display.' (id, score, display, category_id, score_color_percent) VALUES ';
+        $count = 0;
+        foreach ($displays as $display) {
+            if ($count > 0) {
+                $sql .= ',';
+            }
+            $sql .= "(NULL, '".$display['score']."', '".Database::escape_string($display['display'])."', ".$category_id.", ".intval($scorecolpercent).")";
+            $count++;
+        }        
+        Database::query($sql);
+    }
     
     public function insert_defaults($category_id) {
         if (empty($category_id)) {
@@ -295,16 +293,16 @@ class ScoreDisplay
         return floatval(number_format($score, $this->get_number_decimals()));
     }
 
-	/**
-	 * Display a score according to the current settings
-	 * @param array $score score data structure, as returned by the calc_score functions
+    /**
+     * Display a score according to the current settings
+     * @param array $score score data structure, as returned by the calc_score functions
 	 * @param int 	$type one of the following constants: SCORE_DIV, SCORE_PERCENT, SCORE_DIV_PERCENT, SCORE_AVERAGE
 	 * 				(ignored for student's view if custom score display is enabled)
 	 * @param int 	$what one of the following constants: SCORE_BOTH, SCORE_ONLY_DEFAULT, SCORE_ONLY_CUSTOM (default: SCORE_BOTH)
 	 * 				(only taken into account if custom score display is enabled and for course/platform admin)
-	 */
-	public function display_score($score, $type = SCORE_DIV_PERCENT, $what = SCORE_BOTH, $no_color = false) {	  
-		$my_score = $score == 0 ? 1 : $score;	
+     */
+    public function display_score($score, $type = SCORE_DIV_PERCENT, $what = SCORE_BOTH, $no_color = false) {      
+        $my_score = $score == 0 ? 1 : $score;    
         
         if ($type == SCORE_BAR) {
             $percentage = $my_score[0]/$my_score[1]*100;            
@@ -316,54 +314,54 @@ class ScoreDisplay
             return $simple_score;
         }
         
-		if ($this->custom_enabled && isset($this->custom_display_conv)) {		    
-	        $display = $this->display_default($my_score, $type);	        
-		} else {
-			// if no custom display set, use default display
-			$display = $this->display_default($my_score, $type);
-		}        
+        if ($this->custom_enabled && isset($this->custom_display_conv)) {            
+            $display = $this->display_default($my_score, $type);            
+        } else {
+            // if no custom display set, use default display
+            $display = $this->display_default($my_score, $type);
+        }        
         
-		if ($this->coloring_enabled && $no_color == false) {
-		    $my_score_denom = ($score[1]==0)?1:$score[1];		
-		    if (($score[0] / $my_score_denom) < ($this->color_split_value / 100)) {
-		        $display = Display::tag('font', $display, array('color'=>'red'));                
+        if ($this->coloring_enabled && $no_color == false) {
+            $my_score_denom = ($score[1]==0)?1:$score[1];        
+            if (($score[0] / $my_score_denom) < ($this->color_split_value / 100)) {
+                $display = Display::tag('font', $display, array('color'=>'red'));                
                 //$display = Display::label($display, 'important');
-		    }		    
-		}
-		return $display;
-	}
-	
+            }            
+        }
+        return $display;
+    }
+    
     // Internal functions
-	private function display_default ($score, $type) {        
-		switch ($type) {
-			case SCORE_DIV :			                // X / Y
-				return $this->display_as_div($score);
-			case SCORE_PERCENT :		                // XX %
-				return $this->display_as_percent($score);
-			case SCORE_DIV_PERCENT :	                // X / Y (XX %)
-				return $this->display_as_div($score).' (' . $this->display_as_percent($score) . ')';
-			case SCORE_AVERAGE :		                // XX %
-				return $this->display_as_percent($score);
-			case SCORE_DECIMAL :                        // 0.50  (X/Y)
-				return $this->display_as_decimal($score);				
-		    case SCORE_DIV_PERCENT_WITH_CUSTOM :        // X / Y (XX %) - Good!
-		        $custom = $this->display_custom($score);
-		        if (!empty($custom)) {
-		            $custom = ' - '.$custom;
-		        }
-				return $this->display_as_div($score).' (' . $this->display_as_percent($score) . ')'.$custom;
-		    case SCORE_DIV_SIMPLE_WITH_CUSTOM :         // X - Good!
+    private function display_default ($score, $type) {        
+        switch ($type) {
+            case SCORE_DIV :                            // X / Y
+                return $this->display_as_div($score);
+            case SCORE_PERCENT :                        // XX %
+                return $this->display_as_percent($score);
+            case SCORE_DIV_PERCENT :                    // X / Y (XX %)
+                return $this->display_as_div($score).' (' . $this->display_as_percent($score) . ')';
+            case SCORE_AVERAGE :                        // XX %
+                return $this->display_as_percent($score);
+            case SCORE_DECIMAL :                        // 0.50  (X/Y)
+                return $this->display_as_decimal($score);                
+            case SCORE_DIV_PERCENT_WITH_CUSTOM :        // X / Y (XX %) - Good!
+                $custom = $this->display_custom($score);
+                if (!empty($custom)) {
+                    $custom = ' - '.$custom;
+                }
+                return $this->display_as_div($score).' (' . $this->display_as_percent($score) . ')'.$custom;
+            case SCORE_DIV_SIMPLE_WITH_CUSTOM :         // X - Good!
                 $custom = $this->display_custom($score);
-		        if (!empty($custom)) {
-		            $custom = ' - '.$custom;
-		        }
-		        return $this->display_simple_score($score).$custom;		
+                if (!empty($custom)) {
+                    $custom = ' - '.$custom;
+                }
+                return $this->display_simple_score($score).$custom;        
                 break;
             case SCORE_DIV_SIMPLE_WITH_CUSTOM_LETTERS:
                 $custom = $this->display_custom($score);
-		        if (!empty($custom)) {
-		            $custom = ' - '.$custom;
-		        }
+                if (!empty($custom)) {
+                    $custom = ' - '.$custom;
+                }
                 $score = $this->display_simple_score($score);
                 
                 //needs sudo apt-get install php5-intl
@@ -375,75 +373,75 @@ class ScoreDisplay
                     $letters = " ($letters) ";
                 }
                 
-		        return $score.$letters.$custom;		 
+                return $score.$letters.$custom;         
                 break;
-		    case SCORE_CUSTOM:                          // Good!
-		        return $this->display_custom($score);
-		}
-	}
-	
-	private function display_simple_score($score) {
-	    if (isset($score[0])) {
-	        return $this->format_score($score[0]);
-	    }
-	    return '';
-	}
-	
+            case SCORE_CUSTOM:                          // Good!
+                return $this->display_custom($score);
+        }
+    }
+    
+    private function display_simple_score($score) {
+        if (isset($score[0])) {
+            return $this->format_score($score[0]);
+        }
+        return '';
+    }
+    
     /**
      * Returns "1" for array("100", "100");
      */
-	private function display_as_decimal($score) {
-		$score_denom = ($score[1]==0) ? 1 : $score[1];
-		return $this->format_score($score[0]/$score_denom);
-	}
-	
-	/**
-	 * Returns "100 %" for array("100", "100");
-	 */
-	private function display_as_percent($score) {        
-		$score_denom = ($score[1]==0) ? 1 : $score[1];        
-		return $this->format_score($score[0]/$score_denom*100) . ' %';
-	}
-	
+    private function display_as_decimal($score) {
+        $score_denom = ($score[1]==0) ? 1 : $score[1];
+        return $this->format_score($score[0]/$score_denom);
+    }
+    
+    /**
+     * Returns "100 %" for array("100", "100");
+     */
+    private function display_as_percent($score) {        
+        $score_denom = ($score[1]==0) ? 1 : $score[1];        
+        return $this->format_score($score[0]/$score_denom*100) . ' %';
+    }
+    
     /**
      * 
      * Returns 10.00 / 10.00 for array("100", "100");
      * @param array $score
-     */	
+     */    
     private function display_as_div($score) {
-		if ($score == 1) {
-			return '0/0';
-		} else {
+        if ($score == 1) {
+            return '0/0';
+        } else {
             $score[0] =$this->format_score($score[0]);
             $score[1] =$this->format_score($score[1]);
-			return  $score[0] . ' / ' . $score[1];
-		}
-	}
+            return  $score[0] . ' / ' . $score[1];
+        }
+    }
     
     /**
      * Depends on the teacher's configuration of thresholds. i.e. [0 50] "Bad", [50:100] "Good"
      * @param array $score
-     */	
-	private function display_custom ($score) {
-		$my_score_denom= ($score[1]==0) ? 1 : $score[1];
-		$scaledscore = $score[0] / $my_score_denom;
-		if ($this->upperlimit_included) {
-			foreach ($this->custom_display_conv as $displayitem) {
-				if ($scaledscore <= $displayitem['score']) {
-					return $displayitem['display'];
-				}
-			}
-		} else {
-			if (!empty($this->custom_display_conv)) {
-				foreach ($this->custom_display_conv as $displayitem) {
-					if ($scaledscore < $displayitem['score'] || $displayitem['score'] == 1) {
-						return $displayitem['display'];
-					}
-				}
-			}
-		}
-	}
-	
+     */    
+    private function display_custom ($score) {
+        $my_score_denom= ($score[1]==0) ? 1 : $score[1];
+        $scaledscore = $score[0] / $my_score_denom;
+        if ($this->upperlimit_included) {
+            foreach ($this->custom_display_conv as $displayitem) {
+                if ($scaledscore <= $displayitem['score']) {
+                    return $displayitem['display'];
+                }
+            }
+        } else {
+            if (!empty($this->custom_display_conv)) {
+                foreach ($this->custom_display_conv as $displayitem) {
+                    if ($scaledscore < $displayitem['score'] || $displayitem['score'] == 1) {
+                        return $displayitem['display'];
+                    }
+                }
+            }
+        }
+    }
+    
 
     /**
      * Get score color percent by category
@@ -468,66 +466,66 @@ class ScoreDisplay
         return $score;
     }
 
-	/**
-	 * Get current custom score display settings
+    /**
+     * Get current custom score display settings
          * @param   int     Gradebook category id
-	 * @return  array   2-dimensional array - every element contains 3 subelements (id, score, display)
-	 */
-	private function get_custom_displays($category_id = null) {
+     * @return  array   2-dimensional array - every element contains 3 subelements (id, score, display)
+     */
+    private function get_custom_displays($category_id = null) {
         $tbl_display = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_SCORE_DISPLAY);
         if (isset($category_id)) {
             $category_id = intval($category_id);
         } else {
             $category_id = $this->get_current_gradebook_category_id();
         }
-		$sql = 'SELECT * FROM '.$tbl_display.' WHERE category_id = '.$category_id.' ORDER BY score';
-		$result = Database::query($sql);
-		return Database::store_result($result,'ASSOC');
-	}   
+        $sql = 'SELECT * FROM '.$tbl_display.' WHERE category_id = '.$category_id.' ORDER BY score';
+        $result = Database::query($sql);
+        return Database::store_result($result,'ASSOC');
+    }   
  
 
-	/**
-	 * Convert display settings to internally used values
-	 */
-	private function convert_displays($custom_display) {
-		if (isset($custom_display)) {
-			// get highest score entry, and copy each element to a new array
-			$converted = array();
-			$highest = 0;
-			foreach ($custom_display as $element) {
-				if ($element['score'] > $highest) {
-					$highest = $element['score'];
-				}
-				$converted[] = $element;
-			}
-			// sort the new array (ascending)
-			usort($converted, array('ScoreDisplay', 'sort_display'));
+    /**
+     * Convert display settings to internally used values
+     */
+    private function convert_displays($custom_display) {
+        if (isset($custom_display)) {
+            // get highest score entry, and copy each element to a new array
+            $converted = array();
+            $highest = 0;
+            foreach ($custom_display as $element) {
+                if ($element['score'] > $highest) {
+                    $highest = $element['score'];
+                }
+                $converted[] = $element;
+            }
+            // sort the new array (ascending)
+            usort($converted, array('ScoreDisplay', 'sort_display'));
 
-			// adjust each score in such a way that
-			// each score is scaled between 0 and 1
-			// the highest score in this array will be equal to 1
-			$converted2 = array();
-			foreach ($converted as $element) {
-				$newelement = array();
-                if (!empty($highest)) {
+            // adjust each score in such a way that
+            // each score is scaled between 0 and 1
+            // the highest score in this array will be equal to 1
+            $converted2 = array();
+            foreach ($converted as $element) {
+                $newelement = array();
+                if (isset($highest) && !empty($highest) && $highest > 0) {
                     $newelement['score'] = $element['score'] / $highest;
                 } else {
                     $newelement['score'] = 0;
                 }
-				$newelement['display'] = $element['display'];
-				$converted2[] = $newelement;
-			}
-			return $converted2;
-		} else {
-			return null;
-		}
-	}
+                $newelement['display'] = $element['display'];
+                $converted2[] = $newelement;
+            }
+            return $converted2;
+        } else {
+            return null;
+        }
+    }
 
-	private function sort_display($item1, $item2) {
-		if ($item1['score'] == $item2['score']) {
-			return 0;
-		} else {
-			return ($item1['score'] < $item2['score'] ? -1 : 1);
-		}
-	}
+    private function sort_display($item1, $item2) {
+        if ($item1['score'] == $item2['score']) {
+            return 0;
+        } else {
+            return ($item1['score'] < $item2['score'] ? -1 : 1);
+        }
+    }
 }

+ 10 - 2
main/group/group_category.php

@@ -65,6 +65,14 @@ if (api_get_setting('allow_group_categories') == 'true') {
 	$nameTools = get_lang('PropModify');
 }
 
+$htmlHeadXtra[] = '<script>
+$(document).ready( function() {
+    $("#max_member").on("focus", function() {
+        $("#max_member_selected").attr("checked", true);
+    });
+});
+ </script>';
+  
 $interbreadcrumb[] = array ('url' => 'group.php', 'name' => get_lang('Groups'));
 
 $course_id = api_get_course_int_id();
@@ -123,8 +131,8 @@ $form->addElement('html', '</div>');
 // Members per group
 $form->addElement('radio', 'max_member_no_limit', get_lang('GroupLimit'), get_lang('NoLimit'), GroupManager::MEMBER_PER_GROUP_NO_LIMIT);
 $group = array ();
-$group[] = $form->createElement('radio', 'max_member_no_limit', null, get_lang('MaximumOfParticipants'), 1);
-$group[] = $form->createElement('text', 'max_member', null, array ('size' => 2));
+$group[] = $form->createElement('radio', 'max_member_no_limit', null, get_lang('MaximumOfParticipants'), 1, array('id' => 'max_member_selected'));
+$group[] = $form->createElement('text', 'max_member', null, array ('size' => 2, 'id' => 'max_member'));
 $group[] = $form->createElement('static', null, null, get_lang('GroupPlacesThis'));
 $form->addGroup($group, 'max_member_group', null, '', false);
 $form->addRule('max_member_group', get_lang('InvalidMaxNumberOfMembers'), 'callback', 'check_max_number_of_members');

BIN
main/img/icons/22/course_na.png


BIN
main/img/icons/32/platform.png


BIN
main/img/icons/48/platform.png


BIN
main/img/logo.gif


BIN
main/img/logo.png


+ 142 - 1
main/inc/ajax/admin.ajax.php

@@ -5,6 +5,7 @@
  */
 
 require_once '../global.inc.php';
+require_once api_get_path(SYS_CODE_PATH).'admin/statistics/statistics.lib.php';
 
 api_protect_admin_script();
 
@@ -48,5 +49,145 @@ switch ($action) {
             }
         }
         break;
+        
+    case 'version':
+        echo version_check();
+        break;
+}
+    
+
+/**
+ * Displays either the text for the registration or the message that the installation is (not) up to date
+ *
+ * @return string html code
+ * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
+ * @version august 2006
+ * @todo have a 6monthly re-registration
+ */
+function version_check() {
+    $tbl_settings = Database :: get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
+    $sql = 'SELECT selected_value FROM  '.$tbl_settings.' WHERE variable="registered" ';
+    $result = Database::query($sql);
+    $row = Database::fetch_array($result, 'ASSOC');
+
+    // The site has not been registered yet.
+    $return = '';
+    if ($row['selected_value'] == 'false') {
+        $return .= get_lang('VersionCheckExplanation');
+        $return .= '<form class="well" action="'.api_get_self().'" id="VersionCheck" name="VersionCheck" method="post">';
+        $return .= '<label class="checkbox"><input type="checkbox" name="donotlistcampus" value="1" id="checkbox" />'.get_lang('HideCampusFromPublicPlatformsList');
+        $return .= '</label><button type="submit" class="btn btn-primary" name="Register" value="'.get_lang('EnableVersionCheck').'" id="register" >'.get_lang('EnableVersionCheck').'</button>';
+        $return .= '</form>';
+        check_system_version();
+    } else {
+        // site not registered. Call anyway
+        $return .= check_system_version();
+    }
+    return $return;
+}
+
+/**
+ * Check if the current installation is up to date
+ * The code is borrowed from phpBB and slighlty modified
+ * @author The phpBB Group <support@phpbb.com> (the code)
+ * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University (the modifications)
+ * @author Yannick Warnier <ywarnier@beeznest.org> for the move to HTTP request
+ * @copyright (C) 2001 The phpBB Group
+ * @return language string with some layout (color)
+ */
+function check_system_version() {
+    global $_configuration;
+    $system_version = trim($_configuration['system_version']); // the chamilo version of your installation
+
+    if (ini_get('allow_url_fopen') == 1) {
+        // The number of courses
+        $number_of_courses = statistics::count_courses();
+
+        // The number of users
+        $number_of_users = statistics::count_users();
+        $number_of_active_users = statistics::count_users(null,null,null,true);
+
+        $data = array(
+            'url' => api_get_path(WEB_PATH),
+            'campus' => api_get_setting('siteName'),
+            'contact' => api_get_setting('emailAdministrator'),
+            'version' => $system_version,
+            'numberofcourses' => $number_of_courses,
+            'numberofusers' => $number_of_users,
+            'numberofactiveusers' => $number_of_active_users,
+            //The donotlistcampus setting recovery should be improved to make
+            // it true by default - this does not affect numbers counting
+            'donotlistcampus' => api_get_setting('donotlistcampus'),
+            'organisation' => api_get_setting('Institution'),
+            'language' => api_get_setting('platformLanguage'),
+            'adminname' => api_get_setting('administratorName').' '.api_get_setting('administratorSurname'),
+        );
+
+        $res = _http_request('version.chamilo.org', 80, '/version.php', $data);
+
+        if ($res != 0) {
+            $version_info = $res;
+
+            if ($system_version != $version_info) {
+                $output = '<br /><span style="color:red">' . get_lang('YourVersionNotUpToDate') . '. '.get_lang('LatestVersionIs').' <b>Chamilo '.$version_info.'</b>. '.get_lang('YourVersionIs').' <b>Chamilo '.$system_version. '</b>. '.str_replace('http://www.chamilo.org', '<a href="http://www.chamilo.org">http://www.chamilo.org</a>', get_lang('PleaseVisitOurWebsite')).'</span>';
+            } else {
+                $output = '<br /><span style="color:green">'.get_lang('VersionUpToDate').': Chamilo '.$version_info.'</span>';
+            }
+        } else {
+            $output = '<span style="color:red">' . get_lang('ImpossibleToContactVersionServerPleaseTryAgain') . '</span>';
+        }
+    } else {
+        $output = '<span style="color:red">' . get_lang('AllowurlfopenIsSetToOff') . '</span>';
+    }
+    return $output;
+}
+
+/**
+ * Function to make an HTTP request through fsockopen (specialised for GET)
+ * Derived from Jeremy Saintot: http://www.php.net/manual/en/function.fsockopen.php#101872
+ * @param string IP or hostname
+ * @param int    Target port
+ * @param string URI (defaults to '/')
+ * @param array  GET data
+ * @param float  Timeout
+ * @param bool   Include HTTP Request headers?
+ * @param bool   Include HTTP Response headers?
+ */
+function _http_request($ip, $port = 80, $uri = '/', $getdata = array(), $timeout = 1, $req_hdr = false, $res_hdr = false) {
+    $verb = 'GET';
+    $ret = '';
+    $getdata_str = count($getdata) ? '?' : '';
+
+    foreach ($getdata as $k => $v) {
+                $getdata_str .= urlencode($k) .'='. urlencode($v) . '&';
+    }
+
+    $crlf = "\r\n";
+    $req = $verb .' '. $uri . $getdata_str .' HTTP/1.1' . $crlf;
+    $req .= 'Host: '. $ip . $crlf;
+    $req .= 'User-Agent: Mozilla/5.0 Firefox/3.6.12' . $crlf;
+    $req .= 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' . $crlf;
+    $req .= 'Accept-Language: en-us,en;q=0.5' . $crlf;
+    $req .= 'Accept-Encoding: deflate' . $crlf;
+    $req .= 'Accept-Charset: utf-8;q=0.7,*;q=0.7' . $crlf;
+
+    $req .= $crlf;
+
+    if ($req_hdr) { $ret .= $req; }
+    if (($fp = @fsockopen($ip, $port, $errno, $errstr, $timeout)) == false) {
+        return "Error $errno: $errstr\n";
+    }
+
+    stream_set_timeout($fp, $timeout);
+    $r = @fwrite($fp, $req);
+    $line = @fread($fp,512);
+    $ret .= $line;
+    fclose($fp);
+
+    if (!$res_hdr) {
+        $ret = substr($ret, strpos($ret, "\r\n\r\n") + 4);
+    }
+
+    return trim($ret);
 }
-exit;
+exit;

+ 5 - 7
main/inc/ajax/agenda.ajax.php

@@ -70,14 +70,12 @@ switch ($action) {
         $agenda->move_event($id, $day_delta, $minute_delta);
         break;
     case 'get_events':
-        // The following code needs a security check for permissions
-        /*
-        $uid = $user_id;
-        if (!empty($_REQUEST['user_id'])) {
-            $uid = intval($user_id);
+        $user_id = $_REQUEST['user_id'];
+        if (substr($user_id,0,1) == 'G') {
+            $length = strlen($user_id);
+            $group_id = substr($user_id,2,$length-1);
         }
-        */
-        $events = $agenda->get_events($_GET['start'], $_GET['end'], api_get_course_int_id(), $group_id, $user_id);
+        $events = $agenda->get_events($_REQUEST['start'], $_REQUEST['end'], api_get_course_int_id(), $group_id , $user_id);
         echo $events;
         break;
     case 'get_user_agenda':

+ 1 - 1
main/inc/ajax/course.ajax.php

@@ -43,4 +43,4 @@ switch ($action) {
     default:
         echo '';
 }
-exit;
+exit;

+ 25 - 0
main/inc/ajax/form.ajax.php

@@ -0,0 +1,25 @@
+<?php
+/* For licensing terms, see /license.txt */
+
+require_once '../global.inc.php';
+
+$action = isset($_REQUEST['a']) ? $_REQUEST['a'] : null;
+
+switch ($action) {
+    case 'get_captcha':
+        header('Content-Type: image/jpeg');
+
+        $sessionVar = (empty($_REQUEST['var']))
+                      ? '_HTML_QuickForm_CAPTCHA'
+                      : $_REQUEST['var'];
+        // Force a new CAPTCHA for each one displayed
+
+        /** @var Text_CAPTCHA $obj */
+        $obj = $_SESSION[$sessionVar];
+        $obj->generate(true);
+        echo $image = $obj->getCAPTCHA();
+
+        //echo $_SESSION[$sessionVar]->getCAPTCHAAsJPEG();
+        exit;
+        break;
+}

+ 47 - 3
main/inc/ajax/model.ajax.php

@@ -37,6 +37,8 @@ if (!in_array($action,
         'get_exercise_results',
         'get_hotpotatoes_exercise_results',
         'get_work_user_list',
+        'get_work_user_list_others',
+        'get_work_user_list_all',
         'get_timelines',
         'get_user_skill_ranking',
         'get_usergroups_teacher',
@@ -198,11 +200,27 @@ switch ($action) {
         $skill = new Skill();
         $count = $skill->get_user_list_skill_ranking_count();
         break;
-    case 'get_work_user_list':
+    case 'get_work_user_list_all':
         require_once api_get_path(SYS_CODE_PATH).'work/work.lib.php';
         $work_id = $_REQUEST['work_id'];
         $count = get_count_work($work_id);
         break;
+    case 'get_work_user_list_others':
+        require_once api_get_path(SYS_CODE_PATH).'work/work.lib.php';
+        $work_id = $_REQUEST['work_id'];
+        $count = get_count_work($work_id, api_get_user_id());
+        break;
+    case 'get_work_user_list':
+        require_once api_get_path(SYS_CODE_PATH).'work/work.lib.php';
+        $work_id = $_REQUEST['work_id'];
+        $courseInfo = api_get_course_info();
+        // All
+        if ($courseInfo['show_score'] == '0') {
+            $count = get_count_work($work_id, null, api_get_user_id());
+        } else {
+            $count = get_count_work($work_id, api_get_user_id());
+        }
+        break;
     case 'get_exercise_results':
         $exercise_id = $_REQUEST['exerciseId'];
         if (isset($_GET['filter_by_user']) && !empty($_GET['filter_by_user'])) {
@@ -394,12 +412,36 @@ switch ($action) {
 	        }
 	    }
     	break;
+    case 'get_work_user_list_all':
+        if (isset($_GET['type'])  && $_GET['type'] == 'simple') {
+            //$columns = array('type', 'firstname', 'lastname',  'username', 'title', 'qualification', 'sent_date', 'qualificator_id', 'actions');
+            $columns = array('type', 'firstname', 'lastname', 'title', 'qualification', 'sent_date', 'qualificator_id', 'actions');
+        } else {
+            //$columns = array('type', 'firstname', 'lastname',  'username', 'title', 'sent_date', 'actions');
+            $columns = array('type', 'firstname', 'lastname', 'title', 'sent_date', 'actions');
+        }
+        $result = get_work_user_list($start, $limit, $sidx, $sord, $work_id, $where_condition);
+        break;
+    case 'get_work_user_list_others':
+        if (isset($_GET['type'])  && $_GET['type'] == 'simple') {
+            //$columns = array('type', 'firstname', 'lastname',  'username', 'title', 'qualification', 'sent_date', 'qualificator_id', 'actions');
+            $columns = array('type', 'firstname', 'lastname',  'title', 'qualification', 'sent_date', 'qualificator_id', 'actions');
+        } else {
+            //$columns = array('type', 'firstname', 'lastname',  'username', 'title', 'sent_date', 'actions');
+            $columns = array('type', 'firstname', 'lastname',  'title', 'sent_date', 'actions');
+        }
+        $where_condition .= " AND u.user_id <> ".api_get_user_id();
+        $result = get_work_user_list($start, $limit, $sidx, $sord, $work_id, $where_condition);
+        break;
     case 'get_work_user_list':
         if (isset($_GET['type'])  && $_GET['type'] == 'simple') {
-            $columns = array('type', 'firstname', 'lastname',  'username', 'title', 'qualification', 'sent_date', 'qualificator_id', 'actions');
+            //$columns = array('type', 'firstname', 'lastname',  'username', 'title', 'qualification', 'sent_date', 'qualificator_id', 'actions');
+            $columns = array('type', 'firstname', 'lastname', 'title', 'qualification', 'sent_date', 'qualificator_id', 'actions');
         } else {
-            $columns = array('type', 'firstname', 'lastname',  'username', 'title', 'sent_date', 'actions');
+            //$columns = array('type', 'firstname', 'lastname',  'username', 'title', 'sent_date', 'actions');
+            $columns = array('type', 'firstname', 'lastname', 'title', 'sent_date', 'actions');
         }
+        $where_condition .= " AND u.user_id = ".api_get_user_id();
         $result = get_work_user_list($start, $limit, $sidx, $sord, $work_id, $where_condition);
         break;
 	case 'get_exercise_results':
@@ -666,6 +708,8 @@ $allowed_actions = array(
     'get_exercise_results',
     'get_hotpotatoes_exercise_results',
     'get_work_user_list',
+    'get_work_user_list_others',
+    'get_work_user_list_all',
     'get_timelines',
     'get_grade_models',
     'get_event_email_template',

+ 30 - 0
main/inc/ajax/session.ajax.php

@@ -0,0 +1,30 @@
+<?php
+/* For licensing terms, see /license.txt */
+/**
+ * Responses to AJAX calls
+ */
+
+$language_file[] = 'admin';
+require_once '../global.inc.php';
+
+$action = $_REQUEST['a'];
+
+switch ($action) {
+    case 'get_user_sessions':
+        if (api_is_platform_admin()) {
+            $user_id = intval($_POST['user_id']);
+            $list_sessions = SessionManager::get_sessions_by_user($user_id, true);
+            if (!empty($list_sessions)) {
+                foreach ($list_sessions as $session_item) {
+                    echo $session_item['session_name'].'<br />';
+                }
+            } else {
+                echo get_lang('NoSessionsForThisUser');
+            }
+            unset($list_sessions);
+        }
+        break;
+    default:
+        echo '';
+}
+exit;

+ 3 - 1
main/inc/lib/add_courses_to_session_functions.lib.php

@@ -8,6 +8,8 @@
  * Init
  */
 require_once dirname(__FILE__).'/xajax/xajax.inc.php';
+//require_once (api_get_path(SYS_CODE_PATH).'admin/add_courses_to_session.php');
+
 /**
  * AddCourseToSession class
  */
@@ -65,7 +67,7 @@ class AddCourseToSession {
 			}
 
 			if (api_is_multiple_url_enabled()) {
-				$tbl_course_rel_access_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
+				$tbl_course_rel_access_url= Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
 				$access_url_id = api_get_current_access_url_id();
 				if ($access_url_id != -1){
 

+ 1 - 1
main/inc/lib/add_many_session_to_category_functions.lib.php

@@ -7,7 +7,7 @@
 /**
  * Init
  */
-require_once (api_get_path(LIBRARY_PATH).'xajax/xajax.inc.php');
+require_once dirname(__FILE__).'/xajax/xajax.inc.php';
 /**
  * AddManySessionToCategoryFunctions class
  */

+ 21 - 1
main/inc/lib/career.lib.php

@@ -8,6 +8,11 @@
 /**
  * Code
  */
+require_once 'promotion.lib.php';
+require_once 'fckeditor/fckeditor.php';
+
+define ('CAREER_STATUS_ACTIVE',  1);
+define ('CAREER_STATUS_INACTIVE',0);
 
 /**
  * @package chamilo.library
@@ -140,7 +145,7 @@ class Career extends Model {
                 case 'updated_at':
                     break;
                 case 'name':
-                    $val .= ' '.get_lang('Copy');
+                    $val .= ' '.get_lang('CopyLabelSuffix');
                     $new[$key] = $val;
                     break;
                 case 'created_at':
@@ -166,6 +171,21 @@ class Career extends Model {
         return $cid;
     }    
     
+     public function get_status($career_id) {
+        $TBL_CAREER             = Database::get_main_table(TABLE_CAREER);
+        $career_id = intval($career_id);
+        $sql 	= "SELECT status FROM $TBL_CAREER WHERE id = '$career_id'";
+        $result = Database::query($sql);
+        if (Database::num_rows($result) > 0) {
+            $data = Database::fetch_array($result);
+            return $data['status'];
+        } else {
+            return false;
+        }
+        
+    }
+        
+    
     public function save($params, $show_query = false) {
 	    $id = parent::save($params, $show_query);
 	    if (!empty($id)) {

+ 46 - 0
main/inc/lib/course.lib.php

@@ -4916,4 +4916,50 @@ class CourseManager
         return $settings;
     }
 
+
+    function updateTeachers($course_code, $teachers)
+    {
+        if (empty($teachers)) {
+            return false;
+        }
+        if (!is_array($teachers)) {
+            $teachers = array($teachers);
+        }
+
+        $course_user_table  = Database::get_main_table(TABLE_MAIN_COURSE_USER);
+
+        // Delete only teacher relations that doesn't match the selected teachers
+        $cond = null;
+        if (count($teachers)>0) {
+            foreach($teachers as $key) {
+                $cond.= " AND user_id <> '".$key."'";
+            }
+        }
+        $sql = 'DELETE FROM '.$course_user_table.' WHERE course_code="'.Database::escape_string($course_code).'" AND status="1"'.$cond;
+        Database::query($sql);
+
+        if (count($teachers) > 0) {
+            foreach ($teachers as $key) {
+
+                //We check if the teacher is already subscribed in this course
+                $sql_select_teacher = 'SELECT 1 FROM '.$course_user_table.' WHERE user_id = "'.$key.'" AND course_code = "'.$course_code.'" ';
+                $result = Database::query($sql_select_teacher);
+
+                if (Database::num_rows($result) == 1) {
+                    $sql = 'UPDATE '.$course_user_table.' SET status = "1" WHERE course_code = "'.$course_code.'" AND user_id = "'.$key.'"  ';
+                } else {
+                    $sql = "INSERT INTO ".$course_user_table . " SET
+                        course_code = '".Database::escape_string($course_code). "',
+                        user_id = '".$key . "',
+                        status = '1',
+                        role = '',
+                        tutor_id='0',
+                        sort='0',
+                        user_course_cat='0'";
+                }
+                Database::query($sql);
+            }
+        }
+    }
+
 } //end class CourseManager

+ 62 - 132
main/inc/lib/exercise_show_functions.lib.php

@@ -24,15 +24,17 @@ class ExerciseShowFunctions {
 	 * @param int       Question ID
 	 * @return void
 	 */
-	static function display_fill_in_blanks_answer($answer,$id,$questionId) {
-        global $feedback_type;
+	static function display_fill_in_blanks_answer($feedback_type, $answer, $id, $questionId)
+    {
         if (empty($id)) {
-            echo '<tr><td>'. nl2br(Security::remove_XSS($answer,COURSEMANAGERLOWSECURITY)).'</td></tr>';
+            echo '<tr><td>'. (Security::remove_XSS($answer)).'</td></tr>';
         } else {
 		?>
 			<tr>
                 <td>
-                    <?php echo nl2br(Security::remove_XSS($answer,COURSEMANAGERLOWSECURITY)); ?>
+                    <?php
+                    echo (Security::remove_XSS($answer));
+                    ?>
                 </td>
 
 			<?php
@@ -55,9 +57,7 @@ class ExerciseShowFunctions {
 	 * @param int       Question ID
 	 * @return void
 	 */
-	static function display_free_answer($answer, $exe_id, $questionId, $questionScore = null) {
-        global $feedback_type;
-
+	static function display_free_answer($feedback_type, $answer, $exe_id, $questionId, $questionScore = null) {
         $comments = get_comments($exe_id, $questionId);
 
         if (!empty($answer)) {
@@ -76,41 +76,38 @@ class ExerciseShowFunctions {
         }
 	}
 
-    static function display_oral_expression_answer($answer, $id, $questionId, $nano = null)
-    {
-        global $feedback_type;
+	static function display_oral_expression_answer($feedback_type, $answer, $id, $questionId, $nano = null) {
+		if (isset($nano)) {
+			echo $nano->show_audio_file();
+		}
 
-        if (isset($nano)) {
-            echo $nano->show_audio_file();
-        }
-
-        if (empty($id)) {
-            echo '<tr>';
-            echo Display::tag('td',nl2br(Security::remove_XSS($answer,COURSEMANAGERLOWSECURITY)), array('width'=>'55%'));
-            echo '</tr>';
-            if ($feedback_type != EXERCISE_FEEDBACK_TYPE_EXAM) {
-                echo '<tr>';
-                echo Display::tag('td',get_lang('notCorrectedYet'), array('width'=>'45%'));
-                echo '</tr>';
-            } else {
-                echo '<tr><td>&nbsp;</td></tr>';
-            }
-        } else {
-            echo '<tr>';
-            echo '<td>';
-            if (!empty($answer)) {
-                echo nl2br(Security::remove_XSS($answer,COURSEMANAGERLOWSECURITY));
-            }
-            echo '</td>';
+		if (empty($id)) {
+			echo '<tr>';
+			echo Display::tag('td',nl2br(Security::remove_XSS($answer,COURSEMANAGERLOWSECURITY)), array('width'=>'55%'));
+			echo '</tr>';
+			if ($feedback_type != EXERCISE_FEEDBACK_TYPE_EXAM) {
+				echo '<tr>';
+				echo Display::tag('td',get_lang('notCorrectedYet'), array('width'=>'45%'));
+				echo '</tr>';
+			} else {
+				echo '<tr><td>&nbsp;</td></tr>';
+			}
+		} else {
+			echo '<tr>';
+			echo '<td>';
+			if (!empty($answer)) {
+				echo nl2br(Security::remove_XSS($answer,COURSEMANAGERLOWSECURITY));
+			}
+			echo '</td>';
 
-            if (!api_is_allowed_to_edit(null,true) && $feedback_type != EXERCISE_FEEDBACK_TYPE_EXAM) {
-                echo '<td>';
-                $comm = get_comments($id,$questionId);
-                echo '</td>';
-            }
-            echo '</tr>';
-        }
-    }
+			if (!api_is_allowed_to_edit(null,true) && $feedback_type != EXERCISE_FEEDBACK_TYPE_EXAM) {
+				echo '<td>';
+				$comm = get_comments($id,$questionId);
+				echo '</td>';
+			}
+			echo '</tr>';
+		}
+	}
 
 	/**
 	 * Displays the answer to a hotspot question
@@ -120,9 +117,10 @@ class ExerciseShowFunctions {
 	 * @param string $studentChoice
 	 * @param string $answerComment
 	 */
-	static function display_hotspot_answer($answerId, $answer, $studentChoice, $answerComment) {
-		global $feedback_type;
-		$hotspot_colors = array("", // $i starts from 1 on next loop (ugly fix)
+	static function display_hotspot_answer($feedback_type, $answerId, $answer, $studentChoice, $answerComment) {
+
+		$hotspot_colors = array(
+            "", // $i starts from 1 on next loop (ugly fix)
             "#4271B5",
             "#FE8E16",
             "#45C7F0",
@@ -158,9 +156,9 @@ class ExerciseShowFunctions {
 			<td valign="top" align="left" >
 				<?php
                 if ($studentChoice) {
-                    echo '<span style="font-weight: bold; color: #008000;">'.nl2br(Text::make_clickable($answerComment)).'</span>';
+                    echo '<span style="font-weight: bold; color: #008000;">'.nl2br(make_clickable($answerComment)).'</span>';
                 } else {
-                    //echo '<span style="font-weight: bold; color: #FF0000;">'.nl2br(Text::make_clickable($answerComment)).'</span>';
+                    //echo '<span style="font-weight: bold; color: #FF0000;">'.nl2br(make_clickable($answerComment)).'</span>';
                 }
 
 				?>
@@ -186,24 +184,16 @@ class ExerciseShowFunctions {
 	 * @param boolean Whether to show the answer comment or not
 	 * @return void
 	 */
-	static function display_unique_or_multiple_answer($answerType, $studentChoice, $answer, $answerComment, $answerCorrect, $id, $questionId, $ans) {
-		global $feedback_type;
-        // radio_on.gif/radio_off.gif
-
-        $imageType = (in_array($answerType, array(UNIQUE_ANSWER,UNIQUE_ANSWER_IMAGE, UNIQUE_ANSWER_NO_OPTION))) ? 'radio' : 'checkbox';
-        $image = $imageType.($studentChoice ? '_on' : '_off');
-        $image .= '.gif';
-
-        $imageAnswer = $imageType.($answerCorrect ? '_on' : '_off');
-        $imageAnswer .= '.gif';
-
+	static function display_unique_or_multiple_answer($feedback_type, $answerType, $studentChoice, $answer, $answerComment, $answerCorrect, $id, $questionId, $ans) {
 		?>
 		<tr>
 		<td width="5%">
-            <?php Display::display_icon($image); ?>
+			<img src="../img/<?php echo (in_array($answerType, array(UNIQUE_ANSWER, UNIQUE_ANSWER_NO_OPTION))) ? 'radio':'checkbox'; echo $studentChoice?'_on':'_off'; ?>.gif"
+			border="0" alt="" />
 		</td>
 		<td width="5%">
-            <?php Display::display_icon($imageAnswer); ?>
+			<img src="../img/<?php echo (in_array($answerType, array(UNIQUE_ANSWER, UNIQUE_ANSWER_NO_OPTION))) ? 'radio':'checkbox'; echo $answerCorrect?'_on':'_off'; ?>.gif"
+			border="0" alt=" " />
 		</td>
 		<td width="40%">
 			<?php
@@ -217,18 +207,18 @@ class ExerciseShowFunctions {
             if ($studentChoice) {
 				if ($answerCorrect) {
                     $color = 'green';
-					//echo '<span style="font-weight: bold; color: #008000;">'.nl2br(Text::make_clickable($answerComment)).'</span>';
+					//echo '<span style="font-weight: bold; color: #008000;">'.nl2br(make_clickable($answerComment)).'</span>';
 				} else {
                     $color = 'black';
-                    //echo '<span style="font-weight: bold; color: #FF0000;">'.nl2br(Text::make_clickable($answerComment)).'</span>';
+                    //echo '<span style="font-weight: bold; color: #FF0000;">'.nl2br(make_clickable($answerComment)).'</span>';
 				}
-                echo '<span style="font-weight: bold; color: '.$color.';">'.nl2br(Text::make_clickable($answerComment)).'</span>';
+                echo '<span style="font-weight: bold; color: '.$color.';">'.nl2br(make_clickable($answerComment)).'</span>';
 
 			} else {
 				if ($answerCorrect) {
-					//echo '<span style="font-weight: bold; color: #000;">'.nl2br(Text::make_clickable($answerComment)).'</span>';
+					//echo '<span style="font-weight: bold; color: #000;">'.nl2br(make_clickable($answerComment)).'</span>';
 				} else {
-                    //echo '<span style="font-weight: normal; color: #000;">'.nl2br(Text::make_clickable($answerComment)).'</span>';
+                    //echo '<span style="font-weight: normal; color: #000;">'.nl2br(make_clickable($answerComment)).'</span>';
 				}
 			}
 			?>
@@ -245,65 +235,6 @@ class ExerciseShowFunctions {
 		<?php
 	}
 
-    static function display_unique_image_answer($answerType, $studentChoice, $answer, $answerComment, $answerCorrect, $id, $questionId, $ans) {
-        global $feedback_type;
-
-        $imageType = (in_array($answerType, array(UNIQUE_ANSWER,UNIQUE_ANSWER_IMAGE, UNIQUE_ANSWER_NO_OPTION))) ? 'radio' : 'checkbox';
-        $image = $imageType.($studentChoice ? '_on' : '_off');
-        $image .= '.gif';
-
-        $imageAnswer = $imageType.($answerCorrect ? '_on' : '_off');
-        $imageAnswer .= '.gif';
-
-        ?>
-    <tr>
-        <tr>
-		<td width="5%">
-            <?php Display::display_icon($image); ?>
-		</td>
-		<td width="5%">
-            <?php Display::display_icon($imageAnswer); ?>
-		</td>
-        <td width="40%">
-            <?php
-            echo $answer;
-            ?>
-        </td>
-
-        <?php if ($feedback_type != EXERCISE_FEEDBACK_TYPE_EXAM) { ?>
-        <td width="20%">
-            <?php
-            if ($studentChoice) {
-                if ($answerCorrect) {
-                    $color = 'green';
-                    //echo '<span style="font-weight: bold; color: #008000;">'.nl2br(Text::make_clickable($answerComment)).'</span>';
-                } else {
-                    $color = 'black';
-                    //echo '<span style="font-weight: bold; color: #FF0000;">'.nl2br(Text::make_clickable($answerComment)).'</span>';
-                }
-                echo '<span style="font-weight: bold; color: '.$color.';">'.nl2br(Text::make_clickable($answerComment)).'</span>';
-
-            } else {
-                if ($answerCorrect) {
-                    //echo '<span style="font-weight: bold; color: #000;">'.nl2br(Text::make_clickable($answerComment)).'</span>';
-                } else {
-                    //echo '<span style="font-weight: normal; color: #000;">'.nl2br(Text::make_clickable($answerComment)).'</span>';
-                }
-            }
-            ?>
-        </td>
-        <?php
-        if ($ans==1) {
-            $comm = get_comments($id,$questionId);
-        }
-        ?>
-        <?php } else { ?>
-        <td>&nbsp;</td>
-        <?php } ?>
-    </tr>
-        <?php
-    }
-
     /**
      * Display the answers to a multiple choice question
      *
@@ -317,8 +248,7 @@ class ExerciseShowFunctions {
      * @param boolean Whether to show the answer comment or not
      * @return void
      */
-    static function display_multiple_answer_true_false($answerType, $studentChoice, $answer, $answerComment, $answerCorrect, $id, $questionId, $ans) {
-        global $feedback_type;
+    static function display_multiple_answer_true_false($feedback_type, $answerType, $studentChoice, $answer, $answerComment, $answerCorrect, $id, $questionId, $ans) {
         ?>
         <tr>
         <td width="5%">
@@ -344,6 +274,7 @@ class ExerciseShowFunctions {
         } else {
             echo '-';
         }
+
         ?>
         </td>
         <td width="40%">
@@ -358,7 +289,7 @@ class ExerciseShowFunctions {
                 if ($studentChoice == $answerCorrect) {
                     $color = "green";
                 }
-                echo '<span style="font-weight: bold; color: '.$color.';">'.nl2br(Text::make_clickable($answerComment)).'</span>';
+                echo '<span style="font-weight: bold; color: '.$color.';">'.nl2br(make_clickable($answerComment)).'</span>';
             }
             ?>
         </td>
@@ -387,8 +318,7 @@ class ExerciseShowFunctions {
      * @param boolean Whether to show the answer comment or not
      * @return void
      */
-    static function display_multiple_answer_combination_true_false($answerType, $studentChoice, $answer, $answerComment, $answerCorrect, $id, $questionId, $ans) {
-        global $feedback_type;
+    static function display_multiple_answer_combination_true_false($feedback_type, $answerType, $studentChoice, $answer, $answerComment, $answerCorrect, $id, $questionId, $ans) {
         ?>
         <tr>
         <td width="5%">
@@ -428,15 +358,15 @@ class ExerciseShowFunctions {
                 if ($studentChoice == $answerCorrect) {
                     $color = "green";
                 }
-                echo '<span style="font-weight: bold; color: '.$color.';">'.nl2br(Text::make_clickable($answerComment)).'</span>';
+                echo '<span style="font-weight: bold; color: '.$color.';">'.nl2br(make_clickable($answerComment)).'</span>';
             }
             if ($studentChoice == 2 || $studentChoice == '') {
-            	//echo '<span style="font-weight: bold; color: #000;">'.nl2br(Text::make_clickable($answerComment)).'</span>';
+            	//echo '<span style="font-weight: bold; color: #000;">'.nl2br(make_clickable($answerComment)).'</span>';
             } else {
 				if ($studentChoice == $answerCorrect) {
-	            	//echo '<span style="font-weight: bold; color: #008000;">'.nl2br(Text::make_clickable($answerComment)).'</span>';
+	            	//echo '<span style="font-weight: bold; color: #008000;">'.nl2br(make_clickable($answerComment)).'</span>';
 				} else {
-                    //echo '<span style="font-weight: bold; color: #FF0000;">'.nl2br(Text::make_clickable($answerComment)).'</span>';
+                    //echo '<span style="font-weight: bold; color: #FF0000;">'.nl2br(make_clickable($answerComment)).'</span>';
 				}
             }
             ?>
@@ -452,4 +382,4 @@ class ExerciseShowFunctions {
         </tr>
         <?php
     }
-}
+}

+ 2 - 0
main/inc/lib/formvalidator/FormValidator.class.php

@@ -140,6 +140,8 @@ class FormValidator extends HTML_QuickForm
         $this->registerRule('CAPTCHA', 'rule', 'HTML_QuickForm_Rule_CAPTCHA', 'HTML/QuickForm/Rule/CAPTCHA.php');
 
 
+        $this->registerRule('CAPTCHA', 'rule', 'HTML_QuickForm_Rule_CAPTCHA', 'HTML/QuickForm/Rule/CAPTCHA.php');
+
         // Modify the default templates
         $renderer = & $this->defaultRenderer();
 

+ 7 - 2
main/inc/lib/group_portal_manager.lib.php

@@ -354,7 +354,10 @@ class GroupPortalManager
 		$sql = "SELECT DISTINCT count(user_id) as count, g.picture_uri, g.name, g.description, g.id
 				FROM $tbl_group g
 				INNER JOIN $table_group_rel_user gu
-				ON gu.group_id = g.id $where_relation_condition GROUP BY g.id ORDER BY count DESC LIMIT $num";
+				ON gu.group_id = g.id $where_relation_condition
+				GROUP BY g.id
+				ORDER BY count DESC
+				LIMIT $num";
 
 		$result=Database::query($sql);
 		$array = array();
@@ -391,7 +394,9 @@ class GroupPortalManager
 		$sql = "SELECT DISTINCT count(user_id) as count, g.picture_uri, g.name, g.description, g.id
 					 FROM $tbl_group g INNER JOIN $table_group_rel_user gu ON gu.group_id = g.id
 					 $where_relation_condition
-					 ORDER BY created_on desc LIMIT $num ";
+					 GROUP BY g.id
+					 ORDER BY created_on DESC
+					 LIMIT $num ";
 
 		$result=Database::query($sql);
 		$array = array();

+ 4 - 0
main/inc/lib/groupmanager.lib.php

@@ -851,6 +851,10 @@ class GroupManager
         return $users;
     }
 
+    /**
+     * @param int $group_id
+     * @return array
+     */
     public static function get_members_and_tutors($group_id)
     {
         $group_user_table = Database :: get_course_table(TABLE_GROUP_USER);

+ 316 - 313
main/inc/lib/javascript/jqgrid/js/jquery.jqGrid.min.js

@@ -1,173 +1,175 @@
 /* 
-* jqGrid  4.5.0 - jQuery Grid 
+* jqGrid  4.5.2 - jQuery Grid 
 * Copyright (c) 2008, Tony Tomov, tony@trirand.com 
 * Dual licensed under the MIT and GPL licenses 
 * http://www.opensource.org/licenses/mit-license.php 
 * http://www.gnu.org/licenses/gpl-2.0.html 
-* Date:2013-05-13 
+* Date:2013-05-21 
 * Modules: grid.base.js; jquery.fmatter.js; grid.custom.js; grid.common.js; grid.formedit.js; grid.filter.js; grid.inlinedit.js; grid.celledit.js; jqModal.js; jqDnR.js; grid.subgrid.js; grid.grouping.js; grid.treegrid.js; grid.import.js; JsonXml.js; grid.tbltogrid.js; grid.jqueryui.js; 
 */
-(function(b){b.jgrid=b.jgrid||{};b.extend(b.jgrid,{version:"4.5.0",htmlDecode:function(b){return b&&("&nbsp;"===b||"&#160;"===b||1===b.length&&160===b.charCodeAt(0))?"":!b?b:(""+b).replace(/&gt;/g,">").replace(/&lt;/g,"<").replace(/&quot;/g,'"').replace(/&amp;/g,"&")},htmlEncode:function(b){return!b?b:(""+b).replace(/&/g,"&amp;").replace(/\"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")},format:function(d){var g=b.makeArray(arguments).slice(1);null==d&&(d="");return d.replace(/\{(\d+)\}/g,
-function(b,e){return g[e]})},msie:"Microsoft Internet Explorer"==navigator.appName,msiever:function(){var b=-1;null!=/MSIE ([0-9]{1,}[.0-9]{0,})/.exec(navigator.userAgent)&&(b=parseFloat(RegExp.$1));return b},getCellIndex:function(d){d=b(d);if(d.is("tr"))return-1;d=(!d.is("td")&&!d.is("th")?d.closest("td,th"):d)[0];return b.jgrid.msie?b.inArray(d,d.parentNode.cells):d.cellIndex},stripHtml:function(b){var b=""+b,g=/<("[^"]*"|'[^']*'|[^'">])*>/gi;return b?(b=b.replace(g,""))&&"&nbsp;"!==b&&"&#160;"!==
-b?b.replace(/\"/g,"'"):"":b},stripPref:function(d,g){var c=b.type(d);if("string"===c||"number"===c)d=""+d,g=""!==d?(""+g).replace(""+d,""):g;return g},parse:function(d){"while(1);"===d.substr(0,9)&&(d=d.substr(9));"/*"===d.substr(0,2)&&(d=d.substr(2,d.length-4));d||(d="{}");return!0===b.jgrid.useJSON&&"object"===typeof JSON&&"function"===typeof JSON.parse?JSON.parse(d):eval("("+d+")")},parseDate:function(d,g,c,e){var a=/^\/Date\((([-+])?[0-9]+)(([-+])([0-9]{2})([0-9]{2}))?\)\/$/,j="string"===typeof g?
-g.match(a):null,a=function(a,b){a=""+a;for(b=parseInt(b,10)||2;a.length<b;)a="0"+a;return a},f={m:1,d:1,y:1970,h:0,i:0,s:0,u:0},h=0,i,k,h=function(a,b){0===a?12===b&&(b=0):12!==b&&(b+=12);return b};void 0===e&&(e=b.jgrid.formatter.date);void 0===e.parseRe&&(e.parseRe=/[Tt\\\/:_;.,\t\s-]/);e.masks.hasOwnProperty(d)&&(d=e.masks[d]);if(g&&null!=g)if(!isNaN(g-0)&&"u"===(""+d).toLowerCase())h=new Date(1E3*parseFloat(g));else if(g.constructor===Date)h=g;else if(null!==j)h=new Date(parseInt(j[1],10)),j[3]&&
-(d=60*Number(j[5])+Number(j[6]),d*="-"===j[4]?1:-1,d-=h.getTimezoneOffset(),h.setTime(Number(Number(h)+6E4*d)));else{g=(""+g).replace(/\\T/g,"T").replace(/\\t/,"t").split(e.parseRe);d=d.replace(/\\T/g,"T").replace(/\\t/,"t").split(e.parseRe);i=0;for(k=d.length;i<k;i++)"M"===d[i]&&(j=b.inArray(g[i],e.monthNames),-1!==j&&12>j&&(g[i]=j+1,f.m=g[i])),"F"===d[i]&&(j=b.inArray(g[i],e.monthNames),-1!==j&&11<j&&(g[i]=j+1-12,f.m=g[i])),"a"===d[i]&&(j=b.inArray(g[i],e.AmPm),-1!==j&&2>j&&g[i]===e.AmPm[j]&&(g[i]=
-j,f.h=h(g[i],f.h))),"A"===d[i]&&(j=b.inArray(g[i],e.AmPm),-1!==j&&1<j&&g[i]===e.AmPm[j]&&(g[i]=j-2,f.h=h(g[i],f.h))),"g"===d[i]&&(f.h=parseInt(g[i],10)),void 0!==g[i]&&(f[d[i].toLowerCase()]=parseInt(g[i],10));f.f&&(f.m=f.f);if(0===f.m&&0===f.y&&0===f.d)return"&#160;";f.m=parseInt(f.m,10)-1;h=f.y;70<=h&&99>=h?f.y=1900+f.y:0<=h&&69>=h&&(f.y=2E3+f.y);h=new Date(f.y,f.m,f.d,f.h,f.i,f.s,f.u)}else h=new Date(f.y,f.m,f.d,f.h,f.i,f.s,f.u);if(void 0===c)return h;e.masks.hasOwnProperty(c)?c=e.masks[c]:c||
-(c="Y-m-d");d=h.getHours();g=h.getMinutes();f=h.getDate();j=h.getMonth()+1;i=h.getTimezoneOffset();k=h.getSeconds();var m=h.getMilliseconds(),n=h.getDay(),p=h.getFullYear(),l=(n+6)%7+1,o=(new Date(p,j-1,f)-new Date(p,0,1))/864E5,B={d:a(f),D:e.dayNames[n],j:f,l:e.dayNames[n+7],N:l,S:e.S(f),w:n,z:o,W:5>l?Math.floor((o+l-1)/7)+1:Math.floor((o+l-1)/7)||(4>((new Date(p-1,0,1)).getDay()+6)%7?53:52),F:e.monthNames[j-1+12],m:a(j),M:e.monthNames[j-1],n:j,t:"?",L:"?",o:"?",Y:p,y:(""+p).substring(2),a:12>d?
-e.AmPm[0]:e.AmPm[1],A:12>d?e.AmPm[2]:e.AmPm[3],B:"?",g:d%12||12,G:d,h:a(d%12||12),H:a(d),i:a(g),s:a(k),u:m,e:"?",I:"?",O:(0<i?"-":"+")+a(100*Math.floor(Math.abs(i)/60)+Math.abs(i)%60,4),P:"?",T:((""+h).match(/\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g)||[""]).pop().replace(/[^-+\dA-Z]/g,""),Z:"?",c:"?",r:"?",U:Math.floor(h/1E3)};return c.replace(/\\.|[dDjlNSwzWFmMntLoYyaABgGhHisueIOPTZcrU]/g,function(a){return B.hasOwnProperty(a)?
-B[a]:a.substring(1)})},jqID:function(b){return(""+b).replace(/[!"#$%&'()*+,.\/:; <=>?@\[\\\]\^`{|}~]/g,"\\$&")},guid:1,uidPref:"jqg",randId:function(d){return(d||b.jgrid.uidPref)+b.jgrid.guid++},getAccessor:function(b,g){var c,e,a=[],j;if("function"===typeof g)return g(b);c=b[g];if(void 0===c)try{if("string"===typeof g&&(a=g.split(".")),j=a.length)for(c=b;c&&j--;)e=a.shift(),c=c[e]}catch(f){}return c},getXmlData:function(d,g,c){var e="string"===typeof g?g.match(/^(.*)\[(\w+)\]$/):null;if("function"===
-typeof g)return g(d);if(e&&e[2])return e[1]?b(e[1],d).attr(e[2]):b(d).attr(e[2]);d=b(g,d);return c?d:0<d.length?b(d).text():void 0},cellWidth:function(){var d=b("<div class='ui-jqgrid' style='left:10000px'><table class='ui-jqgrid-btable' style='width:5px;'><tr class='jqgrow'><td style='width:5px;'></td></tr></table></div>"),g=d.appendTo("body").find("td").width();d.remove();return 5!==g},cell_width:!0,ajaxOptions:{},from:function(d){return new function(d,c){"string"===typeof d&&(d=b.data(d));var e=
-this,a=d,j=!0,f=!1,h=c,i=/[\$,%]/g,k=null,m=null,n=0,p=!1,l="",o=[],B=!0;if("object"===typeof d&&d.push)0<d.length&&(B="object"!==typeof d[0]?!1:!0);else throw"data provides is not an array";this._hasData=function(){return null===a?!1:0===a.length?!1:!0};this._getStr=function(a){var b=[];f&&b.push("jQuery.trim(");b.push("String("+a+")");f&&b.push(")");j||b.push(".toLowerCase()");return b.join("")};this._strComp=function(a){return"string"===typeof a?".toString()":""};this._group=function(a,b){return{field:a.toString(),
-unique:b,items:[]}};this._toStr=function(a){f&&(a=b.trim(a));a=a.toString().replace(/\\/g,"\\\\").replace(/\"/g,'\\"');return j?a:a.toLowerCase()};this._funcLoop=function(e){var d=[];b.each(a,function(a,b){d.push(e(b))});return d};this._append=function(a){var b;h=null===h?"":h+(""===l?" && ":l);for(b=0;b<n;b++)h+="(";p&&(h+="!");h+="("+a+")";p=!1;l="";n=0};this._setCommand=function(a,b){k=a;m=b};this._resetNegate=function(){p=!1};this._repeatCommand=function(a,b){return null===k?e:null!==a&&null!==
-b?k(a,b):null===m||!B?k(a):k(m,a)};this._equals=function(a,b){return 0===e._compare(a,b,1)};this._compare=function(a,b,e){var d=Object.prototype.toString;void 0===e&&(e=1);void 0===a&&(a=null);void 0===b&&(b=null);if(null===a&&null===b)return 0;if(null===a&&null!==b)return 1;if(null!==a&&null===b)return-1;if("[object Date]"===d.call(a)&&"[object Date]"===d.call(b))return a<b?-e:a>b?e:0;!j&&"number"!==typeof a&&"number"!==typeof b&&(a=""+a,b=""+b);return a<b?-e:a>b?e:0};this._performSort=function(){0!==
-o.length&&(a=e._doSort(a,0))};this._doSort=function(a,b){var d=o[b].by,f=o[b].dir,j=o[b].type,c=o[b].datefmt;if(b===o.length-1)return e._getOrder(a,d,f,j,c);b++;for(var d=e._getGroup(a,d,f,j,c),f=[],g,j=0;j<d.length;j++){g=e._doSort(d[j].items,b);for(c=0;c<g.length;c++)f.push(g[c])}return f};this._getOrder=function(a,d,f,c,g){var h=[],k=[],m="a"===f?1:-1,n,p;void 0===c&&(c="text");p="float"===c||"number"===c||"currency"===c||"numeric"===c?function(a){a=parseFloat((""+a).replace(i,""));return isNaN(a)?
-0:a}:"int"===c||"integer"===c?function(a){return a?parseFloat((""+a).replace(i,"")):0}:"date"===c||"datetime"===c?function(a){return b.jgrid.parseDate(g,a).getTime()}:b.isFunction(c)?c:function(a){a=a?b.trim(""+a):"";return j?a:a.toLowerCase()};b.each(a,function(a,e){n=""!==d?b.jgrid.getAccessor(e,d):e;void 0===n&&(n="");n=p(n,e);k.push({vSort:n,index:a})});k.sort(function(a,b){a=a.vSort;b=b.vSort;return e._compare(a,b,m)});for(var c=0,l=a.length;c<l;)f=k[c].index,h.push(a[f]),c++;return h};this._getGroup=
-function(a,d,f,j,c){var g=[],h=null,i=null,k;b.each(e._getOrder(a,d,f,j,c),function(a,f){k=b.jgrid.getAccessor(f,d);null==k&&(k="");e._equals(i,k)||(i=k,null!==h&&g.push(h),h=e._group(d,k));h.items.push(f)});null!==h&&g.push(h);return g};this.ignoreCase=function(){j=!1;return e};this.useCase=function(){j=!0;return e};this.trim=function(){f=!0;return e};this.noTrim=function(){f=!1;return e};this.execute=function(){var d=h,f=[];if(null===d)return e;b.each(a,function(){eval(d)&&f.push(this)});a=f;return e};
-this.data=function(){return a};this.select=function(d){e._performSort();if(!e._hasData())return[];e.execute();if(b.isFunction(d)){var f=[];b.each(a,function(a,b){f.push(d(b))});return f}return a};this.hasMatch=function(){if(!e._hasData())return!1;e.execute();return 0<a.length};this.andNot=function(a,b,d){p=!p;return e.and(a,b,d)};this.orNot=function(a,b,d){p=!p;return e.or(a,b,d)};this.not=function(a,b,d){return e.andNot(a,b,d)};this.and=function(a,b,d){l=" && ";return void 0===a?e:e._repeatCommand(a,
-b,d)};this.or=function(a,b,d){l=" || ";return void 0===a?e:e._repeatCommand(a,b,d)};this.orBegin=function(){n++;return e};this.orEnd=function(){null!==h&&(h+=")");return e};this.isNot=function(a){p=!p;return e.is(a)};this.is=function(a){e._append("this."+a);e._resetNegate();return e};this._compareValues=function(a,d,f,j,c){var g;g=B?"jQuery.jgrid.getAccessor(this,'"+d+"')":"this";void 0===f&&(f=null);var h=f,k=void 0===c.stype?"text":c.stype;if(null!==f)switch(k){case "int":case "integer":h=isNaN(Number(h))||
-""===h?"0":h;g="parseInt("+g+",10)";h="parseInt("+h+",10)";break;case "float":case "number":case "numeric":h=(""+h).replace(i,"");h=isNaN(Number(h))||""===h?"0":h;g="parseFloat("+g+")";h="parseFloat("+h+")";break;case "date":case "datetime":h=""+b.jgrid.parseDate(c.newfmt||"Y-m-d",h).getTime();g='jQuery.jgrid.parseDate("'+c.srcfmt+'",'+g+").getTime()";break;default:g=e._getStr(g),h=e._getStr('"'+e._toStr(h)+'"')}e._append(g+" "+j+" "+h);e._setCommand(a,d);e._resetNegate();return e};this.equals=function(a,
+
+(function(b){b.jgrid=b.jgrid||{};b.extend(b.jgrid,{version:"4.5.2",htmlDecode:function(b){return b&&("&nbsp;"===b||"&#160;"===b||1===b.length&&160===b.charCodeAt(0))?"":!b?b:(""+b).replace(/&gt;/g,">").replace(/&lt;/g,"<").replace(/&quot;/g,'"').replace(/&amp;/g,"&")},htmlEncode:function(b){return!b?b:(""+b).replace(/&/g,"&amp;").replace(/\"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")},format:function(d){var f=b.makeArray(arguments).slice(1);null==d&&(d="");return d.replace(/\{(\d+)\}/g,
+function(b,e){return f[e]})},msie:"Microsoft Internet Explorer"===navigator.appName,msiever:function(){var b=-1;null!=/MSIE ([0-9]{1,}[.0-9]{0,})/.exec(navigator.userAgent)&&(b=parseFloat(RegExp.$1));return b},getCellIndex:function(d){d=b(d);if(d.is("tr"))return-1;d=(!d.is("td")&&!d.is("th")?d.closest("td,th"):d)[0];return b.jgrid.msie?b.inArray(d,d.parentNode.cells):d.cellIndex},stripHtml:function(b){var b=""+b,f=/<("[^"]*"|'[^']*'|[^'">])*>/gi;return b?(b=b.replace(f,""))&&"&nbsp;"!==b&&"&#160;"!==
+b?b.replace(/\"/g,"'"):"":b},stripPref:function(d,f){var c=b.type(d);if("string"===c||"number"===c)d=""+d,f=""!==d?(""+f).replace(""+d,""):f;return f},parse:function(d){"while(1);"===d.substr(0,9)&&(d=d.substr(9));"/*"===d.substr(0,2)&&(d=d.substr(2,d.length-4));d||(d="{}");return!0===b.jgrid.useJSON&&"object"===typeof JSON&&"function"===typeof JSON.parse?JSON.parse(d):eval("("+d+")")},parseDate:function(d,f,c,e){var a=/^\/Date\((([-+])?[0-9]+)(([-+])([0-9]{2})([0-9]{2}))?\)\/$/,j="string"===typeof f?
+f.match(a):null,a=function(a,b){a=""+a;for(b=parseInt(b,10)||2;a.length<b;)a="0"+a;return a},g={m:1,d:1,y:1970,h:0,i:0,s:0,u:0},h=0,i,k,h=function(a,b){0===a?12===b&&(b=0):12!==b&&(b+=12);return b};void 0===e&&(e=b.jgrid.formatter.date);void 0===e.parseRe&&(e.parseRe=/[Tt\\\/:_;.,\t\s-]/);e.masks.hasOwnProperty(d)&&(d=e.masks[d]);if(f&&null!=f)if(!isNaN(f-0)&&"u"===(""+d).toLowerCase())h=new Date(1E3*parseFloat(f));else if(f.constructor===Date)h=f;else if(null!==j)h=new Date(parseInt(j[1],10)),j[3]&&
+(d=60*Number(j[5])+Number(j[6]),d*="-"===j[4]?1:-1,d-=h.getTimezoneOffset(),h.setTime(Number(Number(h)+6E4*d)));else{f=(""+f).replace(/\\T/g,"T").replace(/\\t/,"t").split(e.parseRe);d=d.replace(/\\T/g,"T").replace(/\\t/,"t").split(e.parseRe);i=0;for(k=d.length;i<k;i++)"M"===d[i]&&(j=b.inArray(f[i],e.monthNames),-1!==j&&12>j&&(f[i]=j+1,g.m=f[i])),"F"===d[i]&&(j=b.inArray(f[i],e.monthNames,12),-1!==j&&11<j&&(f[i]=j+1-12,g.m=f[i])),"a"===d[i]&&(j=b.inArray(f[i],e.AmPm),-1!==j&&2>j&&f[i]===e.AmPm[j]&&
+(f[i]=j,g.h=h(f[i],g.h))),"A"===d[i]&&(j=b.inArray(f[i],e.AmPm),-1!==j&&1<j&&f[i]===e.AmPm[j]&&(f[i]=j-2,g.h=h(f[i],g.h))),"g"===d[i]&&(g.h=parseInt(f[i],10)),void 0!==f[i]&&(g[d[i].toLowerCase()]=parseInt(f[i],10));g.f&&(g.m=g.f);if(0===g.m&&0===g.y&&0===g.d)return"&#160;";g.m=parseInt(g.m,10)-1;h=g.y;70<=h&&99>=h?g.y=1900+g.y:0<=h&&69>=h&&(g.y=2E3+g.y);h=new Date(g.y,g.m,g.d,g.h,g.i,g.s,g.u)}else h=new Date(g.y,g.m,g.d,g.h,g.i,g.s,g.u);if(void 0===c)return h;e.masks.hasOwnProperty(c)?c=e.masks[c]:
+c||(c="Y-m-d");d=h.getHours();f=h.getMinutes();g=h.getDate();j=h.getMonth()+1;i=h.getTimezoneOffset();k=h.getSeconds();var l=h.getMilliseconds(),o=h.getDay(),n=h.getFullYear(),m=(o+6)%7+1,t=(new Date(n,j-1,g)-new Date(n,0,1))/864E5,A={d:a(g),D:e.dayNames[o],j:g,l:e.dayNames[o+7],N:m,S:e.S(g),w:o,z:t,W:5>m?Math.floor((t+m-1)/7)+1:Math.floor((t+m-1)/7)||(4>((new Date(n-1,0,1)).getDay()+6)%7?53:52),F:e.monthNames[j-1+12],m:a(j),M:e.monthNames[j-1],n:j,t:"?",L:"?",o:"?",Y:n,y:(""+n).substring(2),a:12>
+d?e.AmPm[0]:e.AmPm[1],A:12>d?e.AmPm[2]:e.AmPm[3],B:"?",g:d%12||12,G:d,h:a(d%12||12),H:a(d),i:a(f),s:a(k),u:l,e:"?",I:"?",O:(0<i?"-":"+")+a(100*Math.floor(Math.abs(i)/60)+Math.abs(i)%60,4),P:"?",T:((""+h).match(/\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g)||[""]).pop().replace(/[^-+\dA-Z]/g,""),Z:"?",c:"?",r:"?",U:Math.floor(h/1E3)};return c.replace(/\\.|[dDjlNSwzWFmMntLoYyaABgGhHisueIOPTZcrU]/g,function(a){return A.hasOwnProperty(a)?
+A[a]:a.substring(1)})},jqID:function(b){return(""+b).replace(/[!"#$%&'()*+,.\/:; <=>?@\[\\\]\^`{|}~]/g,"\\$&")},guid:1,uidPref:"jqg",randId:function(d){return(d||b.jgrid.uidPref)+b.jgrid.guid++},getAccessor:function(b,f){var c,e,a=[],j;if("function"===typeof f)return f(b);c=b[f];if(void 0===c)try{if("string"===typeof f&&(a=f.split(".")),j=a.length)for(c=b;c&&j--;)e=a.shift(),c=c[e]}catch(g){}return c},getXmlData:function(d,f,c){var e="string"===typeof f?f.match(/^(.*)\[(\w+)\]$/):null;if("function"===
+typeof f)return f(d);if(e&&e[2])return e[1]?b(e[1],d).attr(e[2]):b(d).attr(e[2]);d=b(f,d);return c?d:0<d.length?b(d).text():void 0},cellWidth:function(){var d=b("<div class='ui-jqgrid' style='left:10000px'><table class='ui-jqgrid-btable' style='width:5px;'><tr class='jqgrow'><td style='width:5px;'></td></tr></table></div>"),f=d.appendTo("body").find("td").width();d.remove();return 5!==f},cell_width:!0,ajaxOptions:{},from:function(d){return new function(d,c){"string"===typeof d&&(d=b.data(d));var e=
+this,a=d,j=!0,g=!1,h=c,i=/[\$,%]/g,k=null,l=null,o=0,n=!1,m="",t=[],A=!0;if("object"===typeof d&&d.push)0<d.length&&(A="object"!==typeof d[0]?!1:!0);else throw"data provides is not an array";this._hasData=function(){return null===a?!1:0===a.length?!1:!0};this._getStr=function(a){var b=[];g&&b.push("jQuery.trim(");b.push("String("+a+")");g&&b.push(")");j||b.push(".toLowerCase()");return b.join("")};this._strComp=function(a){return"string"===typeof a?".toString()":""};this._group=function(a,b){return{field:a.toString(),
+unique:b,items:[]}};this._toStr=function(a){g&&(a=b.trim(a));a=a.toString().replace(/\\/g,"\\\\").replace(/\"/g,'\\"');return j?a:a.toLowerCase()};this._funcLoop=function(e){var d=[];b.each(a,function(a,b){d.push(e(b))});return d};this._append=function(a){var b;h=null===h?"":h+(""===m?" && ":m);for(b=0;b<o;b++)h+="(";n&&(h+="!");h+="("+a+")";n=!1;m="";o=0};this._setCommand=function(a,b){k=a;l=b};this._resetNegate=function(){n=!1};this._repeatCommand=function(a,b){return null===k?e:null!==a&&null!==
+b?k(a,b):null===l||!A?k(a):k(l,a)};this._equals=function(a,b){return 0===e._compare(a,b,1)};this._compare=function(a,b,e){var d=Object.prototype.toString;void 0===e&&(e=1);void 0===a&&(a=null);void 0===b&&(b=null);if(null===a&&null===b)return 0;if(null===a&&null!==b)return 1;if(null!==a&&null===b)return-1;if("[object Date]"===d.call(a)&&"[object Date]"===d.call(b))return a<b?-e:a>b?e:0;!j&&"number"!==typeof a&&"number"!==typeof b&&(a=""+a,b=""+b);return a<b?-e:a>b?e:0};this._performSort=function(){0!==
+t.length&&(a=e._doSort(a,0))};this._doSort=function(a,b){var d=t[b].by,g=t[b].dir,j=t[b].type,c=t[b].datefmt;if(b===t.length-1)return e._getOrder(a,d,g,j,c);b++;for(var d=e._getGroup(a,d,g,j,c),g=[],f,j=0;j<d.length;j++){f=e._doSort(d[j].items,b);for(c=0;c<f.length;c++)g.push(f[c])}return g};this._getOrder=function(a,d,g,c,f){var h=[],k=[],l="a"===g?1:-1,o,n;void 0===c&&(c="text");n="float"===c||"number"===c||"currency"===c||"numeric"===c?function(a){a=parseFloat((""+a).replace(i,""));return isNaN(a)?
+0:a}:"int"===c||"integer"===c?function(a){return a?parseFloat((""+a).replace(i,"")):0}:"date"===c||"datetime"===c?function(a){return b.jgrid.parseDate(f,a).getTime()}:b.isFunction(c)?c:function(a){a=a?b.trim(""+a):"";return j?a:a.toLowerCase()};b.each(a,function(a,e){o=""!==d?b.jgrid.getAccessor(e,d):e;void 0===o&&(o="");o=n(o,e);k.push({vSort:o,index:a})});k.sort(function(a,b){a=a.vSort;b=b.vSort;return e._compare(a,b,l)});for(var c=0,m=a.length;c<m;)g=k[c].index,h.push(a[g]),c++;return h};this._getGroup=
+function(a,d,g,j,c){var f=[],h=null,i=null,k;b.each(e._getOrder(a,d,g,j,c),function(a,g){k=b.jgrid.getAccessor(g,d);null==k&&(k="");e._equals(i,k)||(i=k,null!==h&&f.push(h),h=e._group(d,k));h.items.push(g)});null!==h&&f.push(h);return f};this.ignoreCase=function(){j=!1;return e};this.useCase=function(){j=!0;return e};this.trim=function(){g=!0;return e};this.noTrim=function(){g=!1;return e};this.execute=function(){var d=h,g=[];if(null===d)return e;b.each(a,function(){eval(d)&&g.push(this)});a=g;return e};
+this.data=function(){return a};this.select=function(d){e._performSort();if(!e._hasData())return[];e.execute();if(b.isFunction(d)){var g=[];b.each(a,function(a,b){g.push(d(b))});return g}return a};this.hasMatch=function(){if(!e._hasData())return!1;e.execute();return 0<a.length};this.andNot=function(a,b,d){n=!n;return e.and(a,b,d)};this.orNot=function(a,b,d){n=!n;return e.or(a,b,d)};this.not=function(a,b,d){return e.andNot(a,b,d)};this.and=function(a,b,d){m=" && ";return void 0===a?e:e._repeatCommand(a,
+b,d)};this.or=function(a,b,d){m=" || ";return void 0===a?e:e._repeatCommand(a,b,d)};this.orBegin=function(){o++;return e};this.orEnd=function(){null!==h&&(h+=")");return e};this.isNot=function(a){n=!n;return e.is(a)};this.is=function(a){e._append("this."+a);e._resetNegate();return e};this._compareValues=function(a,d,g,j,c){var f;f=A?"jQuery.jgrid.getAccessor(this,'"+d+"')":"this";void 0===g&&(g=null);var h=g,k=void 0===c.stype?"text":c.stype;if(null!==g)switch(k){case "int":case "integer":h=isNaN(Number(h))||
+""===h?"0":h;f="parseInt("+f+",10)";h="parseInt("+h+",10)";break;case "float":case "number":case "numeric":h=(""+h).replace(i,"");h=isNaN(Number(h))||""===h?"0":h;f="parseFloat("+f+")";h="parseFloat("+h+")";break;case "date":case "datetime":h=""+b.jgrid.parseDate(c.newfmt||"Y-m-d",h).getTime();f='jQuery.jgrid.parseDate("'+c.srcfmt+'",'+f+").getTime()";break;default:f=e._getStr(f),h=e._getStr('"'+e._toStr(h)+'"')}e._append(f+" "+j+" "+h);e._setCommand(a,d);e._resetNegate();return e};this.equals=function(a,
 b,d){return e._compareValues(e.equals,a,b,"==",d)};this.notEquals=function(a,b,d){return e._compareValues(e.equals,a,b,"!==",d)};this.isNull=function(a,b,d){return e._compareValues(e.equals,a,null,"===",d)};this.greater=function(a,b,d){return e._compareValues(e.greater,a,b,">",d)};this.less=function(a,b,d){return e._compareValues(e.less,a,b,"<",d)};this.greaterOrEquals=function(a,b,d){return e._compareValues(e.greaterOrEquals,a,b,">=",d)};this.lessOrEquals=function(a,b,d){return e._compareValues(e.lessOrEquals,
-a,b,"<=",d)};this.startsWith=function(a,d){var c=null==d?a:d,c=f?b.trim(c.toString()).length:c.toString().length;B?e._append(e._getStr("jQuery.jgrid.getAccessor(this,'"+a+"')")+".substr(0,"+c+") == "+e._getStr('"'+e._toStr(d)+'"')):(c=f?b.trim(d.toString()).length:d.toString().length,e._append(e._getStr("this")+".substr(0,"+c+") == "+e._getStr('"'+e._toStr(a)+'"')));e._setCommand(e.startsWith,a);e._resetNegate();return e};this.endsWith=function(a,d){var c=null==d?a:d,c=f?b.trim(c.toString()).length:
-c.toString().length;B?e._append(e._getStr("jQuery.jgrid.getAccessor(this,'"+a+"')")+".substr("+e._getStr("jQuery.jgrid.getAccessor(this,'"+a+"')")+".length-"+c+","+c+') == "'+e._toStr(d)+'"'):e._append(e._getStr("this")+".substr("+e._getStr("this")+'.length-"'+e._toStr(a)+'".length,"'+e._toStr(a)+'".length) == "'+e._toStr(a)+'"');e._setCommand(e.endsWith,a);e._resetNegate();return e};this.contains=function(a,b){B?e._append(e._getStr("jQuery.jgrid.getAccessor(this,'"+a+"')")+'.indexOf("'+e._toStr(b)+
-'",0) > -1'):e._append(e._getStr("this")+'.indexOf("'+e._toStr(a)+'",0) > -1');e._setCommand(e.contains,a);e._resetNegate();return e};this.groupBy=function(b,d,f,c){return!e._hasData()?null:e._getGroup(a,b,d,f,c)};this.orderBy=function(a,d,f,c){d=null==d?"a":b.trim(d.toString().toLowerCase());null==f&&(f="text");null==c&&(c="Y-m-d");if("desc"===d||"descending"===d)d="d";if("asc"===d||"ascending"===d)d="a";o.push({by:a,dir:d,type:f,datefmt:c});return e};return e}(d,null)},getMethod:function(d){return this.getAccessor(b.fn.jqGrid,
-d)},extend:function(d){b.extend(b.fn.jqGrid,d);this.no_legacy_api||b.fn.extend(d)}});b.fn.jqGrid=function(d){if("string"===typeof d){var g=b.jgrid.getMethod(d);if(!g)throw"jqGrid - No such method: "+d;var c=b.makeArray(arguments).slice(1);return g.apply(this,c)}return this.each(function(){if(!this.grid){var e=b.extend(!0,{url:"",height:150,page:1,rowNum:20,rowTotal:null,records:0,pager:"",pgbuttons:!0,pginput:!0,colModel:[],rowList:[],colNames:[],sortorder:"asc",sortname:"",datatype:"xml",mtype:"GET",
+a,b,"<=",d)};this.startsWith=function(a,d){var c=null==d?a:d,c=g?b.trim(c.toString()).length:c.toString().length;A?e._append(e._getStr("jQuery.jgrid.getAccessor(this,'"+a+"')")+".substr(0,"+c+") == "+e._getStr('"'+e._toStr(d)+'"')):(c=g?b.trim(d.toString()).length:d.toString().length,e._append(e._getStr("this")+".substr(0,"+c+") == "+e._getStr('"'+e._toStr(a)+'"')));e._setCommand(e.startsWith,a);e._resetNegate();return e};this.endsWith=function(a,d){var c=null==d?a:d,c=g?b.trim(c.toString()).length:
+c.toString().length;A?e._append(e._getStr("jQuery.jgrid.getAccessor(this,'"+a+"')")+".substr("+e._getStr("jQuery.jgrid.getAccessor(this,'"+a+"')")+".length-"+c+","+c+') == "'+e._toStr(d)+'"'):e._append(e._getStr("this")+".substr("+e._getStr("this")+'.length-"'+e._toStr(a)+'".length,"'+e._toStr(a)+'".length) == "'+e._toStr(a)+'"');e._setCommand(e.endsWith,a);e._resetNegate();return e};this.contains=function(a,b){A?e._append(e._getStr("jQuery.jgrid.getAccessor(this,'"+a+"')")+'.indexOf("'+e._toStr(b)+
+'",0) > -1'):e._append(e._getStr("this")+'.indexOf("'+e._toStr(a)+'",0) > -1');e._setCommand(e.contains,a);e._resetNegate();return e};this.groupBy=function(b,d,g,c){return!e._hasData()?null:e._getGroup(a,b,d,g,c)};this.orderBy=function(a,d,g,c){d=null==d?"a":b.trim(d.toString().toLowerCase());null==g&&(g="text");null==c&&(c="Y-m-d");if("desc"===d||"descending"===d)d="d";if("asc"===d||"ascending"===d)d="a";t.push({by:a,dir:d,type:g,datefmt:c});return e};return e}(d,null)},getMethod:function(d){return this.getAccessor(b.fn.jqGrid,
+d)},extend:function(d){b.extend(b.fn.jqGrid,d);this.no_legacy_api||b.fn.extend(d)}});b.fn.jqGrid=function(d){if("string"===typeof d){var f=b.jgrid.getMethod(d);if(!f)throw"jqGrid - No such method: "+d;var c=b.makeArray(arguments).slice(1);return f.apply(this,c)}return this.each(function(){if(!this.grid){var e=b.extend(!0,{url:"",height:150,page:1,rowNum:20,rowTotal:null,records:0,pager:"",pgbuttons:!0,pginput:!0,colModel:[],rowList:[],colNames:[],sortorder:"asc",sortname:"",datatype:"xml",mtype:"GET",
 altRows:!1,selarrrow:[],savedRow:[],shrinkToFit:!0,xmlReader:{},jsonReader:{},subGrid:!1,subGridModel:[],reccount:0,lastpage:0,lastsort:0,selrow:null,beforeSelectRow:null,onSelectRow:null,onSortCol:null,ondblClickRow:null,onRightClickRow:null,onPaging:null,onSelectAll:null,onInitGrid:null,loadComplete:null,gridComplete:null,loadError:null,loadBeforeSend:null,afterInsertRow:null,beforeRequest:null,beforeProcessing:null,onHeaderClick:null,viewrecords:!1,loadonce:!1,multiselect:!1,multikey:!1,editurl:null,
 search:!1,caption:"",hidegrid:!0,hiddengrid:!1,postData:{},userData:{},treeGrid:!1,treeGridModel:"nested",treeReader:{},treeANode:-1,ExpandColumn:null,tree_root_level:0,prmNames:{page:"page",rows:"rows",sort:"sidx",order:"sord",search:"_search",nd:"nd",id:"id",oper:"oper",editoper:"edit",addoper:"add",deloper:"del",subgridid:"id",npage:null,totalrows:"totalrows"},forceFit:!1,gridstate:"visible",cellEdit:!1,cellsubmit:"remote",nv:0,loadui:"enable",toolbar:[!1,""],scroll:!1,multiboxonly:!1,deselectAfterSort:!0,
 scrollrows:!1,autowidth:!1,scrollOffset:18,cellLayout:5,subGridWidth:20,multiselectWidth:20,gridview:!1,rownumWidth:25,rownumbers:!1,pagerpos:"center",recordpos:"right",footerrow:!1,userDataOnFooter:!1,hoverrows:!0,altclass:"ui-priority-secondary",viewsortcols:[!1,"vertical",!0],resizeclass:"",autoencode:!1,remapColumns:[],ajaxGridOptions:{},direction:"ltr",toppager:!1,headertitles:!1,scrollTimeout:40,data:[],_index:{},grouping:!1,groupingView:{groupField:[],groupOrder:[],groupText:[],groupColumnShow:[],
-groupSummary:[],showSummaryOnHide:!1,sortitems:[],sortnames:[],summary:[],summaryval:[],plusicon:"ui-icon-circlesmall-plus",minusicon:"ui-icon-circlesmall-minus",displayField:[]},ignoreCase:!1,cmTemplate:{},idPrefix:"",multiSort:!1},b.jgrid.defaults,d||{}),a=this,c={headers:[],cols:[],footers:[],dragStart:function(c,d,f){this.resizing={idx:c,startX:d.clientX,sOL:f[0]};this.hDiv.style.cursor="col-resize";this.curGbox=b("#rs_m"+b.jgrid.jqID(e.id),"#gbox_"+b.jgrid.jqID(e.id));this.curGbox.css({display:"block",
-left:f[0],top:f[1],height:f[2]});b(a).triggerHandler("jqGridResizeStart",[d,c]);b.isFunction(e.resizeStart)&&e.resizeStart.call(a,d,c);document.onselectstart=function(){return!1}},dragMove:function(a){if(this.resizing){var b=a.clientX-this.resizing.startX,a=this.headers[this.resizing.idx],c="ltr"===e.direction?a.width+b:a.width-b,d;33<c&&(this.curGbox.css({left:this.resizing.sOL+b}),!0===e.forceFit?(d=this.headers[this.resizing.idx+e.nv],b="ltr"===e.direction?d.width-b:d.width+b,33<b&&(a.newWidth=
+groupSummary:[],showSummaryOnHide:!1,sortitems:[],sortnames:[],summary:[],summaryval:[],plusicon:"ui-icon-circlesmall-plus",minusicon:"ui-icon-circlesmall-minus",displayField:[]},ignoreCase:!1,cmTemplate:{},idPrefix:"",multiSort:!1},b.jgrid.defaults,d||{}),a=this,c={headers:[],cols:[],footers:[],dragStart:function(c,d,g){this.resizing={idx:c,startX:d.clientX,sOL:g[0]};this.hDiv.style.cursor="col-resize";this.curGbox=b("#rs_m"+b.jgrid.jqID(e.id),"#gbox_"+b.jgrid.jqID(e.id));this.curGbox.css({display:"block",
+left:g[0],top:g[1],height:g[2]});b(a).triggerHandler("jqGridResizeStart",[d,c]);b.isFunction(e.resizeStart)&&e.resizeStart.call(a,d,c);document.onselectstart=function(){return!1}},dragMove:function(a){if(this.resizing){var b=a.clientX-this.resizing.startX,a=this.headers[this.resizing.idx],c="ltr"===e.direction?a.width+b:a.width-b,d;33<c&&(this.curGbox.css({left:this.resizing.sOL+b}),!0===e.forceFit?(d=this.headers[this.resizing.idx+e.nv],b="ltr"===e.direction?d.width-b:d.width+b,33<b&&(a.newWidth=
 c,d.newWidth=b)):(this.newWidth="ltr"===e.direction?e.tblwidth+b:e.tblwidth-b,a.newWidth=c))}},dragEnd:function(){this.hDiv.style.cursor="default";if(this.resizing){var c=this.resizing.idx,d=this.headers[c].newWidth||this.headers[c].width,d=parseInt(d,10);this.resizing=!1;b("#rs_m"+b.jgrid.jqID(e.id)).css("display","none");e.colModel[c].width=d;this.headers[c].width=d;this.headers[c].el.style.width=d+"px";this.cols[c].style.width=d+"px";0<this.footers.length&&(this.footers[c].style.width=d+"px");
 !0===e.forceFit?(d=this.headers[c+e.nv].newWidth||this.headers[c+e.nv].width,this.headers[c+e.nv].width=d,this.headers[c+e.nv].el.style.width=d+"px",this.cols[c+e.nv].style.width=d+"px",0<this.footers.length&&(this.footers[c+e.nv].style.width=d+"px"),e.colModel[c+e.nv].width=d):(e.tblwidth=this.newWidth||e.tblwidth,b("table:first",this.bDiv).css("width",e.tblwidth+"px"),b("table:first",this.hDiv).css("width",e.tblwidth+"px"),this.hDiv.scrollLeft=this.bDiv.scrollLeft,e.footerrow&&(b("table:first",
-this.sDiv).css("width",e.tblwidth+"px"),this.sDiv.scrollLeft=this.bDiv.scrollLeft));b(a).triggerHandler("jqGridResizeStop",[d,c]);b.isFunction(e.resizeStop)&&e.resizeStop.call(a,d,c)}this.curGbox=null;document.onselectstart=function(){return!0}},populateVisible:function(){c.timer&&clearTimeout(c.timer);c.timer=null;var a=b(c.bDiv).height();if(a){var d=b("table:first",c.bDiv),f,g;if(d[0].rows.length)try{g=(f=d[0].rows[1])?b(f).outerHeight()||c.prevRowHeight:c.prevRowHeight}catch(h){g=c.prevRowHeight}if(g){c.prevRowHeight=
-g;var i=e.rowNum;f=c.scrollTop=c.bDiv.scrollTop;var K=Math.round(d.position().top)-f,k=K+d.height();g*=i;var A,G,w;if(k<a&&0>=K&&(void 0===e.lastpage||parseInt((k+f+g-1)/g,10)<=e.lastpage))G=parseInt((a-k+g-1)/g,10),0<=k||2>G||!0===e.scroll?(A=Math.round((k+f)/g)+1,K=-1):K=1;0<K&&(A=parseInt(f/g,10)+1,G=parseInt((f+a)/g,10)+2-A,w=!0);if(G&&(!e.lastpage||!(A>e.lastpage||1===e.lastpage||A===e.page&&A===e.lastpage)))c.hDiv.loading?c.timer=setTimeout(c.populateVisible,e.scrollTimeout):(e.page=A,w&&(c.selectionPreserver(d[0]),
-c.emptyRows.call(d[0],!1,!1)),c.populate(G))}}},scrollGrid:function(a){if(e.scroll){var b=c.bDiv.scrollTop;void 0===c.scrollTop&&(c.scrollTop=0);b!==c.scrollTop&&(c.scrollTop=b,c.timer&&clearTimeout(c.timer),c.timer=setTimeout(c.populateVisible,e.scrollTimeout))}c.hDiv.scrollLeft=c.bDiv.scrollLeft;e.footerrow&&(c.sDiv.scrollLeft=c.bDiv.scrollLeft);a&&a.stopPropagation()},selectionPreserver:function(a){var c=a.p,d=c.selrow,e=c.selarrrow?b.makeArray(c.selarrrow):null,f=a.grid.bDiv.scrollLeft,g=function(){var h;
-c.selrow=null;c.selarrrow=[];if(c.multiselect&&e&&0<e.length)for(h=0;h<e.length;h++)e[h]!==d&&b(a).jqGrid("setSelection",e[h],!1,null);d&&b(a).jqGrid("setSelection",d,!1,null);a.grid.bDiv.scrollLeft=f;b(a).unbind(".selectionPreserver",g)};b(a).bind("jqGridGridComplete.selectionPreserver",g)}};if("TABLE"!==this.tagName.toUpperCase())alert("Element is not a table");else if(void 0!==document.documentMode&&5>=document.documentMode)alert("Grid can not be used in this ('quirks') mode!");else{b(this).empty().attr("tabindex",
-"0");this.p=e;this.p.useProp=!!b.fn.prop;var f,g;if(0===this.p.colNames.length)for(f=0;f<this.p.colModel.length;f++)this.p.colNames[f]=this.p.colModel[f].label||this.p.colModel[f].name;if(this.p.colNames.length!==this.p.colModel.length)alert(b.jgrid.errors.model);else{var i=b("<div class='ui-jqgrid-view'></div>"),k=b.jgrid.msie;a.p.direction=b.trim(a.p.direction.toLowerCase());-1===b.inArray(a.p.direction,["ltr","rtl"])&&(a.p.direction="ltr");g=a.p.direction;b(i).insertBefore(this);b(this).removeClass("scroll").appendTo(i);
-var m=b("<div class='ui-jqgrid ui-widget ui-widget-content ui-corner-all'></div>");b(m).attr({id:"gbox_"+this.id,dir:g}).insertBefore(i);b(i).attr("id","gview_"+this.id).appendTo(m);b("<div class='ui-widget-overlay jqgrid-overlay' id='lui_"+this.id+"'></div>").insertBefore(i);b("<div class='loading ui-state-default ui-state-active' id='load_"+this.id+"'>"+this.p.loadtext+"</div>").insertBefore(i);b(this).attr({cellspacing:"0",cellpadding:"0",border:"0",role:"grid","aria-multiselectable":!!this.p.multiselect,
-"aria-labelledby":"gbox_"+this.id});var n=function(a,b){a=parseInt(a,10);return isNaN(a)?b||0:a},p=function(d,e,f,g,h,i){var K=a.p.colModel[d],k=K.align,A='style="',G=K.classes,w=K.name,x=[];k&&(A=A+("text-align:"+k+";"));K.hidden===true&&(A=A+"display:none;");if(e===0)A=A+("width: "+c.headers[d].width+"px;");else if(K.cellattr&&b.isFunction(K.cellattr))if((d=K.cellattr.call(a,h,f,g,K,i))&&typeof d==="string"){d=d.replace(/style/i,"style").replace(/title/i,"title");if(d.indexOf("title")>-1)K.title=
-false;d.indexOf("class")>-1&&(G=void 0);x=d.split(/[^-]style/);if(x.length===2){x[1]=b.trim(x[1].replace("=",""));if(x[1].indexOf("'")===0||x[1].indexOf('"')===0)x[1]=x[1].substring(1);A=A+x[1].replace(/'/gi,'"')}else A=A+'"'}if(!x.length){x[0]="";A=A+'"'}A=A+((G!==void 0?' class="'+G+'"':"")+(K.title&&f?' title="'+b.jgrid.stripHtml(f)+'"':""));A=A+(' aria-describedby="'+a.p.id+"_"+w+'"');return A+x[0]},l=function(c){return c==null||c===""?"&#160;":a.p.autoencode?b.jgrid.htmlEncode(c):""+c},o=function(c,
-d,e,f,g){var h=a.p.colModel[e];if(h.formatter!==void 0){c=""+a.p.idPrefix!==""?b.jgrid.stripPref(a.p.idPrefix,c):c;c={rowId:c,colModel:h,gid:a.p.id,pos:e};d=b.isFunction(h.formatter)?h.formatter.call(a,d,c,f,g):b.fmatter?b.fn.fmatter.call(a,h.formatter,d,c,f,g):l(d)}else d=l(d);return d},B=function(a,b,c,d,e,f){b=o(a,b,c,e,"add");return'<td role="gridcell" '+p(c,d,b,e,a,f)+">"+b+"</td>"},S=function(b,c,d,e){e='<input role="checkbox" type="checkbox" id="jqg_'+a.p.id+"_"+b+'" class="cbox" name="jqg_'+
-a.p.id+"_"+b+'"'+(e?'checked="checked"':"")+"/>";return'<td role="gridcell" '+p(c,d,"",null,b,true)+">"+e+"</td>"},M=function(a,b,c,d){c=(parseInt(c,10)-1)*parseInt(d,10)+1+b;return'<td role="gridcell" class="ui-state-default jqgrid-rownum" '+p(a,b,c,null,b,true)+">"+c+"</td>"},Z=function(b){var c,d=[],e=0,f;for(f=0;f<a.p.colModel.length;f++){c=a.p.colModel[f];if(c.name!=="cb"&&c.name!=="subgrid"&&c.name!=="rn"){d[e]=b==="local"?c.name:b==="xml"||b==="xmlstring"?c.xmlmap||c.name:c.jsonmap||c.name;
-e++}}return d},T=function(c){var d=a.p.remapColumns;if(!d||!d.length)d=b.map(a.p.colModel,function(a,b){return b});c&&(d=b.map(d,function(a){return a<c?null:a-c}));return d},U=function(a,c){var d;if(this.p.deepempty)b(this.rows).slice(1).remove();else{d=this.rows.length>0?this.rows[0]:null;b(this.firstChild).empty().append(d)}if(a&&this.p.scroll){b(this.grid.bDiv.firstChild).css({height:"auto"});b(this.grid.bDiv.firstChild.firstChild).css({height:0,display:"none"});if(this.grid.bDiv.scrollTop!==0)this.grid.bDiv.scrollTop=
-0}if(c===true&&this.p.treeGrid){this.p.data=[];this.p._index={}}},N=function(){var c=a.p.data.length,d,e,f;d=a.p.rownumbers===true?1:0;e=a.p.multiselect===true?1:0;f=a.p.subGrid===true?1:0;d=a.p.keyIndex===false||a.p.loadonce===true?a.p.localReader.id:a.p.colModel[a.p.keyIndex+e+f+d].name;for(e=0;e<c;e++){f=b.jgrid.getAccessor(a.p.data[e],d);f===void 0&&(f=""+(e+1));a.p._index[f]=e}},W=function(c,d,e,f,g,h){var j="-1",i="",k,d=d?"display:none;":"",e="ui-widget-content jqgrow ui-row-"+a.p.direction+
-(e?" "+e:"")+(h?" ui-state-highlight":""),h=b(a).triggerHandler("jqGridRowAttr",[f,g,c]);typeof h!=="object"&&(h=b.isFunction(a.p.rowattr)?a.p.rowattr.call(a,f,g,c):{});if(!b.isEmptyObject(h)){if(h.hasOwnProperty("id")){c=h.id;delete h.id}if(h.hasOwnProperty("tabindex")){j=h.tabindex;delete h.tabindex}if(h.hasOwnProperty("style")){d=d+h.style;delete h.style}if(h.hasOwnProperty("class")){e=e+(" "+h["class"]);delete h["class"]}try{delete h.role}catch(G){}for(k in h)h.hasOwnProperty(k)&&(i=i+(" "+k+
-"="+h[k]))}return'<tr role="row" id="'+c+'" tabindex="'+j+'" class="'+e+'"'+(d===""?"":' style="'+d+'"')+i+">"},J=function(c,d,e,f,g){var h=new Date,j=a.p.datatype!=="local"&&a.p.loadonce||a.p.datatype==="xmlstring",i=a.p.xmlReader,k=a.p.datatype==="local"?"local":"xml";if(j){a.p.data=[];a.p._index={};a.p.localReader.id="_id_"}a.p.reccount=0;if(b.isXMLDoc(c)){if(a.p.treeANode===-1&&!a.p.scroll){U.call(a,false,true);e=1}else e=e>1?e:1;var G=b(a),w,x,m=0,n,s=a.p.multiselect===true?1:0,y=0,p,l=a.p.rownumbers===
-true?1:0,o,u=[],F,q={},z,E,r=[],qa=a.p.altRows===true?a.p.altclass:"",t;if(a.p.subGrid===true){y=1;p=b.jgrid.getMethod("addSubGridCell")}i.repeatitems||(u=Z(k));o=a.p.keyIndex===false?b.isFunction(i.id)?i.id.call(a,c):i.id:a.p.keyIndex;if(u.length>0&&!isNaN(o)){a.p.remapColumns&&a.p.remapColumns.length&&(o=b.inArray(o,a.p.remapColumns));o=u[o]}k=(""+o).indexOf("[")===-1?u.length?function(a,c){return b(o,a).text()||c}:function(a,c){return b(i.cell,a).eq(o).text()||c}:function(a,b){return a.getAttribute(o.replace(/[\[\]]/g,
-""))||b};a.p.userData={};a.p.page=b.jgrid.getXmlData(c,i.page)||a.p.page||0;a.p.lastpage=b.jgrid.getXmlData(c,i.total);if(a.p.lastpage===void 0)a.p.lastpage=1;a.p.records=b.jgrid.getXmlData(c,i.records)||0;b.isFunction(i.userdata)?a.p.userData=i.userdata.call(a,c)||{}:b.jgrid.getXmlData(c,i.userdata,true).each(function(){a.p.userData[this.getAttribute("name")]=b(this).text()});c=b.jgrid.getXmlData(c,i.root,true);(c=b.jgrid.getXmlData(c,i.row,true))||(c=[]);var v=c.length,L=0,C=[],D=parseInt(a.p.rowNum,
-10),H=a.p.scroll?b.jgrid.randId():1;if(v>0&&a.p.page<=0)a.p.page=1;if(c&&v){g&&(D=D*(g+1));var g=b.isFunction(a.p.afterInsertRow),J=false,I;if(a.p.grouping){J=a.p.groupingView.groupCollapse===true;I=b.jgrid.getMethod("groupingPrepare")}for(;L<v;){z=c[L];E=k(z,H+L);E=a.p.idPrefix+E;w=e===0?0:e+1;t=(w+L)%2===1?qa:"";var O=r.length;r.push("");l&&r.push(M(0,L,a.p.page,a.p.rowNum));s&&r.push(S(E,l,L,false));y&&r.push(p.call(G,s+l,L+e));if(i.repeatitems){F||(F=T(s+y+l));var N=b.jgrid.getXmlData(z,i.cell,
-true);b.each(F,function(b){var c=N[this];if(!c)return false;n=c.textContent||c.text;q[a.p.colModel[b+s+y+l].name]=n;r.push(B(E,n,b+s+y+l,L+e,z,q))})}else for(w=0;w<u.length;w++){n=b.jgrid.getXmlData(z,u[w]);q[a.p.colModel[w+s+y+l].name]=n;r.push(B(E,n,w+s+y+l,L+e,z,q))}r[O]=W(E,J,t,q,z,false);r.push("</tr>");if(a.p.grouping){C=I.call(G,r,C,q,L);r=[]}if(j||a.p.treeGrid===true){q._id_=b.jgrid.stripPref(a.p.idPrefix,E);a.p.data.push(q);a.p._index[q._id_]=a.p.data.length-1}if(a.p.gridview===false){b("tbody:first",
-d).append(r.join(""));G.triggerHandler("jqGridAfterInsertRow",[E,q,z]);g&&a.p.afterInsertRow.call(a,E,q,z);r=[]}q={};m++;L++;if(m===D)break}}if(a.p.gridview===true){x=a.p.treeANode>-1?a.p.treeANode:0;if(a.p.grouping){G.jqGrid("groupingRender",C,a.p.colModel.length);C=null}else a.p.treeGrid===true&&x>0?b(a.rows[x]).after(r.join("")):b("tbody:first",d).append(r.join(""))}if(a.p.subGrid===true)try{G.jqGrid("addSubGrid",s+l)}catch(Q){}a.p.totaltime=new Date-h;if(m>0&&a.p.records===0)a.p.records=v;r=null;
-if(a.p.treeGrid===true)try{G.jqGrid("setTreeNode",x+1,m+x+1)}catch(R){}if(!a.p.treeGrid&&!a.p.scroll)a.grid.bDiv.scrollTop=0;a.p.reccount=m;a.p.treeANode=-1;a.p.userDataOnFooter&&G.jqGrid("footerData","set",a.p.userData,true);if(j){a.p.records=v;a.p.lastpage=Math.ceil(v/D)}f||a.updatepager(false,true);if(j)for(;m<v;){z=c[m];E=k(z,m+H);E=a.p.idPrefix+E;if(i.repeatitems){F||(F=T(s+y+l));var P=b.jgrid.getXmlData(z,i.cell,true);b.each(F,function(b){var c=P[this];if(!c)return false;n=c.textContent||c.text;
-q[a.p.colModel[b+s+y+l].name]=n})}else for(w=0;w<u.length;w++){n=b.jgrid.getXmlData(z,u[w]);q[a.p.colModel[w+s+y+l].name]=n}q._id_=b.jgrid.stripPref(a.p.idPrefix,E);a.p.data.push(q);a.p._index[q._id_]=a.p.data.length-1;q={};m++}}},R=function(c,d,e,f,g){var h=new Date;if(c){if(a.p.treeANode===-1&&!a.p.scroll){U.call(a,false,true);e=1}else e=e>1?e:1;var i,j=a.p.datatype!=="local"&&a.p.loadonce||a.p.datatype==="jsonstring";if(j){a.p.data=[];a.p._index={};a.p.localReader.id="_id_"}a.p.reccount=0;if(a.p.datatype===
-"local"){d=a.p.localReader;i="local"}else{d=a.p.jsonReader;i="json"}var k=b(a),m=0,w,x,n,l=[],s=a.p.multiselect?1:0,y=a.p.subGrid===true?1:0,p,o=a.p.rownumbers===true?1:0,u=T(s+y+o);i=Z(i);var v,F,q,z={},E,r,t=[],C=a.p.altRows===true?a.p.altclass:"",D;a.p.page=b.jgrid.getAccessor(c,d.page)||a.p.page||0;F=b.jgrid.getAccessor(c,d.total);y&&(p=b.jgrid.getMethod("addSubGridCell"));a.p.lastpage=F===void 0?1:F;a.p.records=b.jgrid.getAccessor(c,d.records)||0;a.p.userData=b.jgrid.getAccessor(c,d.userdata)||
-{};q=a.p.keyIndex===false?b.isFunction(d.id)?d.id.call(a,c):d.id:a.p.keyIndex;if(!d.repeatitems){l=i;if(l.length>0&&!isNaN(q)){a.p.remapColumns&&a.p.remapColumns.length&&(q=b.inArray(q,a.p.remapColumns));q=l[q]}}F=b.jgrid.getAccessor(c,d.root);F==null&&b.isArray(c)&&(F=c);F||(F=[]);c=F.length;x=0;if(c>0&&a.p.page<=0)a.p.page=1;var L=parseInt(a.p.rowNum,10),H=a.p.scroll?b.jgrid.randId():1,J=false,I;g&&(L=L*(g+1));a.p.datatype==="local"&&!a.p.deselectAfterSort&&(J=true);var O=b.isFunction(a.p.afterInsertRow),
-N=[],P=false,Q;if(a.p.grouping){P=a.p.groupingView.groupCollapse===true;Q=b.jgrid.getMethod("groupingPrepare")}for(;x<c;){g=F[x];r=b.jgrid.getAccessor(g,q);if(r===void 0){typeof q==="number"&&a.p.colModel[q+s+y+o]!=null&&(r=b.jgrid.getAccessor(g,a.p.colModel[q+s+y+o].name));if(r===void 0){r=H+x;if(l.length===0&&d.cell){w=b.jgrid.getAccessor(g,d.cell)||g;r=w!=null&&w[q]!==void 0?w[q]:r}}}r=a.p.idPrefix+r;w=e===1?0:e;D=(w+x)%2===1?C:"";J&&(I=a.p.multiselect?b.inArray(r,a.p.selarrrow)!==-1:r===a.p.selrow);
-var R=t.length;t.push("");o&&t.push(M(0,x,a.p.page,a.p.rowNum));s&&t.push(S(r,o,x,I));y&&t.push(p.call(k,s+o,x+e));v=i;if(d.repeatitems){d.cell&&(g=b.jgrid.getAccessor(g,d.cell)||g);b.isArray(g)&&(v=u)}for(n=0;n<v.length;n++){w=b.jgrid.getAccessor(g,v[n]);z[a.p.colModel[n+s+y+o].name]=w;t.push(B(r,w,n+s+y+o,x+e,g,z))}t[R]=W(r,P,D,z,g,I);t.push("</tr>");if(a.p.grouping){N=Q.call(k,t,N,z,x);t=[]}if(j||a.p.treeGrid===true){z._id_=b.jgrid.stripPref(a.p.idPrefix,r);a.p.data.push(z);a.p._index[z._id_]=
-a.p.data.length-1}if(a.p.gridview===false){b("#"+b.jgrid.jqID(a.p.id)+" tbody:first").append(t.join(""));k.triggerHandler("jqGridAfterInsertRow",[r,z,g]);O&&a.p.afterInsertRow.call(a,r,z,g);t=[]}z={};m++;x++;if(m===L)break}if(a.p.gridview===true){E=a.p.treeANode>-1?a.p.treeANode:0;a.p.grouping?k.jqGrid("groupingRender",N,a.p.colModel.length):a.p.treeGrid===true&&E>0?b(a.rows[E]).after(t.join("")):b("#"+b.jgrid.jqID(a.p.id)+" tbody:first").append(t.join(""))}if(a.p.subGrid===true)try{k.jqGrid("addSubGrid",
-s+o)}catch($){}a.p.totaltime=new Date-h;if(m>0&&a.p.records===0)a.p.records=c;if(a.p.treeGrid===true)try{k.jqGrid("setTreeNode",E+1,m+E+1)}catch(V){}if(!a.p.treeGrid&&!a.p.scroll)a.grid.bDiv.scrollTop=0;a.p.reccount=m;a.p.treeANode=-1;a.p.userDataOnFooter&&k.jqGrid("footerData","set",a.p.userData,true);if(j){a.p.records=c;a.p.lastpage=Math.ceil(c/L)}f||a.updatepager(false,true);if(j)for(;m<c&&F[m];){g=F[m];r=b.jgrid.getAccessor(g,q);if(r===void 0){typeof q==="number"&&a.p.colModel[q+s+y+o]!=null&&
-(r=b.jgrid.getAccessor(g,a.p.colModel[q+s+y+o].name));if(r===void 0){r=H+m;if(l.length===0&&d.cell){e=b.jgrid.getAccessor(g,d.cell)||g;r=e!=null&&e[q]!==void 0?e[q]:r}}}if(g){r=a.p.idPrefix+r;v=i;if(d.repeatitems){d.cell&&(g=b.jgrid.getAccessor(g,d.cell)||g);b.isArray(g)&&(v=u)}for(n=0;n<v.length;n++)z[a.p.colModel[n+s+y+o].name]=b.jgrid.getAccessor(g,v[n]);z._id_=b.jgrid.stripPref(a.p.idPrefix,r);a.p.data.push(z);a.p._index[z._id_]=a.p.data.length-1;z={}}m++}}},ia=function(){function c(a){var b=
-0,d,e,f,h,i;if(a.groups!=null){(e=a.groups.length&&a.groupOp.toString().toUpperCase()==="OR")&&s.orBegin();for(d=0;d<a.groups.length;d++){b>0&&e&&s.or();try{c(a.groups[d])}catch(j){alert(j)}b++}e&&s.orEnd()}if(a.rules!=null)try{(f=a.rules.length&&a.groupOp.toString().toUpperCase()==="OR")&&s.orBegin();for(d=0;d<a.rules.length;d++){i=a.rules[d];h=a.groupOp.toString().toUpperCase();if(o[i.op]&&i.field){b>0&&h&&h==="OR"&&(s=s.or());s=o[i.op](s,h)(i.field,i.data,g[i.field])}b++}f&&s.orEnd()}catch(pa){alert(pa)}}
-var d=a.p.multiSort?[]:"",e=[],f=false,g={},h=[],i=[],j,k,m;if(b.isArray(a.p.data)){var n=a.p.grouping?a.p.groupingView:false,x,l;b.each(a.p.colModel,function(){k=this.sorttype||"text";if(k==="date"||k==="datetime"){if(this.formatter&&typeof this.formatter==="string"&&this.formatter==="date"){j=this.formatoptions&&this.formatoptions.srcformat?this.formatoptions.srcformat:b.jgrid.formatter.date.srcformat;m=this.formatoptions&&this.formatoptions.newformat?this.formatoptions.newformat:b.jgrid.formatter.date.newformat}else j=
-m=this.datefmt||"Y-m-d";g[this.name]={stype:k,srcfmt:j,newfmt:m}}else g[this.name]={stype:k,srcfmt:"",newfmt:""};if(a.p.grouping){l=0;for(x=n.groupField.length;l<x;l++)if(this.name===n.groupField[l]){var c=this.name;if(this.index)c=this.index;h[l]=g[c];i[l]=c}}if(a.p.multiSort){if(this.lso){d.push(this.name);c=this.lso.split("-");e.push(c[c.length-1])}}else if(!f&&(this.index===a.p.sortname||this.name===a.p.sortname)){d=this.name;f=true}});if(a.p.treeGrid)b(a).jqGrid("SortTree",d,a.p.sortorder,g[d].stype,
-g[d].srcfmt);else{var o={eq:function(a){return a.equals},ne:function(a){return a.notEquals},lt:function(a){return a.less},le:function(a){return a.lessOrEquals},gt:function(a){return a.greater},ge:function(a){return a.greaterOrEquals},cn:function(a){return a.contains},nc:function(a,b){return b==="OR"?a.orNot().contains:a.andNot().contains},bw:function(a){return a.startsWith},bn:function(a,b){return b==="OR"?a.orNot().startsWith:a.andNot().startsWith},en:function(a,b){return b==="OR"?a.orNot().endsWith:
-a.andNot().endsWith},ew:function(a){return a.endsWith},ni:function(a,b){return b==="OR"?a.orNot().equals:a.andNot().equals},"in":function(a){return a.equals},nu:function(a){return a.isNull},nn:function(a,b){return b==="OR"?a.orNot().isNull:a.andNot().isNull}},s=b.jgrid.from(a.p.data);a.p.ignoreCase&&(s=s.ignoreCase());if(a.p.search===true){var y=a.p.postData.filters;if(y){typeof y==="string"&&(y=b.jgrid.parse(y));c(y)}else try{s=o[a.p.postData.searchOper](s)(a.p.postData.searchField,a.p.postData.searchString,
-g[a.p.postData.searchField])}catch(p){}}if(a.p.grouping)for(l=0;l<x;l++)s.orderBy(i[l],n.groupOrder[l],h[l].stype,h[l].srcfmt);a.p.multiSort?b.each(d,function(a){s.orderBy(this,e[a],g[this].stype,g[this].srcfmt)}):d&&a.p.sortorder&&f&&(a.p.sortorder.toUpperCase()==="DESC"?s.orderBy(a.p.sortname,"d",g[d].stype,g[d].srcfmt):s.orderBy(a.p.sortname,"a",g[d].stype,g[d].srcfmt));var y=s.select(),t=parseInt(a.p.rowNum,10),u=y.length,v=parseInt(a.p.page,10),B=Math.ceil(u/t),q={},y=y.slice((v-1)*t,v*t),g=
-s=null;q[a.p.localReader.total]=B;q[a.p.localReader.page]=v;q[a.p.localReader.records]=u;q[a.p.localReader.root]=y;q[a.p.localReader.userdata]=a.p.userData;y=null;return q}}},$=function(){a.grid.hDiv.loading=true;if(!a.p.hiddengrid)switch(a.p.loadui){case "enable":b("#load_"+b.jgrid.jqID(a.p.id)).show();break;case "block":b("#lui_"+b.jgrid.jqID(a.p.id)).show();b("#load_"+b.jgrid.jqID(a.p.id)).show()}},P=function(){a.grid.hDiv.loading=false;switch(a.p.loadui){case "enable":b("#load_"+b.jgrid.jqID(a.p.id)).hide();
-break;case "block":b("#lui_"+b.jgrid.jqID(a.p.id)).hide();b("#load_"+b.jgrid.jqID(a.p.id)).hide()}},O=function(c){if(!a.grid.hDiv.loading){var d=a.p.scroll&&c===false,e={},f,g=a.p.prmNames;if(a.p.page<=0)a.p.page=1;if(g.search!==null)e[g.search]=a.p.search;g.nd!==null&&(e[g.nd]=(new Date).getTime());if(g.rows!==null)e[g.rows]=a.p.rowNum;if(g.page!==null)e[g.page]=a.p.page;if(g.sort!==null)e[g.sort]=a.p.sortname;if(g.order!==null)e[g.order]=a.p.sortorder;if(a.p.rowTotal!==null&&g.totalrows!==null)e[g.totalrows]=
-a.p.rowTotal;var h=b.isFunction(a.p.loadComplete),i=h?a.p.loadComplete:null,j=0,c=c||1;if(c>1)if(g.npage!==null){e[g.npage]=c;j=c-1;c=1}else i=function(b){a.p.page++;a.grid.hDiv.loading=false;h&&a.p.loadComplete.call(a,b);O(c-1)};else g.npage!==null&&delete a.p.postData[g.npage];if(a.p.grouping){b(a).jqGrid("groupingSetup");var k=a.p.groupingView,m,n="";for(m=0;m<k.groupField.length;m++){var l=k.groupField[m];b.each(a.p.colModel,function(a,b){if(b.name===l&&b.index)l=b.index});n=n+(l+" "+k.groupOrder[m]+
-", ")}e[g.sort]=n+e[g.sort]}b.extend(a.p.postData,e);var o=!a.p.scroll?1:a.rows.length-1,e=b(a).triggerHandler("jqGridBeforeRequest");if(!(e===false||e==="stop"))if(b.isFunction(a.p.datatype))a.p.datatype.call(a,a.p.postData,"load_"+a.p.id);else{if(b.isFunction(a.p.beforeRequest)){e=a.p.beforeRequest.call(a);e===void 0&&(e=true);if(e===false)return}f=a.p.datatype.toLowerCase();switch(f){case "json":case "jsonp":case "xml":case "script":b.ajax(b.extend({url:a.p.url,type:a.p.mtype,dataType:f,data:b.isFunction(a.p.serializeGridData)?
-a.p.serializeGridData.call(a,a.p.postData):a.p.postData,success:function(e,g,h){if(b.isFunction(a.p.beforeProcessing)&&a.p.beforeProcessing.call(a,e,g,h)===false)P();else{f==="xml"?J(e,a.grid.bDiv,o,c>1,j):R(e,a.grid.bDiv,o,c>1,j);b(a).triggerHandler("jqGridLoadComplete",[e]);i&&i.call(a,e);b(a).triggerHandler("jqGridAfterLoadComplete",[e]);d&&a.grid.populateVisible();if(a.p.loadonce||a.p.treeGrid)a.p.datatype="local";c===1&&P()}},error:function(d,e,g){b.isFunction(a.p.loadError)&&a.p.loadError.call(a,
-d,e,g);c===1&&P()},beforeSend:function(c,d){var e=true;b.isFunction(a.p.loadBeforeSend)&&(e=a.p.loadBeforeSend.call(a,c,d));e===void 0&&(e=true);if(e===false)return false;$()}},b.jgrid.ajaxOptions,a.p.ajaxGridOptions));break;case "xmlstring":$();e=typeof a.p.datastr!=="string"?a.p.datastr:b.parseXML(a.p.datastr);J(e,a.grid.bDiv);b(a).triggerHandler("jqGridLoadComplete",[e]);h&&a.p.loadComplete.call(a,e);b(a).triggerHandler("jqGridAfterLoadComplete",[e]);a.p.datatype="local";a.p.datastr=null;P();break;
-case "jsonstring":$();e=typeof a.p.datastr==="string"?b.jgrid.parse(a.p.datastr):a.p.datastr;R(e,a.grid.bDiv);b(a).triggerHandler("jqGridLoadComplete",[e]);h&&a.p.loadComplete.call(a,e);b(a).triggerHandler("jqGridAfterLoadComplete",[e]);a.p.datatype="local";a.p.datastr=null;P();break;case "local":case "clientside":$();a.p.datatype="local";e=ia();R(e,a.grid.bDiv,o,c>1,j);b(a).triggerHandler("jqGridLoadComplete",[e]);i&&i.call(a,e);b(a).triggerHandler("jqGridAfterLoadComplete",[e]);d&&a.grid.populateVisible();
-P()}}}},ba=function(c){b("#cb_"+b.jgrid.jqID(a.p.id),a.grid.hDiv)[a.p.useProp?"prop":"attr"]("checked",c);if(a.p.frozenColumns&&a.p.id+"_frozen")b("#cb_"+b.jgrid.jqID(a.p.id),a.grid.fhDiv)[a.p.useProp?"prop":"attr"]("checked",c)},ja=function(c,d){var e="",f="<table cellspacing='0' cellpadding='0' border='0' style='table-layout:auto;' class='ui-pg-table'><tbody><tr>",i="",j,k,m,l,o=function(c){var d;b.isFunction(a.p.onPaging)&&(d=a.p.onPaging.call(a,c));a.p.selrow=null;if(a.p.multiselect){a.p.selarrrow=
-[];ba(false)}a.p.savedRow=[];return d==="stop"?false:true},c=c.substr(1),d=d+("_"+c);j="pg_"+c;k=c+"_left";m=c+"_center";l=c+"_right";b("#"+b.jgrid.jqID(c)).append("<div id='"+j+"' class='ui-pager-control' role='group'><table cellspacing='0' cellpadding='0' border='0' class='ui-pg-table' style='width:100%;table-layout:fixed;height:100%;' role='row'><tbody><tr><td id='"+k+"' align='left'></td><td id='"+m+"' align='center' style='white-space:pre;'></td><td id='"+l+"' align='right'></td></tr></tbody></table></div>").attr("dir",
-"ltr");if(a.p.rowList.length>0){i="<td dir='"+g+"'>";i=i+"<select class='ui-pg-selbox' role='listbox'>";for(k=0;k<a.p.rowList.length;k++)i=i+('<option role="option" value="'+a.p.rowList[k]+'"'+(a.p.rowNum===a.p.rowList[k]?' selected="selected"':"")+">"+a.p.rowList[k]+"</option>");i=i+"</select></td>"}g==="rtl"&&(f=f+i);a.p.pginput===true&&(e="<td dir='"+g+"'>"+b.jgrid.format(a.p.pgtext||"","<input class='ui-pg-input' type='text' size='2' maxlength='7' value='0' role='textbox'/>","<span id='sp_1_"+
-b.jgrid.jqID(c)+"'></span>")+"</td>");if(a.p.pgbuttons===true){k=["first"+d,"prev"+d,"next"+d,"last"+d];g==="rtl"&&k.reverse();f=f+("<td id='"+k[0]+"' class='ui-pg-button ui-corner-all'><span class='ui-icon ui-icon-seek-first'></span></td>");f=f+("<td id='"+k[1]+"' class='ui-pg-button ui-corner-all'><span class='ui-icon ui-icon-seek-prev'></span></td>");f=f+(e!==""?"<td class='ui-pg-button ui-state-disabled' style='width:4px;'><span class='ui-separator'></span></td>"+e+"<td class='ui-pg-button ui-state-disabled' style='width:4px;'><span class='ui-separator'></span></td>":
-"")+("<td id='"+k[2]+"' class='ui-pg-button ui-corner-all'><span class='ui-icon ui-icon-seek-next'></span></td>");f=f+("<td id='"+k[3]+"' class='ui-pg-button ui-corner-all'><span class='ui-icon ui-icon-seek-end'></span></td>")}else e!==""&&(f=f+e);g==="ltr"&&(f=f+i);f=f+"</tr></tbody></table>";a.p.viewrecords===true&&b("td#"+c+"_"+a.p.recordpos,"#"+j).append("<div dir='"+g+"' style='text-align:"+a.p.recordpos+"' class='ui-paging-info'></div>");b("td#"+c+"_"+a.p.pagerpos,"#"+j).append(f);i=b(".ui-jqgrid").css("font-size")||
-"11px";b(document.body).append("<div id='testpg' class='ui-jqgrid ui-widget ui-widget-content' style='font-size:"+i+";visibility:hidden;' ></div>");f=b(f).clone().appendTo("#testpg").width();b("#testpg").remove();if(f>0){e!==""&&(f=f+50);b("td#"+c+"_"+a.p.pagerpos,"#"+j).width(f)}a.p._nvtd=[];a.p._nvtd[0]=f?Math.floor((a.p.width-f)/2):Math.floor(a.p.width/3);a.p._nvtd[1]=0;f=null;b(".ui-pg-selbox","#"+j).bind("change",function(){if(!o("records"))return false;a.p.page=Math.round(a.p.rowNum*(a.p.page-
+this.sDiv).css("width",e.tblwidth+"px"),this.sDiv.scrollLeft=this.bDiv.scrollLeft));b(a).triggerHandler("jqGridResizeStop",[d,c]);b.isFunction(e.resizeStop)&&e.resizeStop.call(a,d,c)}this.curGbox=null;document.onselectstart=function(){return!0}},populateVisible:function(){c.timer&&clearTimeout(c.timer);c.timer=null;var a=b(c.bDiv).height();if(a){var d=b("table:first",c.bDiv),g,f;if(d[0].rows.length)try{f=(g=d[0].rows[1])?b(g).outerHeight()||c.prevRowHeight:c.prevRowHeight}catch(ua){f=c.prevRowHeight}if(f){c.prevRowHeight=
+f;var h=e.rowNum;g=c.scrollTop=c.bDiv.scrollTop;var i=Math.round(d.position().top)-g,k=i+d.height();f*=h;var z,F,y;if(k<a&&0>=i&&(void 0===e.lastpage||parseInt((k+g+f-1)/f,10)<=e.lastpage))F=parseInt((a-k+f-1)/f,10),0<=k||2>F||!0===e.scroll?(z=Math.round((k+g)/f)+1,i=-1):i=1;0<i&&(z=parseInt(g/f,10)+1,F=parseInt((g+a)/f,10)+2-z,y=!0);if(F&&(!e.lastpage||!(z>e.lastpage||1===e.lastpage||z===e.page&&z===e.lastpage)))c.hDiv.loading?c.timer=setTimeout(c.populateVisible,e.scrollTimeout):(e.page=z,y&&(c.selectionPreserver(d[0]),
+c.emptyRows.call(d[0],!1,!1)),c.populate(F))}}},scrollGrid:function(a){if(e.scroll){var b=c.bDiv.scrollTop;void 0===c.scrollTop&&(c.scrollTop=0);b!==c.scrollTop&&(c.scrollTop=b,c.timer&&clearTimeout(c.timer),c.timer=setTimeout(c.populateVisible,e.scrollTimeout))}c.hDiv.scrollLeft=c.bDiv.scrollLeft;e.footerrow&&(c.sDiv.scrollLeft=c.bDiv.scrollLeft);a&&a.stopPropagation()},selectionPreserver:function(a){var c=a.p,d=c.selrow,e=c.selarrrow?b.makeArray(c.selarrrow):null,g=a.grid.bDiv.scrollLeft,f=function(){var h;
+c.selrow=null;c.selarrrow=[];if(c.multiselect&&e&&0<e.length)for(h=0;h<e.length;h++)e[h]!==d&&b(a).jqGrid("setSelection",e[h],!1,null);d&&b(a).jqGrid("setSelection",d,!1,null);a.grid.bDiv.scrollLeft=g;b(a).unbind(".selectionPreserver",f)};b(a).bind("jqGridGridComplete.selectionPreserver",f)}};if("TABLE"!==this.tagName.toUpperCase())alert("Element is not a table");else if(void 0!==document.documentMode&&5>=document.documentMode)alert("Grid can not be used in this ('quirks') mode!");else{b(this).empty().attr("tabindex",
+"0");this.p=e;this.p.useProp=!!b.fn.prop;var g,f;if(0===this.p.colNames.length)for(g=0;g<this.p.colModel.length;g++)this.p.colNames[g]=this.p.colModel[g].label||this.p.colModel[g].name;if(this.p.colNames.length!==this.p.colModel.length)alert(b.jgrid.errors.model);else{var i=b("<div class='ui-jqgrid-view'></div>"),k=b.jgrid.msie;a.p.direction=b.trim(a.p.direction.toLowerCase());-1===b.inArray(a.p.direction,["ltr","rtl"])&&(a.p.direction="ltr");f=a.p.direction;b(i).insertBefore(this);b(this).removeClass("scroll").appendTo(i);
+var l=b("<div class='ui-jqgrid ui-widget ui-widget-content ui-corner-all'></div>");b(l).attr({id:"gbox_"+this.id,dir:f}).insertBefore(i);b(i).attr("id","gview_"+this.id).appendTo(l);b("<div class='ui-widget-overlay jqgrid-overlay' id='lui_"+this.id+"'></div>").insertBefore(i);b("<div class='loading ui-state-default ui-state-active' id='load_"+this.id+"'>"+this.p.loadtext+"</div>").insertBefore(i);b(this).attr({cellspacing:"0",cellpadding:"0",border:"0",role:"grid","aria-multiselectable":!!this.p.multiselect,
+"aria-labelledby":"gbox_"+this.id});var o=function(a,b){a=parseInt(a,10);return isNaN(a)?b||0:a},n=function(d,e,g,f,h,i){var R=a.p.colModel[d],k=R.align,z='style="',F=R.classes,y=R.name,G=[];k&&(z=z+("text-align:"+k+";"));R.hidden===true&&(z=z+"display:none;");if(e===0)z=z+("width: "+c.headers[d].width+"px;");else if(R.cellattr&&b.isFunction(R.cellattr))if((d=R.cellattr.call(a,h,g,f,R,i))&&typeof d==="string"){d=d.replace(/style/i,"style").replace(/title/i,"title");if(d.indexOf("title")>-1)R.title=
+false;d.indexOf("class")>-1&&(F=void 0);G=d.split(/[^-]style/);if(G.length===2){G[1]=b.trim(G[1].replace("=",""));if(G[1].indexOf("'")===0||G[1].indexOf('"')===0)G[1]=G[1].substring(1);z=z+G[1].replace(/'/gi,'"')}else z=z+'"'}if(!G.length){G[0]="";z=z+'"'}z=z+((F!==void 0?' class="'+F+'"':"")+(R.title&&g?' title="'+b.jgrid.stripHtml(g)+'"':""));z=z+(' aria-describedby="'+a.p.id+"_"+y+'"');return z+G[0]},m=function(c){return c==null||c===""?"&#160;":a.p.autoencode?b.jgrid.htmlEncode(c):""+c},t=function(c,
+d,e,g,f){var h=a.p.colModel[e];if(h.formatter!==void 0){c=""+a.p.idPrefix!==""?b.jgrid.stripPref(a.p.idPrefix,c):c;c={rowId:c,colModel:h,gid:a.p.id,pos:e};d=b.isFunction(h.formatter)?h.formatter.call(a,d,c,g,f):b.fmatter?b.fn.fmatter.call(a,h.formatter,d,c,g,f):m(d)}else d=m(d);return d},A=function(a,b,c,d,e,g){b=t(a,b,c,e,"add");return'<td role="gridcell" '+n(c,d,b,e,a,g)+">"+b+"</td>"},T=function(b,c,d,e){e='<input role="checkbox" type="checkbox" id="jqg_'+a.p.id+"_"+b+'" class="cbox" name="jqg_'+
+a.p.id+"_"+b+'"'+(e?'checked="checked"':"")+"/>";return'<td role="gridcell" '+n(c,d,"",null,b,true)+">"+e+"</td>"},M=function(a,b,c,d){c=(parseInt(c,10)-1)*parseInt(d,10)+1+b;return'<td role="gridcell" class="ui-state-default jqgrid-rownum" '+n(a,b,c,null,b,true)+">"+c+"</td>"},$=function(b){var c,d=[],e=0,g;for(g=0;g<a.p.colModel.length;g++){c=a.p.colModel[g];if(c.name!=="cb"&&c.name!=="subgrid"&&c.name!=="rn"){d[e]=b==="local"?c.name:b==="xml"||b==="xmlstring"?c.xmlmap||c.name:c.jsonmap||c.name;
+e++}}return d},U=function(c){var d=a.p.remapColumns;if(!d||!d.length)d=b.map(a.p.colModel,function(a,b){return b});c&&(d=b.map(d,function(a){return a<c?null:a-c}));return d},V=function(a,c){var d;if(this.p.deepempty)b(this.rows).slice(1).remove();else{d=this.rows.length>0?this.rows[0]:null;b(this.firstChild).empty().append(d)}if(a&&this.p.scroll){b(this.grid.bDiv.firstChild).css({height:"auto"});b(this.grid.bDiv.firstChild.firstChild).css({height:0,display:"none"});if(this.grid.bDiv.scrollTop!==0)this.grid.bDiv.scrollTop=
+0}if(c===true&&this.p.treeGrid){this.p.data=[];this.p._index={}}},N=function(){var c=a.p.data.length,d,e,g;d=a.p.rownumbers===true?1:0;e=a.p.multiselect===true?1:0;g=a.p.subGrid===true?1:0;d=a.p.keyIndex===false||a.p.loadonce===true?a.p.localReader.id:a.p.colModel[a.p.keyIndex+e+g+d].name;for(e=0;e<c;e++){g=b.jgrid.getAccessor(a.p.data[e],d);g===void 0&&(g=""+(e+1));a.p._index[g]=e}},X=function(c,d,e,g,f,h){var j="-1",i="",k,d=d?"display:none;":"",e="ui-widget-content jqgrow ui-row-"+a.p.direction+
+(e?" "+e:"")+(h?" ui-state-highlight":""),h=b(a).triggerHandler("jqGridRowAttr",[g,f,c]);typeof h!=="object"&&(h=b.isFunction(a.p.rowattr)?a.p.rowattr.call(a,g,f,c):{});if(!b.isEmptyObject(h)){if(h.hasOwnProperty("id")){c=h.id;delete h.id}if(h.hasOwnProperty("tabindex")){j=h.tabindex;delete h.tabindex}if(h.hasOwnProperty("style")){d=d+h.style;delete h.style}if(h.hasOwnProperty("class")){e=e+(" "+h["class"]);delete h["class"]}try{delete h.role}catch(F){}for(k in h)h.hasOwnProperty(k)&&(i=i+(" "+k+
+"="+h[k]))}return'<tr role="row" id="'+c+'" tabindex="'+j+'" class="'+e+'"'+(d===""?"":' style="'+d+'"')+i+">"},J=function(c,d,e,g,f){var h=new Date,j=a.p.datatype!=="local"&&a.p.loadonce||a.p.datatype==="xmlstring",i=a.p.xmlReader,k=a.p.datatype==="local"?"local":"xml";if(j){a.p.data=[];a.p._index={};a.p.localReader.id="_id_"}a.p.reccount=0;if(b.isXMLDoc(c)){if(a.p.treeANode===-1&&!a.p.scroll){V.call(a,false,true);e=1}else e=e>1?e:1;var F=b(a),y,G,l=0,o,s=a.p.multiselect===true?1:0,u=0,n,m=a.p.rownumbers===
+true?1:0,t,p=[],E,q={},x,D,r=[],K=a.p.altRows===true?a.p.altclass:"",v;if(a.p.subGrid===true){u=1;n=b.jgrid.getMethod("addSubGridCell")}i.repeatitems||(p=$(k));t=a.p.keyIndex===false?b.isFunction(i.id)?i.id.call(a,c):i.id:a.p.keyIndex;if(p.length>0&&!isNaN(t)){a.p.remapColumns&&a.p.remapColumns.length&&(t=b.inArray(t,a.p.remapColumns));t=p[t]}k=(""+t).indexOf("[")===-1?p.length?function(a,c){return b(t,a).text()||c}:function(a,c){return b(i.cell,a).eq(t).text()||c}:function(a,b){return a.getAttribute(t.replace(/[\[\]]/g,
+""))||b};a.p.userData={};a.p.page=b.jgrid.getXmlData(c,i.page)||a.p.page||0;a.p.lastpage=b.jgrid.getXmlData(c,i.total);if(a.p.lastpage===void 0)a.p.lastpage=1;a.p.records=b.jgrid.getXmlData(c,i.records)||0;b.isFunction(i.userdata)?a.p.userData=i.userdata.call(a,c)||{}:b.jgrid.getXmlData(c,i.userdata,true).each(function(){a.p.userData[this.getAttribute("name")]=b(this).text()});c=b.jgrid.getXmlData(c,i.root,true);(c=b.jgrid.getXmlData(c,i.row,true))||(c=[]);var w=c.length,L=0,B=[],C=parseInt(a.p.rowNum,
+10),H=a.p.scroll?b.jgrid.randId():1;if(w>0&&a.p.page<=0)a.p.page=1;if(c&&w){f&&(C=C*(f+1));var f=b.isFunction(a.p.afterInsertRow),J=false,I;if(a.p.grouping){J=a.p.groupingView.groupCollapse===true;I=b.jgrid.getMethod("groupingPrepare")}for(;L<w;){x=c[L];D=k(x,H+L);D=a.p.idPrefix+D;y=e===0?0:e+1;v=(y+L)%2===1?K:"";var O=r.length;r.push("");m&&r.push(M(0,L,a.p.page,a.p.rowNum));s&&r.push(T(D,m,L,false));u&&r.push(n.call(F,s+m,L+e));if(i.repeatitems){E||(E=U(s+u+m));var N=b.jgrid.getXmlData(x,i.cell,
+true);b.each(E,function(b){var c=N[this];if(!c)return false;o=c.textContent||c.text;q[a.p.colModel[b+s+u+m].name]=o;r.push(A(D,o,b+s+u+m,L+e,x,q))})}else for(y=0;y<p.length;y++){o=b.jgrid.getXmlData(x,p[y]);q[a.p.colModel[y+s+u+m].name]=o;r.push(A(D,o,y+s+u+m,L+e,x,q))}r[O]=X(D,J,v,q,x,false);r.push("</tr>");if(a.p.grouping){B=I.call(F,r,B,q,L);r=[]}if(j||a.p.treeGrid===true){q._id_=b.jgrid.stripPref(a.p.idPrefix,D);a.p.data.push(q);a.p._index[q._id_]=a.p.data.length-1}if(a.p.gridview===false){b("tbody:first",
+d).append(r.join(""));F.triggerHandler("jqGridAfterInsertRow",[D,q,x]);f&&a.p.afterInsertRow.call(a,D,q,x);r=[]}q={};l++;L++;if(l===C)break}}if(a.p.gridview===true){G=a.p.treeANode>-1?a.p.treeANode:0;if(a.p.grouping){F.jqGrid("groupingRender",B,a.p.colModel.length);B=null}else a.p.treeGrid===true&&G>0?b(a.rows[G]).after(r.join("")):b("tbody:first",d).append(r.join(""))}if(a.p.subGrid===true)try{F.jqGrid("addSubGrid",s+m)}catch(Q){}a.p.totaltime=new Date-h;if(l>0&&a.p.records===0)a.p.records=w;r=null;
+if(a.p.treeGrid===true)try{F.jqGrid("setTreeNode",G+1,l+G+1)}catch(S){}if(!a.p.treeGrid&&!a.p.scroll)a.grid.bDiv.scrollTop=0;a.p.reccount=l;a.p.treeANode=-1;a.p.userDataOnFooter&&F.jqGrid("footerData","set",a.p.userData,true);if(j){a.p.records=w;a.p.lastpage=Math.ceil(w/C)}g||a.updatepager(false,true);if(j)for(;l<w;){x=c[l];D=k(x,l+H);D=a.p.idPrefix+D;if(i.repeatitems){E||(E=U(s+u+m));var P=b.jgrid.getXmlData(x,i.cell,true);b.each(E,function(b){var c=P[this];if(!c)return false;o=c.textContent||c.text;
+q[a.p.colModel[b+s+u+m].name]=o})}else for(y=0;y<p.length;y++){o=b.jgrid.getXmlData(x,p[y]);q[a.p.colModel[y+s+u+m].name]=o}q._id_=b.jgrid.stripPref(a.p.idPrefix,D);a.p.data.push(q);a.p._index[q._id_]=a.p.data.length-1;q={};l++}}},S=function(c,d,e,g,f){var h=new Date;if(c){if(a.p.treeANode===-1&&!a.p.scroll){V.call(a,false,true);e=1}else e=e>1?e:1;var i,j=a.p.datatype!=="local"&&a.p.loadonce||a.p.datatype==="jsonstring";if(j){a.p.data=[];a.p._index={};a.p.localReader.id="_id_"}a.p.reccount=0;if(a.p.datatype===
+"local"){d=a.p.localReader;i="local"}else{d=a.p.jsonReader;i="json"}var k=b(a),l=0,y,o,n,m=[],s=a.p.multiselect?1:0,u=a.p.subGrid===true?1:0,t,p=a.p.rownumbers===true?1:0,w=U(s+u+p);i=$(i);var v,E,q,x={},D,r,K=[],B=a.p.altRows===true?a.p.altclass:"",C;a.p.page=b.jgrid.getAccessor(c,d.page)||a.p.page||0;E=b.jgrid.getAccessor(c,d.total);u&&(t=b.jgrid.getMethod("addSubGridCell"));a.p.lastpage=E===void 0?1:E;a.p.records=b.jgrid.getAccessor(c,d.records)||0;a.p.userData=b.jgrid.getAccessor(c,d.userdata)||
+{};q=a.p.keyIndex===false?b.isFunction(d.id)?d.id.call(a,c):d.id:a.p.keyIndex;if(!d.repeatitems){m=i;if(m.length>0&&!isNaN(q)){a.p.remapColumns&&a.p.remapColumns.length&&(q=b.inArray(q,a.p.remapColumns));q=m[q]}}E=b.jgrid.getAccessor(c,d.root);E==null&&b.isArray(c)&&(E=c);E||(E=[]);c=E.length;o=0;if(c>0&&a.p.page<=0)a.p.page=1;var L=parseInt(a.p.rowNum,10),H=a.p.scroll?b.jgrid.randId():1,J=false,I;f&&(L=L*(f+1));a.p.datatype==="local"&&!a.p.deselectAfterSort&&(J=true);var O=b.isFunction(a.p.afterInsertRow),
+N=[],P=false,Q;if(a.p.grouping){P=a.p.groupingView.groupCollapse===true;Q=b.jgrid.getMethod("groupingPrepare")}for(;o<c;){f=E[o];r=b.jgrid.getAccessor(f,q);if(r===void 0){typeof q==="number"&&a.p.colModel[q+s+u+p]!=null&&(r=b.jgrid.getAccessor(f,a.p.colModel[q+s+u+p].name));if(r===void 0){r=H+o;if(m.length===0&&d.cell){y=b.jgrid.getAccessor(f,d.cell)||f;r=y!=null&&y[q]!==void 0?y[q]:r}}}r=a.p.idPrefix+r;y=e===1?0:e;C=(y+o)%2===1?B:"";J&&(I=a.p.multiselect?b.inArray(r,a.p.selarrrow)!==-1:r===a.p.selrow);
+var S=K.length;K.push("");p&&K.push(M(0,o,a.p.page,a.p.rowNum));s&&K.push(T(r,p,o,I));u&&K.push(t.call(k,s+p,o+e));v=i;if(d.repeatitems){d.cell&&(f=b.jgrid.getAccessor(f,d.cell)||f);b.isArray(f)&&(v=w)}for(n=0;n<v.length;n++){y=b.jgrid.getAccessor(f,v[n]);x[a.p.colModel[n+s+u+p].name]=y;K.push(A(r,y,n+s+u+p,o+e,f,x))}K[S]=X(r,P,C,x,f,I);K.push("</tr>");if(a.p.grouping){N=Q.call(k,K,N,x,o);K=[]}if(j||a.p.treeGrid===true){x._id_=b.jgrid.stripPref(a.p.idPrefix,r);a.p.data.push(x);a.p._index[x._id_]=
+a.p.data.length-1}if(a.p.gridview===false){b("#"+b.jgrid.jqID(a.p.id)+" tbody:first").append(K.join(""));k.triggerHandler("jqGridAfterInsertRow",[r,x,f]);O&&a.p.afterInsertRow.call(a,r,x,f);K=[]}x={};l++;o++;if(l===L)break}if(a.p.gridview===true){D=a.p.treeANode>-1?a.p.treeANode:0;a.p.grouping?k.jqGrid("groupingRender",N,a.p.colModel.length):a.p.treeGrid===true&&D>0?b(a.rows[D]).after(K.join("")):b("#"+b.jgrid.jqID(a.p.id)+" tbody:first").append(K.join(""))}if(a.p.subGrid===true)try{k.jqGrid("addSubGrid",
+s+p)}catch(aa){}a.p.totaltime=new Date-h;if(l>0&&a.p.records===0)a.p.records=c;if(a.p.treeGrid===true)try{k.jqGrid("setTreeNode",D+1,l+D+1)}catch(W){}if(!a.p.treeGrid&&!a.p.scroll)a.grid.bDiv.scrollTop=0;a.p.reccount=l;a.p.treeANode=-1;a.p.userDataOnFooter&&k.jqGrid("footerData","set",a.p.userData,true);if(j){a.p.records=c;a.p.lastpage=Math.ceil(c/L)}g||a.updatepager(false,true);if(j)for(;l<c&&E[l];){f=E[l];r=b.jgrid.getAccessor(f,q);if(r===void 0){typeof q==="number"&&a.p.colModel[q+s+u+p]!=null&&
+(r=b.jgrid.getAccessor(f,a.p.colModel[q+s+u+p].name));if(r===void 0){r=H+l;if(m.length===0&&d.cell){e=b.jgrid.getAccessor(f,d.cell)||f;r=e!=null&&e[q]!==void 0?e[q]:r}}}if(f){r=a.p.idPrefix+r;v=i;if(d.repeatitems){d.cell&&(f=b.jgrid.getAccessor(f,d.cell)||f);b.isArray(f)&&(v=w)}for(n=0;n<v.length;n++)x[a.p.colModel[n+s+u+p].name]=b.jgrid.getAccessor(f,v[n]);x._id_=b.jgrid.stripPref(a.p.idPrefix,r);a.p.data.push(x);a.p._index[x._id_]=a.p.data.length-1;x={}}l++}}},ja=function(){function c(a){var b=
+0,d,e,g,h,i;if(a.groups!=null){(e=a.groups.length&&a.groupOp.toString().toUpperCase()==="OR")&&s.orBegin();for(d=0;d<a.groups.length;d++){b>0&&e&&s.or();try{c(a.groups[d])}catch(j){alert(j)}b++}e&&s.orEnd()}if(a.rules!=null)try{(g=a.rules.length&&a.groupOp.toString().toUpperCase()==="OR")&&s.orBegin();for(d=0;d<a.rules.length;d++){i=a.rules[d];h=a.groupOp.toString().toUpperCase();if(p[i.op]&&i.field){b>0&&h&&h==="OR"&&(s=s.or());s=p[i.op](s,h)(i.field,i.data,f[i.field])}b++}g&&s.orEnd()}catch(qa){alert(qa)}}
+var d=a.p.multiSort?[]:"",e=[],g=false,f={},h=[],i=[],j,k,l;if(b.isArray(a.p.data)){var o=a.p.grouping?a.p.groupingView:false,n,m;b.each(a.p.colModel,function(){k=this.sorttype||"text";if(k==="date"||k==="datetime"){if(this.formatter&&typeof this.formatter==="string"&&this.formatter==="date"){j=this.formatoptions&&this.formatoptions.srcformat?this.formatoptions.srcformat:b.jgrid.formatter.date.srcformat;l=this.formatoptions&&this.formatoptions.newformat?this.formatoptions.newformat:b.jgrid.formatter.date.newformat}else j=
+l=this.datefmt||"Y-m-d";f[this.name]={stype:k,srcfmt:j,newfmt:l}}else f[this.name]={stype:k,srcfmt:"",newfmt:""};if(a.p.grouping){m=0;for(n=o.groupField.length;m<n;m++)if(this.name===o.groupField[m]){var c=this.name;if(this.index)c=this.index;h[m]=f[c];i[m]=c}}if(a.p.multiSort){if(this.lso){d.push(this.name);c=this.lso.split("-");e.push(c[c.length-1])}}else if(!g&&(this.index===a.p.sortname||this.name===a.p.sortname)){d=this.name;g=true}});if(a.p.treeGrid)b(a).jqGrid("SortTree",d,a.p.sortorder,f[d].stype,
+f[d].srcfmt);else{var p={eq:function(a){return a.equals},ne:function(a){return a.notEquals},lt:function(a){return a.less},le:function(a){return a.lessOrEquals},gt:function(a){return a.greater},ge:function(a){return a.greaterOrEquals},cn:function(a){return a.contains},nc:function(a,b){return b==="OR"?a.orNot().contains:a.andNot().contains},bw:function(a){return a.startsWith},bn:function(a,b){return b==="OR"?a.orNot().startsWith:a.andNot().startsWith},en:function(a,b){return b==="OR"?a.orNot().endsWith:
+a.andNot().endsWith},ew:function(a){return a.endsWith},ni:function(a,b){return b==="OR"?a.orNot().equals:a.andNot().equals},"in":function(a){return a.equals},nu:function(a){return a.isNull},nn:function(a,b){return b==="OR"?a.orNot().isNull:a.andNot().isNull}},s=b.jgrid.from(a.p.data);a.p.ignoreCase&&(s=s.ignoreCase());if(a.p.search===true){var u=a.p.postData.filters;if(u){typeof u==="string"&&(u=b.jgrid.parse(u));c(u)}else try{s=p[a.p.postData.searchOper](s)(a.p.postData.searchField,a.p.postData.searchString,
+f[a.p.postData.searchField])}catch(t){}}if(a.p.grouping)for(m=0;m<n;m++)s.orderBy(i[m],o.groupOrder[m],h[m].stype,h[m].srcfmt);a.p.multiSort?b.each(d,function(a){s.orderBy(this,e[a],f[this].stype,f[this].srcfmt)}):d&&a.p.sortorder&&g&&(a.p.sortorder.toUpperCase()==="DESC"?s.orderBy(a.p.sortname,"d",f[d].stype,f[d].srcfmt):s.orderBy(a.p.sortname,"a",f[d].stype,f[d].srcfmt));var u=s.select(),v=parseInt(a.p.rowNum,10),w=u.length,A=parseInt(a.p.page,10),B=Math.ceil(w/v),q={},u=u.slice((A-1)*v,A*v),f=
+s=null;q[a.p.localReader.total]=B;q[a.p.localReader.page]=A;q[a.p.localReader.records]=w;q[a.p.localReader.root]=u;q[a.p.localReader.userdata]=a.p.userData;u=null;return q}}},aa=function(){a.grid.hDiv.loading=true;if(!a.p.hiddengrid)switch(a.p.loadui){case "enable":b("#load_"+b.jgrid.jqID(a.p.id)).show();break;case "block":b("#lui_"+b.jgrid.jqID(a.p.id)).show();b("#load_"+b.jgrid.jqID(a.p.id)).show()}},P=function(){a.grid.hDiv.loading=false;switch(a.p.loadui){case "enable":b("#load_"+b.jgrid.jqID(a.p.id)).hide();
+break;case "block":b("#lui_"+b.jgrid.jqID(a.p.id)).hide();b("#load_"+b.jgrid.jqID(a.p.id)).hide()}},O=function(c){if(!a.grid.hDiv.loading){var d=a.p.scroll&&c===false,e={},g,f=a.p.prmNames;if(a.p.page<=0)a.p.page=1;if(f.search!==null)e[f.search]=a.p.search;f.nd!==null&&(e[f.nd]=(new Date).getTime());if(f.rows!==null)e[f.rows]=a.p.rowNum;if(f.page!==null)e[f.page]=a.p.page;if(f.sort!==null)e[f.sort]=a.p.sortname;if(f.order!==null)e[f.order]=a.p.sortorder;if(a.p.rowTotal!==null&&f.totalrows!==null)e[f.totalrows]=
+a.p.rowTotal;var h=b.isFunction(a.p.loadComplete),i=h?a.p.loadComplete:null,j=0,c=c||1;if(c>1)if(f.npage!==null){e[f.npage]=c;j=c-1;c=1}else i=function(b){a.p.page++;a.grid.hDiv.loading=false;h&&a.p.loadComplete.call(a,b);O(c-1)};else f.npage!==null&&delete a.p.postData[f.npage];if(a.p.grouping){b(a).jqGrid("groupingSetup");var k=a.p.groupingView,l,o="";for(l=0;l<k.groupField.length;l++){var m=k.groupField[l];b.each(a.p.colModel,function(a,b){if(b.name===m&&b.index)m=b.index});o=o+(m+" "+k.groupOrder[l]+
+", ")}e[f.sort]=o+e[f.sort]}b.extend(a.p.postData,e);var n=!a.p.scroll?1:a.rows.length-1,e=b(a).triggerHandler("jqGridBeforeRequest");if(!(e===false||e==="stop"))if(b.isFunction(a.p.datatype))a.p.datatype.call(a,a.p.postData,"load_"+a.p.id);else{if(b.isFunction(a.p.beforeRequest)){e=a.p.beforeRequest.call(a);e===void 0&&(e=true);if(e===false)return}g=a.p.datatype.toLowerCase();switch(g){case "json":case "jsonp":case "xml":case "script":b.ajax(b.extend({url:a.p.url,type:a.p.mtype,dataType:g,data:b.isFunction(a.p.serializeGridData)?
+a.p.serializeGridData.call(a,a.p.postData):a.p.postData,success:function(e,f,h){if(b.isFunction(a.p.beforeProcessing)&&a.p.beforeProcessing.call(a,e,f,h)===false)P();else{g==="xml"?J(e,a.grid.bDiv,n,c>1,j):S(e,a.grid.bDiv,n,c>1,j);b(a).triggerHandler("jqGridLoadComplete",[e]);i&&i.call(a,e);b(a).triggerHandler("jqGridAfterLoadComplete",[e]);d&&a.grid.populateVisible();if(a.p.loadonce||a.p.treeGrid)a.p.datatype="local";c===1&&P()}},error:function(d,e,f){b.isFunction(a.p.loadError)&&a.p.loadError.call(a,
+d,e,f);c===1&&P()},beforeSend:function(c,d){var e=true;b.isFunction(a.p.loadBeforeSend)&&(e=a.p.loadBeforeSend.call(a,c,d));e===void 0&&(e=true);if(e===false)return false;aa()}},b.jgrid.ajaxOptions,a.p.ajaxGridOptions));break;case "xmlstring":aa();e=typeof a.p.datastr!=="string"?a.p.datastr:b.parseXML(a.p.datastr);J(e,a.grid.bDiv);b(a).triggerHandler("jqGridLoadComplete",[e]);h&&a.p.loadComplete.call(a,e);b(a).triggerHandler("jqGridAfterLoadComplete",[e]);a.p.datatype="local";a.p.datastr=null;P();
+break;case "jsonstring":aa();e=typeof a.p.datastr==="string"?b.jgrid.parse(a.p.datastr):a.p.datastr;S(e,a.grid.bDiv);b(a).triggerHandler("jqGridLoadComplete",[e]);h&&a.p.loadComplete.call(a,e);b(a).triggerHandler("jqGridAfterLoadComplete",[e]);a.p.datatype="local";a.p.datastr=null;P();break;case "local":case "clientside":aa();a.p.datatype="local";e=ja();S(e,a.grid.bDiv,n,c>1,j);b(a).triggerHandler("jqGridLoadComplete",[e]);i&&i.call(a,e);b(a).triggerHandler("jqGridAfterLoadComplete",[e]);d&&a.grid.populateVisible();
+P()}}}},ca=function(c){b("#cb_"+b.jgrid.jqID(a.p.id),a.grid.hDiv)[a.p.useProp?"prop":"attr"]("checked",c);if(a.p.frozenColumns&&a.p.id+"_frozen")b("#cb_"+b.jgrid.jqID(a.p.id),a.grid.fhDiv)[a.p.useProp?"prop":"attr"]("checked",c)},ka=function(c,d){var e="",g="<table cellspacing='0' cellpadding='0' border='0' style='table-layout:auto;' class='ui-pg-table'><tbody><tr>",i="",j,k,l,m,n=function(c){var d;b.isFunction(a.p.onPaging)&&(d=a.p.onPaging.call(a,c));a.p.selrow=null;if(a.p.multiselect){a.p.selarrrow=
+[];ca(false)}a.p.savedRow=[];return d==="stop"?false:true},c=c.substr(1),d=d+("_"+c);j="pg_"+c;k=c+"_left";l=c+"_center";m=c+"_right";b("#"+b.jgrid.jqID(c)).append("<div id='"+j+"' class='ui-pager-control' role='group'><table cellspacing='0' cellpadding='0' border='0' class='ui-pg-table' style='width:100%;table-layout:fixed;height:100%;' role='row'><tbody><tr><td id='"+k+"' align='left'></td><td id='"+l+"' align='center' style='white-space:pre;'></td><td id='"+m+"' align='right'></td></tr></tbody></table></div>").attr("dir",
+"ltr");if(a.p.rowList.length>0){i="<td dir='"+f+"'>";i=i+"<select class='ui-pg-selbox' role='listbox'>";for(k=0;k<a.p.rowList.length;k++)i=i+('<option role="option" value="'+a.p.rowList[k]+'"'+(a.p.rowNum===a.p.rowList[k]?' selected="selected"':"")+">"+a.p.rowList[k]+"</option>");i=i+"</select></td>"}f==="rtl"&&(g=g+i);a.p.pginput===true&&(e="<td dir='"+f+"'>"+b.jgrid.format(a.p.pgtext||"","<input class='ui-pg-input' type='text' size='2' maxlength='7' value='0' role='textbox'/>","<span id='sp_1_"+
+b.jgrid.jqID(c)+"'></span>")+"</td>");if(a.p.pgbuttons===true){k=["first"+d,"prev"+d,"next"+d,"last"+d];f==="rtl"&&k.reverse();g=g+("<td id='"+k[0]+"' class='ui-pg-button ui-corner-all'><span class='ui-icon ui-icon-seek-first'></span></td>");g=g+("<td id='"+k[1]+"' class='ui-pg-button ui-corner-all'><span class='ui-icon ui-icon-seek-prev'></span></td>");g=g+(e!==""?"<td class='ui-pg-button ui-state-disabled' style='width:4px;'><span class='ui-separator'></span></td>"+e+"<td class='ui-pg-button ui-state-disabled' style='width:4px;'><span class='ui-separator'></span></td>":
+"")+("<td id='"+k[2]+"' class='ui-pg-button ui-corner-all'><span class='ui-icon ui-icon-seek-next'></span></td>");g=g+("<td id='"+k[3]+"' class='ui-pg-button ui-corner-all'><span class='ui-icon ui-icon-seek-end'></span></td>")}else e!==""&&(g=g+e);f==="ltr"&&(g=g+i);g=g+"</tr></tbody></table>";a.p.viewrecords===true&&b("td#"+c+"_"+a.p.recordpos,"#"+j).append("<div dir='"+f+"' style='text-align:"+a.p.recordpos+"' class='ui-paging-info'></div>");b("td#"+c+"_"+a.p.pagerpos,"#"+j).append(g);i=b(".ui-jqgrid").css("font-size")||
+"11px";b(document.body).append("<div id='testpg' class='ui-jqgrid ui-widget ui-widget-content' style='font-size:"+i+";visibility:hidden;' ></div>");g=b(g).clone().appendTo("#testpg").width();b("#testpg").remove();if(g>0){e!==""&&(g=g+50);b("td#"+c+"_"+a.p.pagerpos,"#"+j).width(g)}a.p._nvtd=[];a.p._nvtd[0]=g?Math.floor((a.p.width-g)/2):Math.floor(a.p.width/3);a.p._nvtd[1]=0;g=null;b(".ui-pg-selbox","#"+j).bind("change",function(){if(!n("records"))return false;a.p.page=Math.round(a.p.rowNum*(a.p.page-
 1)/this.value-0.5)+1;a.p.rowNum=this.value;a.p.pager&&b(".ui-pg-selbox",a.p.pager).val(this.value);a.p.toppager&&b(".ui-pg-selbox",a.p.toppager).val(this.value);O();return false});if(a.p.pgbuttons===true){b(".ui-pg-button","#"+j).hover(function(){if(b(this).hasClass("ui-state-disabled"))this.style.cursor="default";else{b(this).addClass("ui-state-hover");this.style.cursor="pointer"}},function(){if(!b(this).hasClass("ui-state-disabled")){b(this).removeClass("ui-state-hover");this.style.cursor="default"}});
-b("#first"+b.jgrid.jqID(d)+", #prev"+b.jgrid.jqID(d)+", #next"+b.jgrid.jqID(d)+", #last"+b.jgrid.jqID(d)).click(function(){var b=n(a.p.page,1),c=n(a.p.lastpage,1),e=false,f=true,g=true,h=true,i=true;if(c===0||c===1)i=h=g=f=false;else if(c>1&&b>=1)if(b===1)g=f=false;else{if(b===c)i=h=false}else if(c>1&&b===0){i=h=false;b=c-1}if(!o(this.id))return false;if(this.id==="first"+d&&f){a.p.page=1;e=true}if(this.id==="prev"+d&&g){a.p.page=b-1;e=true}if(this.id==="next"+d&&h){a.p.page=b+1;e=true}if(this.id===
-"last"+d&&i){a.p.page=c;e=true}e&&O();return false})}a.p.pginput===true&&b("input.ui-pg-input","#"+j).keypress(function(c){if((c.charCode||c.keyCode||0)===13){if(!o("user"))return false;b(this).val(n(b(this).val(),1));a.p.page=b(this).val()>0?b(this).val():a.p.page;O();return false}return this})},ra=function(c){var d,e="",f=a.p.colModel,g=false,h=a.grid.headers[c].el,i="";b("span.ui-grid-ico-sort",h).addClass("ui-state-disabled");b(h).attr("aria-selected","false");if(f[c].lso)if(f[c].lso==="asc"){f[c].lso=
-f[c].lso+"-desc";i="desc"}else if(f[c].lso==="desc"){f[c].lso=f[c].lso+"-asc";i="asc"}else{if(f[c].lso==="asc-desc"||f[c].lso==="desc-asc")f[c].lso=""}else f[c].lso=i=f.firstsortorder||"asc";if(i){b("span.s-ico",h).show();b("span.ui-icon-"+i,h).removeClass("ui-state-disabled");b(h).attr("aria-selected","true")}else a.p.viewsortcols[0]||b("span.s-ico",h).hide();a.p.sortorder="";b.each(f,function(b){if(this.lso){b>0&&g&&(e=e+", ");d=this.lso.split("-");e=e+(f[b].index||f[b].name);e=e+(" "+d[d.length-
-1]);g=true;a.p.sortorder=d[d.length-1]}});c=e.lastIndexOf(a.p.sortorder);e=e.substring(0,c);a.p.sortname=e},ka=function(c,d,e,f){if(a.p.colModel[d].sortable){var g;if(!(a.p.savedRow.length>0)){if(!e){if(a.p.lastsort===d)if(a.p.sortorder==="asc")a.p.sortorder="desc";else{if(a.p.sortorder==="desc")a.p.sortorder="asc"}else a.p.sortorder=a.p.colModel[d].firstsortorder||"asc";a.p.page=1}if(a.p.multiSort)ra(d,e,g);else{if(f){if(a.p.lastsort===d&&a.p.sortorder===f&&!e)return;a.p.sortorder=f}e=a.grid.headers[a.p.lastsort].el;
-f=a.grid.headers[d].el;b("span.ui-grid-ico-sort",e).addClass("ui-state-disabled");b(e).attr("aria-selected","false");b("span.ui-icon-"+a.p.sortorder,f).removeClass("ui-state-disabled");b(f).attr("aria-selected","true");if(!a.p.viewsortcols[0]&&a.p.lastsort!==d){b("span.s-ico",e).hide();b("span.s-ico",f).show()}c=c.substring(5+a.p.id.length+1);a.p.sortname=a.p.colModel[d].index||c;g=a.p.sortorder}if(b(a).triggerHandler("jqGridSortCol",[c,d,g])==="stop")a.p.lastsort=d;else if(b.isFunction(a.p.onSortCol)&&
-a.p.onSortCol.call(a,c,d,g)==="stop")a.p.lastsort=d;else{if(a.p.datatype==="local")a.p.deselectAfterSort&&b(a).jqGrid("resetSelection");else{a.p.selrow=null;a.p.multiselect&&ba(false);a.p.selarrrow=[];a.p.savedRow=[]}if(a.p.scroll){e=a.grid.bDiv.scrollLeft;U.call(a,true,false);a.grid.hDiv.scrollLeft=e}a.p.subGrid&&a.p.datatype==="local"&&b("td.sgexpanded","#"+b.jgrid.jqID(a.p.id)).each(function(){b(this).trigger("click")});O();a.p.lastsort=d;if(a.p.sortname!==c&&d)a.p.lastsort=d}}}},sa=function(c){c=
-b(a.grid.headers[c].el);c=[c.position().left+c.outerWidth()];a.p.direction==="rtl"&&(c[0]=a.p.width-c[0]);c[0]=c[0]-a.grid.bDiv.scrollLeft;c.push(b(a.grid.hDiv).position().top);c.push(b(a.grid.bDiv).offset().top-b(a.grid.hDiv).offset().top+b(a.grid.bDiv).height());return c},la=function(c){var d,e=a.grid.headers,f=b.jgrid.getCellIndex(c);for(d=0;d<e.length;d++)if(c===e[d].el){f=d;break}return f};this.p.id=this.id;-1===b.inArray(a.p.multikey,["shiftKey","altKey","ctrlKey"])&&(a.p.multikey=!1);a.p.keyIndex=
-!1;for(f=0;f<a.p.colModel.length;f++)a.p.colModel[f]=b.extend(!0,{},a.p.cmTemplate,a.p.colModel[f].template||{},a.p.colModel[f]),!1===a.p.keyIndex&&!0===a.p.colModel[f].key&&(a.p.keyIndex=f);a.p.sortorder=a.p.sortorder.toLowerCase();b.jgrid.cell_width=b.jgrid.cellWidth();!0===a.p.grouping&&(a.p.scroll=!1,a.p.rownumbers=!1,a.p.treeGrid=!1,a.p.gridview=!0);if(!0===this.p.treeGrid){try{b(this).jqGrid("setTreeGrid")}catch(ua){}"local"!==a.p.datatype&&(a.p.localReader={id:"_id_"})}if(this.p.subGrid)try{b(a).jqGrid("setSubGrid")}catch(va){}this.p.multiselect&&
-(this.p.colNames.unshift("<input role='checkbox' id='cb_"+this.p.id+"' class='cbox' type='checkbox'/>"),this.p.colModel.unshift({name:"cb",width:b.jgrid.cell_width?a.p.multiselectWidth+a.p.cellLayout:a.p.multiselectWidth,sortable:!1,resizable:!1,hidedlg:!0,search:!1,align:"center",fixed:!0}));this.p.rownumbers&&(this.p.colNames.unshift(""),this.p.colModel.unshift({name:"rn",width:a.p.rownumWidth,sortable:!1,resizable:!1,hidedlg:!0,search:!1,align:"center",fixed:!0}));a.p.xmlReader=b.extend(!0,{root:"rows",
-row:"row",page:"rows>page",total:"rows>total",records:"rows>records",repeatitems:!0,cell:"cell",id:"[id]",userdata:"userdata",subgrid:{root:"rows",row:"row",repeatitems:!0,cell:"cell"}},a.p.xmlReader);a.p.jsonReader=b.extend(!0,{root:"rows",page:"page",total:"total",records:"records",repeatitems:!0,cell:"cell",id:"id",userdata:"userdata",subgrid:{root:"rows",repeatitems:!0,cell:"cell"}},a.p.jsonReader);a.p.localReader=b.extend(!0,{root:"rows",page:"page",total:"total",records:"records",repeatitems:!1,
-cell:"cell",id:"id",userdata:"userdata",subgrid:{root:"rows",repeatitems:!0,cell:"cell"}},a.p.localReader);a.p.scroll&&(a.p.pgbuttons=!1,a.p.pginput=!1,a.p.rowList=[]);a.p.data.length&&N();var C="<thead><tr class='ui-jqgrid-labels' role='rowheader'>",ma,D,ca,da,ea,t,u,V,na=V="",aa=[],oa=[];D=[];if(!0===a.p.shrinkToFit&&!0===a.p.forceFit)for(f=a.p.colModel.length-1;0<=f;f--)if(!a.p.colModel[f].hidden){a.p.colModel[f].resizable=!1;break}"horizontal"===a.p.viewsortcols[1]&&(V=" ui-i-asc",na=" ui-i-desc");
-ma=k?"class='ui-th-div-ie'":"";V="<span class='s-ico' style='display:none'><span sort='asc' class='ui-grid-ico-sort ui-icon-asc"+V+" ui-state-disabled ui-icon ui-icon-triangle-1-n ui-sort-"+g+"'></span>"+("<span sort='desc' class='ui-grid-ico-sort ui-icon-desc"+na+" ui-state-disabled ui-icon ui-icon-triangle-1-s ui-sort-"+g+"'></span></span>");if(a.p.multiSort){aa=a.p.sortname.split(",");for(f=0;f<aa.length;f++)D=b.trim(aa[f]).split(" "),aa[f]=b.trim(D[0]),oa[f]=D[1]?b.trim(D[1]):a.p.sortorder||"asc"}for(f=
-0;f<this.p.colNames.length;f++)D=a.p.headertitles?' title="'+b.jgrid.stripHtml(a.p.colNames[f])+'"':"",C+="<th id='"+a.p.id+"_"+a.p.colModel[f].name+"' role='columnheader' class='ui-state-default ui-th-column ui-th-"+g+"'"+D+">",D=a.p.colModel[f].index||a.p.colModel[f].name,C+="<div id='jqgh_"+a.p.id+"_"+a.p.colModel[f].name+"' "+ma+">"+a.p.colNames[f],a.p.colModel[f].width=a.p.colModel[f].width?parseInt(a.p.colModel[f].width,10):150,"boolean"!==typeof a.p.colModel[f].title&&(a.p.colModel[f].title=
-!0),a.p.colModel[f].lso="",D===a.p.sortname&&(a.p.lastsort=f),a.p.multiSort&&(D=b.inArray(D,aa),-1!==D&&(a.p.colModel[f].lso=oa[D])),C+=V+"</div></th>";V=null;b(this).append(C+"</tr></thead>");b("thead tr:first th",this).hover(function(){b(this).addClass("ui-state-hover")},function(){b(this).removeClass("ui-state-hover")});if(this.p.multiselect){var fa=[],X;b("#cb_"+b.jgrid.jqID(a.p.id),this).bind("click",function(){a.p.selarrrow=[];var c=a.p.frozenColumns===true?a.p.id+"_frozen":"";if(this.checked){b(a.rows).each(function(d){if(d>
-0&&!b(this).hasClass("ui-subgrid")&&!b(this).hasClass("jqgroup")&&!b(this).hasClass("ui-state-disabled")){b("#jqg_"+b.jgrid.jqID(a.p.id)+"_"+b.jgrid.jqID(this.id))[a.p.useProp?"prop":"attr"]("checked",true);b(this).addClass("ui-state-highlight").attr("aria-selected","true");a.p.selarrrow.push(this.id);a.p.selrow=this.id;if(c){b("#jqg_"+b.jgrid.jqID(a.p.id)+"_"+b.jgrid.jqID(this.id),a.grid.fbDiv)[a.p.useProp?"prop":"attr"]("checked",true);b("#"+b.jgrid.jqID(this.id),a.grid.fbDiv).addClass("ui-state-highlight")}}});
-X=true;fa=[]}else{b(a.rows).each(function(d){if(d>0&&!b(this).hasClass("ui-subgrid")&&!b(this).hasClass("ui-state-disabled")){b("#jqg_"+b.jgrid.jqID(a.p.id)+"_"+b.jgrid.jqID(this.id))[a.p.useProp?"prop":"attr"]("checked",false);b(this).removeClass("ui-state-highlight").attr("aria-selected","false");fa.push(this.id);if(c){b("#jqg_"+b.jgrid.jqID(a.p.id)+"_"+b.jgrid.jqID(this.id),a.grid.fbDiv)[a.p.useProp?"prop":"attr"]("checked",false);b("#"+b.jgrid.jqID(this.id),a.grid.fbDiv).removeClass("ui-state-highlight")}}});
-a.p.selrow=null;X=false}b(a).triggerHandler("jqGridSelectAll",[X?a.p.selarrrow:fa,X]);b.isFunction(a.p.onSelectAll)&&a.p.onSelectAll.call(a,X?a.p.selarrrow:fa,X)})}!0===a.p.autowidth&&(C=b(m).innerWidth(),a.p.width=0<C?C:"nw");(function(){var d=0,e=b.jgrid.cell_width?0:n(a.p.cellLayout,0),f=0,g,h=n(a.p.scrollOffset,0),i,k=false,m,l=0,o=0,w;b.each(a.p.colModel,function(){if(this.hidden===void 0)this.hidden=false;if(a.p.grouping&&a.p.autowidth){var c=b.inArray(this.name,a.p.groupingView.groupField);
-if(c>=0&&a.p.groupingView.groupColumnShow.length>c)this.hidden=!a.p.groupingView.groupColumnShow[c]}this.widthOrg=i=n(this.width,0);if(this.hidden===false){d=d+(i+e);this.fixed?l=l+(i+e):f++;o++}});if(isNaN(a.p.width))a.p.width=d+(a.p.shrinkToFit===false&&!isNaN(a.p.height)?h:0);c.width=a.p.width;a.p.tblwidth=d;if(a.p.shrinkToFit===false&&a.p.forceFit===true)a.p.forceFit=false;if(a.p.shrinkToFit===true&&f>0){m=c.width-e*f-l;if(!isNaN(a.p.height)){m=m-h;k=true}d=0;b.each(a.p.colModel,function(b){if(this.hidden===
-false&&!this.fixed){this.width=i=Math.round(m*this.width/(a.p.tblwidth-e*f-l));d=d+i;g=b}});w=0;k?c.width-l-(d+e*f)!==h&&(w=c.width-l-(d+e*f)-h):!k&&Math.abs(c.width-l-(d+e*f))!==1&&(w=c.width-l-(d+e*f));a.p.colModel[g].width=a.p.colModel[g].width+w;a.p.tblwidth=d+w+e*f+l;if(a.p.tblwidth>a.p.width){a.p.colModel[g].width=a.p.colModel[g].width-(a.p.tblwidth-parseInt(a.p.width,10));a.p.tblwidth=a.p.width}}})();b(m).css("width",c.width+"px").append("<div class='ui-jqgrid-resize-mark' id='rs_m"+a.p.id+
-"'>&#160;</div>");b(i).css("width",c.width+"px");var C=b("thead:first",a).get(0),Q="";a.p.footerrow&&(Q+="<table role='grid' style='width:"+a.p.tblwidth+"px' class='ui-jqgrid-ftable' cellspacing='0' cellpadding='0' border='0'><tbody><tr role='row' class='ui-widget-content footrow footrow-"+g+"'>");var i=b("tr:first",C),Y="<tr class='jqgfirstrow' role='row' style='height:auto'>";a.p.disableClick=!1;b("th",i).each(function(d){ca=a.p.colModel[d].width;if(a.p.colModel[d].resizable===void 0)a.p.colModel[d].resizable=
-true;if(a.p.colModel[d].resizable){da=document.createElement("span");b(da).html("&#160;").addClass("ui-jqgrid-resize ui-jqgrid-resize-"+g).css("cursor","col-resize");b(this).addClass(a.p.resizeclass)}else da="";b(this).css("width",ca+"px").prepend(da);var e="";if(a.p.colModel[d].hidden){b(this).css("display","none");e="display:none;"}Y=Y+("<td role='gridcell' style='height:0px;width:"+ca+"px;"+e+"'></td>");c.headers[d]={width:ca,el:this};ea=a.p.colModel[d].sortable;if(typeof ea!=="boolean")ea=a.p.colModel[d].sortable=
-true;e=a.p.colModel[d].name;e==="cb"||e==="subgrid"||e==="rn"||a.p.viewsortcols[2]&&b(">div",this).addClass("ui-jqgrid-sortable");if(ea)if(a.p.multiSort)if(a.p.viewsortcols[0]){b("div span.s-ico",this).show();a.p.colModel[d].lso&&b("div span.ui-icon-"+a.p.colModel[d].lso,this).removeClass("ui-state-disabled")}else{if(a.p.colModel[d].lso){b("div span.s-ico",this).show();b("div span.ui-icon-"+a.p.colModel[d].lso,this).removeClass("ui-state-disabled")}}else if(a.p.viewsortcols[0]){b("div span.s-ico",
-this).show();d===a.p.lastsort&&b("div span.ui-icon-"+a.p.sortorder,this).removeClass("ui-state-disabled")}else if(d===a.p.lastsort){b("div span.s-ico",this).show();b("div span.ui-icon-"+a.p.sortorder,this).removeClass("ui-state-disabled")}a.p.footerrow&&(Q=Q+("<td role='gridcell' "+p(d,0,"",null,"",false)+">&#160;</td>"))}).mousedown(function(d){if(b(d.target).closest("th>span.ui-jqgrid-resize").length===1){var e=la(this);if(a.p.forceFit===true){var f=a.p,g=e,h;for(h=e+1;h<a.p.colModel.length;h++)if(a.p.colModel[h].hidden!==
-true){g=h;break}f.nv=g-e}c.dragStart(e,d,sa(e));return false}}).click(function(c){if(a.p.disableClick)return a.p.disableClick=false;var d="th>div.ui-jqgrid-sortable",e,f;a.p.viewsortcols[2]||(d="th>div>span>span.ui-grid-ico-sort");c=b(c.target).closest(d);if(c.length===1){d=la(this);if(!a.p.viewsortcols[2]){e=true;f=c.attr("sort")}ka(b("div",this)[0].id,d,e,f);return false}});if(a.p.sortable&&b.fn.sortable)try{b(a).jqGrid("sortableColumns",i)}catch(wa){}a.p.footerrow&&(Q+="</tr></tbody></table>");
-Y+="</tr>";this.appendChild(document.createElement("tbody"));b(this).addClass("ui-jqgrid-btable").append(Y);var Y=null,i=b("<table class='ui-jqgrid-htable' style='width:"+a.p.tblwidth+"px' role='grid' aria-labelledby='gbox_"+this.id+"' cellspacing='0' cellpadding='0' border='0'></table>").append(C),H=a.p.caption&&!0===a.p.hiddengrid?!0:!1;f=b("<div class='ui-jqgrid-hbox"+("rtl"===g?"-rtl":"")+"'></div>");C=null;c.hDiv=document.createElement("div");b(c.hDiv).css({width:c.width+"px"}).addClass("ui-state-default ui-jqgrid-hdiv").append(f);
-b(f).append(i);i=null;H&&b(c.hDiv).hide();a.p.pager&&("string"===typeof a.p.pager?"#"!==a.p.pager.substr(0,1)&&(a.p.pager="#"+a.p.pager):a.p.pager="#"+b(a.p.pager).attr("id"),b(a.p.pager).css({width:c.width+"px"}).addClass("ui-state-default ui-jqgrid-pager ui-corner-bottom").appendTo(m),H&&b(a.p.pager).hide(),ja(a.p.pager,""));!1===a.p.cellEdit&&!0===a.p.hoverrows&&b(a).bind("mouseover",function(a){u=b(a.target).closest("tr.jqgrow");b(u).attr("class")!=="ui-subgrid"&&b(u).addClass("ui-state-hover")}).bind("mouseout",
-function(a){u=b(a.target).closest("tr.jqgrow");b(u).removeClass("ui-state-hover")});var v,I,ga;b(a).before(c.hDiv).click(function(c){t=c.target;u=b(t,a.rows).closest("tr.jqgrow");if(b(u).length===0||u[0].className.indexOf("ui-state-disabled")>-1||(b(t,a).closest("table.ui-jqgrid-btable").attr("id")||"").replace("_frozen","")!==a.id)return this;var d=b(t).hasClass("cbox"),e=b(a).triggerHandler("jqGridBeforeSelectRow",[u[0].id,c]);(e=e===false||e==="stop"?false:true)&&b.isFunction(a.p.beforeSelectRow)&&
-(e=a.p.beforeSelectRow.call(a,u[0].id,c));if(!(t.tagName==="A"||(t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.tagName==="OPTION"||t.tagName==="SELECT")&&!d)&&e===true){v=u[0].id;I=b.jgrid.getCellIndex(t);ga=b(t).closest("td,th").html();b(a).triggerHandler("jqGridCellSelect",[v,I,ga,c]);b.isFunction(a.p.onCellSelect)&&a.p.onCellSelect.call(a,v,I,ga,c);if(a.p.cellEdit===true)if(a.p.multiselect&&d)b(a).jqGrid("setSelection",v,true,c);else{v=u[0].rowIndex;try{b(a).jqGrid("editCell",v,I,true)}catch(f){}}else if(a.p.multikey)if(c[a.p.multikey])b(a).jqGrid("setSelection",
-v,true,c);else{if(a.p.multiselect&&d){d=b("#jqg_"+b.jgrid.jqID(a.p.id)+"_"+v).is(":checked");b("#jqg_"+b.jgrid.jqID(a.p.id)+"_"+v)[a.p.useProp?"prop":"attr"]("checked",d)}}else{if(a.p.multiselect&&a.p.multiboxonly&&!d){var g=a.p.frozenColumns?a.p.id+"_frozen":"";b(a.p.selarrrow).each(function(c,d){var e=a.rows.namedItem(d);b(e).removeClass("ui-state-highlight");b("#jqg_"+b.jgrid.jqID(a.p.id)+"_"+b.jgrid.jqID(d))[a.p.useProp?"prop":"attr"]("checked",false);if(g){b("#"+b.jgrid.jqID(d),"#"+b.jgrid.jqID(g)).removeClass("ui-state-highlight");
-b("#jqg_"+b.jgrid.jqID(a.p.id)+"_"+b.jgrid.jqID(d),"#"+b.jgrid.jqID(g))[a.p.useProp?"prop":"attr"]("checked",false)}});a.p.selarrrow=[]}b(a).jqGrid("setSelection",v,true,c)}}}).bind("reloadGrid",function(c,d){if(a.p.treeGrid===true)a.p.datatype=a.p.treedatatype;d&&d.current&&a.grid.selectionPreserver(a);if(a.p.datatype==="local"){b(a).jqGrid("resetSelection");a.p.data.length&&N()}else if(!a.p.treeGrid){a.p.selrow=null;if(a.p.multiselect){a.p.selarrrow=[];ba(false)}a.p.savedRow=[]}a.p.scroll&&U.call(a,
-true,false);if(d&&d.page){var e=d.page;if(e>a.p.lastpage)e=a.p.lastpage;e<1&&(e=1);a.p.page=e;a.grid.bDiv.scrollTop=a.grid.prevRowHeight?(e-1)*a.grid.prevRowHeight*a.p.rowNum:0}if(a.grid.prevRowHeight&&a.p.scroll){delete a.p.lastpage;a.grid.populateVisible()}else a.grid.populate();a.p._inlinenav===true&&b(a).jqGrid("showAddEditButtons");return false}).dblclick(function(c){t=c.target;u=b(t,a.rows).closest("tr.jqgrow");if(b(u).length!==0){v=u[0].rowIndex;I=b.jgrid.getCellIndex(t);b(a).triggerHandler("jqGridDblClickRow",
-[b(u).attr("id"),v,I,c]);b.isFunction(a.p.ondblClickRow)&&a.p.ondblClickRow.call(a,b(u).attr("id"),v,I,c)}}).bind("contextmenu",function(c){t=c.target;u=b(t,a.rows).closest("tr.jqgrow");if(b(u).length!==0){a.p.multiselect||b(a).jqGrid("setSelection",u[0].id,true,c);v=u[0].rowIndex;I=b.jgrid.getCellIndex(t);b(a).triggerHandler("jqGridRightClickRow",[b(u).attr("id"),v,I,c]);b.isFunction(a.p.onRightClickRow)&&a.p.onRightClickRow.call(a,b(u).attr("id"),v,I,c)}});c.bDiv=document.createElement("div");k&&
-"auto"===(""+a.p.height).toLowerCase()&&(a.p.height="100%");b(c.bDiv).append(b('<div style="position:relative;'+(k&&8>b.jgrid.msiever()?"height:0.01%;":"")+'"></div>').append("<div></div>").append(this)).addClass("ui-jqgrid-bdiv").css({height:a.p.height+(isNaN(a.p.height)?"":"px"),width:c.width+"px"}).scroll(c.scrollGrid);b("table:first",c.bDiv).css({width:a.p.tblwidth+"px"});b.support.tbody||2===b("tbody",this).length&&b("tbody:gt(0)",this).remove();a.p.multikey&&(b.jgrid.msie?b(c.bDiv).bind("selectstart",
-function(){return false}):b(c.bDiv).bind("mousedown",function(){return false}));H&&b(c.bDiv).hide();c.cDiv=document.createElement("div");var ha=!0===a.p.hidegrid?b("<a role='link' href='javascript:void(0)'/>").addClass("ui-jqgrid-titlebar-close HeaderButton").hover(function(){ha.addClass("ui-state-hover")},function(){ha.removeClass("ui-state-hover")}).append("<span class='ui-icon ui-icon-circle-triangle-n'></span>").css("rtl"===g?"left":"right","0px"):"";b(c.cDiv).append(ha).append("<span class='ui-jqgrid-title"+
-("rtl"===g?"-rtl":"")+"'>"+a.p.caption+"</span>").addClass("ui-jqgrid-titlebar ui-widget-header ui-corner-top ui-helper-clearfix");b(c.cDiv).insertBefore(c.hDiv);a.p.toolbar[0]&&(c.uDiv=document.createElement("div"),"top"===a.p.toolbar[1]?b(c.uDiv).insertBefore(c.hDiv):"bottom"===a.p.toolbar[1]&&b(c.uDiv).insertAfter(c.hDiv),"both"===a.p.toolbar[1]?(c.ubDiv=document.createElement("div"),b(c.uDiv).addClass("ui-userdata ui-state-default").attr("id","t_"+this.id).insertBefore(c.hDiv),b(c.ubDiv).addClass("ui-userdata ui-state-default").attr("id",
-"tb_"+this.id).insertAfter(c.hDiv),H&&b(c.ubDiv).hide()):b(c.uDiv).width(c.width).addClass("ui-userdata ui-state-default").attr("id","t_"+this.id),H&&b(c.uDiv).hide());a.p.toppager&&(a.p.toppager=b.jgrid.jqID(a.p.id)+"_toppager",c.topDiv=b("<div id='"+a.p.toppager+"'></div>")[0],a.p.toppager="#"+a.p.toppager,b(c.topDiv).addClass("ui-state-default ui-jqgrid-toppager").width(c.width).insertBefore(c.hDiv),ja(a.p.toppager,"_t"));a.p.footerrow&&(c.sDiv=b("<div class='ui-jqgrid-sdiv'></div>")[0],f=b("<div class='ui-jqgrid-hbox"+
-("rtl"===g?"-rtl":"")+"'></div>"),b(c.sDiv).append(f).width(c.width).insertAfter(c.hDiv),b(f).append(Q),c.footers=b(".ui-jqgrid-ftable",c.sDiv)[0].rows[0].cells,a.p.rownumbers&&(c.footers[0].className="ui-state-default jqgrid-rownum"),H&&b(c.sDiv).hide());f=null;if(a.p.caption){var ta=a.p.datatype;!0===a.p.hidegrid&&(b(".ui-jqgrid-titlebar-close",c.cDiv).click(function(d){var e=b.isFunction(a.p.onHeaderClick),f=".ui-jqgrid-bdiv, .ui-jqgrid-hdiv, .ui-jqgrid-pager, .ui-jqgrid-sdiv",g,h=this;if(a.p.toolbar[0]===
-true){a.p.toolbar[1]==="both"&&(f=f+(", #"+b(c.ubDiv).attr("id")));f=f+(", #"+b(c.uDiv).attr("id"))}g=b(f,"#gview_"+b.jgrid.jqID(a.p.id)).length;a.p.gridstate==="visible"?b(f,"#gbox_"+b.jgrid.jqID(a.p.id)).slideUp("fast",function(){g--;if(g===0){b("span",h).removeClass("ui-icon-circle-triangle-n").addClass("ui-icon-circle-triangle-s");a.p.gridstate="hidden";b("#gbox_"+b.jgrid.jqID(a.p.id)).hasClass("ui-resizable")&&b(".ui-resizable-handle","#gbox_"+b.jgrid.jqID(a.p.id)).hide();b(a).triggerHandler("jqGridHeaderClick",
-[a.p.gridstate,d]);e&&(H||a.p.onHeaderClick.call(a,a.p.gridstate,d))}}):a.p.gridstate==="hidden"&&b(f,"#gbox_"+b.jgrid.jqID(a.p.id)).slideDown("fast",function(){g--;if(g===0){b("span",h).removeClass("ui-icon-circle-triangle-s").addClass("ui-icon-circle-triangle-n");if(H){a.p.datatype=ta;O();H=false}a.p.gridstate="visible";b("#gbox_"+b.jgrid.jqID(a.p.id)).hasClass("ui-resizable")&&b(".ui-resizable-handle","#gbox_"+b.jgrid.jqID(a.p.id)).show();b(a).triggerHandler("jqGridHeaderClick",[a.p.gridstate,
-d]);e&&(H||a.p.onHeaderClick.call(a,a.p.gridstate,d))}});return false}),H&&(a.p.datatype="local",b(".ui-jqgrid-titlebar-close",c.cDiv).trigger("click")))}else b(c.cDiv).hide();b(c.hDiv).after(c.bDiv).mousemove(function(a){if(c.resizing){c.dragMove(a);return false}});b(".ui-jqgrid-labels",c.hDiv).bind("selectstart",function(){return false});b(document).mouseup(function(){if(c.resizing){c.dragEnd();return false}return true});a.formatCol=p;a.sortData=ka;a.updatepager=function(c,d){var e,f,g,h,i,j,k,
-m="",l=a.p.pager?"_"+b.jgrid.jqID(a.p.pager.substr(1)):"",o=a.p.toppager?"_"+a.p.toppager.substr(1):"";g=parseInt(a.p.page,10)-1;g<0&&(g=0);g=g*parseInt(a.p.rowNum,10);i=g+a.p.reccount;if(a.p.scroll){e=b("tbody:first > tr:gt(0)",a.grid.bDiv);g=i-e.length;a.p.reccount=e.length;if(e=e.outerHeight()||a.grid.prevRowHeight){f=g*e;k=parseInt(a.p.records,10)*e;b(">div:first",a.grid.bDiv).css({height:k}).children("div:first").css({height:f,display:f?"":"none"});if(a.grid.bDiv.scrollTop==0&&a.p.page>1)a.grid.bDiv.scrollTop=
-a.p.rowNum*(a.p.page-1)*e}a.grid.bDiv.scrollLeft=a.grid.hDiv.scrollLeft}m=a.p.pager||"";if(m=m+(a.p.toppager?m?","+a.p.toppager:a.p.toppager:"")){k=b.jgrid.formatter.integer||{};e=n(a.p.page);f=n(a.p.lastpage);b(".selbox",m)[this.p.useProp?"prop":"attr"]("disabled",false);if(a.p.pginput===true){b(".ui-pg-input",m).val(a.p.page);h=a.p.toppager?"#sp_1"+l+",#sp_1"+o:"#sp_1"+l;b(h).html(b.fmatter?b.fmatter.util.NumberFormat(a.p.lastpage,k):a.p.lastpage)}if(a.p.viewrecords)if(a.p.reccount===0)b(".ui-paging-info",
-m).html(a.p.emptyrecords);else{h=g+1;j=a.p.records;if(b.fmatter){h=b.fmatter.util.NumberFormat(h,k);i=b.fmatter.util.NumberFormat(i,k);j=b.fmatter.util.NumberFormat(j,k)}b(".ui-paging-info",m).html(b.jgrid.format(a.p.recordtext,h,i,j))}if(a.p.pgbuttons===true){e<=0&&(e=f=0);if(e===1||e===0){b("#first"+l+", #prev"+l).addClass("ui-state-disabled").removeClass("ui-state-hover");a.p.toppager&&b("#first_t"+o+", #prev_t"+o).addClass("ui-state-disabled").removeClass("ui-state-hover")}else{b("#first"+l+", #prev"+
-l).removeClass("ui-state-disabled");a.p.toppager&&b("#first_t"+o+", #prev_t"+o).removeClass("ui-state-disabled")}if(e===f||e===0){b("#next"+l+", #last"+l).addClass("ui-state-disabled").removeClass("ui-state-hover");a.p.toppager&&b("#next_t"+o+", #last_t"+o).addClass("ui-state-disabled").removeClass("ui-state-hover")}else{b("#next"+l+", #last"+l).removeClass("ui-state-disabled");a.p.toppager&&b("#next_t"+o+", #last_t"+o).removeClass("ui-state-disabled")}}}c===true&&a.p.rownumbers===true&&b(">td.jqgrid-rownum",
-a.rows).each(function(a){b(this).html(g+1+a)});d&&a.p.jqgdnd&&b(a).jqGrid("gridDnD","updateDnD");b(a).triggerHandler("jqGridGridComplete");b.isFunction(a.p.gridComplete)&&a.p.gridComplete.call(a);b(a).triggerHandler("jqGridAfterGridComplete")};a.refreshIndex=N;a.setHeadCheckBox=ba;a.constructTr=W;a.formatter=function(a,b,c,d,e){return o(a,b,c,d,e)};b.extend(c,{populate:O,emptyRows:U});this.grid=c;a.addXmlData=function(b){J(b,a.grid.bDiv)};a.addJSONData=function(b){R(b,a.grid.bDiv)};this.grid.cols=
-this.rows[0].cells;b(a).triggerHandler("jqGridInitGrid");b.isFunction(a.p.onInitGrid)&&a.p.onInitGrid.call(a);O();a.p.hiddengrid=!1}}}})};b.jgrid.extend({getGridParam:function(b){var g=this[0];return!g||!g.grid?void 0:!b?g.p:void 0!==g.p[b]?g.p[b]:null},setGridParam:function(d){return this.each(function(){this.grid&&"object"===typeof d&&b.extend(!0,this.p,d)})},getDataIDs:function(){var d=[],g=0,c,e=0;this.each(function(){if((c=this.rows.length)&&0<c)for(;g<c;)b(this.rows[g]).hasClass("jqgrow")&&
-(d[e]=this.rows[g].id,e++),g++});return d},setSelection:function(d,g,c){return this.each(function(){var e,a,j,f,h,i;if(void 0!==d&&(g=!1===g?!1:!0,(a=this.rows.namedItem(""+d))&&a.className&&!(-1<a.className.indexOf("ui-state-disabled"))))if(!0===this.p.scrollrows&&(j=this.rows.namedItem(d).rowIndex,0<=j&&(e=b(this.grid.bDiv)[0].clientHeight,f=b(this.grid.bDiv)[0].scrollTop,h=b(this.rows[j]).position().top,j=this.rows[j].clientHeight,h+j>=e+f?b(this.grid.bDiv)[0].scrollTop=h-(e+f)+j+f:h<e+f&&h<f&&
-(b(this.grid.bDiv)[0].scrollTop=h))),!0===this.p.frozenColumns&&(i=this.p.id+"_frozen"),this.p.multiselect){if(this.setHeadCheckBox(!1),this.p.selrow=a.id,f=b.inArray(this.p.selrow,this.p.selarrrow),-1===f?("ui-subgrid"!==a.className&&b(a).addClass("ui-state-highlight").attr("aria-selected","true"),e=!0,this.p.selarrrow.push(this.p.selrow)):("ui-subgrid"!==a.className&&b(a).removeClass("ui-state-highlight").attr("aria-selected","false"),e=!1,this.p.selarrrow.splice(f,1),h=this.p.selarrrow[0],this.p.selrow=
-void 0===h?null:h),b("#jqg_"+b.jgrid.jqID(this.p.id)+"_"+b.jgrid.jqID(a.id))[this.p.useProp?"prop":"attr"]("checked",e),i&&(-1===f?b("#"+b.jgrid.jqID(d),"#"+b.jgrid.jqID(i)).addClass("ui-state-highlight"):b("#"+b.jgrid.jqID(d),"#"+b.jgrid.jqID(i)).removeClass("ui-state-highlight"),b("#jqg_"+b.jgrid.jqID(this.p.id)+"_"+b.jgrid.jqID(d),"#"+b.jgrid.jqID(i))[this.p.useProp?"prop":"attr"]("checked",e)),g)b(this).triggerHandler("jqGridSelectRow",[a.id,e,c]),this.p.onSelectRow&&this.p.onSelectRow.call(this,
-a.id,e,c)}else if("ui-subgrid"!==a.className&&(this.p.selrow!==a.id?(b(this.rows.namedItem(this.p.selrow)).removeClass("ui-state-highlight").attr({"aria-selected":"false",tabindex:"-1"}),b(a).addClass("ui-state-highlight").attr({"aria-selected":"true",tabindex:"0"}),i&&(b("#"+b.jgrid.jqID(this.p.selrow),"#"+b.jgrid.jqID(i)).removeClass("ui-state-highlight"),b("#"+b.jgrid.jqID(d),"#"+b.jgrid.jqID(i)).addClass("ui-state-highlight")),e=!0):e=!1,this.p.selrow=a.id,g))b(this).triggerHandler("jqGridSelectRow",
-[a.id,e,c]),this.p.onSelectRow&&this.p.onSelectRow.call(this,a.id,e,c)})},resetSelection:function(d){return this.each(function(){var g=this,c,e,a;!0===g.p.frozenColumns&&(a=g.p.id+"_frozen");if(void 0!==d){e=d===g.p.selrow?g.p.selrow:d;b("#"+b.jgrid.jqID(g.p.id)+" tbody:first tr#"+b.jgrid.jqID(e)).removeClass("ui-state-highlight").attr("aria-selected","false");a&&b("#"+b.jgrid.jqID(e),"#"+b.jgrid.jqID(a)).removeClass("ui-state-highlight");if(g.p.multiselect){b("#jqg_"+b.jgrid.jqID(g.p.id)+"_"+b.jgrid.jqID(e),
-"#"+b.jgrid.jqID(g.p.id))[g.p.useProp?"prop":"attr"]("checked",!1);if(a)b("#jqg_"+b.jgrid.jqID(g.p.id)+"_"+b.jgrid.jqID(e),"#"+b.jgrid.jqID(a))[g.p.useProp?"prop":"attr"]("checked",!1);g.setHeadCheckBox(!1)}e=null}else g.p.multiselect?(b(g.p.selarrrow).each(function(d,e){c=g.rows.namedItem(e);b(c).removeClass("ui-state-highlight").attr("aria-selected","false");b("#jqg_"+b.jgrid.jqID(g.p.id)+"_"+b.jgrid.jqID(e))[g.p.useProp?"prop":"attr"]("checked",!1);a&&(b("#"+b.jgrid.jqID(e),"#"+b.jgrid.jqID(a)).removeClass("ui-state-highlight"),
-b("#jqg_"+b.jgrid.jqID(g.p.id)+"_"+b.jgrid.jqID(e),"#"+b.jgrid.jqID(a))[g.p.useProp?"prop":"attr"]("checked",!1))}),g.setHeadCheckBox(!1),g.p.selarrrow=[]):g.p.selrow&&(b("#"+b.jgrid.jqID(g.p.id)+" tbody:first tr#"+b.jgrid.jqID(g.p.selrow)).removeClass("ui-state-highlight").attr("aria-selected","false"),a&&b("#"+b.jgrid.jqID(g.p.selrow),"#"+b.jgrid.jqID(a)).removeClass("ui-state-highlight"),g.p.selrow=null);!0===g.p.cellEdit&&0<=parseInt(g.p.iCol,10)&&0<=parseInt(g.p.iRow,10)&&(b("td:eq("+g.p.iCol+
-")",g.rows[g.p.iRow]).removeClass("edit-cell ui-state-highlight"),b(g.rows[g.p.iRow]).removeClass("selected-row ui-state-hover"));g.p.savedRow=[]})},getRowData:function(d){var g={},c,e=!1,a,j=0;this.each(function(){var f=this,h,i;if(void 0===d)e=!0,c=[],a=f.rows.length;else{i=f.rows.namedItem(d);if(!i)return g;a=2}for(;j<a;)e&&(i=f.rows[j]),b(i).hasClass("jqgrow")&&(b('td[role="gridcell"]',i).each(function(a){h=f.p.colModel[a].name;if("cb"!==h&&"subgrid"!==h&&"rn"!==h)if(!0===f.p.treeGrid&&h===f.p.ExpandColumn)g[h]=
-b.jgrid.htmlDecode(b("span:first",this).html());else try{g[h]=b.unformat.call(f,this,{rowId:i.id,colModel:f.p.colModel[a]},a)}catch(c){g[h]=b.jgrid.htmlDecode(b(this).html())}}),e&&(c.push(g),g={})),j++});return c||g},delRowData:function(d){var g=!1,c,e;this.each(function(){c=this.rows.namedItem(d);if(!c)return!1;b(c).remove();this.p.records--;this.p.reccount--;this.updatepager(!0,!1);g=!0;this.p.multiselect&&(e=b.inArray(d,this.p.selarrrow),-1!==e&&this.p.selarrrow.splice(e,1));this.p.selrow=this.p.multiselect&&
-0<this.p.selarrrow.length?this.p.selarrrow[this.p.selarrrow.length-1]:null;if("local"===this.p.datatype){var a=this.p._index[b.jgrid.stripPref(this.p.idPrefix,d)];void 0!==a&&(this.p.data.splice(a,1),this.refreshIndex())}if(!0===this.p.altRows&&g){var j=this.p.altclass;b(this.rows).each(function(a){a%2===1?b(this).addClass(j):b(this).removeClass(j)})}});return g},setRowData:function(d,g,c){var e,a=!0,j;this.each(function(){if(!this.grid)return!1;var f=this,h,i,k=typeof c,m={};i=f.rows.namedItem(d);
-if(!i)return!1;if(g)try{if(b(this.p.colModel).each(function(a){e=this.name;var c=b.jgrid.getAccessor(g,e);void 0!==c&&(m[e]=this.formatter&&"string"===typeof this.formatter&&"date"===this.formatter?b.unformat.date.call(f,c,this):c,h=f.formatter(d,c,a,g,"edit"),j=this.title?{title:b.jgrid.stripHtml(h)}:{},!0===f.p.treeGrid&&e===f.p.ExpandColumn?b("td[role='gridcell']:eq("+a+") > span:first",i).html(h).attr(j):b("td[role='gridcell']:eq("+a+")",i).html(h).attr(j))}),"local"===f.p.datatype){var n=b.jgrid.stripPref(f.p.idPrefix,
-d),p=f.p._index[n],l;if(f.p.treeGrid)for(l in f.p.treeReader)f.p.treeReader.hasOwnProperty(l)&&delete m[f.p.treeReader[l]];void 0!==p&&(f.p.data[p]=b.extend(!0,f.p.data[p],m));m=null}}catch(o){a=!1}a&&("string"===k?b(i).addClass(c):"object"===k&&b(i).css(c),b(f).triggerHandler("jqGridAfterGridComplete"))});return a},addRowData:function(d,g,c,e){c||(c="last");var a=!1,j,f,h,i,k,m,n,p,l="",o,B,S,M,Z,T;g&&(b.isArray(g)?(o=!0,c="last",B=d):(g=[g],o=!1),this.each(function(){var U=g.length;k=this.p.rownumbers===
-true?1:0;h=this.p.multiselect===true?1:0;i=this.p.subGrid===true?1:0;if(!o)if(d!==void 0)d=""+d;else{d=b.jgrid.randId();if(this.p.keyIndex!==false){B=this.p.colModel[this.p.keyIndex+h+i+k].name;g[0][B]!==void 0&&(d=g[0][B])}}S=this.p.altclass;for(var N=0,W="",J={},R=b.isFunction(this.p.afterInsertRow)?true:false;N<U;){M=g[N];f=[];if(o){try{d=M[B];d===void 0&&(d=b.jgrid.randId())}catch(ia){d=b.jgrid.randId()}W=this.p.altRows===true?(this.rows.length-1)%2===0?S:"":""}T=d;d=this.p.idPrefix+d;if(k){l=
-this.formatCol(0,1,"",null,d,true);f[f.length]='<td role="gridcell" class="ui-state-default jqgrid-rownum" '+l+">0</td>"}if(h){p='<input role="checkbox" type="checkbox" id="jqg_'+this.p.id+"_"+d+'" class="cbox"/>';l=this.formatCol(k,1,"",null,d,true);f[f.length]='<td role="gridcell" '+l+">"+p+"</td>"}i&&(f[f.length]=b(this).jqGrid("addSubGridCell",h+k,1));for(n=h+i+k;n<this.p.colModel.length;n++){Z=this.p.colModel[n];j=Z.name;J[j]=M[j];p=this.formatter(d,b.jgrid.getAccessor(M,j),n,M);l=this.formatCol(n,
-1,p,M,d,J);f[f.length]='<td role="gridcell" '+l+">"+p+"</td>"}f.unshift(this.constructTr(d,false,W,J,M,false));f[f.length]="</tr>";if(this.rows.length===0)b("table:first",this.grid.bDiv).append(f.join(""));else switch(c){case "last":b(this.rows[this.rows.length-1]).after(f.join(""));m=this.rows.length-1;break;case "first":b(this.rows[0]).after(f.join(""));m=1;break;case "after":(m=this.rows.namedItem(e))&&(b(this.rows[m.rowIndex+1]).hasClass("ui-subgrid")?b(this.rows[m.rowIndex+1]).after(f):b(m).after(f.join("")));
-m++;break;case "before":if(m=this.rows.namedItem(e)){b(m).before(f.join(""));m=m.rowIndex}m--}this.p.subGrid===true&&b(this).jqGrid("addSubGrid",h+k,m);this.p.records++;this.p.reccount++;b(this).triggerHandler("jqGridAfterInsertRow",[d,M,M]);R&&this.p.afterInsertRow.call(this,d,M,M);N++;if(this.p.datatype==="local"){J[this.p.localReader.id]=T;this.p._index[T]=this.p.data.length;this.p.data.push(J);J={}}}this.p.altRows===true&&!o&&(c==="last"?(this.rows.length-1)%2===1&&b(this.rows[this.rows.length-
-1]).addClass(S):b(this.rows).each(function(a){a%2===1?b(this).addClass(S):b(this).removeClass(S)}));this.updatepager(true,true);a=true}));return a},footerData:function(d,g,c){function e(a){for(var b in a)if(a.hasOwnProperty(b))return!1;return!0}var a,j=!1,f={},h;void 0===d&&(d="get");"boolean"!==typeof c&&(c=!0);d=d.toLowerCase();this.each(function(){var i=this,k;if(!i.grid||!i.p.footerrow||"set"===d&&e(g))return!1;j=!0;b(this.p.colModel).each(function(e){a=this.name;"set"===d?void 0!==g[a]&&(k=c?
-i.formatter("",g[a],e,g,"edit"):g[a],h=this.title?{title:b.jgrid.stripHtml(k)}:{},b("tr.footrow td:eq("+e+")",i.grid.sDiv).html(k).attr(h),j=!0):"get"===d&&(f[a]=b("tr.footrow td:eq("+e+")",i.grid.sDiv).html())})});return"get"===d?f:j},showHideCol:function(d,g){return this.each(function(){var c=this,e=!1,a=b.jgrid.cell_width?0:c.p.cellLayout,j;if(c.grid){"string"===typeof d&&(d=[d]);g="none"!==g?"":"none";var f=""===g?!0:!1,h=c.p.groupHeader&&("object"===typeof c.p.groupHeader||b.isFunction(c.p.groupHeader));
-h&&b(c).jqGrid("destroyGroupHeader",!1);b(this.p.colModel).each(function(h){if(-1!==b.inArray(this.name,d)&&this.hidden===f){if(!0===c.p.frozenColumns&&!0===this.frozen)return!0;b("tr",c.grid.hDiv).each(function(){b(this.cells[h]).css("display",g)});b(c.rows).each(function(){b(this).hasClass("jqgroup")||b(this.cells[h]).css("display",g)});c.p.footerrow&&b("tr.footrow td:eq("+h+")",c.grid.sDiv).css("display",g);j=parseInt(this.width,10);c.p.tblwidth="none"===g?c.p.tblwidth-(j+a):c.p.tblwidth+(j+a);
-this.hidden=!f;e=!0;b(c).triggerHandler("jqGridShowHideCol",[f,this.name,h])}});!0===e&&(!0===c.p.shrinkToFit&&!isNaN(c.p.height)&&(c.p.tblwidth+=parseInt(c.p.scrollOffset,10)),b(c).jqGrid("setGridWidth",!0===c.p.shrinkToFit?c.p.tblwidth:c.p.width));h&&b(c).jqGrid("setGroupHeaders",c.p.groupHeader)}})},hideCol:function(d){return this.each(function(){b(this).jqGrid("showHideCol",d,"none")})},showCol:function(d){return this.each(function(){b(this).jqGrid("showHideCol",d,"")})},remapColumns:function(d,
-g,c){function e(a){var c;c=a.length?b.makeArray(a):b.extend({},a);b.each(d,function(b){a[b]=c[this]})}function a(a,c){b(">tr"+(c||""),a).each(function(){var a=this,c=b.makeArray(a.cells);b.each(d,function(){var b=c[this];b&&a.appendChild(b)})})}var j=this.get(0);e(j.p.colModel);e(j.p.colNames);e(j.grid.headers);a(b("thead:first",j.grid.hDiv),c&&":not(.ui-jqgrid-labels)");g&&a(b("#"+b.jgrid.jqID(j.p.id)+" tbody:first"),".jqgfirstrow, tr.jqgrow, tr.jqfoot");j.p.footerrow&&a(b("tbody:first",j.grid.sDiv));
-j.p.remapColumns&&(j.p.remapColumns.length?e(j.p.remapColumns):j.p.remapColumns=b.makeArray(d));j.p.lastsort=b.inArray(j.p.lastsort,d);j.p.treeGrid&&(j.p.expColInd=b.inArray(j.p.expColInd,d));b(j).triggerHandler("jqGridRemapColumns",[d,g,c])},setGridWidth:function(d,g){return this.each(function(){if(this.grid){var c=this,e,a=0,j=b.jgrid.cell_width?0:c.p.cellLayout,f,h=0,i=!1,k=c.p.scrollOffset,m,n=0,p=0,l;"boolean"!==typeof g&&(g=c.p.shrinkToFit);if(!isNaN(d)){d=parseInt(d,10);c.grid.width=c.p.width=
-d;b("#gbox_"+b.jgrid.jqID(c.p.id)).css("width",d+"px");b("#gview_"+b.jgrid.jqID(c.p.id)).css("width",d+"px");b(c.grid.bDiv).css("width",d+"px");b(c.grid.hDiv).css("width",d+"px");c.p.pager&&b(c.p.pager).css("width",d+"px");c.p.toppager&&b(c.p.toppager).css("width",d+"px");!0===c.p.toolbar[0]&&(b(c.grid.uDiv).css("width",d+"px"),"both"===c.p.toolbar[1]&&b(c.grid.ubDiv).css("width",d+"px"));c.p.footerrow&&b(c.grid.sDiv).css("width",d+"px");!1===g&&!0===c.p.forceFit&&(c.p.forceFit=!1);if(!0===g){b.each(c.p.colModel,
-function(){if(this.hidden===false){e=this.widthOrg;a=a+(e+j);this.fixed?n=n+(e+j):h++;p++}});if(0===h)return;c.p.tblwidth=a;m=d-j*h-n;if(!isNaN(c.p.height)&&(b(c.grid.bDiv)[0].clientHeight<b(c.grid.bDiv)[0].scrollHeight||1===c.rows.length))i=!0,m-=k;var a=0,o=0<c.grid.cols.length;b.each(c.p.colModel,function(b){if(this.hidden===false&&!this.fixed){e=this.widthOrg;e=Math.round(m*e/(c.p.tblwidth-j*h-n));if(!(e<0)){this.width=e;a=a+e;c.grid.headers[b].width=e;c.grid.headers[b].el.style.width=e+"px";
-if(c.p.footerrow)c.grid.footers[b].style.width=e+"px";if(o)c.grid.cols[b].style.width=e+"px";f=b}}});if(!f)return;l=0;i?d-n-(a+j*h)!==k&&(l=d-n-(a+j*h)-k):1!==Math.abs(d-n-(a+j*h))&&(l=d-n-(a+j*h));c.p.colModel[f].width+=l;c.p.tblwidth=a+l+j*h+n;c.p.tblwidth>d?(i=c.p.tblwidth-parseInt(d,10),c.p.tblwidth=d,e=c.p.colModel[f].width-=i):e=c.p.colModel[f].width;c.grid.headers[f].width=e;c.grid.headers[f].el.style.width=e+"px";o&&(c.grid.cols[f].style.width=e+"px");c.p.footerrow&&(c.grid.footers[f].style.width=
-e+"px")}c.p.tblwidth&&(b("table:first",c.grid.bDiv).css("width",c.p.tblwidth+"px"),b("table:first",c.grid.hDiv).css("width",c.p.tblwidth+"px"),c.grid.hDiv.scrollLeft=c.grid.bDiv.scrollLeft,c.p.footerrow&&b("table:first",c.grid.sDiv).css("width",c.p.tblwidth+"px"))}}})},setGridHeight:function(d){return this.each(function(){if(this.grid){var g=b(this.grid.bDiv);g.css({height:d+(isNaN(d)?"":"px")});!0===this.p.frozenColumns&&b("#"+b.jgrid.jqID(this.p.id)+"_frozen").parent().height(g.height()-16);this.p.height=
-d;this.p.scroll&&this.grid.populateVisible()}})},setCaption:function(d){return this.each(function(){this.p.caption=d;b("span.ui-jqgrid-title, span.ui-jqgrid-title-rtl",this.grid.cDiv).html(d);b(this.grid.cDiv).show()})},setLabel:function(d,g,c,e){return this.each(function(){var a=-1;if(this.grid&&void 0!==d&&(b(this.p.colModel).each(function(b){if(this.name===d)return a=b,!1}),0<=a)){var j=b("tr.ui-jqgrid-labels th:eq("+a+")",this.grid.hDiv);if(g){var f=b(".s-ico",j);b("[id^=jqgh_]",j).empty().html(g).append(f);
-this.p.colNames[a]=g}c&&("string"===typeof c?b(j).addClass(c):b(j).css(c));"object"===typeof e&&b(j).attr(e)}})},setCell:function(d,g,c,e,a,j){return this.each(function(){var f=-1,h,i;if(this.grid&&(isNaN(g)?b(this.p.colModel).each(function(a){if(this.name===g)return f=a,!1}):f=parseInt(g,10),0<=f&&(h=this.rows.namedItem(d)))){var k=b("td:eq("+f+")",h);if(""!==c||!0===j)h=this.formatter(d,c,f,h,"edit"),i=this.p.colModel[f].title?{title:b.jgrid.stripHtml(h)}:{},this.p.treeGrid&&0<b(".tree-wrap",b(k)).length?
-b("span",b(k)).html(h).attr(i):b(k).html(h).attr(i),"local"===this.p.datatype&&(h=this.p.colModel[f],c=h.formatter&&"string"===typeof h.formatter&&"date"===h.formatter?b.unformat.date.call(this,c,h):c,i=this.p._index[b.jgrid.stripPref(this.p.idPrefix,d)],void 0!==i&&(this.p.data[i][h.name]=c));"string"===typeof e?b(k).addClass(e):e&&b(k).css(e);"object"===typeof a&&b(k).attr(a)}})},getCell:function(d,g){var c=!1;this.each(function(){var e=-1;if(this.grid&&(isNaN(g)?b(this.p.colModel).each(function(a){if(this.name===
-g)return e=a,!1}):e=parseInt(g,10),0<=e)){var a=this.rows.namedItem(d);if(a)try{c=b.unformat.call(this,b("td:eq("+e+")",a),{rowId:a.id,colModel:this.p.colModel[e]},e)}catch(j){c=b.jgrid.htmlDecode(b("td:eq("+e+")",a).html())}}});return c},getCol:function(d,g,c){var e=[],a,j=0,f,h,i,g="boolean"!==typeof g?!1:g;void 0===c&&(c=!1);this.each(function(){var k=-1;if(this.grid&&(isNaN(d)?b(this.p.colModel).each(function(a){if(this.name===d)return k=a,!1}):k=parseInt(d,10),0<=k)){var m=this.rows.length,n=
-0;if(m&&0<m){for(;n<m;){if(b(this.rows[n]).hasClass("jqgrow")){try{a=b.unformat.call(this,b(this.rows[n].cells[k]),{rowId:this.rows[n].id,colModel:this.p.colModel[k]},k)}catch(p){a=b.jgrid.htmlDecode(this.rows[n].cells[k].innerHTML)}c?(i=parseFloat(a),j+=i,void 0===h&&(h=f=i),f=Math.min(f,i),h=Math.max(h,i)):g?e.push({id:this.rows[n].id,value:a}):e.push(a)}n++}if(c)switch(c.toLowerCase()){case "sum":e=j;break;case "avg":e=j/m;break;case "count":e=m;break;case "min":e=f;break;case "max":e=h}}}});return e},
-clearGridData:function(d){return this.each(function(){if(this.grid){"boolean"!==typeof d&&(d=!1);if(this.p.deepempty)b("#"+b.jgrid.jqID(this.p.id)+" tbody:first tr:gt(0)").remove();else{var g=b("#"+b.jgrid.jqID(this.p.id)+" tbody:first tr:first")[0];b("#"+b.jgrid.jqID(this.p.id)+" tbody:first").empty().append(g)}this.p.footerrow&&d&&b(".ui-jqgrid-ftable td",this.grid.sDiv).html("&#160;");this.p.selrow=null;this.p.selarrrow=[];this.p.savedRow=[];this.p.records=0;this.p.page=1;this.p.lastpage=0;this.p.reccount=
-0;this.p.data=[];this.p._index={};this.updatepager(!0,!1)}})},getInd:function(b,g){var c=!1,e;this.each(function(){(e=this.rows.namedItem(b))&&(c=!0===g?e:e.rowIndex)});return c},bindKeys:function(d){var g=b.extend({onEnter:null,onSpace:null,onLeftKey:null,onRightKey:null,scrollingRows:!0},d||{});return this.each(function(){var c=this;b("body").is("[role]")||b("body").attr("role","application");c.p.scrollrows=g.scrollingRows;b(c).keydown(function(d){var a=b(c).find("tr[tabindex=0]")[0],j,f,h,i=c.p.treeReader.expanded_field;
-if(a)if(h=c.p._index[b.jgrid.stripPref(c.p.idPrefix,a.id)],37===d.keyCode||38===d.keyCode||39===d.keyCode||40===d.keyCode){if(38===d.keyCode){f=a.previousSibling;j="";if(f)if(b(f).is(":hidden"))for(;f;){if(f=f.previousSibling,!b(f).is(":hidden")&&b(f).hasClass("jqgrow")){j=f.id;break}}else j=f.id;b(c).jqGrid("setSelection",j,!0,d);d.preventDefault()}if(40===d.keyCode){f=a.nextSibling;j="";if(f)if(b(f).is(":hidden"))for(;f;){if(f=f.nextSibling,!b(f).is(":hidden")&&b(f).hasClass("jqgrow")){j=f.id;break}}else j=
-f.id;b(c).jqGrid("setSelection",j,!0,d);d.preventDefault()}37===d.keyCode&&(c.p.treeGrid&&c.p.data[h][i]&&b(a).find("div.treeclick").trigger("click"),b(c).triggerHandler("jqGridKeyLeft",[c.p.selrow]),b.isFunction(g.onLeftKey)&&g.onLeftKey.call(c,c.p.selrow));39===d.keyCode&&(c.p.treeGrid&&!c.p.data[h][i]&&b(a).find("div.treeclick").trigger("click"),b(c).triggerHandler("jqGridKeyRight",[c.p.selrow]),b.isFunction(g.onRightKey)&&g.onRightKey.call(c,c.p.selrow))}else 13===d.keyCode?(b(c).triggerHandler("jqGridKeyEnter",
-[c.p.selrow]),b.isFunction(g.onEnter)&&g.onEnter.call(c,c.p.selrow)):32===d.keyCode&&(b(c).triggerHandler("jqGridKeySpace",[c.p.selrow]),b.isFunction(g.onSpace)&&g.onSpace.call(c,c.p.selrow))})})},unbindKeys:function(){return this.each(function(){b(this).unbind("keydown")})},getLocalRow:function(d){var g=!1,c;this.each(function(){void 0!==d&&(c=this.p._index[b.jgrid.stripPref(this.p.idPrefix,d)],0<=c&&(g=this.p.data[c]))});return g}})})(jQuery);
+b("#first"+b.jgrid.jqID(d)+", #prev"+b.jgrid.jqID(d)+", #next"+b.jgrid.jqID(d)+", #last"+b.jgrid.jqID(d)).click(function(){var b=o(a.p.page,1),c=o(a.p.lastpage,1),e=false,g=true,f=true,h=true,i=true;if(c===0||c===1)i=h=f=g=false;else if(c>1&&b>=1)if(b===1)f=g=false;else{if(b===c)i=h=false}else if(c>1&&b===0){i=h=false;b=c-1}if(!n(this.id))return false;if(this.id==="first"+d&&g){a.p.page=1;e=true}if(this.id==="prev"+d&&f){a.p.page=b-1;e=true}if(this.id==="next"+d&&h){a.p.page=b+1;e=true}if(this.id===
+"last"+d&&i){a.p.page=c;e=true}e&&O();return false})}a.p.pginput===true&&b("input.ui-pg-input","#"+j).keypress(function(c){if((c.charCode||c.keyCode||0)===13){if(!n("user"))return false;b(this).val(o(b(this).val(),1));a.p.page=b(this).val()>0?b(this).val():a.p.page;O();return false}return this})},ra=function(c,d){var e,g="",f=a.p.colModel,h=false,i;i=a.p.frozenColumns?d:a.grid.headers[c].el;var j="";b("span.ui-grid-ico-sort",i).addClass("ui-state-disabled");b(i).attr("aria-selected","false");if(f[c].lso)if(f[c].lso===
+"asc"){f[c].lso=f[c].lso+"-desc";j="desc"}else if(f[c].lso==="desc"){f[c].lso=f[c].lso+"-asc";j="asc"}else{if(f[c].lso==="asc-desc"||f[c].lso==="desc-asc")f[c].lso=""}else f[c].lso=j=f.firstsortorder||"asc";if(j){b("span.s-ico",i).show();b("span.ui-icon-"+j,i).removeClass("ui-state-disabled");b(i).attr("aria-selected","true")}else a.p.viewsortcols[0]||b("span.s-ico",i).hide();a.p.sortorder="";b.each(f,function(b){if(this.lso){b>0&&h&&(g=g+", ");e=this.lso.split("-");g=g+(f[b].index||f[b].name);g=
+g+(" "+e[e.length-1]);h=true;a.p.sortorder=e[e.length-1]}});i=g.lastIndexOf(a.p.sortorder);g=g.substring(0,i);a.p.sortname=g},la=function(c,d,e,g,f){if(a.p.colModel[d].sortable){var h;if(!(a.p.savedRow.length>0)){if(!e){if(a.p.lastsort===d)if(a.p.sortorder==="asc")a.p.sortorder="desc";else{if(a.p.sortorder==="desc")a.p.sortorder="asc"}else a.p.sortorder=a.p.colModel[d].firstsortorder||"asc";a.p.page=1}if(a.p.multiSort)ra(d,f);else{if(g){if(a.p.lastsort===d&&a.p.sortorder===g&&!e)return;a.p.sortorder=
+g}e=a.grid.headers[a.p.lastsort].el;f=a.p.frozenColumns?f:a.grid.headers[d].el;b("span.ui-grid-ico-sort",e).addClass("ui-state-disabled");b(e).attr("aria-selected","false");if(a.p.frozenColumns){a.grid.fhDiv.find("span.ui-grid-ico-sort").addClass("ui-state-disabled");a.grid.fhDiv.find("th").attr("aria-selected","false")}b("span.ui-icon-"+a.p.sortorder,f).removeClass("ui-state-disabled");b(f).attr("aria-selected","true");if(!a.p.viewsortcols[0]&&a.p.lastsort!==d){a.p.frozenColumns&&a.grid.fhDiv.find("span.s-ico").hide();
+b("span.s-ico",e).hide();b("span.s-ico",f).show()}c=c.substring(5+a.p.id.length+1);a.p.sortname=a.p.colModel[d].index||c;h=a.p.sortorder}if(b(a).triggerHandler("jqGridSortCol",[c,d,h])==="stop")a.p.lastsort=d;else if(b.isFunction(a.p.onSortCol)&&a.p.onSortCol.call(a,c,d,h)==="stop")a.p.lastsort=d;else{if(a.p.datatype==="local")a.p.deselectAfterSort&&b(a).jqGrid("resetSelection");else{a.p.selrow=null;a.p.multiselect&&ca(false);a.p.selarrrow=[];a.p.savedRow=[]}if(a.p.scroll){f=a.grid.bDiv.scrollLeft;
+V.call(a,true,false);a.grid.hDiv.scrollLeft=f}a.p.subGrid&&a.p.datatype==="local"&&b("td.sgexpanded","#"+b.jgrid.jqID(a.p.id)).each(function(){b(this).trigger("click")});O();a.p.lastsort=d;if(a.p.sortname!==c&&d)a.p.lastsort=d}}}},sa=function(c){c=b(a.grid.headers[c].el);c=[c.position().left+c.outerWidth()];a.p.direction==="rtl"&&(c[0]=a.p.width-c[0]);c[0]=c[0]-a.grid.bDiv.scrollLeft;c.push(b(a.grid.hDiv).position().top);c.push(b(a.grid.bDiv).offset().top-b(a.grid.hDiv).offset().top+b(a.grid.bDiv).height());
+return c},ma=function(c){var d,e=a.grid.headers,g=b.jgrid.getCellIndex(c);for(d=0;d<e.length;d++)if(c===e[d].el){g=d;break}return g};this.p.id=this.id;-1===b.inArray(a.p.multikey,["shiftKey","altKey","ctrlKey"])&&(a.p.multikey=!1);a.p.keyIndex=!1;for(g=0;g<a.p.colModel.length;g++)a.p.colModel[g]=b.extend(!0,{},a.p.cmTemplate,a.p.colModel[g].template||{},a.p.colModel[g]),!1===a.p.keyIndex&&!0===a.p.colModel[g].key&&(a.p.keyIndex=g);a.p.sortorder=a.p.sortorder.toLowerCase();b.jgrid.cell_width=b.jgrid.cellWidth();
+!0===a.p.grouping&&(a.p.scroll=!1,a.p.rownumbers=!1,a.p.treeGrid=!1,a.p.gridview=!0);if(!0===this.p.treeGrid){try{b(this).jqGrid("setTreeGrid")}catch(va){}"local"!==a.p.datatype&&(a.p.localReader={id:"_id_"})}if(this.p.subGrid)try{b(a).jqGrid("setSubGrid")}catch(wa){}this.p.multiselect&&(this.p.colNames.unshift("<input role='checkbox' id='cb_"+this.p.id+"' class='cbox' type='checkbox'/>"),this.p.colModel.unshift({name:"cb",width:b.jgrid.cell_width?a.p.multiselectWidth+a.p.cellLayout:a.p.multiselectWidth,
+sortable:!1,resizable:!1,hidedlg:!0,search:!1,align:"center",fixed:!0}));this.p.rownumbers&&(this.p.colNames.unshift(""),this.p.colModel.unshift({name:"rn",width:a.p.rownumWidth,sortable:!1,resizable:!1,hidedlg:!0,search:!1,align:"center",fixed:!0}));a.p.xmlReader=b.extend(!0,{root:"rows",row:"row",page:"rows>page",total:"rows>total",records:"rows>records",repeatitems:!0,cell:"cell",id:"[id]",userdata:"userdata",subgrid:{root:"rows",row:"row",repeatitems:!0,cell:"cell"}},a.p.xmlReader);a.p.jsonReader=
+b.extend(!0,{root:"rows",page:"page",total:"total",records:"records",repeatitems:!0,cell:"cell",id:"id",userdata:"userdata",subgrid:{root:"rows",repeatitems:!0,cell:"cell"}},a.p.jsonReader);a.p.localReader=b.extend(!0,{root:"rows",page:"page",total:"total",records:"records",repeatitems:!1,cell:"cell",id:"id",userdata:"userdata",subgrid:{root:"rows",repeatitems:!0,cell:"cell"}},a.p.localReader);a.p.scroll&&(a.p.pgbuttons=!1,a.p.pginput=!1,a.p.rowList=[]);a.p.data.length&&N();var B="<thead><tr class='ui-jqgrid-labels' role='rowheader'>",
+na,C,da,ea,fa,v,p,W,oa=W="",ba=[],pa=[];C=[];if(!0===a.p.shrinkToFit&&!0===a.p.forceFit)for(g=a.p.colModel.length-1;0<=g;g--)if(!a.p.colModel[g].hidden){a.p.colModel[g].resizable=!1;break}"horizontal"===a.p.viewsortcols[1]&&(W=" ui-i-asc",oa=" ui-i-desc");na=k?"class='ui-th-div-ie'":"";W="<span class='s-ico' style='display:none'><span sort='asc' class='ui-grid-ico-sort ui-icon-asc"+W+" ui-state-disabled ui-icon ui-icon-triangle-1-n ui-sort-"+f+"'></span>"+("<span sort='desc' class='ui-grid-ico-sort ui-icon-desc"+
+oa+" ui-state-disabled ui-icon ui-icon-triangle-1-s ui-sort-"+f+"'></span></span>");if(a.p.multiSort){ba=a.p.sortname.split(",");for(g=0;g<ba.length;g++)C=b.trim(ba[g]).split(" "),ba[g]=b.trim(C[0]),pa[g]=C[1]?b.trim(C[1]):a.p.sortorder||"asc"}for(g=0;g<this.p.colNames.length;g++)C=a.p.headertitles?' title="'+b.jgrid.stripHtml(a.p.colNames[g])+'"':"",B+="<th id='"+a.p.id+"_"+a.p.colModel[g].name+"' role='columnheader' class='ui-state-default ui-th-column ui-th-"+f+"'"+C+">",C=a.p.colModel[g].index||
+a.p.colModel[g].name,B+="<div id='jqgh_"+a.p.id+"_"+a.p.colModel[g].name+"' "+na+">"+a.p.colNames[g],a.p.colModel[g].width=a.p.colModel[g].width?parseInt(a.p.colModel[g].width,10):150,"boolean"!==typeof a.p.colModel[g].title&&(a.p.colModel[g].title=!0),a.p.colModel[g].lso="",C===a.p.sortname&&(a.p.lastsort=g),a.p.multiSort&&(C=b.inArray(C,ba),-1!==C&&(a.p.colModel[g].lso=pa[C])),B+=W+"</div></th>";W=null;b(this).append(B+"</tr></thead>");b("thead tr:first th",this).hover(function(){b(this).addClass("ui-state-hover")},
+function(){b(this).removeClass("ui-state-hover")});if(this.p.multiselect){var ga=[],Y;b("#cb_"+b.jgrid.jqID(a.p.id),this).bind("click",function(){a.p.selarrrow=[];var c=a.p.frozenColumns===true?a.p.id+"_frozen":"";if(this.checked){b(a.rows).each(function(d){if(d>0&&!b(this).hasClass("ui-subgrid")&&!b(this).hasClass("jqgroup")&&!b(this).hasClass("ui-state-disabled")){b("#jqg_"+b.jgrid.jqID(a.p.id)+"_"+b.jgrid.jqID(this.id))[a.p.useProp?"prop":"attr"]("checked",true);b(this).addClass("ui-state-highlight").attr("aria-selected",
+"true");a.p.selarrrow.push(this.id);a.p.selrow=this.id;if(c){b("#jqg_"+b.jgrid.jqID(a.p.id)+"_"+b.jgrid.jqID(this.id),a.grid.fbDiv)[a.p.useProp?"prop":"attr"]("checked",true);b("#"+b.jgrid.jqID(this.id),a.grid.fbDiv).addClass("ui-state-highlight")}}});Y=true;ga=[]}else{b(a.rows).each(function(d){if(d>0&&!b(this).hasClass("ui-subgrid")&&!b(this).hasClass("ui-state-disabled")){b("#jqg_"+b.jgrid.jqID(a.p.id)+"_"+b.jgrid.jqID(this.id))[a.p.useProp?"prop":"attr"]("checked",false);b(this).removeClass("ui-state-highlight").attr("aria-selected",
+"false");ga.push(this.id);if(c){b("#jqg_"+b.jgrid.jqID(a.p.id)+"_"+b.jgrid.jqID(this.id),a.grid.fbDiv)[a.p.useProp?"prop":"attr"]("checked",false);b("#"+b.jgrid.jqID(this.id),a.grid.fbDiv).removeClass("ui-state-highlight")}}});a.p.selrow=null;Y=false}b(a).triggerHandler("jqGridSelectAll",[Y?a.p.selarrrow:ga,Y]);b.isFunction(a.p.onSelectAll)&&a.p.onSelectAll.call(a,Y?a.p.selarrrow:ga,Y)})}!0===a.p.autowidth&&(B=b(l).innerWidth(),a.p.width=0<B?B:"nw");(function(){var d=0,e=b.jgrid.cell_width?0:o(a.p.cellLayout,
+0),g=0,f,h=o(a.p.scrollOffset,0),i,k=false,l,m=0,n;b.each(a.p.colModel,function(){if(this.hidden===void 0)this.hidden=false;if(a.p.grouping&&a.p.autowidth){var c=b.inArray(this.name,a.p.groupingView.groupField);if(c>=0&&a.p.groupingView.groupColumnShow.length>c)this.hidden=!a.p.groupingView.groupColumnShow[c]}this.widthOrg=i=o(this.width,0);if(this.hidden===false){d=d+(i+e);this.fixed?m=m+(i+e):g++}});if(isNaN(a.p.width))a.p.width=d+(a.p.shrinkToFit===false&&!isNaN(a.p.height)?h:0);c.width=a.p.width;
+a.p.tblwidth=d;if(a.p.shrinkToFit===false&&a.p.forceFit===true)a.p.forceFit=false;if(a.p.shrinkToFit===true&&g>0){l=c.width-e*g-m;if(!isNaN(a.p.height)){l=l-h;k=true}d=0;b.each(a.p.colModel,function(b){if(this.hidden===false&&!this.fixed){this.width=i=Math.round(l*this.width/(a.p.tblwidth-e*g-m));d=d+i;f=b}});n=0;k?c.width-m-(d+e*g)!==h&&(n=c.width-m-(d+e*g)-h):!k&&Math.abs(c.width-m-(d+e*g))!==1&&(n=c.width-m-(d+e*g));a.p.colModel[f].width=a.p.colModel[f].width+n;a.p.tblwidth=d+n+e*g+m;if(a.p.tblwidth>
+a.p.width){a.p.colModel[f].width=a.p.colModel[f].width-(a.p.tblwidth-parseInt(a.p.width,10));a.p.tblwidth=a.p.width}}})();b(l).css("width",c.width+"px").append("<div class='ui-jqgrid-resize-mark' id='rs_m"+a.p.id+"'>&#160;</div>");b(i).css("width",c.width+"px");var B=b("thead:first",a).get(0),Q="";a.p.footerrow&&(Q+="<table role='grid' style='width:"+a.p.tblwidth+"px' class='ui-jqgrid-ftable' cellspacing='0' cellpadding='0' border='0'><tbody><tr role='row' class='ui-widget-content footrow footrow-"+
+f+"'>");var i=b("tr:first",B),Z="<tr class='jqgfirstrow' role='row' style='height:auto'>";a.p.disableClick=!1;b("th",i).each(function(d){da=a.p.colModel[d].width;if(a.p.colModel[d].resizable===void 0)a.p.colModel[d].resizable=true;if(a.p.colModel[d].resizable){ea=document.createElement("span");b(ea).html("&#160;").addClass("ui-jqgrid-resize ui-jqgrid-resize-"+f).css("cursor","col-resize");b(this).addClass(a.p.resizeclass)}else ea="";b(this).css("width",da+"px").prepend(ea);var e="";if(a.p.colModel[d].hidden){b(this).css("display",
+"none");e="display:none;"}Z=Z+("<td role='gridcell' style='height:0px;width:"+da+"px;"+e+"'></td>");c.headers[d]={width:da,el:this};fa=a.p.colModel[d].sortable;if(typeof fa!=="boolean")fa=a.p.colModel[d].sortable=true;e=a.p.colModel[d].name;e==="cb"||e==="subgrid"||e==="rn"||a.p.viewsortcols[2]&&b(">div",this).addClass("ui-jqgrid-sortable");if(fa)if(a.p.multiSort)if(a.p.viewsortcols[0]){b("div span.s-ico",this).show();a.p.colModel[d].lso&&b("div span.ui-icon-"+a.p.colModel[d].lso,this).removeClass("ui-state-disabled")}else{if(a.p.colModel[d].lso){b("div span.s-ico",
+this).show();b("div span.ui-icon-"+a.p.colModel[d].lso,this).removeClass("ui-state-disabled")}}else if(a.p.viewsortcols[0]){b("div span.s-ico",this).show();d===a.p.lastsort&&b("div span.ui-icon-"+a.p.sortorder,this).removeClass("ui-state-disabled")}else if(d===a.p.lastsort){b("div span.s-ico",this).show();b("div span.ui-icon-"+a.p.sortorder,this).removeClass("ui-state-disabled")}a.p.footerrow&&(Q=Q+("<td role='gridcell' "+n(d,0,"",null,"",false)+">&#160;</td>"))}).mousedown(function(d){if(b(d.target).closest("th>span.ui-jqgrid-resize").length===
+1){var e=ma(this);if(a.p.forceFit===true){var g=a.p,f=e,h;for(h=e+1;h<a.p.colModel.length;h++)if(a.p.colModel[h].hidden!==true){f=h;break}g.nv=f-e}c.dragStart(e,d,sa(e));return false}}).click(function(c){if(a.p.disableClick)return a.p.disableClick=false;var d="th>div.ui-jqgrid-sortable",e,g;a.p.viewsortcols[2]||(d="th>div>span>span.ui-grid-ico-sort");c=b(c.target).closest(d);if(c.length===1){var f;if(a.p.frozenColumns){var h=b(this)[0].id.substring(5);b(a.p.colModel).each(function(a){if(this.name===
+h){f=a;return false}})}else f=ma(this);if(!a.p.viewsortcols[2]){e=true;g=c.attr("sort")}f!=null&&la(b("div",this)[0].id,f,e,g,this);return false}});if(a.p.sortable&&b.fn.sortable)try{b(a).jqGrid("sortableColumns",i)}catch(xa){}a.p.footerrow&&(Q+="</tr></tbody></table>");Z+="</tr>";this.appendChild(document.createElement("tbody"));b(this).addClass("ui-jqgrid-btable").append(Z);var Z=null,i=b("<table class='ui-jqgrid-htable' style='width:"+a.p.tblwidth+"px' role='grid' aria-labelledby='gbox_"+this.id+
+"' cellspacing='0' cellpadding='0' border='0'></table>").append(B),H=a.p.caption&&!0===a.p.hiddengrid?!0:!1;g=b("<div class='ui-jqgrid-hbox"+("rtl"===f?"-rtl":"")+"'></div>");B=null;c.hDiv=document.createElement("div");b(c.hDiv).css({width:c.width+"px"}).addClass("ui-state-default ui-jqgrid-hdiv").append(g);b(g).append(i);i=null;H&&b(c.hDiv).hide();a.p.pager&&("string"===typeof a.p.pager?"#"!==a.p.pager.substr(0,1)&&(a.p.pager="#"+a.p.pager):a.p.pager="#"+b(a.p.pager).attr("id"),b(a.p.pager).css({width:c.width+
+"px"}).addClass("ui-state-default ui-jqgrid-pager ui-corner-bottom").appendTo(l),H&&b(a.p.pager).hide(),ka(a.p.pager,""));!1===a.p.cellEdit&&!0===a.p.hoverrows&&b(a).bind("mouseover",function(a){p=b(a.target).closest("tr.jqgrow");b(p).attr("class")!=="ui-subgrid"&&b(p).addClass("ui-state-hover")}).bind("mouseout",function(a){p=b(a.target).closest("tr.jqgrow");b(p).removeClass("ui-state-hover")});var w,I,ha;b(a).before(c.hDiv).click(function(c){v=c.target;p=b(v,a.rows).closest("tr.jqgrow");if(b(p).length===
+0||p[0].className.indexOf("ui-state-disabled")>-1||(b(v,a).closest("table.ui-jqgrid-btable").attr("id")||"").replace("_frozen","")!==a.id)return this;var d=b(v).hasClass("cbox"),e=b(a).triggerHandler("jqGridBeforeSelectRow",[p[0].id,c]);(e=e===false||e==="stop"?false:true)&&b.isFunction(a.p.beforeSelectRow)&&(e=a.p.beforeSelectRow.call(a,p[0].id,c));if(!(v.tagName==="A"||(v.tagName==="INPUT"||v.tagName==="TEXTAREA"||v.tagName==="OPTION"||v.tagName==="SELECT")&&!d)&&e===true){w=p[0].id;I=b.jgrid.getCellIndex(v);
+ha=b(v).closest("td,th").html();b(a).triggerHandler("jqGridCellSelect",[w,I,ha,c]);b.isFunction(a.p.onCellSelect)&&a.p.onCellSelect.call(a,w,I,ha,c);if(a.p.cellEdit===true)if(a.p.multiselect&&d)b(a).jqGrid("setSelection",w,true,c);else{w=p[0].rowIndex;try{b(a).jqGrid("editCell",w,I,true)}catch(g){}}else if(a.p.multikey)if(c[a.p.multikey])b(a).jqGrid("setSelection",w,true,c);else{if(a.p.multiselect&&d){d=b("#jqg_"+b.jgrid.jqID(a.p.id)+"_"+w).is(":checked");b("#jqg_"+b.jgrid.jqID(a.p.id)+"_"+w)[a.p.useProp?
+"prop":"attr"]("checked",d)}}else{if(a.p.multiselect&&a.p.multiboxonly&&!d){var f=a.p.frozenColumns?a.p.id+"_frozen":"";b(a.p.selarrrow).each(function(c,d){var e=a.rows.namedItem(d);b(e).removeClass("ui-state-highlight");b("#jqg_"+b.jgrid.jqID(a.p.id)+"_"+b.jgrid.jqID(d))[a.p.useProp?"prop":"attr"]("checked",false);if(f){b("#"+b.jgrid.jqID(d),"#"+b.jgrid.jqID(f)).removeClass("ui-state-highlight");b("#jqg_"+b.jgrid.jqID(a.p.id)+"_"+b.jgrid.jqID(d),"#"+b.jgrid.jqID(f))[a.p.useProp?"prop":"attr"]("checked",
+false)}});a.p.selarrrow=[]}b(a).jqGrid("setSelection",w,true,c)}}}).bind("reloadGrid",function(c,d){if(a.p.treeGrid===true)a.p.datatype=a.p.treedatatype;d&&d.current&&a.grid.selectionPreserver(a);if(a.p.datatype==="local"){b(a).jqGrid("resetSelection");a.p.data.length&&N()}else if(!a.p.treeGrid){a.p.selrow=null;if(a.p.multiselect){a.p.selarrrow=[];ca(false)}a.p.savedRow=[]}a.p.scroll&&V.call(a,true,false);if(d&&d.page){var e=d.page;if(e>a.p.lastpage)e=a.p.lastpage;e<1&&(e=1);a.p.page=e;a.grid.bDiv.scrollTop=
+a.grid.prevRowHeight?(e-1)*a.grid.prevRowHeight*a.p.rowNum:0}if(a.grid.prevRowHeight&&a.p.scroll){delete a.p.lastpage;a.grid.populateVisible()}else a.grid.populate();a.p._inlinenav===true&&b(a).jqGrid("showAddEditButtons");return false}).dblclick(function(c){v=c.target;p=b(v,a.rows).closest("tr.jqgrow");if(b(p).length!==0){w=p[0].rowIndex;I=b.jgrid.getCellIndex(v);b(a).triggerHandler("jqGridDblClickRow",[b(p).attr("id"),w,I,c]);b.isFunction(a.p.ondblClickRow)&&a.p.ondblClickRow.call(a,b(p).attr("id"),
+w,I,c)}}).bind("contextmenu",function(c){v=c.target;p=b(v,a.rows).closest("tr.jqgrow");if(b(p).length!==0){a.p.multiselect||b(a).jqGrid("setSelection",p[0].id,true,c);w=p[0].rowIndex;I=b.jgrid.getCellIndex(v);b(a).triggerHandler("jqGridRightClickRow",[b(p).attr("id"),w,I,c]);b.isFunction(a.p.onRightClickRow)&&a.p.onRightClickRow.call(a,b(p).attr("id"),w,I,c)}});c.bDiv=document.createElement("div");k&&"auto"===(""+a.p.height).toLowerCase()&&(a.p.height="100%");b(c.bDiv).append(b('<div style="position:relative;'+
+(k&&8>b.jgrid.msiever()?"height:0.01%;":"")+'"></div>').append("<div></div>").append(this)).addClass("ui-jqgrid-bdiv").css({height:a.p.height+(isNaN(a.p.height)?"":"px"),width:c.width+"px"}).scroll(c.scrollGrid);b("table:first",c.bDiv).css({width:a.p.tblwidth+"px"});b.support.tbody||2===b("tbody",this).length&&b("tbody:gt(0)",this).remove();a.p.multikey&&(b.jgrid.msie?b(c.bDiv).bind("selectstart",function(){return false}):b(c.bDiv).bind("mousedown",function(){return false}));H&&b(c.bDiv).hide();c.cDiv=
+document.createElement("div");var ia=!0===a.p.hidegrid?b("<a role='link' href='javascript:void(0)'/>").addClass("ui-jqgrid-titlebar-close HeaderButton").hover(function(){ia.addClass("ui-state-hover")},function(){ia.removeClass("ui-state-hover")}).append("<span class='ui-icon ui-icon-circle-triangle-n'></span>").css("rtl"===f?"left":"right","0px"):"";b(c.cDiv).append(ia).append("<span class='ui-jqgrid-title"+("rtl"===f?"-rtl":"")+"'>"+a.p.caption+"</span>").addClass("ui-jqgrid-titlebar ui-widget-header ui-corner-top ui-helper-clearfix");
+b(c.cDiv).insertBefore(c.hDiv);a.p.toolbar[0]&&(c.uDiv=document.createElement("div"),"top"===a.p.toolbar[1]?b(c.uDiv).insertBefore(c.hDiv):"bottom"===a.p.toolbar[1]&&b(c.uDiv).insertAfter(c.hDiv),"both"===a.p.toolbar[1]?(c.ubDiv=document.createElement("div"),b(c.uDiv).addClass("ui-userdata ui-state-default").attr("id","t_"+this.id).insertBefore(c.hDiv),b(c.ubDiv).addClass("ui-userdata ui-state-default").attr("id","tb_"+this.id).insertAfter(c.hDiv),H&&b(c.ubDiv).hide()):b(c.uDiv).width(c.width).addClass("ui-userdata ui-state-default").attr("id",
+"t_"+this.id),H&&b(c.uDiv).hide());a.p.toppager&&(a.p.toppager=b.jgrid.jqID(a.p.id)+"_toppager",c.topDiv=b("<div id='"+a.p.toppager+"'></div>")[0],a.p.toppager="#"+a.p.toppager,b(c.topDiv).addClass("ui-state-default ui-jqgrid-toppager").width(c.width).insertBefore(c.hDiv),ka(a.p.toppager,"_t"));a.p.footerrow&&(c.sDiv=b("<div class='ui-jqgrid-sdiv'></div>")[0],g=b("<div class='ui-jqgrid-hbox"+("rtl"===f?"-rtl":"")+"'></div>"),b(c.sDiv).append(g).width(c.width).insertAfter(c.hDiv),b(g).append(Q),c.footers=
+b(".ui-jqgrid-ftable",c.sDiv)[0].rows[0].cells,a.p.rownumbers&&(c.footers[0].className="ui-state-default jqgrid-rownum"),H&&b(c.sDiv).hide());g=null;if(a.p.caption){var ta=a.p.datatype;!0===a.p.hidegrid&&(b(".ui-jqgrid-titlebar-close",c.cDiv).click(function(d){var e=b.isFunction(a.p.onHeaderClick),g=".ui-jqgrid-bdiv, .ui-jqgrid-hdiv, .ui-jqgrid-pager, .ui-jqgrid-sdiv",f,h=this;if(a.p.toolbar[0]===true){a.p.toolbar[1]==="both"&&(g=g+(", #"+b(c.ubDiv).attr("id")));g=g+(", #"+b(c.uDiv).attr("id"))}f=
+b(g,"#gview_"+b.jgrid.jqID(a.p.id)).length;a.p.gridstate==="visible"?b(g,"#gbox_"+b.jgrid.jqID(a.p.id)).slideUp("fast",function(){f--;if(f===0){b("span",h).removeClass("ui-icon-circle-triangle-n").addClass("ui-icon-circle-triangle-s");a.p.gridstate="hidden";b("#gbox_"+b.jgrid.jqID(a.p.id)).hasClass("ui-resizable")&&b(".ui-resizable-handle","#gbox_"+b.jgrid.jqID(a.p.id)).hide();b(a).triggerHandler("jqGridHeaderClick",[a.p.gridstate,d]);e&&(H||a.p.onHeaderClick.call(a,a.p.gridstate,d))}}):a.p.gridstate===
+"hidden"&&b(g,"#gbox_"+b.jgrid.jqID(a.p.id)).slideDown("fast",function(){f--;if(f===0){b("span",h).removeClass("ui-icon-circle-triangle-s").addClass("ui-icon-circle-triangle-n");if(H){a.p.datatype=ta;O();H=false}a.p.gridstate="visible";b("#gbox_"+b.jgrid.jqID(a.p.id)).hasClass("ui-resizable")&&b(".ui-resizable-handle","#gbox_"+b.jgrid.jqID(a.p.id)).show();b(a).triggerHandler("jqGridHeaderClick",[a.p.gridstate,d]);e&&(H||a.p.onHeaderClick.call(a,a.p.gridstate,d))}});return false}),H&&(a.p.datatype=
+"local",b(".ui-jqgrid-titlebar-close",c.cDiv).trigger("click")))}else b(c.cDiv).hide();b(c.hDiv).after(c.bDiv).mousemove(function(a){if(c.resizing){c.dragMove(a);return false}});b(".ui-jqgrid-labels",c.hDiv).bind("selectstart",function(){return false});b(document).mouseup(function(){if(c.resizing){c.dragEnd();return false}return true});a.formatCol=n;a.sortData=la;a.updatepager=function(c,d){var e,g,f,h,i,j,k,l="",m=a.p.pager?"_"+b.jgrid.jqID(a.p.pager.substr(1)):"",n=a.p.toppager?"_"+a.p.toppager.substr(1):
+"";f=parseInt(a.p.page,10)-1;f<0&&(f=0);f=f*parseInt(a.p.rowNum,10);i=f+a.p.reccount;if(a.p.scroll){e=b("tbody:first > tr:gt(0)",a.grid.bDiv);f=i-e.length;a.p.reccount=e.length;if(e=e.outerHeight()||a.grid.prevRowHeight){g=f*e;k=parseInt(a.p.records,10)*e;b(">div:first",a.grid.bDiv).css({height:k}).children("div:first").css({height:g,display:g?"":"none"});if(a.grid.bDiv.scrollTop==0&&a.p.page>1)a.grid.bDiv.scrollTop=a.p.rowNum*(a.p.page-1)*e}a.grid.bDiv.scrollLeft=a.grid.hDiv.scrollLeft}l=a.p.pager||
+"";if(l=l+(a.p.toppager?l?","+a.p.toppager:a.p.toppager:"")){k=b.jgrid.formatter.integer||{};e=o(a.p.page);g=o(a.p.lastpage);b(".selbox",l)[this.p.useProp?"prop":"attr"]("disabled",false);if(a.p.pginput===true){b(".ui-pg-input",l).val(a.p.page);h=a.p.toppager?"#sp_1"+m+",#sp_1"+n:"#sp_1"+m;b(h).html(b.fmatter?b.fmatter.util.NumberFormat(a.p.lastpage,k):a.p.lastpage)}if(a.p.viewrecords)if(a.p.reccount===0)b(".ui-paging-info",l).html(a.p.emptyrecords);else{h=f+1;j=a.p.records;if(b.fmatter){h=b.fmatter.util.NumberFormat(h,
+k);i=b.fmatter.util.NumberFormat(i,k);j=b.fmatter.util.NumberFormat(j,k)}b(".ui-paging-info",l).html(b.jgrid.format(a.p.recordtext,h,i,j))}if(a.p.pgbuttons===true){e<=0&&(e=g=0);if(e===1||e===0){b("#first"+m+", #prev"+m).addClass("ui-state-disabled").removeClass("ui-state-hover");a.p.toppager&&b("#first_t"+n+", #prev_t"+n).addClass("ui-state-disabled").removeClass("ui-state-hover")}else{b("#first"+m+", #prev"+m).removeClass("ui-state-disabled");a.p.toppager&&b("#first_t"+n+", #prev_t"+n).removeClass("ui-state-disabled")}if(e===
+g||e===0){b("#next"+m+", #last"+m).addClass("ui-state-disabled").removeClass("ui-state-hover");a.p.toppager&&b("#next_t"+n+", #last_t"+n).addClass("ui-state-disabled").removeClass("ui-state-hover")}else{b("#next"+m+", #last"+m).removeClass("ui-state-disabled");a.p.toppager&&b("#next_t"+n+", #last_t"+n).removeClass("ui-state-disabled")}}}c===true&&a.p.rownumbers===true&&b(">td.jqgrid-rownum",a.rows).each(function(a){b(this).html(f+1+a)});d&&a.p.jqgdnd&&b(a).jqGrid("gridDnD","updateDnD");b(a).triggerHandler("jqGridGridComplete");
+b.isFunction(a.p.gridComplete)&&a.p.gridComplete.call(a);b(a).triggerHandler("jqGridAfterGridComplete")};a.refreshIndex=N;a.setHeadCheckBox=ca;a.constructTr=X;a.formatter=function(a,b,c,d,e){return t(a,b,c,d,e)};b.extend(c,{populate:O,emptyRows:V});this.grid=c;a.addXmlData=function(b){J(b,a.grid.bDiv)};a.addJSONData=function(b){S(b,a.grid.bDiv)};this.grid.cols=this.rows[0].cells;b(a).triggerHandler("jqGridInitGrid");b.isFunction(a.p.onInitGrid)&&a.p.onInitGrid.call(a);O();a.p.hiddengrid=!1}}}})};
+b.jgrid.extend({getGridParam:function(b){var f=this[0];return!f||!f.grid?void 0:!b?f.p:void 0!==f.p[b]?f.p[b]:null},setGridParam:function(d){return this.each(function(){this.grid&&"object"===typeof d&&b.extend(!0,this.p,d)})},getDataIDs:function(){var d=[],f=0,c,e=0;this.each(function(){if((c=this.rows.length)&&0<c)for(;f<c;)b(this.rows[f]).hasClass("jqgrow")&&(d[e]=this.rows[f].id,e++),f++});return d},setSelection:function(d,f,c){return this.each(function(){var e,a,j,g,h,i;if(void 0!==d&&(f=!1===
+f?!1:!0,(a=this.rows.namedItem(""+d))&&a.className&&!(-1<a.className.indexOf("ui-state-disabled"))))if(!0===this.p.scrollrows&&(j=this.rows.namedItem(d).rowIndex,0<=j&&(e=b(this.grid.bDiv)[0].clientHeight,g=b(this.grid.bDiv)[0].scrollTop,h=b(this.rows[j]).position().top,j=this.rows[j].clientHeight,h+j>=e+g?b(this.grid.bDiv)[0].scrollTop=h-(e+g)+j+g:h<e+g&&h<g&&(b(this.grid.bDiv)[0].scrollTop=h))),!0===this.p.frozenColumns&&(i=this.p.id+"_frozen"),this.p.multiselect){if(this.setHeadCheckBox(!1),this.p.selrow=
+a.id,g=b.inArray(this.p.selrow,this.p.selarrrow),-1===g?("ui-subgrid"!==a.className&&b(a).addClass("ui-state-highlight").attr("aria-selected","true"),e=!0,this.p.selarrrow.push(this.p.selrow)):("ui-subgrid"!==a.className&&b(a).removeClass("ui-state-highlight").attr("aria-selected","false"),e=!1,this.p.selarrrow.splice(g,1),h=this.p.selarrrow[0],this.p.selrow=void 0===h?null:h),b("#jqg_"+b.jgrid.jqID(this.p.id)+"_"+b.jgrid.jqID(a.id))[this.p.useProp?"prop":"attr"]("checked",e),i&&(-1===g?b("#"+b.jgrid.jqID(d),
+"#"+b.jgrid.jqID(i)).addClass("ui-state-highlight"):b("#"+b.jgrid.jqID(d),"#"+b.jgrid.jqID(i)).removeClass("ui-state-highlight"),b("#jqg_"+b.jgrid.jqID(this.p.id)+"_"+b.jgrid.jqID(d),"#"+b.jgrid.jqID(i))[this.p.useProp?"prop":"attr"]("checked",e)),f)b(this).triggerHandler("jqGridSelectRow",[a.id,e,c]),this.p.onSelectRow&&this.p.onSelectRow.call(this,a.id,e,c)}else if("ui-subgrid"!==a.className&&(this.p.selrow!==a.id?(b(this.rows.namedItem(this.p.selrow)).removeClass("ui-state-highlight").attr({"aria-selected":"false",
+tabindex:"-1"}),b(a).addClass("ui-state-highlight").attr({"aria-selected":"true",tabindex:"0"}),i&&(b("#"+b.jgrid.jqID(this.p.selrow),"#"+b.jgrid.jqID(i)).removeClass("ui-state-highlight"),b("#"+b.jgrid.jqID(d),"#"+b.jgrid.jqID(i)).addClass("ui-state-highlight")),e=!0):e=!1,this.p.selrow=a.id,f))b(this).triggerHandler("jqGridSelectRow",[a.id,e,c]),this.p.onSelectRow&&this.p.onSelectRow.call(this,a.id,e,c)})},resetSelection:function(d){return this.each(function(){var f=this,c,e,a;!0===f.p.frozenColumns&&
+(a=f.p.id+"_frozen");if(void 0!==d){e=d===f.p.selrow?f.p.selrow:d;b("#"+b.jgrid.jqID(f.p.id)+" tbody:first tr#"+b.jgrid.jqID(e)).removeClass("ui-state-highlight").attr("aria-selected","false");a&&b("#"+b.jgrid.jqID(e),"#"+b.jgrid.jqID(a)).removeClass("ui-state-highlight");if(f.p.multiselect){b("#jqg_"+b.jgrid.jqID(f.p.id)+"_"+b.jgrid.jqID(e),"#"+b.jgrid.jqID(f.p.id))[f.p.useProp?"prop":"attr"]("checked",!1);if(a)b("#jqg_"+b.jgrid.jqID(f.p.id)+"_"+b.jgrid.jqID(e),"#"+b.jgrid.jqID(a))[f.p.useProp?"prop":
+"attr"]("checked",!1);f.setHeadCheckBox(!1)}e=null}else f.p.multiselect?(b(f.p.selarrrow).each(function(d,e){c=f.rows.namedItem(e);b(c).removeClass("ui-state-highlight").attr("aria-selected","false");b("#jqg_"+b.jgrid.jqID(f.p.id)+"_"+b.jgrid.jqID(e))[f.p.useProp?"prop":"attr"]("checked",!1);a&&(b("#"+b.jgrid.jqID(e),"#"+b.jgrid.jqID(a)).removeClass("ui-state-highlight"),b("#jqg_"+b.jgrid.jqID(f.p.id)+"_"+b.jgrid.jqID(e),"#"+b.jgrid.jqID(a))[f.p.useProp?"prop":"attr"]("checked",!1))}),f.setHeadCheckBox(!1),
+f.p.selarrrow=[]):f.p.selrow&&(b("#"+b.jgrid.jqID(f.p.id)+" tbody:first tr#"+b.jgrid.jqID(f.p.selrow)).removeClass("ui-state-highlight").attr("aria-selected","false"),a&&b("#"+b.jgrid.jqID(f.p.selrow),"#"+b.jgrid.jqID(a)).removeClass("ui-state-highlight"),f.p.selrow=null);!0===f.p.cellEdit&&0<=parseInt(f.p.iCol,10)&&0<=parseInt(f.p.iRow,10)&&(b("td:eq("+f.p.iCol+")",f.rows[f.p.iRow]).removeClass("edit-cell ui-state-highlight"),b(f.rows[f.p.iRow]).removeClass("selected-row ui-state-hover"));f.p.savedRow=
+[]})},getRowData:function(d){var f={},c,e=!1,a,j=0;this.each(function(){var g=this,h,i;if(void 0===d)e=!0,c=[],a=g.rows.length;else{i=g.rows.namedItem(d);if(!i)return f;a=2}for(;j<a;)e&&(i=g.rows[j]),b(i).hasClass("jqgrow")&&(b('td[role="gridcell"]',i).each(function(a){h=g.p.colModel[a].name;if("cb"!==h&&"subgrid"!==h&&"rn"!==h)if(!0===g.p.treeGrid&&h===g.p.ExpandColumn)f[h]=b.jgrid.htmlDecode(b("span:first",this).html());else try{f[h]=b.unformat.call(g,this,{rowId:i.id,colModel:g.p.colModel[a]},
+a)}catch(c){f[h]=b.jgrid.htmlDecode(b(this).html())}}),e&&(c.push(f),f={})),j++});return c||f},delRowData:function(d){var f=!1,c,e;this.each(function(){c=this.rows.namedItem(d);if(!c)return!1;b(c).remove();this.p.records--;this.p.reccount--;this.updatepager(!0,!1);f=!0;this.p.multiselect&&(e=b.inArray(d,this.p.selarrrow),-1!==e&&this.p.selarrrow.splice(e,1));this.p.selrow=this.p.multiselect&&0<this.p.selarrrow.length?this.p.selarrrow[this.p.selarrrow.length-1]:null;if("local"===this.p.datatype){var a=
+this.p._index[b.jgrid.stripPref(this.p.idPrefix,d)];void 0!==a&&(this.p.data.splice(a,1),this.refreshIndex())}if(!0===this.p.altRows&&f){var j=this.p.altclass;b(this.rows).each(function(a){a%2===1?b(this).addClass(j):b(this).removeClass(j)})}});return f},setRowData:function(d,f,c){var e,a=!0,j;this.each(function(){if(!this.grid)return!1;var g=this,h,i,k=typeof c,l={};i=g.rows.namedItem(d);if(!i)return!1;if(f)try{if(b(this.p.colModel).each(function(a){e=this.name;var c=b.jgrid.getAccessor(f,e);void 0!==
+c&&(l[e]=this.formatter&&"string"===typeof this.formatter&&"date"===this.formatter?b.unformat.date.call(g,c,this):c,h=g.formatter(d,c,a,f,"edit"),j=this.title?{title:b.jgrid.stripHtml(h)}:{},!0===g.p.treeGrid&&e===g.p.ExpandColumn?b("td[role='gridcell']:eq("+a+") > span:first",i).html(h).attr(j):b("td[role='gridcell']:eq("+a+")",i).html(h).attr(j))}),"local"===g.p.datatype){var o=b.jgrid.stripPref(g.p.idPrefix,d),n=g.p._index[o],m;if(g.p.treeGrid)for(m in g.p.treeReader)g.p.treeReader.hasOwnProperty(m)&&
+delete l[g.p.treeReader[m]];void 0!==n&&(g.p.data[n]=b.extend(!0,g.p.data[n],l));l=null}}catch(t){a=!1}a&&("string"===k?b(i).addClass(c):"object"===k&&b(i).css(c),b(g).triggerHandler("jqGridAfterGridComplete"))});return a},addRowData:function(d,f,c,e){c||(c="last");var a=!1,j,g,h,i,k,l,o,n,m="",t,A,T,M,$,U;f&&(b.isArray(f)?(t=!0,c="last",A=d):(f=[f],t=!1),this.each(function(){var V=f.length;k=this.p.rownumbers===true?1:0;h=this.p.multiselect===true?1:0;i=this.p.subGrid===true?1:0;if(!t)if(d!==void 0)d=
+""+d;else{d=b.jgrid.randId();if(this.p.keyIndex!==false){A=this.p.colModel[this.p.keyIndex+h+i+k].name;f[0][A]!==void 0&&(d=f[0][A])}}T=this.p.altclass;for(var N=0,X="",J={},S=b.isFunction(this.p.afterInsertRow)?true:false;N<V;){M=f[N];g=[];if(t){try{d=M[A];d===void 0&&(d=b.jgrid.randId())}catch(ja){d=b.jgrid.randId()}X=this.p.altRows===true?(this.rows.length-1)%2===0?T:"":""}U=d;d=this.p.idPrefix+d;if(k){m=this.formatCol(0,1,"",null,d,true);g[g.length]='<td role="gridcell" class="ui-state-default jqgrid-rownum" '+
+m+">0</td>"}if(h){n='<input role="checkbox" type="checkbox" id="jqg_'+this.p.id+"_"+d+'" class="cbox"/>';m=this.formatCol(k,1,"",null,d,true);g[g.length]='<td role="gridcell" '+m+">"+n+"</td>"}i&&(g[g.length]=b(this).jqGrid("addSubGridCell",h+k,1));for(o=h+i+k;o<this.p.colModel.length;o++){$=this.p.colModel[o];j=$.name;J[j]=M[j];n=this.formatter(d,b.jgrid.getAccessor(M,j),o,M);m=this.formatCol(o,1,n,M,d,J);g[g.length]='<td role="gridcell" '+m+">"+n+"</td>"}g.unshift(this.constructTr(d,false,X,J,M,
+false));g[g.length]="</tr>";if(this.rows.length===0)b("table:first",this.grid.bDiv).append(g.join(""));else switch(c){case "last":b(this.rows[this.rows.length-1]).after(g.join(""));l=this.rows.length-1;break;case "first":b(this.rows[0]).after(g.join(""));l=1;break;case "after":(l=this.rows.namedItem(e))&&(b(this.rows[l.rowIndex+1]).hasClass("ui-subgrid")?b(this.rows[l.rowIndex+1]).after(g):b(l).after(g.join("")));l++;break;case "before":if(l=this.rows.namedItem(e)){b(l).before(g.join(""));l=l.rowIndex}l--}this.p.subGrid===
+true&&b(this).jqGrid("addSubGrid",h+k,l);this.p.records++;this.p.reccount++;b(this).triggerHandler("jqGridAfterInsertRow",[d,M,M]);S&&this.p.afterInsertRow.call(this,d,M,M);N++;if(this.p.datatype==="local"){J[this.p.localReader.id]=U;this.p._index[U]=this.p.data.length;this.p.data.push(J);J={}}}this.p.altRows===true&&!t&&(c==="last"?(this.rows.length-1)%2===1&&b(this.rows[this.rows.length-1]).addClass(T):b(this.rows).each(function(a){a%2===1?b(this).addClass(T):b(this).removeClass(T)}));this.updatepager(true,
+true);a=true}));return a},footerData:function(d,f,c){function e(a){for(var b in a)if(a.hasOwnProperty(b))return!1;return!0}var a,j=!1,g={},h;void 0===d&&(d="get");"boolean"!==typeof c&&(c=!0);d=d.toLowerCase();this.each(function(){var i=this,k;if(!i.grid||!i.p.footerrow||"set"===d&&e(f))return!1;j=!0;b(this.p.colModel).each(function(e){a=this.name;"set"===d?void 0!==f[a]&&(k=c?i.formatter("",f[a],e,f,"edit"):f[a],h=this.title?{title:b.jgrid.stripHtml(k)}:{},b("tr.footrow td:eq("+e+")",i.grid.sDiv).html(k).attr(h),
+j=!0):"get"===d&&(g[a]=b("tr.footrow td:eq("+e+")",i.grid.sDiv).html())})});return"get"===d?g:j},showHideCol:function(d,f){return this.each(function(){var c=this,e=!1,a=b.jgrid.cell_width?0:c.p.cellLayout,j;if(c.grid){"string"===typeof d&&(d=[d]);f="none"!==f?"":"none";var g=""===f?!0:!1,h=c.p.groupHeader&&("object"===typeof c.p.groupHeader||b.isFunction(c.p.groupHeader));h&&b(c).jqGrid("destroyGroupHeader",!1);b(this.p.colModel).each(function(h){if(-1!==b.inArray(this.name,d)&&this.hidden===g){if(!0===
+c.p.frozenColumns&&!0===this.frozen)return!0;b("tr",c.grid.hDiv).each(function(){b(this.cells[h]).css("display",f)});b(c.rows).each(function(){b(this).hasClass("jqgroup")||b(this.cells[h]).css("display",f)});c.p.footerrow&&b("tr.footrow td:eq("+h+")",c.grid.sDiv).css("display",f);j=parseInt(this.width,10);c.p.tblwidth="none"===f?c.p.tblwidth-(j+a):c.p.tblwidth+(j+a);this.hidden=!g;e=!0;b(c).triggerHandler("jqGridShowHideCol",[g,this.name,h])}});!0===e&&(!0===c.p.shrinkToFit&&!isNaN(c.p.height)&&(c.p.tblwidth+=
+parseInt(c.p.scrollOffset,10)),b(c).jqGrid("setGridWidth",!0===c.p.shrinkToFit?c.p.tblwidth:c.p.width));h&&b(c).jqGrid("setGroupHeaders",c.p.groupHeader)}})},hideCol:function(d){return this.each(function(){b(this).jqGrid("showHideCol",d,"none")})},showCol:function(d){return this.each(function(){b(this).jqGrid("showHideCol",d,"")})},remapColumns:function(d,f,c){function e(a){var c;c=a.length?b.makeArray(a):b.extend({},a);b.each(d,function(b){a[b]=c[this]})}function a(a,c){b(">tr"+(c||""),a).each(function(){var a=
+this,c=b.makeArray(a.cells);b.each(d,function(){var b=c[this];b&&a.appendChild(b)})})}var j=this.get(0);e(j.p.colModel);e(j.p.colNames);e(j.grid.headers);a(b("thead:first",j.grid.hDiv),c&&":not(.ui-jqgrid-labels)");f&&a(b("#"+b.jgrid.jqID(j.p.id)+" tbody:first"),".jqgfirstrow, tr.jqgrow, tr.jqfoot");j.p.footerrow&&a(b("tbody:first",j.grid.sDiv));j.p.remapColumns&&(j.p.remapColumns.length?e(j.p.remapColumns):j.p.remapColumns=b.makeArray(d));j.p.lastsort=b.inArray(j.p.lastsort,d);j.p.treeGrid&&(j.p.expColInd=
+b.inArray(j.p.expColInd,d));b(j).triggerHandler("jqGridRemapColumns",[d,f,c])},setGridWidth:function(d,f){return this.each(function(){if(this.grid){var c=this,e,a=0,j=b.jgrid.cell_width?0:c.p.cellLayout,g,h=0,i=!1,k=c.p.scrollOffset,l,o=0,n;"boolean"!==typeof f&&(f=c.p.shrinkToFit);if(!isNaN(d)){d=parseInt(d,10);c.grid.width=c.p.width=d;b("#gbox_"+b.jgrid.jqID(c.p.id)).css("width",d+"px");b("#gview_"+b.jgrid.jqID(c.p.id)).css("width",d+"px");b(c.grid.bDiv).css("width",d+"px");b(c.grid.hDiv).css("width",
+d+"px");c.p.pager&&b(c.p.pager).css("width",d+"px");c.p.toppager&&b(c.p.toppager).css("width",d+"px");!0===c.p.toolbar[0]&&(b(c.grid.uDiv).css("width",d+"px"),"both"===c.p.toolbar[1]&&b(c.grid.ubDiv).css("width",d+"px"));c.p.footerrow&&b(c.grid.sDiv).css("width",d+"px");!1===f&&!0===c.p.forceFit&&(c.p.forceFit=!1);if(!0===f){b.each(c.p.colModel,function(){if(this.hidden===false){e=this.widthOrg;a=a+(e+j);this.fixed?o=o+(e+j):h++}});if(0===h)return;c.p.tblwidth=a;l=d-j*h-o;if(!isNaN(c.p.height)&&(b(c.grid.bDiv)[0].clientHeight<
+b(c.grid.bDiv)[0].scrollHeight||1===c.rows.length))i=!0,l-=k;var a=0,m=0<c.grid.cols.length;b.each(c.p.colModel,function(b){if(this.hidden===false&&!this.fixed){e=this.widthOrg;e=Math.round(l*e/(c.p.tblwidth-j*h-o));if(!(e<0)){this.width=e;a=a+e;c.grid.headers[b].width=e;c.grid.headers[b].el.style.width=e+"px";if(c.p.footerrow)c.grid.footers[b].style.width=e+"px";if(m)c.grid.cols[b].style.width=e+"px";g=b}}});if(!g)return;n=0;i?d-o-(a+j*h)!==k&&(n=d-o-(a+j*h)-k):1!==Math.abs(d-o-(a+j*h))&&(n=d-o-
+(a+j*h));c.p.colModel[g].width+=n;c.p.tblwidth=a+n+j*h+o;c.p.tblwidth>d?(i=c.p.tblwidth-parseInt(d,10),c.p.tblwidth=d,e=c.p.colModel[g].width-=i):e=c.p.colModel[g].width;c.grid.headers[g].width=e;c.grid.headers[g].el.style.width=e+"px";m&&(c.grid.cols[g].style.width=e+"px");c.p.footerrow&&(c.grid.footers[g].style.width=e+"px")}c.p.tblwidth&&(b("table:first",c.grid.bDiv).css("width",c.p.tblwidth+"px"),b("table:first",c.grid.hDiv).css("width",c.p.tblwidth+"px"),c.grid.hDiv.scrollLeft=c.grid.bDiv.scrollLeft,
+c.p.footerrow&&b("table:first",c.grid.sDiv).css("width",c.p.tblwidth+"px"))}}})},setGridHeight:function(d){return this.each(function(){if(this.grid){var f=b(this.grid.bDiv);f.css({height:d+(isNaN(d)?"":"px")});!0===this.p.frozenColumns&&b("#"+b.jgrid.jqID(this.p.id)+"_frozen").parent().height(f.height()-16);this.p.height=d;this.p.scroll&&this.grid.populateVisible()}})},setCaption:function(d){return this.each(function(){this.p.caption=d;b("span.ui-jqgrid-title, span.ui-jqgrid-title-rtl",this.grid.cDiv).html(d);
+b(this.grid.cDiv).show()})},setLabel:function(d,f,c,e){return this.each(function(){var a=-1;if(this.grid&&void 0!==d&&(b(this.p.colModel).each(function(b){if(this.name===d)return a=b,!1}),0<=a)){var j=b("tr.ui-jqgrid-labels th:eq("+a+")",this.grid.hDiv);if(f){var g=b(".s-ico",j);b("[id^=jqgh_]",j).empty().html(f).append(g);this.p.colNames[a]=f}c&&("string"===typeof c?b(j).addClass(c):b(j).css(c));"object"===typeof e&&b(j).attr(e)}})},setCell:function(d,f,c,e,a,j){return this.each(function(){var g=
+-1,h,i;if(this.grid&&(isNaN(f)?b(this.p.colModel).each(function(a){if(this.name===f)return g=a,!1}):g=parseInt(f,10),0<=g&&(h=this.rows.namedItem(d)))){var k=b("td:eq("+g+")",h);if(""!==c||!0===j)h=this.formatter(d,c,g,h,"edit"),i=this.p.colModel[g].title?{title:b.jgrid.stripHtml(h)}:{},this.p.treeGrid&&0<b(".tree-wrap",b(k)).length?b("span",b(k)).html(h).attr(i):b(k).html(h).attr(i),"local"===this.p.datatype&&(h=this.p.colModel[g],c=h.formatter&&"string"===typeof h.formatter&&"date"===h.formatter?
+b.unformat.date.call(this,c,h):c,i=this.p._index[b.jgrid.stripPref(this.p.idPrefix,d)],void 0!==i&&(this.p.data[i][h.name]=c));"string"===typeof e?b(k).addClass(e):e&&b(k).css(e);"object"===typeof a&&b(k).attr(a)}})},getCell:function(d,f){var c=!1;this.each(function(){var e=-1;if(this.grid&&(isNaN(f)?b(this.p.colModel).each(function(a){if(this.name===f)return e=a,!1}):e=parseInt(f,10),0<=e)){var a=this.rows.namedItem(d);if(a)try{c=b.unformat.call(this,b("td:eq("+e+")",a),{rowId:a.id,colModel:this.p.colModel[e]},
+e)}catch(j){c=b.jgrid.htmlDecode(b("td:eq("+e+")",a).html())}}});return c},getCol:function(d,f,c){var e=[],a,j=0,g,h,i,f="boolean"!==typeof f?!1:f;void 0===c&&(c=!1);this.each(function(){var k=-1;if(this.grid&&(isNaN(d)?b(this.p.colModel).each(function(a){if(this.name===d)return k=a,!1}):k=parseInt(d,10),0<=k)){var l=this.rows.length,o=0;if(l&&0<l){for(;o<l;){if(b(this.rows[o]).hasClass("jqgrow")){try{a=b.unformat.call(this,b(this.rows[o].cells[k]),{rowId:this.rows[o].id,colModel:this.p.colModel[k]},
+k)}catch(n){a=b.jgrid.htmlDecode(this.rows[o].cells[k].innerHTML)}c?(i=parseFloat(a),j+=i,void 0===h&&(h=g=i),g=Math.min(g,i),h=Math.max(h,i)):f?e.push({id:this.rows[o].id,value:a}):e.push(a)}o++}if(c)switch(c.toLowerCase()){case "sum":e=j;break;case "avg":e=j/l;break;case "count":e=l;break;case "min":e=g;break;case "max":e=h}}}});return e},clearGridData:function(d){return this.each(function(){if(this.grid){"boolean"!==typeof d&&(d=!1);if(this.p.deepempty)b("#"+b.jgrid.jqID(this.p.id)+" tbody:first tr:gt(0)").remove();
+else{var f=b("#"+b.jgrid.jqID(this.p.id)+" tbody:first tr:first")[0];b("#"+b.jgrid.jqID(this.p.id)+" tbody:first").empty().append(f)}this.p.footerrow&&d&&b(".ui-jqgrid-ftable td",this.grid.sDiv).html("&#160;");this.p.selrow=null;this.p.selarrrow=[];this.p.savedRow=[];this.p.records=0;this.p.page=1;this.p.lastpage=0;this.p.reccount=0;this.p.data=[];this.p._index={};this.updatepager(!0,!1)}})},getInd:function(b,f){var c=!1,e;this.each(function(){(e=this.rows.namedItem(b))&&(c=!0===f?e:e.rowIndex)});
+return c},bindKeys:function(d){var f=b.extend({onEnter:null,onSpace:null,onLeftKey:null,onRightKey:null,scrollingRows:!0},d||{});return this.each(function(){var c=this;b("body").is("[role]")||b("body").attr("role","application");c.p.scrollrows=f.scrollingRows;b(c).keydown(function(d){var a=b(c).find("tr[tabindex=0]")[0],j,g,h,i=c.p.treeReader.expanded_field;if(a)if(h=c.p._index[b.jgrid.stripPref(c.p.idPrefix,a.id)],37===d.keyCode||38===d.keyCode||39===d.keyCode||40===d.keyCode){if(38===d.keyCode){g=
+a.previousSibling;j="";if(g)if(b(g).is(":hidden"))for(;g;){if(g=g.previousSibling,!b(g).is(":hidden")&&b(g).hasClass("jqgrow")){j=g.id;break}}else j=g.id;b(c).jqGrid("setSelection",j,!0,d);d.preventDefault()}if(40===d.keyCode){g=a.nextSibling;j="";if(g)if(b(g).is(":hidden"))for(;g;){if(g=g.nextSibling,!b(g).is(":hidden")&&b(g).hasClass("jqgrow")){j=g.id;break}}else j=g.id;b(c).jqGrid("setSelection",j,!0,d);d.preventDefault()}37===d.keyCode&&(c.p.treeGrid&&c.p.data[h][i]&&b(a).find("div.treeclick").trigger("click"),
+b(c).triggerHandler("jqGridKeyLeft",[c.p.selrow]),b.isFunction(f.onLeftKey)&&f.onLeftKey.call(c,c.p.selrow));39===d.keyCode&&(c.p.treeGrid&&!c.p.data[h][i]&&b(a).find("div.treeclick").trigger("click"),b(c).triggerHandler("jqGridKeyRight",[c.p.selrow]),b.isFunction(f.onRightKey)&&f.onRightKey.call(c,c.p.selrow))}else 13===d.keyCode?(b(c).triggerHandler("jqGridKeyEnter",[c.p.selrow]),b.isFunction(f.onEnter)&&f.onEnter.call(c,c.p.selrow)):32===d.keyCode&&(b(c).triggerHandler("jqGridKeySpace",[c.p.selrow]),
+b.isFunction(f.onSpace)&&f.onSpace.call(c,c.p.selrow))})})},unbindKeys:function(){return this.each(function(){b(this).unbind("keydown")})},getLocalRow:function(d){var f=!1,c;this.each(function(){void 0!==d&&(c=this.p._index[b.jgrid.stripPref(this.p.idPrefix,d)],0<=c&&(f=this.p.data[c]))});return f}})})(jQuery);
 (function(a){a.fmatter={};a.extend(a.fmatter,{isBoolean:function(a){return"boolean"===typeof a},isObject:function(c){return c&&("object"===typeof c||a.isFunction(c))||!1},isString:function(a){return"string"===typeof a},isNumber:function(a){return"number"===typeof a&&isFinite(a)},isValue:function(a){return this.isObject(a)||this.isString(a)||this.isNumber(a)||this.isBoolean(a)},isEmpty:function(c){if(!this.isString(c)&&this.isValue(c))return!1;if(!this.isValue(c))return!0;c=a.trim(c).replace(/\&nbsp\;/ig,
 "").replace(/\&#160\;/ig,"");return""===c}});a.fn.fmatter=function(c,b,d,e,f){var g=b,d=a.extend({},a.jgrid.formatter,d);try{g=a.fn.fmatter[c].call(this,b,d,e,f)}catch(h){}return g};a.fmatter.util={NumberFormat:function(c,b){a.fmatter.isNumber(c)||(c*=1);if(a.fmatter.isNumber(c)){var d=0>c,e=""+c,f=b.decimalSeparator||".",g;if(a.fmatter.isNumber(b.decimalPlaces)){var h=b.decimalPlaces,e=Math.pow(10,h),e=""+Math.round(c*e)/e;g=e.lastIndexOf(".");if(0<h){0>g?(e+=f,g=e.length-1):"."!==f&&(e=e.replace(".",
 f));for(;e.length-1-g<h;)e+="0"}}if(b.thousandsSeparator){h=b.thousandsSeparator;g=e.lastIndexOf(f);g=-1<g?g:e.length;var f=e.substring(g),j=-1,i;for(i=g;0<i;i--){j++;if(0===j%3&&i!==g&&(!d||1<i))f=h+f;f=e.charAt(i-1)+f}e=f}e=b.prefix?b.prefix+e:e;return e=b.suffix?e+b.suffix:e}return c}};a.fn.fmatter.defaultFormat=function(c,b){return a.fmatter.isValue(c)&&""!==c?c:b.defaultValue||"&#160;"};a.fn.fmatter.email=function(c,b){return!a.fmatter.isEmpty(c)?'<a href="mailto:'+c+'">'+c+"</a>":a.fn.fmatter.defaultFormat(c,
@@ -190,48 +192,48 @@ a.jgrid.nav.edittitle+"' style='float:left;cursor:pointer;' class='ui-pg-div ui-
 break;case "checkbox":h=b.colModel.editoptions?b.colModel.editoptions.value.split(":"):["Yes","No"];f=a("input",c).is(":checked")?h[0]:h[1];break;case "select":f=a.unformat.select(c,b,d,e);break;case "actions":return"";default:f=a(c).text()}return void 0!==f?f:!0===e?a(c).text():a.jgrid.htmlDecode(a(c).html())};a.unformat.select=function(c,b,d,e){d=[];c=a(c).text();if(!0===e)return c;var e=a.extend({},void 0!==b.colModel.formatoptions?b.colModel.formatoptions:b.colModel.editoptions),b=void 0===e.separator?
 ":":e.separator,f=void 0===e.delimiter?";":e.delimiter;if(e.value){var g=e.value,e=!0===e.multiple?!0:!1,h=[];e&&(h=c.split(","),h=a.map(h,function(b){return a.trim(b)}));if(a.fmatter.isString(g)){var j=g.split(f),i=0,k;for(k=0;k<j.length;k++)if(f=j[k].split(b),2<f.length&&(f[1]=a.map(f,function(a,b){if(b>0)return a}).join(b)),e)-1<a.inArray(f[1],h)&&(d[i]=f[0],i++);else if(a.trim(f[1])===a.trim(c)){d[0]=f[0];break}}else if(a.fmatter.isObject(g)||a.isArray(g))e||(h[0]=c),d=a.map(h,function(b){var c;
 a.each(g,function(a,d){if(d===b){c=a;return false}});if(c!==void 0)return c});return d.join(", ")}return c||""};a.unformat.date=function(c,b){var d=a.jgrid.formatter.date||{};void 0!==b.formatoptions&&(d=a.extend({},d,b.formatoptions));return!a.fmatter.isEmpty(c)?a.jgrid.parseDate(d.newformat,c,d.srcformat,d):a.fn.fmatter.defaultFormat(c,b)}})(jQuery);
-(function(a){a.jgrid.extend({getColProp:function(a){var c={},d=this[0];if(!d.grid)return!1;var d=d.p.colModel,j;for(j=0;j<d.length;j++)if(d[j].name===a){c=d[j];break}return c},setColProp:function(b,c){return this.each(function(){if(this.grid&&c){var d=this.p.colModel,j;for(j=0;j<d.length;j++)if(d[j].name===b){a.extend(!0,this.p.colModel[j],c);break}}})},sortGrid:function(a,c,d){return this.each(function(){var j=-1,h;if(this.grid){a||(a=this.p.sortname);for(h=0;h<this.p.colModel.length;h++)if(this.p.colModel[h].index===
-a||this.p.colModel[h].name===a){j=h;break}-1!==j&&(h=this.p.colModel[j].sortable,"boolean"!==typeof h&&(h=!0),"boolean"!==typeof c&&(c=!1),h&&this.sortData("jqgh_"+this.p.id+"_"+a,j,c,d))}})},clearBeforeUnload:function(){return this.each(function(){var b=this.grid;b.emptyRows.call(this,!0,!0);a(b.hDiv).unbind("mousemove");a(this).unbind();b.dragEnd=null;b.dragMove=null;b.dragStart=null;b.emptyRows=null;b.populate=null;b.populateVisible=null;b.scrollGrid=null;b.selectionPreserver=null;b.bDiv=null;
-b.cDiv=null;b.hDiv=null;b.cols=null;var c,d=b.headers.length;for(c=0;c<d;c++)b.headers[c].el=null;this.addJSONData=this.addXmlData=this.formatter=this.constructTr=this.setHeadCheckBox=this.refreshIndex=this.updatepager=this.sortData=this.formatCol=null})},GridDestroy:function(){return this.each(function(){if(this.grid){this.p.pager&&a(this.p.pager).remove();try{a(this).jqGrid("clearBeforeUnload"),a("#gbox_"+a.jgrid.jqID(this.id)).remove()}catch(b){}}})},GridUnload:function(){return this.each(function(){if(this.grid){var b=
-a(this).attr("id"),c=a(this).attr("class");this.p.pager&&a(this.p.pager).empty().removeClass("ui-state-default ui-jqgrid-pager corner-bottom");var d=document.createElement("table");a(d).attr({id:b});d.className=c;b=a.jgrid.jqID(this.id);a(d).removeClass("ui-jqgrid-btable");1===a(this.p.pager).parents("#gbox_"+b).length?(a(d).insertBefore("#gbox_"+b).show(),a(this.p.pager).insertBefore("#gbox_"+b)):a(d).insertBefore("#gbox_"+b).show();a(this).jqGrid("clearBeforeUnload");a("#gbox_"+b).remove()}})},
+(function(a){a.jgrid.extend({getColProp:function(a){var c={},f=this[0];if(!f.grid)return!1;var f=f.p.colModel,g;for(g=0;g<f.length;g++)if(f[g].name===a){c=f[g];break}return c},setColProp:function(b,c){return this.each(function(){if(this.grid&&c){var f=this.p.colModel,g;for(g=0;g<f.length;g++)if(f[g].name===b){a.extend(!0,this.p.colModel[g],c);break}}})},sortGrid:function(a,c,f){return this.each(function(){var g=-1,j;if(this.grid){a||(a=this.p.sortname);for(j=0;j<this.p.colModel.length;j++)if(this.p.colModel[j].index===
+a||this.p.colModel[j].name===a){g=j;break}-1!==g&&(j=this.p.colModel[g].sortable,"boolean"!==typeof j&&(j=!0),"boolean"!==typeof c&&(c=!1),j&&this.sortData("jqgh_"+this.p.id+"_"+a,g,c,f))}})},clearBeforeUnload:function(){return this.each(function(){var b=this.grid;b.emptyRows.call(this,!0,!0);a(b.hDiv).unbind("mousemove");a(this).unbind();b.dragEnd=null;b.dragMove=null;b.dragStart=null;b.emptyRows=null;b.populate=null;b.populateVisible=null;b.scrollGrid=null;b.selectionPreserver=null;b.bDiv=null;
+b.cDiv=null;b.hDiv=null;b.cols=null;var c,f=b.headers.length;for(c=0;c<f;c++)b.headers[c].el=null;this.addJSONData=this.addXmlData=this.formatter=this.constructTr=this.setHeadCheckBox=this.refreshIndex=this.updatepager=this.sortData=this.formatCol=null})},GridDestroy:function(){return this.each(function(){if(this.grid){this.p.pager&&a(this.p.pager).remove();try{a(this).jqGrid("clearBeforeUnload"),a("#gbox_"+a.jgrid.jqID(this.id)).remove()}catch(b){}}})},GridUnload:function(){return this.each(function(){if(this.grid){var b=
+a(this).attr("id"),c=a(this).attr("class");this.p.pager&&a(this.p.pager).empty().removeClass("ui-state-default ui-jqgrid-pager corner-bottom");var f=document.createElement("table");a(f).attr({id:b});f.className=c;b=a.jgrid.jqID(this.id);a(f).removeClass("ui-jqgrid-btable");1===a(this.p.pager).parents("#gbox_"+b).length?(a(f).insertBefore("#gbox_"+b).show(),a(this.p.pager).insertBefore("#gbox_"+b)):a(f).insertBefore("#gbox_"+b).show();a(this).jqGrid("clearBeforeUnload");a("#gbox_"+b).remove()}})},
 setGridState:function(b){return this.each(function(){this.grid&&("hidden"===b?(a(".ui-jqgrid-bdiv, .ui-jqgrid-hdiv","#gview_"+a.jgrid.jqID(this.p.id)).slideUp("fast"),this.p.pager&&a(this.p.pager).slideUp("fast"),this.p.toppager&&a(this.p.toppager).slideUp("fast"),!0===this.p.toolbar[0]&&("both"===this.p.toolbar[1]&&a(this.grid.ubDiv).slideUp("fast"),a(this.grid.uDiv).slideUp("fast")),this.p.footerrow&&a(".ui-jqgrid-sdiv","#gbox_"+a.jgrid.jqID(this.p.id)).slideUp("fast"),a(".ui-jqgrid-titlebar-close span",
 this.grid.cDiv).removeClass("ui-icon-circle-triangle-n").addClass("ui-icon-circle-triangle-s"),this.p.gridstate="hidden"):"visible"===b&&(a(".ui-jqgrid-hdiv, .ui-jqgrid-bdiv","#gview_"+a.jgrid.jqID(this.p.id)).slideDown("fast"),this.p.pager&&a(this.p.pager).slideDown("fast"),this.p.toppager&&a(this.p.toppager).slideDown("fast"),!0===this.p.toolbar[0]&&("both"===this.p.toolbar[1]&&a(this.grid.ubDiv).slideDown("fast"),a(this.grid.uDiv).slideDown("fast")),this.p.footerrow&&a(".ui-jqgrid-sdiv","#gbox_"+
 a.jgrid.jqID(this.p.id)).slideDown("fast"),a(".ui-jqgrid-titlebar-close span",this.grid.cDiv).removeClass("ui-icon-circle-triangle-s").addClass("ui-icon-circle-triangle-n"),this.p.gridstate="visible"))})},filterToolbar:function(b){b=a.extend({autosearch:!0,searchOnEnter:!0,beforeSearch:null,afterSearch:null,beforeClear:null,afterClear:null,searchurl:"",stringResult:!1,groupOp:"AND",defaultSearch:"bw",searchOperators:!1,operandTitle:"Click to select search operation.",operands:{eq:"==",ne:"!",lt:"<",
-le:"<=",gt:">",ge:">=",bw:"^",bn:"!^","in":"=",ni:"!=",ew:"|",en:"!@",cn:"~",nc:"!~",nu:"#",nn:"!#"}},a.jgrid.search,b||{});return this.each(function(){var c=this;if(!this.ftoolbar){var d=function(){var d={},e=0,g,l,h={},f;a.each(c.p.colModel,function(){var i=a("#gs_"+a.jgrid.jqID(this.name),!0===this.frozen&&!0===c.p.frozenColumns?c.grid.fhDiv:c.grid.hDiv);l=this.index||this.name;f=b.searchOperators?i.parent().prev().children("a").attr("soper")||b.defaultSearch:this.searchoptions&&this.searchoptions.sopt?
-this.searchoptions.sopt[0]:"select"===this.stype?"eq":b.defaultSearch;if((g="custom"===this.stype&&a.isFunction(this.searchoptions.custom_value)&&0<i.length&&"SPAN"===i[0].nodeName.toUpperCase()?this.searchoptions.custom_value.call(c,i.children(".customelement:first"),"get"):i.val())||"nu"===f||"nn"===f)d[l]=g,h[l]=f,e++;else try{delete c.p.postData[l]}catch(m){}});var i=0<e?!0:!1;if(!0===b.stringResult||"local"===c.p.datatype){var m='{"groupOp":"'+b.groupOp+'","rules":[',j=0;a.each(d,function(a,
-b){0<j&&(m+=",");m+='{"field":"'+a+'",';m+='"op":"'+h[a]+'",';m+='"data":"'+(b+"").replace(/\\/g,"\\\\").replace(/\"/g,'\\"')+'"}';j++});m+="]}";a.extend(c.p.postData,{filters:m});a.each(["searchField","searchString","searchOper"],function(a,b){c.p.postData.hasOwnProperty(b)&&delete c.p.postData[b]})}else a.extend(c.p.postData,d);var n;c.p.searchurl&&(n=c.p.url,a(c).jqGrid("setGridParam",{url:c.p.searchurl}));var p="stop"===a(c).triggerHandler("jqGridToolbarBeforeSearch")?!0:!1;!p&&a.isFunction(b.beforeSearch)&&
-(p=b.beforeSearch.call(c));p||a(c).jqGrid("setGridParam",{search:i}).trigger("reloadGrid",[{page:1}]);n&&a(c).jqGrid("setGridParam",{url:n});a(c).triggerHandler("jqGridToolbarAfterSearch");a.isFunction(b.afterSearch)&&b.afterSearch.call(c)},j=function(k,e,g){a("#sopt_menu").remove();var e=parseInt(e,10),g=parseInt(g,10)+18,e='<ul id="sopt_menu" class="ui-search-menu" role="menu" tabindex="0" style="font-size:'+(a(".ui-jqgrid-view").css("font-size")||"11px")+";left:"+e+"px;top:"+g+'px;">',l=c.p.colModel[parseInt(a(k).attr("colindex"))],
-g=a(k).attr("soper"),f=[],h,i,m=a.extend({},l.searchoptions);m.sopt||(m.sopt=[],m.sopt[0]="select"===l.stype?"eq":b.defaultSearch);a.each(b.odata,function(){f.push(this.oper)});for(h=0;h<m.sopt.length;h++)i=a.inArray(m.sopt[h],f),-1!==i&&(l=g===b.odata[i].oper?"ui-state-highlight":"",e+='<li class="ui-menu-item '+l+'" role="presentation"><a href="#" class="ui-corner-all g-menu-item" tabindex="0" role="menuitem" value="'+b.odata[i].oper+'" oper="'+b.operands[b.odata[i].oper]+'"><table cellspacing="0" cellpadding="0" border="0"><tr><td width="25px">'+
-b.operands[b.odata[i].oper]+"</td><td>"+b.odata[i].text+"</td></tr></table></a></li>");a("body").append(e+"</ul>");a("#sopt_menu").addClass("ui-menu ui-widget ui-widget-content ui-corner-all");a("#sopt_menu > li > a").hover(function(){a(this).addClass("ui-state-hover")},function(){a(this).removeClass("ui-state-hover")}).click(function(){var g=a(this).attr("value"),e=a(this).attr("oper");a(c).triggerHandler("jqGridToolbarSelectOper",[g,e,k]);a("#sopt_menu").hide();a(k).text(e).attr("soper",g);if(b.autosearch===
-true){e=a(k).parent().next().children()[0];(a(e).val()||g==="nu"||g==="nn")&&d()}})},h=a("<tr class='ui-search-toolbar' role='rowheader'></tr>"),f;a.each(c.p.colModel,function(k){var e=this,g,l;l="";var j="=",s=a("<th role='columnheader' class='ui-state-default ui-th-column ui-th-"+c.p.direction+"'></th>"),i=a("<div style='position:relative;height:100%;padding-right:0.3em;padding-left:0.3em;'></div>"),m=a("<table class='ui-search-table' cellspacing='0'><tr><td class='ui-search-oper'></td><td class='ui-search-input'></td></tr></table>");
-!0===this.hidden&&a(s).css("display","none");this.search=!1===this.search?!1:!0;void 0===this.stype&&(this.stype="text");g=a.extend({},this.searchoptions||{});if(this.search){if(b.searchOperators){l=g.sopt?g.sopt[0]:"select"===e.stype?"eq":b.defaultSearch;for(var q=0;q<b.odata.length;q++)if(b.odata[q].oper===l){j=b.operands[l]||"";break}l="<a href='#' title='"+(null!=g.searchtitle?g.searchtitle:b.operandTitle)+"' style='padding-right: 0.5em;' soper='"+l+"' class='soptclass' colindex='"+k+"'>"+j+"</a>"}a("td:eq(0)",
-m).append(l);switch(this.stype){case "select":if(l=this.surl||g.dataUrl)a.ajax(a.extend({url:l,dataType:"html",success:function(k){if(g.buildSelect!==void 0){if(k=g.buildSelect(k)){a("td:eq(1)",m).append(k);a(i).append(m)}}else{a("td:eq(1)",m).append(k);a(i).append(m)}g.defaultValue!==void 0&&a("select",i).val(g.defaultValue);a("select",i).attr({name:e.index||e.name,id:"gs_"+e.name});g.attr&&a("select",i).attr(g.attr);a("select",i).css({width:"100%"});a.jgrid.bindEv.call(c,a("select",i)[0],g);b.autosearch===
-true&&a("select",i).change(function(){d();return false});k=null}},a.jgrid.ajaxOptions,c.p.ajaxSelectOptions||{}));else{var n,p,o;e.searchoptions?(n=void 0===e.searchoptions.value?"":e.searchoptions.value,p=void 0===e.searchoptions.separator?":":e.searchoptions.separator,o=void 0===e.searchoptions.delimiter?";":e.searchoptions.delimiter):e.editoptions&&(n=void 0===e.editoptions.value?"":e.editoptions.value,p=void 0===e.editoptions.separator?":":e.editoptions.separator,o=void 0===e.editoptions.delimiter?
-";":e.editoptions.delimiter);if(n){k=document.createElement("select");k.style.width="100%";a(k).attr({name:e.index||e.name,id:"gs_"+e.name});var r;if("string"===typeof n){l=n.split(o);for(r=0;r<l.length;r++)n=l[r].split(p),o=document.createElement("option"),o.value=n[0],o.innerHTML=n[1],k.appendChild(o)}else if("object"===typeof n)for(r in n)n.hasOwnProperty(r)&&(o=document.createElement("option"),o.value=r,o.innerHTML=n[r],k.appendChild(o));void 0!==g.defaultValue&&a(k).val(g.defaultValue);g.attr&&
-a(k).attr(g.attr);a.jgrid.bindEv.call(c,k,g);a("td:eq(1)",m).append(k);a(i).append(m);!0===b.autosearch&&a(k).change(function(){d();return false})}}break;case "text":p=void 0!==g.defaultValue?g.defaultValue:"";a("td:eq(1)",m).append("<input type='text' style='width:100%;padding:0px;' name='"+(e.index||e.name)+"' id='gs_"+e.name+"' value='"+p+"'/>");a(i).append(m);g.attr&&a("input",i).attr(g.attr);a.jgrid.bindEv.call(c,a("input",i)[0],g);!0===b.autosearch&&(b.searchOnEnter?a("input",i).keypress(function(a){if((a.charCode||
-a.keyCode||0)===13){d();return false}return this}):a("input",i).keydown(function(a){switch(a.which){case 13:return false;case 9:case 16:case 37:case 38:case 39:case 40:case 27:break;default:f&&clearTimeout(f);f=setTimeout(function(){d()},500)}}));break;case "custom":a("td:eq(1)",m).append("<span style='width:95%;padding:0px;' name='"+(e.index||e.name)+"' id='gs_"+e.name+"'/>");a(i).append(m);try{if(a.isFunction(g.custom_element)){var u=g.custom_element.call(c,void 0!==g.defaultValue?g.defaultValue:
-"",g);if(u)u=a(u).addClass("customelement"),a(i).find(">span").append(u);else throw"e2";}else throw"e1";}catch(t){"e1"===t&&a.jgrid.info_dialog(a.jgrid.errors.errcap,"function 'custom_element' "+a.jgrid.edit.msg.nodefined,a.jgrid.edit.bClose),"e2"===t?a.jgrid.info_dialog(a.jgrid.errors.errcap,"function 'custom_element' "+a.jgrid.edit.msg.novalue,a.jgrid.edit.bClose):a.jgrid.info_dialog(a.jgrid.errors.errcap,"string"===typeof t?t:t.message,a.jgrid.edit.bClose)}}}a(s).append(i);a(h).append(s);b.searchOperators||
-a("td:eq(0)",m).hide()});a("table thead",c.grid.hDiv).append(h);b.searchOperators&&a(".soptclass").click(function(){var b=a(this).offset();j(this,b.left,b.top)});this.ftoolbar=!0;this.triggerToolbar=d;this.clearToolbar=function(d){var e={},g=0,l,d="boolean"!==typeof d?!0:d;a.each(c.p.colModel,function(){var b,d=a("#gs_"+a.jgrid.jqID(this.name),!0===this.frozen&&!0===c.p.frozenColumns?c.grid.fhDiv:c.grid.hDiv);this.searchoptions&&void 0!==this.searchoptions.defaultValue&&(b=this.searchoptions.defaultValue);
-l=this.index||this.name;switch(this.stype){case "select":d.find("option").each(function(c){if(c===0)this.selected=true;if(a(this).val()===b){this.selected=true;return false}});if(void 0!==b)e[l]=b,g++;else try{delete c.p.postData[l]}catch(f){}break;case "text":d.val(b);if(void 0!==b)e[l]=b,g++;else try{delete c.p.postData[l]}catch(h){}break;case "custom":a.isFunction(this.searchoptions.custom_value)&&0<d.length&&"SPAN"===d[0].nodeName.toUpperCase()&&this.searchoptions.custom_value.call(c,d.children(".customelement:first"),
-"set",b)}});var h=0<g?!0:!1;if(!0===b.stringResult||"local"===c.p.datatype){var f='{"groupOp":"'+b.groupOp+'","rules":[',i=0;a.each(e,function(a,b){0<i&&(f+=",");f+='{"field":"'+a+'",';f+='"op":"eq",';f+='"data":"'+(b+"").replace(/\\/g,"\\\\").replace(/\"/g,'\\"')+'"}';i++});f+="]}";a.extend(c.p.postData,{filters:f});a.each(["searchField","searchString","searchOper"],function(a,b){c.p.postData.hasOwnProperty(b)&&delete c.p.postData[b]})}else a.extend(c.p.postData,e);var m;c.p.searchurl&&(m=c.p.url,
-a(c).jqGrid("setGridParam",{url:c.p.searchurl}));var j="stop"===a(c).triggerHandler("jqGridToolbarBeforeClear")?!0:!1;!j&&a.isFunction(b.beforeClear)&&(j=b.beforeClear.call(c));j||d&&a(c).jqGrid("setGridParam",{search:h}).trigger("reloadGrid",[{page:1}]);m&&a(c).jqGrid("setGridParam",{url:m});a(c).triggerHandler("jqGridToolbarAfterClear");a.isFunction(b.afterClear)&&b.afterClear()};this.toggleToolbar=function(){var b=a("tr.ui-search-toolbar",c.grid.hDiv),d=!0===c.p.frozenColumns?a("tr.ui-search-toolbar",
-c.grid.fhDiv):!1;"none"===b.css("display")?(b.show(),d&&d.show()):(b.hide(),d&&d.hide())}}})},destroyFilterToolbar:function(){return this.each(function(){this.ftoolbar&&(this.toggleToolbar=this.clearToolbar=this.triggerToolbar=null,this.ftoolbar=!1,a(this.grid.hDiv).find("table thead tr.ui-search-toolbar").remove())})},destroyGroupHeader:function(b){void 0===b&&(b=!0);return this.each(function(){var c,d,j,h,f,k;d=this.grid;var e=a("table.ui-jqgrid-htable thead",d.hDiv),g=this.p.colModel;if(d){a(this).unbind(".setGroupHeaders");
-c=a("<tr>",{role:"rowheader"}).addClass("ui-jqgrid-labels");h=d.headers;d=0;for(j=h.length;d<j;d++){f=g[d].hidden?"none":"";f=a(h[d].el).width(h[d].width).css("display",f);try{f.removeAttr("rowSpan")}catch(l){f.attr("rowSpan",1)}c.append(f);k=f.children("span.ui-jqgrid-resize");0<k.length&&(k[0].style.height="");f.children("div")[0].style.top=""}a(e).children("tr.ui-jqgrid-labels").remove();a(e).prepend(c);!0===b&&a(this).jqGrid("setGridParam",{groupHeader:null})}})},setGroupHeaders:function(b){b=
-a.extend({useColSpanStyle:!1,groupHeaders:[]},b||{});return this.each(function(){this.p.groupHeader=b;var c,d,j=0,h,f,k,e,g,l=this.p.colModel,v=l.length,s=this.grid.headers,i=a("table.ui-jqgrid-htable",this.grid.hDiv),m=i.children("thead").children("tr.ui-jqgrid-labels:last").addClass("jqg-second-row-header");h=i.children("thead");var q=i.find(".jqg-first-row-header");void 0===q[0]?q=a("<tr>",{role:"row","aria-hidden":"true"}).addClass("jqg-first-row-header").css("height","auto"):q.empty();var n,
-p=function(a,b){var c=b.length,d;for(d=0;d<c;d++)if(b[d].startColumnName===a)return d;return-1};a(this).prepend(h);h=a("<tr>",{role:"rowheader"}).addClass("ui-jqgrid-labels jqg-third-row-header");for(c=0;c<v;c++)if(k=s[c].el,e=a(k),d=l[c],f={height:"0px",width:s[c].width+"px",display:d.hidden?"none":""},a("<th>",{role:"gridcell"}).css(f).addClass("ui-first-th-"+this.p.direction).appendTo(q),k.style.width="",f=p(d.name,b.groupHeaders),0<=f){f=b.groupHeaders[f];j=f.numberOfColumns;g=f.titleText;for(f=
-d=0;f<j&&c+f<v;f++)l[c+f].hidden||d++;f=a("<th>").attr({role:"columnheader"}).addClass("ui-state-default ui-th-column-header ui-th-"+this.p.direction).css({height:"22px","border-top":"0px none"}).html(g);0<d&&f.attr("colspan",""+d);this.p.headertitles&&f.attr("title",f.text());0===d&&f.hide();e.before(f);h.append(k);j-=1}else 0===j?b.useColSpanStyle?e.attr("rowspan","2"):(a("<th>",{role:"columnheader"}).addClass("ui-state-default ui-th-column-header ui-th-"+this.p.direction).css({display:d.hidden?
-"none":"","border-top":"0px none"}).insertBefore(e),h.append(k)):(h.append(k),j--);l=a(this).children("thead");l.prepend(q);h.insertAfter(m);i.append(l);b.useColSpanStyle&&(i.find("span.ui-jqgrid-resize").each(function(){var b=a(this).parent();b.is(":visible")&&(this.style.cssText="height: "+b.height()+"px !important; cursor: col-resize;")}),i.find("div.ui-jqgrid-sortable").each(function(){var b=a(this),c=b.parent();c.is(":visible")&&c.is(":has(span.ui-jqgrid-resize)")&&b.css("top",(c.height()-b.outerHeight())/
-2+"px")}));n=l.find("tr.jqg-first-row-header");a(this).bind("jqGridResizeStop.setGroupHeaders",function(a,b,c){n.find("th").eq(c).width(b)})})},setFrozenColumns:function(){return this.each(function(){if(this.grid){var b=this,c=b.p.colModel,d=0,j=c.length,h=-1,f=!1;if(!(!0===b.p.subGrid||!0===b.p.treeGrid||!0===b.p.cellEdit||b.p.sortable||b.p.scroll||b.p.grouping)){b.p.rownumbers&&d++;for(b.p.multiselect&&d++;d<j;){if(!0===c[d].frozen)f=!0,h=d;else break;d++}if(0<=h&&f){c=b.p.caption?a(b.grid.cDiv).outerHeight():
-0;d=a(".ui-jqgrid-htable","#gview_"+a.jgrid.jqID(b.p.id)).height();b.p.toppager&&(c+=a(b.grid.topDiv).outerHeight());!0===b.p.toolbar[0]&&"bottom"!==b.p.toolbar[1]&&(c+=a(b.grid.uDiv).outerHeight());b.grid.fhDiv=a('<div style="position:absolute;left:0px;top:'+c+"px;height:"+d+'px;" class="frozen-div ui-state-default ui-jqgrid-hdiv"></div>');b.grid.fbDiv=a('<div style="position:absolute;left:0px;top:'+(parseInt(c,10)+parseInt(d,10)+1)+'px;overflow-y:hidden" class="frozen-bdiv ui-jqgrid-bdiv"></div>');
-a("#gview_"+a.jgrid.jqID(b.p.id)).append(b.grid.fhDiv);c=a(".ui-jqgrid-htable","#gview_"+a.jgrid.jqID(b.p.id)).clone(!0);if(b.p.groupHeader){a("tr.jqg-first-row-header, tr.jqg-third-row-header",c).each(function(){a("th:gt("+h+")",this).remove()});var k=-1,e=-1;a("tr.jqg-second-row-header th",c).each(function(){var b=parseInt(a(this).attr("colspan"),10);b&&(k+=b,e++);if(k===h)return!1});k!==h&&(e=h);a("tr.jqg-second-row-header",c).each(function(){a("th:gt("+e+")",this).remove()})}else a("tr",c).each(function(){a("th:gt("+
-h+")",this).remove()});a(c).width(1);a(b.grid.fhDiv).append(c).mousemove(function(a){if(b.grid.resizing)return b.grid.dragMove(a),!1});a(b).bind("jqGridResizeStop.setFrozenColumns",function(c,d,e){c=a(".ui-jqgrid-htable",b.grid.fhDiv);a("th:eq("+e+")",c).width(d);c=a(".ui-jqgrid-btable",b.grid.fbDiv);a("tr:first td:eq("+e+")",c).width(d)});a(b).bind("jqGridOnSortCol.setFrozenColumns",function(c,d,e){c=a("tr.ui-jqgrid-labels:last th:eq("+b.p.lastsort+")",b.grid.fhDiv);d=a("tr.ui-jqgrid-labels:last th:eq("+
-e+")",b.grid.fhDiv);a("span.ui-grid-ico-sort",c).addClass("ui-state-disabled");a(c).attr("aria-selected","false");a("span.ui-icon-"+b.p.sortorder,d).removeClass("ui-state-disabled");a(d).attr("aria-selected","true");!b.p.viewsortcols[0]&&b.p.lastsort!==e&&(a("span.s-ico",c).hide(),a("span.s-ico",d).show())});a("#gview_"+a.jgrid.jqID(b.p.id)).append(b.grid.fbDiv);a(b.grid.bDiv).scroll(function(){a(b.grid.fbDiv).scrollTop(a(this).scrollTop())});!0===b.p.hoverrows&&a("#"+a.jgrid.jqID(b.p.id)).unbind("mouseover").unbind("mouseout");
-a(b).bind("jqGridAfterGridComplete.setFrozenColumns",function(){a("#"+a.jgrid.jqID(b.p.id)+"_frozen").remove();a(b.grid.fbDiv).height(a(b.grid.bDiv).height()-16);var c=a("#"+a.jgrid.jqID(b.p.id)).clone(!0);a("tr",c).each(function(){a("td:gt("+h+")",this).remove()});a(c).width(1).attr("id",b.p.id+"_frozen");a(b.grid.fbDiv).append(c);!0===b.p.hoverrows&&(a("tr.jqgrow",c).hover(function(){a(this).addClass("ui-state-hover");a("#"+a.jgrid.jqID(this.id),"#"+a.jgrid.jqID(b.p.id)).addClass("ui-state-hover")},
-function(){a(this).removeClass("ui-state-hover");a("#"+a.jgrid.jqID(this.id),"#"+a.jgrid.jqID(b.p.id)).removeClass("ui-state-hover")}),a("tr.jqgrow","#"+a.jgrid.jqID(b.p.id)).hover(function(){a(this).addClass("ui-state-hover");a("#"+a.jgrid.jqID(this.id),"#"+a.jgrid.jqID(b.p.id)+"_frozen").addClass("ui-state-hover")},function(){a(this).removeClass("ui-state-hover");a("#"+a.jgrid.jqID(this.id),"#"+a.jgrid.jqID(b.p.id)+"_frozen").removeClass("ui-state-hover")}));c=null});b.p.frozenColumns=!0}}}})},
-destroyFrozenColumns:function(){return this.each(function(){if(this.grid&&!0===this.p.frozenColumns){a(this.grid.fhDiv).remove();a(this.grid.fbDiv).remove();this.grid.fhDiv=null;this.grid.fbDiv=null;a(this).unbind(".setFrozenColumns");if(!0===this.p.hoverrows){var b;a("#"+a.jgrid.jqID(this.p.id)).bind("mouseover",function(c){b=a(c.target).closest("tr.jqgrow");"ui-subgrid"!==a(b).attr("class")&&a(b).addClass("ui-state-hover")}).bind("mouseout",function(c){b=a(c.target).closest("tr.jqgrow");a(b).removeClass("ui-state-hover")})}this.p.frozenColumns=
-!1}})}})})(jQuery);
+le:"<=",gt:">",ge:">=",bw:"^",bn:"!^","in":"=",ni:"!=",ew:"|",en:"!@",cn:"~",nc:"!~",nu:"#",nn:"!#"}},a.jgrid.search,b||{});return this.each(function(){var c=this;if(!this.ftoolbar){var f=function(){var e={},d=0,f,l,j={},n;a.each(c.p.colModel,function(){var i=a("#gs_"+a.jgrid.jqID(this.name),!0===this.frozen&&!0===c.p.frozenColumns?c.grid.fhDiv:c.grid.hDiv);l=this.index||this.name;n=b.searchOperators?i.parent().prev().children("a").attr("soper")||b.defaultSearch:this.searchoptions&&this.searchoptions.sopt?
+this.searchoptions.sopt[0]:"select"===this.stype?"eq":b.defaultSearch;if((f="custom"===this.stype&&a.isFunction(this.searchoptions.custom_value)&&0<i.length&&"SPAN"===i[0].nodeName.toUpperCase()?this.searchoptions.custom_value.call(c,i.children(".customelement:first"),"get"):i.val())||"nu"===n||"nn"===n)e[l]=f,j[l]=n,d++;else try{delete c.p.postData[l]}catch(k){}});var i=0<d?!0:!1;if(!0===b.stringResult||"local"===c.p.datatype){var k='{"groupOp":"'+b.groupOp+'","rules":[',h=0;a.each(e,function(a,
+b){0<h&&(k+=",");k+='{"field":"'+a+'",';k+='"op":"'+j[a]+'",';k+='"data":"'+(b+"").replace(/\\/g,"\\\\").replace(/\"/g,'\\"')+'"}';h++});k+="]}";a.extend(c.p.postData,{filters:k});a.each(["searchField","searchString","searchOper"],function(a,b){c.p.postData.hasOwnProperty(b)&&delete c.p.postData[b]})}else a.extend(c.p.postData,e);var g;c.p.searchurl&&(g=c.p.url,a(c).jqGrid("setGridParam",{url:c.p.searchurl}));var o="stop"===a(c).triggerHandler("jqGridToolbarBeforeSearch")?!0:!1;!o&&a.isFunction(b.beforeSearch)&&
+(o=b.beforeSearch.call(c));o||a(c).jqGrid("setGridParam",{search:i}).trigger("reloadGrid",[{page:1}]);g&&a(c).jqGrid("setGridParam",{url:g});a(c).triggerHandler("jqGridToolbarAfterSearch");a.isFunction(b.afterSearch)&&b.afterSearch.call(c)},g=function(e,d,j){a("#sopt_menu").remove();var d=parseInt(d,10),j=parseInt(j,10)+18,d='<ul id="sopt_menu" class="ui-search-menu" role="menu" tabindex="0" style="font-size:'+(a(".ui-jqgrid-view").css("font-size")||"11px")+";left:"+d+"px;top:"+j+'px;">',j=a(e).attr("soper"),
+l,h=[],n,i=0,k=a(e).attr("colname");for(l=c.p.colModel.length;i<l&&c.p.colModel[i].name!==k;)i++;i=c.p.colModel[i];k=a.extend({},i.searchoptions);k.sopt||(k.sopt=[],k.sopt[0]="select"===i.stype?"eq":b.defaultSearch);a.each(b.odata,function(){h.push(this.oper)});for(i=0;i<k.sopt.length;i++)n=a.inArray(k.sopt[i],h),-1!==n&&(l=j===b.odata[n].oper?"ui-state-highlight":"",d+='<li class="ui-menu-item '+l+'" role="presentation"><a class="ui-corner-all g-menu-item" tabindex="0" role="menuitem" value="'+b.odata[n].oper+
+'" oper="'+b.operands[b.odata[n].oper]+'"><table cellspacing="0" cellpadding="0" border="0"><tr><td width="25px">'+b.operands[b.odata[n].oper]+"</td><td>"+b.odata[n].text+"</td></tr></table></a></li>");a("body").append(d+"</ul>");a("#sopt_menu").addClass("ui-menu ui-widget ui-widget-content ui-corner-all");a("#sopt_menu > li > a").hover(function(){a(this).addClass("ui-state-hover")},function(){a(this).removeClass("ui-state-hover")}).click(function(){var d=a(this).attr("value"),i=a(this).attr("oper");
+a(c).triggerHandler("jqGridToolbarSelectOper",[d,i,e]);a("#sopt_menu").hide();a(e).text(i).attr("soper",d);if(b.autosearch===true){i=a(e).parent().next().children()[0];(a(i).val()||d==="nu"||d==="nn")&&f()}})},j=a("<tr class='ui-search-toolbar' role='rowheader'></tr>"),h;a.each(c.p.colModel,function(){var e=this,d,g;g="";var l="=",s,n=a("<th role='columnheader' class='ui-state-default ui-th-column ui-th-"+c.p.direction+"'></th>"),i=a("<div style='position:relative;height:100%;padding-right:0.3em;padding-left:0.3em;'></div>"),
+k=a("<table class='ui-search-table' cellspacing='0'><tr><td class='ui-search-oper'></td><td class='ui-search-input'></td></tr></table>");!0===this.hidden&&a(n).css("display","none");this.search=!1===this.search?!1:!0;void 0===this.stype&&(this.stype="text");d=a.extend({},this.searchoptions||{});if(this.search){if(b.searchOperators){g=d.sopt?d.sopt[0]:"select"===e.stype?"eq":b.defaultSearch;for(s=0;s<b.odata.length;s++)if(b.odata[s].oper===g){l=b.operands[g]||"";break}g="<a title='"+(null!=d.searchtitle?
+d.searchtitle:b.operandTitle)+"' style='padding-right: 0.5em;' soper='"+g+"' class='soptclass' colname='"+this.name+"'>"+l+"</a>"}a("td:eq(0)",k).append(g);switch(this.stype){case "select":if(g=this.surl||d.dataUrl)a.ajax(a.extend({url:g,dataType:"html",success:function(g){if(d.buildSelect!==void 0){if(g=d.buildSelect(g)){a("td:eq(1)",k).append(g);a(i).append(k)}}else{a("td:eq(1)",k).append(g);a(i).append(k)}d.defaultValue!==void 0&&a("select",i).val(d.defaultValue);a("select",i).attr({name:e.index||
+e.name,id:"gs_"+e.name});d.attr&&a("select",i).attr(d.attr);a("select",i).css({width:"100%"});a.jgrid.bindEv.call(c,a("select",i)[0],d);b.autosearch===true&&a("select",i).change(function(){f();return false});g=null}},a.jgrid.ajaxOptions,c.p.ajaxSelectOptions||{}));else{var m,r,o;e.searchoptions?(m=void 0===e.searchoptions.value?"":e.searchoptions.value,r=void 0===e.searchoptions.separator?":":e.searchoptions.separator,o=void 0===e.searchoptions.delimiter?";":e.searchoptions.delimiter):e.editoptions&&
+(m=void 0===e.editoptions.value?"":e.editoptions.value,r=void 0===e.editoptions.separator?":":e.editoptions.separator,o=void 0===e.editoptions.delimiter?";":e.editoptions.delimiter);if(m){l=document.createElement("select");l.style.width="100%";a(l).attr({name:e.index||e.name,id:"gs_"+e.name});var q;if("string"===typeof m){g=m.split(o);for(q=0;q<g.length;q++)m=g[q].split(r),o=document.createElement("option"),o.value=m[0],o.innerHTML=m[1],l.appendChild(o)}else if("object"===typeof m)for(q in m)m.hasOwnProperty(q)&&
+(o=document.createElement("option"),o.value=q,o.innerHTML=m[q],l.appendChild(o));void 0!==d.defaultValue&&a(l).val(d.defaultValue);d.attr&&a(l).attr(d.attr);a.jgrid.bindEv.call(c,l,d);a("td:eq(1)",k).append(l);a(i).append(k);!0===b.autosearch&&a(l).change(function(){f();return false})}}break;case "text":r=void 0!==d.defaultValue?d.defaultValue:"";a("td:eq(1)",k).append("<input type='text' style='width:100%;padding:0px;' name='"+(e.index||e.name)+"' id='gs_"+e.name+"' value='"+r+"'/>");a(i).append(k);
+d.attr&&a("input",i).attr(d.attr);a.jgrid.bindEv.call(c,a("input",i)[0],d);!0===b.autosearch&&(b.searchOnEnter?a("input",i).keypress(function(a){if((a.charCode||a.keyCode||0)===13){f();return false}return this}):a("input",i).keydown(function(a){switch(a.which){case 13:return false;case 9:case 16:case 37:case 38:case 39:case 40:case 27:break;default:h&&clearTimeout(h);h=setTimeout(function(){f()},500)}}));break;case "custom":a("td:eq(1)",k).append("<span style='width:95%;padding:0px;' name='"+(e.index||
+e.name)+"' id='gs_"+e.name+"'/>");a(i).append(k);try{if(a.isFunction(d.custom_element)){var u=d.custom_element.call(c,void 0!==d.defaultValue?d.defaultValue:"",d);if(u)u=a(u).addClass("customelement"),a(i).find(">span").append(u);else throw"e2";}else throw"e1";}catch(t){"e1"===t&&a.jgrid.info_dialog(a.jgrid.errors.errcap,"function 'custom_element' "+a.jgrid.edit.msg.nodefined,a.jgrid.edit.bClose),"e2"===t?a.jgrid.info_dialog(a.jgrid.errors.errcap,"function 'custom_element' "+a.jgrid.edit.msg.novalue,
+a.jgrid.edit.bClose):a.jgrid.info_dialog(a.jgrid.errors.errcap,"string"===typeof t?t:t.message,a.jgrid.edit.bClose)}}}a(n).append(i);a(j).append(n);b.searchOperators||a("td:eq(0)",k).hide()});a("table thead",c.grid.hDiv).append(j);b.searchOperators&&(a(".soptclass").click(function(b){var c=a(this).offset();g(this,c.left,c.top);b.stopPropagation()}),a("body").on("click",function(b){"soptclass"!==b.target.className&&a("#sopt_menu").hide()}));this.ftoolbar=!0;this.triggerToolbar=f;this.clearToolbar=
+function(e){var d={},f=0,g,e=typeof e!=="boolean"?true:e;a.each(c.p.colModel,function(){var b,e=a("#gs_"+a.jgrid.jqID(this.name),this.frozen===true&&c.p.frozenColumns===true?c.grid.fhDiv:c.grid.hDiv);if(this.searchoptions&&this.searchoptions.defaultValue!==void 0)b=this.searchoptions.defaultValue;g=this.index||this.name;switch(this.stype){case "select":e.find("option").each(function(c){if(c===0)this.selected=true;if(a(this).val()===b){this.selected=true;return false}});if(b!==void 0){d[g]=b;f++}else try{delete c.p.postData[g]}catch(i){}break;
+case "text":e.val(b);if(b!==void 0){d[g]=b;f++}else try{delete c.p.postData[g]}catch(h){}break;case "custom":a.isFunction(this.searchoptions.custom_value)&&e.length>0&&e[0].nodeName.toUpperCase()==="SPAN"&&this.searchoptions.custom_value.call(c,e.children(".customelement:first"),"set",b)}});var j=f>0?true:false;if(b.stringResult===true||c.p.datatype==="local"){var h='{"groupOp":"'+b.groupOp+'","rules":[',i=0;a.each(d,function(a,b){i>0&&(h=h+",");h=h+('{"field":"'+a+'",');h=h+'"op":"eq",';h=h+('"data":"'+
+(b+"").replace(/\\/g,"\\\\").replace(/\"/g,'\\"')+'"}');i++});h=h+"]}";a.extend(c.p.postData,{filters:h});a.each(["searchField","searchString","searchOper"],function(a,b){c.p.postData.hasOwnProperty(b)&&delete c.p.postData[b]})}else a.extend(c.p.postData,d);var k;if(c.p.searchurl){k=c.p.url;a(c).jqGrid("setGridParam",{url:c.p.searchurl})}var m=a(c).triggerHandler("jqGridToolbarBeforeClear")==="stop"?true:false;!m&&a.isFunction(b.beforeClear)&&(m=b.beforeClear.call(c));m||e&&a(c).jqGrid("setGridParam",
+{search:j}).trigger("reloadGrid",[{page:1}]);k&&a(c).jqGrid("setGridParam",{url:k});a(c).triggerHandler("jqGridToolbarAfterClear");a.isFunction(b.afterClear)&&b.afterClear()};this.toggleToolbar=function(){var b=a("tr.ui-search-toolbar",c.grid.hDiv),d=c.p.frozenColumns===true?a("tr.ui-search-toolbar",c.grid.fhDiv):false;if(b.css("display")==="none"){b.show();d&&d.show()}else{b.hide();d&&d.hide()}}}})},destroyFilterToolbar:function(){return this.each(function(){this.ftoolbar&&(this.toggleToolbar=this.clearToolbar=
+this.triggerToolbar=null,this.ftoolbar=!1,a(this.grid.hDiv).find("table thead tr.ui-search-toolbar").remove())})},destroyGroupHeader:function(b){void 0===b&&(b=!0);return this.each(function(){var c,f,g,j,h,e;f=this.grid;var d=a("table.ui-jqgrid-htable thead",f.hDiv),p=this.p.colModel;if(f){a(this).unbind(".setGroupHeaders");c=a("<tr>",{role:"rowheader"}).addClass("ui-jqgrid-labels");j=f.headers;f=0;for(g=j.length;f<g;f++){h=p[f].hidden?"none":"";h=a(j[f].el).width(j[f].width).css("display",h);try{h.removeAttr("rowSpan")}catch(l){h.attr("rowSpan",
+1)}c.append(h);e=h.children("span.ui-jqgrid-resize");0<e.length&&(e[0].style.height="");h.children("div")[0].style.top=""}a(d).children("tr.ui-jqgrid-labels").remove();a(d).prepend(c);!0===b&&a(this).jqGrid("setGridParam",{groupHeader:null})}})},setGroupHeaders:function(b){b=a.extend({useColSpanStyle:!1,groupHeaders:[]},b||{});return this.each(function(){this.p.groupHeader=b;var c,f,g=0,j,h,e,d,p,l=this.p.colModel,s=l.length,n=this.grid.headers,i=a("table.ui-jqgrid-htable",this.grid.hDiv),k=i.children("thead").children("tr.ui-jqgrid-labels:last").addClass("jqg-second-row-header");
+j=i.children("thead");var m=i.find(".jqg-first-row-header");void 0===m[0]?m=a("<tr>",{role:"row","aria-hidden":"true"}).addClass("jqg-first-row-header").css("height","auto"):m.empty();var r,o=function(a,b){var c=b.length,d;for(d=0;d<c;d++)if(b[d].startColumnName===a)return d;return-1};a(this).prepend(j);j=a("<tr>",{role:"rowheader"}).addClass("ui-jqgrid-labels jqg-third-row-header");for(c=0;c<s;c++)if(e=n[c].el,d=a(e),f=l[c],h={height:"0px",width:n[c].width+"px",display:f.hidden?"none":""},a("<th>",
+{role:"gridcell"}).css(h).addClass("ui-first-th-"+this.p.direction).appendTo(m),e.style.width="",h=o(f.name,b.groupHeaders),0<=h){h=b.groupHeaders[h];g=h.numberOfColumns;p=h.titleText;for(h=f=0;h<g&&c+h<s;h++)l[c+h].hidden||f++;h=a("<th>").attr({role:"columnheader"}).addClass("ui-state-default ui-th-column-header ui-th-"+this.p.direction).css({height:"22px","border-top":"0px none"}).html(p);0<f&&h.attr("colspan",""+f);this.p.headertitles&&h.attr("title",h.text());0===f&&h.hide();d.before(h);j.append(e);
+g-=1}else 0===g?b.useColSpanStyle?d.attr("rowspan","2"):(a("<th>",{role:"columnheader"}).addClass("ui-state-default ui-th-column-header ui-th-"+this.p.direction).css({display:f.hidden?"none":"","border-top":"0px none"}).insertBefore(d),j.append(e)):(j.append(e),g--);l=a(this).children("thead");l.prepend(m);j.insertAfter(k);i.append(l);b.useColSpanStyle&&(i.find("span.ui-jqgrid-resize").each(function(){var b=a(this).parent();b.is(":visible")&&(this.style.cssText="height: "+b.height()+"px !important; cursor: col-resize;")}),
+i.find("div.ui-jqgrid-sortable").each(function(){var b=a(this),c=b.parent();c.is(":visible")&&c.is(":has(span.ui-jqgrid-resize)")&&b.css("top",(c.height()-b.outerHeight())/2+"px")}));r=l.find("tr.jqg-first-row-header");a(this).bind("jqGridResizeStop.setGroupHeaders",function(a,b,c){r.find("th").eq(c).width(b)})})},setFrozenColumns:function(){return this.each(function(){if(this.grid){var b=this,c=b.p.colModel,f=0,g=c.length,j=-1,h=!1;if(!(!0===b.p.subGrid||!0===b.p.treeGrid||!0===b.p.cellEdit||b.p.sortable||
+b.p.scroll||b.p.grouping)){b.p.rownumbers&&f++;for(b.p.multiselect&&f++;f<g;){if(!0===c[f].frozen)h=!0,j=f;else break;f++}if(0<=j&&h){c=b.p.caption?a(b.grid.cDiv).outerHeight():0;f=a(".ui-jqgrid-htable","#gview_"+a.jgrid.jqID(b.p.id)).height();b.p.toppager&&(c+=a(b.grid.topDiv).outerHeight());!0===b.p.toolbar[0]&&"bottom"!==b.p.toolbar[1]&&(c+=a(b.grid.uDiv).outerHeight());b.grid.fhDiv=a('<div style="position:absolute;left:0px;top:'+c+"px;height:"+f+'px;" class="frozen-div ui-state-default ui-jqgrid-hdiv"></div>');
+b.grid.fbDiv=a('<div style="position:absolute;left:0px;top:'+(parseInt(c,10)+parseInt(f,10)+1)+'px;overflow-y:hidden" class="frozen-bdiv ui-jqgrid-bdiv"></div>');a("#gview_"+a.jgrid.jqID(b.p.id)).append(b.grid.fhDiv);c=a(".ui-jqgrid-htable","#gview_"+a.jgrid.jqID(b.p.id)).clone(!0);if(b.p.groupHeader){a("tr.jqg-first-row-header, tr.jqg-third-row-header",c).each(function(){a("th:gt("+j+")",this).remove()});var e=-1,d=-1,p,l;a("tr.jqg-second-row-header th",c).each(function(){p=parseInt(a(this).attr("colspan"),
+10);if(l=parseInt(a(this).attr("rowspan"),10))e++,d++;p&&(e+=p,d++);if(e===j)return!1});e!==j&&(d=j);a("tr.jqg-second-row-header",c).each(function(){a("th:gt("+d+")",this).remove()})}else a("tr",c).each(function(){a("th:gt("+j+")",this).remove()});a(c).width(1);a(b.grid.fhDiv).append(c).mousemove(function(a){if(b.grid.resizing)return b.grid.dragMove(a),!1});a(b).bind("jqGridResizeStop.setFrozenColumns",function(c,d,e){c=a(".ui-jqgrid-htable",b.grid.fhDiv);a("th:eq("+e+")",c).width(d);c=a(".ui-jqgrid-btable",
+b.grid.fbDiv);a("tr:first td:eq("+e+")",c).width(d)});a(b).bind("jqGridOnSortCol.setFrozenColumns",function(c,d,e){c=a("tr.ui-jqgrid-labels:last th:eq("+b.p.lastsort+")",b.grid.fhDiv);d=a("tr.ui-jqgrid-labels:last th:eq("+e+")",b.grid.fhDiv);a("span.ui-grid-ico-sort",c).addClass("ui-state-disabled");a(c).attr("aria-selected","false");a("span.ui-icon-"+b.p.sortorder,d).removeClass("ui-state-disabled");a(d).attr("aria-selected","true");!b.p.viewsortcols[0]&&b.p.lastsort!==e&&(a("span.s-ico",c).hide(),
+a("span.s-ico",d).show())});a("#gview_"+a.jgrid.jqID(b.p.id)).append(b.grid.fbDiv);a(b.grid.bDiv).scroll(function(){a(b.grid.fbDiv).scrollTop(a(this).scrollTop())});!0===b.p.hoverrows&&a("#"+a.jgrid.jqID(b.p.id)).unbind("mouseover").unbind("mouseout");a(b).bind("jqGridAfterGridComplete.setFrozenColumns",function(){a("#"+a.jgrid.jqID(b.p.id)+"_frozen").remove();a(b.grid.fbDiv).height(a(b.grid.bDiv).height()-16);var c=a("#"+a.jgrid.jqID(b.p.id)).clone(!0);a("tr",c).each(function(){a("td:gt("+j+")",
+this).remove()});a(c).width(1).attr("id",b.p.id+"_frozen");a(b.grid.fbDiv).append(c);!0===b.p.hoverrows&&(a("tr.jqgrow",c).hover(function(){a(this).addClass("ui-state-hover");a("#"+a.jgrid.jqID(this.id),"#"+a.jgrid.jqID(b.p.id)).addClass("ui-state-hover")},function(){a(this).removeClass("ui-state-hover");a("#"+a.jgrid.jqID(this.id),"#"+a.jgrid.jqID(b.p.id)).removeClass("ui-state-hover")}),a("tr.jqgrow","#"+a.jgrid.jqID(b.p.id)).hover(function(){a(this).addClass("ui-state-hover");a("#"+a.jgrid.jqID(this.id),
+"#"+a.jgrid.jqID(b.p.id)+"_frozen").addClass("ui-state-hover")},function(){a(this).removeClass("ui-state-hover");a("#"+a.jgrid.jqID(this.id),"#"+a.jgrid.jqID(b.p.id)+"_frozen").removeClass("ui-state-hover")}));c=null});b.p.frozenColumns=!0}}}})},destroyFrozenColumns:function(){return this.each(function(){if(this.grid&&!0===this.p.frozenColumns){a(this.grid.fhDiv).remove();a(this.grid.fbDiv).remove();this.grid.fhDiv=null;this.grid.fbDiv=null;a(this).unbind(".setFrozenColumns");if(!0===this.p.hoverrows){var b;
+a("#"+a.jgrid.jqID(this.p.id)).bind("mouseover",function(c){b=a(c.target).closest("tr.jqgrow");"ui-subgrid"!==a(b).attr("class")&&a(b).addClass("ui-state-hover")}).bind("mouseout",function(c){b=a(c.target).closest("tr.jqgrow");a(b).removeClass("ui-state-hover")})}this.p.frozenColumns=!1}})}})})(jQuery);
 (function(a){a.extend(a.jgrid,{showModal:function(a){a.w.show()},closeModal:function(a){a.w.hide().attr("aria-hidden","true");a.o&&a.o.remove()},hideModal:function(d,b){b=a.extend({jqm:!0,gb:""},b||{});if(b.onClose){var c=b.gb&&"string"===typeof b.gb&&"#gbox_"===b.gb.substr(0,6)?b.onClose.call(a("#"+b.gb.substr(6))[0],d):b.onClose(d);if("boolean"===typeof c&&!c)return}if(a.fn.jqm&&!0===b.jqm)a(d).attr("aria-hidden","true").jqmHide();else{if(""!==b.gb)try{a(".jqgrid-overlay:first",b.gb).hide()}catch(g){}a(d).hide().attr("aria-hidden",
-"true")}},findPos:function(a){var b=0,c=0;if(a.offsetParent){do b+=a.offsetLeft,c+=a.offsetTop;while(a=a.offsetParent)}return[b,c]},createModal:function(d,b,c,g,e,h,f){var c=a.extend(!0,{},a.jgrid.jqModal||{},c),i=document.createElement("div"),j,n=this,f=a.extend({},f||{});j="rtl"==a(c.gbox).attr("dir")?!0:!1;i.className="ui-widget ui-widget-content ui-corner-all ui-jqdialog";i.id=d.themodal;var k=document.createElement("div");k.className="ui-jqdialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix";
+"true")}},findPos:function(a){var b=0,c=0;if(a.offsetParent){do b+=a.offsetLeft,c+=a.offsetTop;while(a=a.offsetParent)}return[b,c]},createModal:function(d,b,c,g,e,h,f){var c=a.extend(!0,{},a.jgrid.jqModal||{},c),i=document.createElement("div"),j,n=this,f=a.extend({},f||{});j="rtl"===a(c.gbox).attr("dir")?!0:!1;i.className="ui-widget ui-widget-content ui-corner-all ui-jqdialog";i.id=d.themodal;var k=document.createElement("div");k.className="ui-jqdialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix";
 k.id=d.modalhead;a(k).append("<span class='ui-jqdialog-title'>"+c.caption+"</span>");var l=a("<a href='javascript:void(0)' class='ui-jqdialog-titlebar-close ui-corner-all'></a>").hover(function(){l.addClass("ui-state-hover")},function(){l.removeClass("ui-state-hover")}).append("<span class='ui-icon ui-icon-closethick'></span>");a(k).append(l);j?(i.dir="rtl",a(".ui-jqdialog-title",k).css("float","right"),a(".ui-jqdialog-titlebar-close",k).css("left","0.3em")):(i.dir="ltr",a(".ui-jqdialog-title",k).css("float",
 "left"),a(".ui-jqdialog-titlebar-close",k).css("right","0.3em"));var m=document.createElement("div");a(m).addClass("ui-jqdialog-content ui-widget-content").attr("id",d.modalcontent);a(m).append(b);i.appendChild(m);a(i).prepend(k);!0===h?a("body").append(i):"string"===typeof h?a(h).append(i):a(i).insertBefore(g);a(i).css(f);void 0===c.jqModal&&(c.jqModal=!0);b={};if(a.fn.jqm&&!0===c.jqModal)0===c.left&&0===c.top&&c.overlay&&(f=[],f=a.jgrid.findPos(e),c.left=f[0]+4,c.top=f[1]+4),b.top=c.top+"px",b.left=
 c.left;else if(0!==c.left||0!==c.top)b.left=c.left,b.top=c.top+"px";a("a.ui-jqdialog-titlebar-close",k).click(function(){var b=a("#"+a.jgrid.jqID(d.themodal)).data("onClose")||c.onClose,e=a("#"+a.jgrid.jqID(d.themodal)).data("gbox")||c.gbox;n.hideModal("#"+a.jgrid.jqID(d.themodal),{gb:e,jqm:c.jqModal,onClose:b});return false});if(0===c.width||!c.width)c.width=300;if(0===c.height||!c.height)c.height=200;c.zIndex||(g=a(g).parents("*[role=dialog]").filter(":first").css("z-index"),c.zIndex=g?parseInt(g,
@@ -240,23 +242,23 @@ else try{a(i).draggable({handle:a("#"+a.jgrid.jqID(k.id))})}catch(o){}if(c.resiz
 c.onClose;n.hideModal("#"+a.jgrid.jqID(d.themodal),{gb:c.gbox,jqm:c.jqModal,onClose:b})}})},viewModal:function(d,b){b=a.extend({toTop:!0,overlay:10,modal:!1,overlayClass:"ui-widget-overlay",onShow:a.jgrid.showModal,onHide:a.jgrid.closeModal,gbox:"",jqm:!0,jqM:!0},b||{});if(a.fn.jqm&&!0===b.jqm)b.jqM?a(d).attr("aria-hidden","false").jqm(b).jqmShow():a(d).attr("aria-hidden","false").jqmShow();else{""!==b.gbox&&(a(".jqgrid-overlay:first",b.gbox).show(),a(d).data("gbox",b.gbox));a(d).show().attr("aria-hidden",
 "false");try{a(":input:visible",d)[0].focus()}catch(c){}}},info_dialog:function(d,b,c,g){var e={width:290,height:"auto",dataheight:"auto",drag:!0,resize:!1,left:250,top:170,zIndex:1E3,jqModal:!0,modal:!1,closeOnEscape:!0,align:"center",buttonalign:"center",buttons:[]};a.extend(!0,e,a.jgrid.jqModal||{},{caption:"<b>"+d+"</b>"},g||{});var h=e.jqModal,f=this;a.fn.jqm&&!h&&(h=!1);d="";if(0<e.buttons.length)for(g=0;g<e.buttons.length;g++)void 0===e.buttons[g].id&&(e.buttons[g].id="info_button_"+g),d+=
 "<a href='javascript:void(0)' id='"+e.buttons[g].id+"' class='fm-button ui-state-default ui-corner-all'>"+e.buttons[g].text+"</a>";g=isNaN(e.dataheight)?e.dataheight:e.dataheight+"px";b="<div id='info_id'>"+("<div id='infocnt' style='margin:0px;padding-bottom:1em;width:100%;overflow:auto;position:relative;height:"+g+";"+("text-align:"+e.align+";")+"'>"+b+"</div>");b+=c?"<div class='ui-widget-content ui-helper-clearfix' style='text-align:"+e.buttonalign+";padding-bottom:0.8em;padding-top:0.5em;background-image: none;border-width: 1px 0 0 0;'><a href='javascript:void(0)' id='closedialog' class='fm-button ui-state-default ui-corner-all'>"+
-c+"</a>"+d+"</div>":""!==d?"<div class='ui-widget-content ui-helper-clearfix' style='text-align:"+e.buttonalign+";padding-bottom:0.8em;padding-top:0.5em;background-image: none;border-width: 1px 0 0 0;'>"+d+"</div>":"";b+="</div>";try{"false"==a("#info_dialog").attr("aria-hidden")&&a.jgrid.hideModal("#info_dialog",{jqm:h}),a("#info_dialog").remove()}catch(i){}a.jgrid.createModal({themodal:"info_dialog",modalhead:"info_head",modalcontent:"info_content",scrollelm:"infocnt"},b,e,"","",!0);d&&a.each(e.buttons,
+c+"</a>"+d+"</div>":""!==d?"<div class='ui-widget-content ui-helper-clearfix' style='text-align:"+e.buttonalign+";padding-bottom:0.8em;padding-top:0.5em;background-image: none;border-width: 1px 0 0 0;'>"+d+"</div>":"";b+="</div>";try{"false"===a("#info_dialog").attr("aria-hidden")&&a.jgrid.hideModal("#info_dialog",{jqm:h}),a("#info_dialog").remove()}catch(i){}a.jgrid.createModal({themodal:"info_dialog",modalhead:"info_head",modalcontent:"info_content",scrollelm:"infocnt"},b,e,"","",!0);d&&a.each(e.buttons,
 function(d){a("#"+a.jgrid.jqID(this.id),"#info_id").bind("click",function(){e.buttons[d].onClick.call(a("#info_dialog"));return!1})});a("#closedialog","#info_id").click(function(){f.hideModal("#info_dialog",{jqm:h,onClose:a("#info_dialog").data("onClose")||e.onClose,gb:a("#info_dialog").data("gbox")||e.gbox});return!1});a(".fm-button","#info_dialog").hover(function(){a(this).addClass("ui-state-hover")},function(){a(this).removeClass("ui-state-hover")});a.isFunction(e.beforeOpen)&&e.beforeOpen();a.jgrid.viewModal("#info_dialog",
 {onHide:function(a){a.w.hide().remove();a.o&&a.o.remove()},modal:e.modal,jqm:h});a.isFunction(e.afterOpen)&&e.afterOpen();try{a("#info_dialog").focus()}catch(j){}},bindEv:function(d,b){a.isFunction(b.dataInit)&&b.dataInit.call(this,d);b.dataEvents&&a.each(b.dataEvents,function(){void 0!==this.data?a(d).bind(this.type,this.data,this.fn):a(d).bind(this.type,this.fn)})},createEl:function(d,b,c,g,e){function h(d,b,c){var e="dataInit,dataEvents,dataUrl,buildSelect,sopt,searchhidden,defaultValue,attr,custom_element,custom_value".split(",");
-void 0!==c&&a.isArray(c)&&a.merge(e,c);a.each(b,function(b,c){-1===a.inArray(b,e)&&a(d).attr(b,c)});b.hasOwnProperty("id")||a(d).attr("id",a.jgrid.randId())}var f="",i=this;switch(d){case "textarea":f=document.createElement("textarea");g?b.cols||a(f).css({width:"98%"}):b.cols||(b.cols=20);b.rows||(b.rows=2);if("&nbsp;"==c||"&#160;"==c||1==c.length&&160==c.charCodeAt(0))c="";f.value=c;h(f,b);a(f).attr({role:"textbox",multiline:"true"});break;case "checkbox":f=document.createElement("input");f.type=
+void 0!==c&&a.isArray(c)&&a.merge(e,c);a.each(b,function(b,c){-1===a.inArray(b,e)&&a(d).attr(b,c)});b.hasOwnProperty("id")||a(d).attr("id",a.jgrid.randId())}var f="",i=this;switch(d){case "textarea":f=document.createElement("textarea");g?b.cols||a(f).css({width:"98%"}):b.cols||(b.cols=20);b.rows||(b.rows=2);if("&nbsp;"===c||"&#160;"===c||1===c.length&&160===c.charCodeAt(0))c="";f.value=c;h(f,b);a(f).attr({role:"textbox",multiline:"true"});break;case "checkbox":f=document.createElement("input");f.type=
 "checkbox";b.value?(d=b.value.split(":"),c===d[0]&&(f.checked=!0,f.defaultChecked=!0),f.value=d[0],a(f).attr("offval",d[1])):(d=c.toLowerCase(),0>d.search(/(false|f|0|no|n|off|undefined)/i)&&""!==d?(f.checked=!0,f.defaultChecked=!0,f.value=c):f.value="on",a(f).attr("offval","off"));h(f,b,["value"]);a(f).attr("role","checkbox");break;case "select":f=document.createElement("select");f.setAttribute("role","select");g=[];!0===b.multiple?(d=!0,f.multiple="multiple",a(f).attr("aria-multiselectable","true")):
 d=!1;if(void 0!==b.dataUrl)d=b.name?(""+b.id).substring(0,(""+b.id).length-(""+b.name).length-1):""+b.id,g=b.postData||e.postData,i.p&&i.p.idPrefix?d=a.jgrid.stripPref(i.p.idPrefix,d):g=void 0,a.ajax(a.extend({url:b.dataUrl,type:"GET",dataType:"html",data:a.isFunction(g)?g.call(i,d,c,""+b.name):g,context:{elem:f,options:b,vl:c},success:function(d){var b=[],c=this.elem,e=this.vl,f=a.extend({},this.options),g=f.multiple===true,d=a.isFunction(f.buildSelect)?f.buildSelect.call(i,d):d;typeof d==="string"&&
 (d=a(a.trim(d)).html());if(d){a(c).append(d);h(c,f);if(f.size===void 0)f.size=g?3:1;if(g){b=e.split(",");b=a.map(b,function(d){return a.trim(d)})}else b[0]=a.trim(e);setTimeout(function(){a("option",c).each(function(d){if(d===0&&c.multiple)this.selected=false;a(this).attr("role","option");if(a.inArray(a.trim(a(this).text()),b)>-1||a.inArray(a.trim(a(this).val()),b)>-1)this.selected="selected"})},0)}}},e||{}));else if(b.value){var j;void 0===b.size&&(b.size=d?3:1);d&&(g=c.split(","),g=a.map(g,function(d){return a.trim(d)}));
-"function"===typeof b.value&&(b.value=b.value());var n,k,l=void 0===b.separator?":":b.separator,e=void 0===b.delimiter?";":b.delimiter;if("string"===typeof b.value){n=b.value.split(e);for(j=0;j<n.length;j++){k=n[j].split(l);2<k.length&&(k[1]=a.map(k,function(a,d){if(d>0)return a}).join(l));e=document.createElement("option");e.setAttribute("role","option");e.value=k[0];e.innerHTML=k[1];f.appendChild(e);if(!d&&(a.trim(k[0])==a.trim(c)||a.trim(k[1])==a.trim(c)))e.selected="selected";if(d&&(-1<a.inArray(a.trim(k[1]),
-g)||-1<a.inArray(a.trim(k[0]),g)))e.selected="selected"}}else if("object"===typeof b.value)for(j in l=b.value,l)if(l.hasOwnProperty(j)){e=document.createElement("option");e.setAttribute("role","option");e.value=j;e.innerHTML=l[j];f.appendChild(e);if(!d&&(a.trim(j)==a.trim(c)||a.trim(l[j])==a.trim(c)))e.selected="selected";if(d&&(-1<a.inArray(a.trim(l[j]),g)||-1<a.inArray(a.trim(j),g)))e.selected="selected"}h(f,b,["value"])}break;case "text":case "password":case "button":j="button"==d?"button":"textbox";
-f=document.createElement("input");f.type=d;f.value=c;h(f,b);"button"!=d&&(g?b.size||a(f).css({width:"98%"}):b.size||(b.size=20));a(f).attr("role",j);break;case "image":case "file":f=document.createElement("input");f.type=d;h(f,b);break;case "custom":f=document.createElement("span");try{if(a.isFunction(b.custom_element))if(l=b.custom_element.call(i,c,b))l=a(l).addClass("customelement").attr({id:b.id,name:b.name}),a(f).empty().append(l);else throw"e2";else throw"e1";}catch(m){"e1"==m&&a.jgrid.info_dialog(a.jgrid.errors.errcap,
-"function 'custom_element' "+a.jgrid.edit.msg.nodefined,a.jgrid.edit.bClose),"e2"==m?a.jgrid.info_dialog(a.jgrid.errors.errcap,"function 'custom_element' "+a.jgrid.edit.msg.novalue,a.jgrid.edit.bClose):a.jgrid.info_dialog(a.jgrid.errors.errcap,"string"===typeof m?m:m.message,a.jgrid.edit.bClose)}}return f},checkDate:function(a,b){var c={},g,a=a.toLowerCase();g=-1!==a.indexOf("/")?"/":-1!==a.indexOf("-")?"-":-1!==a.indexOf(".")?".":"/";a=a.split(g);b=b.split(g);if(3!==b.length)return!1;g=-1;var e,
+"function"===typeof b.value&&(b.value=b.value());var n,k,l=void 0===b.separator?":":b.separator,e=void 0===b.delimiter?";":b.delimiter;if("string"===typeof b.value){n=b.value.split(e);for(j=0;j<n.length;j++){k=n[j].split(l);2<k.length&&(k[1]=a.map(k,function(a,d){if(d>0)return a}).join(l));e=document.createElement("option");e.setAttribute("role","option");e.value=k[0];e.innerHTML=k[1];f.appendChild(e);if(!d&&(a.trim(k[0])===a.trim(c)||a.trim(k[1])===a.trim(c)))e.selected="selected";if(d&&(-1<a.inArray(a.trim(k[1]),
+g)||-1<a.inArray(a.trim(k[0]),g)))e.selected="selected"}}else if("object"===typeof b.value)for(j in l=b.value,l)if(l.hasOwnProperty(j)){e=document.createElement("option");e.setAttribute("role","option");e.value=j;e.innerHTML=l[j];f.appendChild(e);if(!d&&(a.trim(j)===a.trim(c)||a.trim(l[j])===a.trim(c)))e.selected="selected";if(d&&(-1<a.inArray(a.trim(l[j]),g)||-1<a.inArray(a.trim(j),g)))e.selected="selected"}h(f,b,["value"])}break;case "text":case "password":case "button":j="button"===d?"button":
+"textbox";f=document.createElement("input");f.type=d;f.value=c;h(f,b);"button"!==d&&(g?b.size||a(f).css({width:"98%"}):b.size||(b.size=20));a(f).attr("role",j);break;case "image":case "file":f=document.createElement("input");f.type=d;h(f,b);break;case "custom":f=document.createElement("span");try{if(a.isFunction(b.custom_element))if(l=b.custom_element.call(i,c,b))l=a(l).addClass("customelement").attr({id:b.id,name:b.name}),a(f).empty().append(l);else throw"e2";else throw"e1";}catch(m){"e1"===m&&a.jgrid.info_dialog(a.jgrid.errors.errcap,
+"function 'custom_element' "+a.jgrid.edit.msg.nodefined,a.jgrid.edit.bClose),"e2"===m?a.jgrid.info_dialog(a.jgrid.errors.errcap,"function 'custom_element' "+a.jgrid.edit.msg.novalue,a.jgrid.edit.bClose):a.jgrid.info_dialog(a.jgrid.errors.errcap,"string"===typeof m?m:m.message,a.jgrid.edit.bClose)}}return f},checkDate:function(a,b){var c={},g,a=a.toLowerCase();g=-1!==a.indexOf("/")?"/":-1!==a.indexOf("-")?"-":-1!==a.indexOf(".")?".":"/";a=a.split(g);b=b.split(g);if(3!==b.length)return!1;g=-1;var e,
 h=-1,f=-1,i;for(i=0;i<a.length;i++)e=isNaN(b[i])?0:parseInt(b[i],10),c[a[i]]=e,e=a[i],-1!==e.indexOf("y")&&(g=i),-1!==e.indexOf("m")&&(f=i),-1!==e.indexOf("d")&&(h=i);e="y"===a[g]||"yyyy"===a[g]?4:"yy"===a[g]?2:-1;i=[0,31,29,31,30,31,30,31,31,30,31,30,31];var j;if(-1===g)return!1;j=c[a[g]].toString();2===e&&1===j.length&&(e=1);if(j.length!==e||0===c[a[g]]&&"00"!==b[g]||-1===f)return!1;j=c[a[f]].toString();if(1>j.length||1>c[a[f]]||12<c[a[f]]||-1===h)return!1;j=c[a[h]].toString();return 1>j.length||
-1>c[a[h]]||31<c[a[h]]||2==c[a[f]]&&c[a[h]]>(0===c[a[g]]%4&&(0!==c[a[g]]%100||0===c[a[g]]%400)?29:28)||c[a[h]]>i[c[a[f]]]?!1:!0},isEmpty:function(a){return a.match(/^\s+$/)||""===a?!0:!1},checkTime:function(d){var b=/^(\d{1,2}):(\d{2})([apAP][Mm])?$/;if(!a.jgrid.isEmpty(d))if(d=d.match(b)){if(d[3]){if(1>d[1]||12<d[1])return!1}else if(23<d[1])return!1;if(59<d[2])return!1}else return!1;return!0},checkValues:function(d,b,c,g){var e,h,f;f=this.p.colModel;if(void 0===c)if("string"===typeof b){c=0;for(g=
+1>c[a[h]]||31<c[a[h]]||2===c[a[f]]&&c[a[h]]>(0===c[a[g]]%4&&(0!==c[a[g]]%100||0===c[a[g]]%400)?29:28)||c[a[h]]>i[c[a[f]]]?!1:!0},isEmpty:function(a){return a.match(/^\s+$/)||""===a?!0:!1},checkTime:function(d){var b=/^(\d{1,2}):(\d{2})([apAP][Mm])?$/;if(!a.jgrid.isEmpty(d))if(d=d.match(b)){if(d[3]){if(1>d[1]||12<d[1])return!1}else if(23<d[1])return!1;if(59<d[2])return!1}else return!1;return!0},checkValues:function(d,b,c,g){var e,h,f;f=this.p.colModel;if(void 0===c)if("string"===typeof b){c=0;for(g=
 f.length;c<g;c++)if(f[c].name===b){e=f[c].editrules;b=c;null!=f[c].formoptions&&(h=f[c].formoptions.label);break}}else 0<=b&&(e=f[b].editrules);else e=c,h=void 0===g?"_":g;if(e){h||(h=null!=this.p.colNames?this.p.colNames[b]:f[b].label);if(!0===e.required&&a.jgrid.isEmpty(d))return[!1,h+": "+a.jgrid.edit.msg.required,""];c=!1===e.required?!1:!0;if(!0===e.number&&!(!1===c&&a.jgrid.isEmpty(d))&&isNaN(d))return[!1,h+": "+a.jgrid.edit.msg.number,""];if(void 0!==e.minValue&&!isNaN(e.minValue)&&parseFloat(d)<
 parseFloat(e.minValue))return[!1,h+": "+a.jgrid.edit.msg.minValue+" "+e.minValue,""];if(void 0!==e.maxValue&&!isNaN(e.maxValue)&&parseFloat(d)>parseFloat(e.maxValue))return[!1,h+": "+a.jgrid.edit.msg.maxValue+" "+e.maxValue,""];if(!0===e.email&&!(!1===c&&a.jgrid.isEmpty(d))&&(g=/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,
-!g.test(d)))return[!1,h+": "+a.jgrid.edit.msg.email,""];if(!0===e.integer&&!(!1===c&&a.jgrid.isEmpty(d))&&(isNaN(d)||0!==d%1||-1!=d.indexOf(".")))return[!1,h+": "+a.jgrid.edit.msg.integer,""];if(!0===e.date&&!(!1===c&&a.jgrid.isEmpty(d))&&(f[b].formatoptions&&f[b].formatoptions.newformat?(f=f[b].formatoptions.newformat,a.jgrid.formatter.date.masks.hasOwnProperty(f)&&(f=a.jgrid.formatter.date.masks[f])):f=f[b].datefmt||"Y-m-d",!a.jgrid.checkDate(f,d)))return[!1,h+": "+a.jgrid.edit.msg.date+" - "+f,
-""];if(!0===e.time&&!(!1===c&&a.jgrid.isEmpty(d))&&!a.jgrid.checkTime(d))return[!1,h+": "+a.jgrid.edit.msg.date+" - hh:mm (am/pm)",""];if(!0===e.url&&!(!1===c&&a.jgrid.isEmpty(d))&&(g=/^(((https?)|(ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i,!g.test(d)))return[!1,h+": "+a.jgrid.edit.msg.url,""];if(!0===e.custom&&!(!1===c&&a.jgrid.isEmpty(d)))return a.isFunction(e.custom_func)?(d=e.custom_func.call(this,d,h,b),a.isArray(d)?d:[!1,a.jgrid.edit.msg.customarray,
+!g.test(d)))return[!1,h+": "+a.jgrid.edit.msg.email,""];if(!0===e.integer&&!(!1===c&&a.jgrid.isEmpty(d))&&(isNaN(d)||0!==d%1||-1!==d.indexOf(".")))return[!1,h+": "+a.jgrid.edit.msg.integer,""];if(!0===e.date&&!(!1===c&&a.jgrid.isEmpty(d))&&(f[b].formatoptions&&f[b].formatoptions.newformat?(f=f[b].formatoptions.newformat,a.jgrid.formatter.date.masks.hasOwnProperty(f)&&(f=a.jgrid.formatter.date.masks[f])):f=f[b].datefmt||"Y-m-d",!a.jgrid.checkDate(f,d)))return[!1,h+": "+a.jgrid.edit.msg.date+" - "+
+f,""];if(!0===e.time&&!(!1===c&&a.jgrid.isEmpty(d))&&!a.jgrid.checkTime(d))return[!1,h+": "+a.jgrid.edit.msg.date+" - hh:mm (am/pm)",""];if(!0===e.url&&!(!1===c&&a.jgrid.isEmpty(d))&&(g=/^(((https?)|(ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i,!g.test(d)))return[!1,h+": "+a.jgrid.edit.msg.url,""];if(!0===e.custom&&!(!1===c&&a.jgrid.isEmpty(d)))return a.isFunction(e.custom_func)?(d=e.custom_func.call(this,d,h,b),a.isArray(d)?d:[!1,a.jgrid.edit.msg.customarray,
 ""]):[!1,a.jgrid.edit.msg.customfcheck,""]}return[!0,"",""]}})})(jQuery);
 (function(a){var b={};a.jgrid.extend({searchGrid:function(b){b=a.extend(!0,{recreateFilter:!1,drag:!0,sField:"searchField",sValue:"searchString",sOper:"searchOper",sFilter:"filters",loadDefaults:!0,beforeShowSearch:null,afterShowSearch:null,onInitializeSearch:null,afterRedraw:null,afterChange:null,closeAfterSearch:!1,closeAfterReset:!1,closeOnEscape:!1,searchOnEnter:!1,multipleSearch:!1,multipleGroup:!1,top:0,left:0,jqModal:!0,modal:!1,resize:!0,width:450,height:"auto",dataheight:"auto",showQuery:!1,
 errorcheck:!0,sopt:null,stringResult:void 0,onClose:null,onSearch:null,onReset:null,toTop:!0,overlay:30,columns:[],tmplNames:null,tmplFilters:null,tmplLabel:" Template: ",showOnLoad:!1,layer:null,operands:{eq:"=",ne:"<>",lt:"<",le:"<=",gt:">",ge:">=",bw:"LIKE",bn:"NOT LIKE","in":"IN",ni:"NOT IN",ew:"LIKE",en:"NOT LIKE",cn:"LIKE",nc:"NOT LIKE",nu:"IS NULL",nn:"ISNOT NULL"}},a.jgrid.search,b||{});return this.each(function(){function c(c){t=a(e).triggerHandler("jqGridFilterBeforeShow",[c]);void 0===
@@ -275,92 +277,92 @@ function(){a(this).removeClass("ui-state-hover")})}}})},editGridRow:function(r,c
 jqModal:!0,closeOnEscape:!1,addedrow:"first",topinfo:"",bottominfo:"",saveicon:[],closeicon:[],savekey:[!1,13],navkeys:[!1,38,40],checkOnSubmit:!1,checkOnUpdate:!1,_savedData:{},processing:!1,onClose:null,ajaxEditOptions:{},serializeEditData:null,viewPagerButtons:!0,overlayClass:"ui-widget-overlay"},a.jgrid.edit,c||{});b[a(this)[0].p.id]=c;return this.each(function(){function e(){a(k+" > tbody > tr > td > .FormElement").each(function(){var c=a(".customelement",this);if(c.length){var b=a(c[0]).attr("name");
 a.each(d.p.colModel,function(){if(this.name===b&&this.editoptions&&a.isFunction(this.editoptions.custom_value)){try{if(j[b]=this.editoptions.custom_value.call(d,a("#"+a.jgrid.jqID(b),k),"get"),void 0===j[b])throw"e1";}catch(c){"e1"===c?a.jgrid.info_dialog(a.jgrid.errors.errcap,"function 'custom_value' "+a.jgrid.edit.msg.novalue,a.jgrid.edit.bClose):a.jgrid.info_dialog(a.jgrid.errors.errcap,c.message,a.jgrid.edit.bClose)}return!0}})}else{switch(a(this).get(0).type){case "checkbox":a(this).is(":checked")?
 j[this.name]=a(this).val():(c=a(this).attr("offval"),j[this.name]=c);break;case "select-one":j[this.name]=a("option:selected",this).val();break;case "select-multiple":j[this.name]=a(this).val();j[this.name]=j[this.name]?j[this.name].join(","):"";a("option:selected",this).each(function(c,b){a(b).text()});break;case "password":case "text":case "textarea":case "button":j[this.name]=a(this).val()}d.p.autoencode&&(j[this.name]=a.jgrid.htmlEncode(j[this.name]))}});return!0}function i(c,e,l,g){var h,j,k,
-p=0,i,m,o,n=[],q=!1,z="",r;for(r=1;r<=g;r++)z+="<td class='CaptionTD'>&#160;</td><td class='DataTD'>&#160;</td>";"_empty"!=c&&(q=a(e).jqGrid("getInd",c));a(e.p.colModel).each(function(r){h=this.name;m=(j=this.editrules&&!0===this.editrules.edithidden?!1:!0===this.hidden?!0:!1)?"style='display:none'":"";if("cb"!==h&&"subgrid"!==h&&!0===this.editable&&"rn"!==h){if(!1===q)i="";else if(h==e.p.ExpandColumn&&!0===e.p.treeGrid)i=a("td[role='gridcell']:eq("+r+")",e.rows[q]).text();else{try{i=a.unformat.call(e,
-a("td[role='gridcell']:eq("+r+")",e.rows[q]),{rowId:c,colModel:this},r)}catch(t){i=this.edittype&&"textarea"==this.edittype?a("td[role='gridcell']:eq("+r+")",e.rows[q]).text():a("td[role='gridcell']:eq("+r+")",e.rows[q]).html()}if(!i||"&nbsp;"==i||"&#160;"==i||1==i.length&&160==i.charCodeAt(0))i=""}var v=a.extend({},this.editoptions||{},{id:h,name:h}),s=a.extend({},{elmprefix:"",elmsuffix:"",rowabove:!1,rowcontent:""},this.formoptions||{}),w=parseInt(s.rowpos,10)||p+1,u=parseInt(2*(parseInt(s.colpos,
-10)||1),10);"_empty"==c&&v.defaultValue&&(i=a.isFunction(v.defaultValue)?v.defaultValue.call(d):v.defaultValue);this.edittype||(this.edittype="text");d.p.autoencode&&(i=a.jgrid.htmlDecode(i));o=a.jgrid.createEl.call(d,this.edittype,v,i,!1,a.extend({},a.jgrid.ajaxOptions,e.p.ajaxSelectOptions||{}));if(b[d.p.id].checkOnSubmit||b[d.p.id].checkOnUpdate)b[d.p.id]._savedData[h]=i;a(o).addClass("FormElement");-1<a.inArray(this.edittype,["text","textarea","password","select"])&&a(o).addClass("ui-widget-content ui-corner-all");
+p=0,i,m,o,n=[],q=!1,z="",r;for(r=1;r<=g;r++)z+="<td class='CaptionTD'>&#160;</td><td class='DataTD'>&#160;</td>";"_empty"!==c&&(q=a(e).jqGrid("getInd",c));a(e.p.colModel).each(function(r){h=this.name;m=(j=this.editrules&&!0===this.editrules.edithidden?!1:!0===this.hidden?!0:!1)?"style='display:none'":"";if("cb"!==h&&"subgrid"!==h&&!0===this.editable&&"rn"!==h){if(!1===q)i="";else if(h===e.p.ExpandColumn&&!0===e.p.treeGrid)i=a("td[role='gridcell']:eq("+r+")",e.rows[q]).text();else{try{i=a.unformat.call(e,
+a("td[role='gridcell']:eq("+r+")",e.rows[q]),{rowId:c,colModel:this},r)}catch(t){i=this.edittype&&"textarea"===this.edittype?a("td[role='gridcell']:eq("+r+")",e.rows[q]).text():a("td[role='gridcell']:eq("+r+")",e.rows[q]).html()}if(!i||"&nbsp;"===i||"&#160;"===i||1===i.length&&160===i.charCodeAt(0))i=""}var v=a.extend({},this.editoptions||{},{id:h,name:h}),s=a.extend({},{elmprefix:"",elmsuffix:"",rowabove:!1,rowcontent:""},this.formoptions||{}),w=parseInt(s.rowpos,10)||p+1,u=parseInt(2*(parseInt(s.colpos,
+10)||1),10);"_empty"===c&&v.defaultValue&&(i=a.isFunction(v.defaultValue)?v.defaultValue.call(d):v.defaultValue);this.edittype||(this.edittype="text");d.p.autoencode&&(i=a.jgrid.htmlDecode(i));o=a.jgrid.createEl.call(d,this.edittype,v,i,!1,a.extend({},a.jgrid.ajaxOptions,e.p.ajaxSelectOptions||{}));if(b[d.p.id].checkOnSubmit||b[d.p.id].checkOnUpdate)b[d.p.id]._savedData[h]=i;a(o).addClass("FormElement");-1<a.inArray(this.edittype,["text","textarea","password","select"])&&a(o).addClass("ui-widget-content ui-corner-all");
 k=a(l).find("tr[rowpos="+w+"]");if(s.rowabove){var y=a("<tr><td class='contentinfo' colspan='"+2*g+"'>"+s.rowcontent+"</td></tr>");a(l).append(y);y[0].rp=w}0===k.length&&(k=a("<tr "+m+" rowpos='"+w+"'></tr>").addClass("FormData").attr("id","tr_"+h),a(k).append(z),a(l).append(k),k[0].rp=w);a("td:eq("+(u-2)+")",k[0]).html(void 0===s.label?e.p.colNames[r]:s.label);a("td:eq("+(u-1)+")",k[0]).append(s.elmprefix).append(o).append(s.elmsuffix);a.isFunction(v.custom_value)&&"_empty"!==c&&v.custom_value.call(d,
 a("#"+h,"#"+f),"set",i);a.jgrid.bindEv.call(d,o,v);n[p]=r;p++}});if(0<p&&(r=a("<tr class='FormData' style='display:none'><td class='CaptionTD'></td><td colspan='"+(2*g-1)+"' class='DataTD'><input class='FormElement' id='id_g' type='text' name='"+e.p.id+"_id' value='"+c+"'/></td></tr>"),r[0].rp=p+999,a(l).append(r),b[d.p.id].checkOnSubmit||b[d.p.id].checkOnUpdate))b[d.p.id]._savedData[e.p.id+"_id"]=c;return n}function t(c,e,f){var l,h=0,g,j,i,p,r;if(b[d.p.id].checkOnSubmit||b[d.p.id].checkOnUpdate)b[d.p.id]._savedData=
-{},b[d.p.id]._savedData[e.p.id+"_id"]=c;var m=e.p.colModel;if("_empty"==c)a(m).each(function(){l=this.name;i=a.extend({},this.editoptions||{});if((j=a("#"+a.jgrid.jqID(l),"#"+f))&&j.length&&null!==j[0])if(p="",i.defaultValue?(p=a.isFunction(i.defaultValue)?i.defaultValue.call(d):i.defaultValue,"checkbox"==j[0].type?(r=p.toLowerCase(),0>r.search(/(false|f|0|no|n|off|undefined)/i)&&""!==r?(j[0].checked=!0,j[0].defaultChecked=!0,j[0].value=p):(j[0].checked=!1,j[0].defaultChecked=!1)):j.val(p)):"checkbox"==
-j[0].type?(j[0].checked=!1,j[0].defaultChecked=!1,p=a(j).attr("offval")):j[0].type&&"select"==j[0].type.substr(0,6)?j[0].selectedIndex=0:j.val(p),!0===b[d.p.id].checkOnSubmit||b[d.p.id].checkOnUpdate)b[d.p.id]._savedData[l]=p}),a("#id_g","#"+f).val(c);else{var o=a(e).jqGrid("getInd",c,!0);o&&(a('td[role="gridcell"]',o).each(function(j){l=m[j].name;if("cb"!==l&&"subgrid"!==l&&"rn"!==l&&!0===m[j].editable){if(l==e.p.ExpandColumn&&!0===e.p.treeGrid)g=a(this).text();else try{g=a.unformat.call(e,a(this),
-{rowId:c,colModel:m[j]},j)}catch(i){g="textarea"==m[j].edittype?a(this).text():a(this).html()}d.p.autoencode&&(g=a.jgrid.htmlDecode(g));if(!0===b[d.p.id].checkOnSubmit||b[d.p.id].checkOnUpdate)b[d.p.id]._savedData[l]=g;l=a.jgrid.jqID(l);switch(m[j].edittype){case "password":case "text":case "button":case "image":case "textarea":if("&nbsp;"==g||"&#160;"==g||1==g.length&&160==g.charCodeAt(0))g="";a("#"+l,"#"+f).val(g);break;case "select":var k=g.split(","),k=a.map(k,function(c){return a.trim(c)});a("#"+
-l+" option","#"+f).each(function(){this.selected=!m[j].editoptions.multiple&&(a.trim(g)==a.trim(a(this).text())||k[0]==a.trim(a(this).text())||k[0]==a.trim(a(this).val()))?!0:m[j].editoptions.multiple?-1<a.inArray(a.trim(a(this).text()),k)||-1<a.inArray(a.trim(a(this).val()),k)?!0:!1:!1});break;case "checkbox":g=""+g;if(m[j].editoptions&&m[j].editoptions.value)if(m[j].editoptions.value.split(":")[0]==g)a("#"+l,"#"+f)[d.p.useProp?"prop":"attr"]({checked:!0,defaultChecked:!0});else a("#"+l,"#"+f)[d.p.useProp?
-"prop":"attr"]({checked:!1,defaultChecked:!1});else g=g.toLowerCase(),0>g.search(/(false|f|0|no|n|off|undefined)/i)&&""!==g?(a("#"+l,"#"+f)[d.p.useProp?"prop":"attr"]("checked",!0),a("#"+l,"#"+f)[d.p.useProp?"prop":"attr"]("defaultChecked",!0)):(a("#"+l,"#"+f)[d.p.useProp?"prop":"attr"]("checked",!1),a("#"+l,"#"+f)[d.p.useProp?"prop":"attr"]("defaultChecked",!1));break;case "custom":try{if(m[j].editoptions&&a.isFunction(m[j].editoptions.custom_value))m[j].editoptions.custom_value.call(d,a("#"+l,"#"+
-f),"set",g);else throw"e1";}catch(p){"e1"==p?a.jgrid.info_dialog(a.jgrid.errors.errcap,"function 'custom_value' "+a.jgrid.edit.msg.nodefined,a.jgrid.edit.bClose):a.jgrid.info_dialog(a.jgrid.errors.errcap,p.message,a.jgrid.edit.bClose)}}h++}}),0<h&&a("#id_g",k).val(c))}}function u(){a.each(d.p.colModel,function(a,c){c.editoptions&&!0===c.editoptions.NullIfEmpty&&j.hasOwnProperty(c.name)&&""===j[c.name]&&(j[c.name]="null")})}function s(){var e,l=[!0,"",""],g={},h=d.p.prmNames,i,m,r,o,n,z=a(d).triggerHandler("jqGridAddEditBeforeCheckValues",
-[a("#"+f),v]);z&&"object"===typeof z&&(j=z);a.isFunction(b[d.p.id].beforeCheckValues)&&(z=b[d.p.id].beforeCheckValues.call(d,j,a("#"+f),v))&&"object"===typeof z&&(j=z);for(r in j)if(j.hasOwnProperty(r)&&(l=a.jgrid.checkValues.call(d,j[r],r),!1===l[0]))break;u();l[0]&&(g=a(d).triggerHandler("jqGridAddEditClickSubmit",[b[d.p.id],j,v]),void 0===g&&a.isFunction(b[d.p.id].onclickSubmit)&&(g=b[d.p.id].onclickSubmit.call(d,b[d.p.id],j,v)||{}),l=a(d).triggerHandler("jqGridAddEditBeforeSubmit",[j,a("#"+f),
-v]),void 0===l&&(l=[!0,"",""]),l[0]&&a.isFunction(b[d.p.id].beforeSubmit)&&(l=b[d.p.id].beforeSubmit.call(d,j,a("#"+f),v)));if(l[0]&&!b[d.p.id].processing){b[d.p.id].processing=!0;a("#sData",k+"_2").addClass("ui-state-active");m=h.oper;i=h.id;j[m]="_empty"==a.trim(j[d.p.id+"_id"])?h.addoper:h.editoper;j[m]!=h.addoper?j[i]=j[d.p.id+"_id"]:void 0===j[i]&&(j[i]=j[d.p.id+"_id"]);delete j[d.p.id+"_id"];j=a.extend(j,b[d.p.id].editData,g);if(!0===d.p.treeGrid)for(n in j[m]==h.addoper&&(o=a(d).jqGrid("getGridParam",
-"selrow"),j["adjacency"==d.p.treeGridModel?d.p.treeReader.parent_id_field:"parent_id"]=o),d.p.treeReader)d.p.treeReader.hasOwnProperty(n)&&(g=d.p.treeReader[n],j.hasOwnProperty(g)&&!(j[m]==h.addoper&&"parent_id_field"===n)&&delete j[g]);j[i]=a.jgrid.stripPref(d.p.idPrefix,j[i]);n=a.extend({url:b[d.p.id].url||a(d).jqGrid("getGridParam","editurl"),type:b[d.p.id].mtype,data:a.isFunction(b[d.p.id].serializeEditData)?b[d.p.id].serializeEditData.call(d,j):j,complete:function(g,r){var n;j[i]=d.p.idPrefix+
-j[i];if(g.status>=300&&g.status!==304){l[0]=false;l[1]=a(d).triggerHandler("jqGridAddEditErrorTextFormat",[g,v]);l[1]=a.isFunction(b[d.p.id].errorTextFormat)?b[d.p.id].errorTextFormat.call(d,g,v):r+" Status: '"+g.statusText+"'. Error code: "+g.status}else{l=a(d).triggerHandler("jqGridAddEditAfterSubmit",[g,j,v]);l===void 0&&(l=[true,"",""]);l[0]&&a.isFunction(b[d.p.id].afterSubmit)&&(l=b[d.p.id].afterSubmit.call(d,g,j,v))}if(l[0]===false){a("#FormError>td",k).html(l[1]);a("#FormError",k).show()}else{d.p.autoencode&&
-a.each(j,function(c,b){j[c]=a.jgrid.htmlDecode(b)});if(j[m]===h.addoper){l[2]||(l[2]=a.jgrid.randId());j[i]=l[2];if(b[d.p.id].reloadAfterSubmit)a(d).trigger("reloadGrid");else{d.p.treeGrid===true?a(d).jqGrid("addChildNode",l[2],o,j):a(d).jqGrid("addRowData",l[2],j,c.addedrow);if(b[d.p.id].closeAfterAdd){d.p.treeGrid!==true&&a(d).jqGrid("setSelection",l[2]);a.jgrid.hideModal("#"+a.jgrid.jqID(p.themodal),{gb:"#gbox_"+a.jgrid.jqID(q),jqm:c.jqModal,onClose:b[d.p.id].onClose})}else b[d.p.id].clearAfterAdd&&
-t("_empty",d,f)}}else{if(b[d.p.id].reloadAfterSubmit){a(d).trigger("reloadGrid");b[d.p.id].closeAfterEdit||setTimeout(function(){a(d).jqGrid("setSelection",j[i])},1E3)}else d.p.treeGrid===true?a(d).jqGrid("setTreeRow",j[i],j):a(d).jqGrid("setRowData",j[i],j);b[d.p.id].closeAfterEdit&&a.jgrid.hideModal("#"+a.jgrid.jqID(p.themodal),{gb:"#gbox_"+a.jgrid.jqID(q),jqm:c.jqModal,onClose:b[d.p.id].onClose})}if(a.isFunction(b[d.p.id].afterComplete)){e=g;setTimeout(function(){a(d).triggerHandler("jqGridAddEditAfterComplete",
-[e,j,a("#"+f),v]);b[d.p.id].afterComplete.call(d,e,j,a("#"+f),v);e=null},500)}if(b[d.p.id].checkOnSubmit||b[d.p.id].checkOnUpdate){a("#"+f).data("disabled",false);if(b[d.p.id]._savedData[d.p.id+"_id"]!="_empty")for(n in b[d.p.id]._savedData)b[d.p.id]._savedData.hasOwnProperty(n)&&j[n]&&(b[d.p.id]._savedData[n]=j[n])}}b[d.p.id].processing=false;a("#sData",k+"_2").removeClass("ui-state-active");try{a(":input:visible","#"+f)[0].focus()}catch(z){}}},a.jgrid.ajaxOptions,b[d.p.id].ajaxEditOptions);!n.url&&
-!b[d.p.id].useDataProxy&&(a.isFunction(d.p.dataProxy)?b[d.p.id].useDataProxy=!0:(l[0]=!1,l[1]+=" "+a.jgrid.errors.nourl));l[0]&&(b[d.p.id].useDataProxy?(g=d.p.dataProxy.call(d,n,"set_"+d.p.id),void 0===g&&(g=[!0,""]),!1===g[0]?(l[0]=!1,l[1]=g[1]||"Error deleting the selected row!"):(n.data.oper==h.addoper&&b[d.p.id].closeAfterAdd&&a.jgrid.hideModal("#"+a.jgrid.jqID(p.themodal),{gb:"#gbox_"+a.jgrid.jqID(q),jqm:c.jqModal,onClose:b[d.p.id].onClose}),n.data.oper==h.editoper&&b[d.p.id].closeAfterEdit&&
+{},b[d.p.id]._savedData[e.p.id+"_id"]=c;var m=e.p.colModel;if("_empty"===c)a(m).each(function(){l=this.name;i=a.extend({},this.editoptions||{});if((j=a("#"+a.jgrid.jqID(l),"#"+f))&&j.length&&null!==j[0])if(p="",i.defaultValue?(p=a.isFunction(i.defaultValue)?i.defaultValue.call(d):i.defaultValue,"checkbox"===j[0].type?(r=p.toLowerCase(),0>r.search(/(false|f|0|no|n|off|undefined)/i)&&""!==r?(j[0].checked=!0,j[0].defaultChecked=!0,j[0].value=p):(j[0].checked=!1,j[0].defaultChecked=!1)):j.val(p)):"checkbox"===
+j[0].type?(j[0].checked=!1,j[0].defaultChecked=!1,p=a(j).attr("offval")):j[0].type&&"select"===j[0].type.substr(0,6)?j[0].selectedIndex=0:j.val(p),!0===b[d.p.id].checkOnSubmit||b[d.p.id].checkOnUpdate)b[d.p.id]._savedData[l]=p}),a("#id_g","#"+f).val(c);else{var o=a(e).jqGrid("getInd",c,!0);o&&(a('td[role="gridcell"]',o).each(function(j){l=m[j].name;if("cb"!==l&&"subgrid"!==l&&"rn"!==l&&!0===m[j].editable){if(l===e.p.ExpandColumn&&!0===e.p.treeGrid)g=a(this).text();else try{g=a.unformat.call(e,a(this),
+{rowId:c,colModel:m[j]},j)}catch(i){g="textarea"===m[j].edittype?a(this).text():a(this).html()}d.p.autoencode&&(g=a.jgrid.htmlDecode(g));if(!0===b[d.p.id].checkOnSubmit||b[d.p.id].checkOnUpdate)b[d.p.id]._savedData[l]=g;l=a.jgrid.jqID(l);switch(m[j].edittype){case "password":case "text":case "button":case "image":case "textarea":if("&nbsp;"===g||"&#160;"===g||1===g.length&&160===g.charCodeAt(0))g="";a("#"+l,"#"+f).val(g);break;case "select":var k=g.split(","),k=a.map(k,function(c){return a.trim(c)});
+a("#"+l+" option","#"+f).each(function(){this.selected=!m[j].editoptions.multiple&&(a.trim(g)===a.trim(a(this).text())||k[0]===a.trim(a(this).text())||k[0]===a.trim(a(this).val()))?!0:m[j].editoptions.multiple?-1<a.inArray(a.trim(a(this).text()),k)||-1<a.inArray(a.trim(a(this).val()),k)?!0:!1:!1});break;case "checkbox":g=""+g;if(m[j].editoptions&&m[j].editoptions.value)if(m[j].editoptions.value.split(":")[0]===g)a("#"+l,"#"+f)[d.p.useProp?"prop":"attr"]({checked:!0,defaultChecked:!0});else a("#"+
+l,"#"+f)[d.p.useProp?"prop":"attr"]({checked:!1,defaultChecked:!1});else g=g.toLowerCase(),0>g.search(/(false|f|0|no|n|off|undefined)/i)&&""!==g?(a("#"+l,"#"+f)[d.p.useProp?"prop":"attr"]("checked",!0),a("#"+l,"#"+f)[d.p.useProp?"prop":"attr"]("defaultChecked",!0)):(a("#"+l,"#"+f)[d.p.useProp?"prop":"attr"]("checked",!1),a("#"+l,"#"+f)[d.p.useProp?"prop":"attr"]("defaultChecked",!1));break;case "custom":try{if(m[j].editoptions&&a.isFunction(m[j].editoptions.custom_value))m[j].editoptions.custom_value.call(d,
+a("#"+l,"#"+f),"set",g);else throw"e1";}catch(p){"e1"===p?a.jgrid.info_dialog(a.jgrid.errors.errcap,"function 'custom_value' "+a.jgrid.edit.msg.nodefined,a.jgrid.edit.bClose):a.jgrid.info_dialog(a.jgrid.errors.errcap,p.message,a.jgrid.edit.bClose)}}h++}}),0<h&&a("#id_g",k).val(c))}}function u(){a.each(d.p.colModel,function(a,c){c.editoptions&&!0===c.editoptions.NullIfEmpty&&j.hasOwnProperty(c.name)&&""===j[c.name]&&(j[c.name]="null")})}function s(){var e,l=[!0,"",""],g={},h=d.p.prmNames,i,m,r,o,n,
+z=a(d).triggerHandler("jqGridAddEditBeforeCheckValues",[a("#"+f),v]);z&&"object"===typeof z&&(j=z);a.isFunction(b[d.p.id].beforeCheckValues)&&(z=b[d.p.id].beforeCheckValues.call(d,j,a("#"+f),v))&&"object"===typeof z&&(j=z);for(r in j)if(j.hasOwnProperty(r)&&(l=a.jgrid.checkValues.call(d,j[r],r),!1===l[0]))break;u();l[0]&&(g=a(d).triggerHandler("jqGridAddEditClickSubmit",[b[d.p.id],j,v]),void 0===g&&a.isFunction(b[d.p.id].onclickSubmit)&&(g=b[d.p.id].onclickSubmit.call(d,b[d.p.id],j,v)||{}),l=a(d).triggerHandler("jqGridAddEditBeforeSubmit",
+[j,a("#"+f),v]),void 0===l&&(l=[!0,"",""]),l[0]&&a.isFunction(b[d.p.id].beforeSubmit)&&(l=b[d.p.id].beforeSubmit.call(d,j,a("#"+f),v)));if(l[0]&&!b[d.p.id].processing){b[d.p.id].processing=!0;a("#sData",k+"_2").addClass("ui-state-active");m=h.oper;i=h.id;j[m]="_empty"===a.trim(j[d.p.id+"_id"])?h.addoper:h.editoper;j[m]!==h.addoper?j[i]=j[d.p.id+"_id"]:void 0===j[i]&&(j[i]=j[d.p.id+"_id"]);delete j[d.p.id+"_id"];j=a.extend(j,b[d.p.id].editData,g);if(!0===d.p.treeGrid)for(n in j[m]===h.addoper&&(o=
+a(d).jqGrid("getGridParam","selrow"),j["adjacency"===d.p.treeGridModel?d.p.treeReader.parent_id_field:"parent_id"]=o),d.p.treeReader)d.p.treeReader.hasOwnProperty(n)&&(g=d.p.treeReader[n],j.hasOwnProperty(g)&&!(j[m]===h.addoper&&"parent_id_field"===n)&&delete j[g]);j[i]=a.jgrid.stripPref(d.p.idPrefix,j[i]);n=a.extend({url:b[d.p.id].url||a(d).jqGrid("getGridParam","editurl"),type:b[d.p.id].mtype,data:a.isFunction(b[d.p.id].serializeEditData)?b[d.p.id].serializeEditData.call(d,j):j,complete:function(g,
+r){var n;j[i]=d.p.idPrefix+j[i];if(g.status>=300&&g.status!==304){l[0]=false;l[1]=a(d).triggerHandler("jqGridAddEditErrorTextFormat",[g,v]);l[1]=a.isFunction(b[d.p.id].errorTextFormat)?b[d.p.id].errorTextFormat.call(d,g,v):r+" Status: '"+g.statusText+"'. Error code: "+g.status}else{l=a(d).triggerHandler("jqGridAddEditAfterSubmit",[g,j,v]);l===void 0&&(l=[true,"",""]);l[0]&&a.isFunction(b[d.p.id].afterSubmit)&&(l=b[d.p.id].afterSubmit.call(d,g,j,v))}if(l[0]===false){a("#FormError>td",k).html(l[1]);
+a("#FormError",k).show()}else{d.p.autoencode&&a.each(j,function(c,b){j[c]=a.jgrid.htmlDecode(b)});if(j[m]===h.addoper){l[2]||(l[2]=a.jgrid.randId());j[i]=l[2];b[d.p.id].reloadAfterSubmit?a(d).trigger("reloadGrid"):d.p.treeGrid===true?a(d).jqGrid("addChildNode",l[2],o,j):a(d).jqGrid("addRowData",l[2],j,c.addedrow);if(b[d.p.id].closeAfterAdd){d.p.treeGrid!==true&&a(d).jqGrid("setSelection",l[2]);a.jgrid.hideModal("#"+a.jgrid.jqID(p.themodal),{gb:"#gbox_"+a.jgrid.jqID(q),jqm:c.jqModal,onClose:b[d.p.id].onClose})}else b[d.p.id].clearAfterAdd&&
+t("_empty",d,f)}else{if(b[d.p.id].reloadAfterSubmit){a(d).trigger("reloadGrid");b[d.p.id].closeAfterEdit||setTimeout(function(){a(d).jqGrid("setSelection",j[i])},1E3)}else d.p.treeGrid===true?a(d).jqGrid("setTreeRow",j[i],j):a(d).jqGrid("setRowData",j[i],j);b[d.p.id].closeAfterEdit&&a.jgrid.hideModal("#"+a.jgrid.jqID(p.themodal),{gb:"#gbox_"+a.jgrid.jqID(q),jqm:c.jqModal,onClose:b[d.p.id].onClose})}if(a.isFunction(b[d.p.id].afterComplete)){e=g;setTimeout(function(){a(d).triggerHandler("jqGridAddEditAfterComplete",
+[e,j,a("#"+f),v]);b[d.p.id].afterComplete.call(d,e,j,a("#"+f),v);e=null},500)}if(b[d.p.id].checkOnSubmit||b[d.p.id].checkOnUpdate){a("#"+f).data("disabled",false);if(b[d.p.id]._savedData[d.p.id+"_id"]!=="_empty")for(n in b[d.p.id]._savedData)b[d.p.id]._savedData.hasOwnProperty(n)&&j[n]&&(b[d.p.id]._savedData[n]=j[n])}}b[d.p.id].processing=false;a("#sData",k+"_2").removeClass("ui-state-active");try{a(":input:visible","#"+f)[0].focus()}catch(z){}}},a.jgrid.ajaxOptions,b[d.p.id].ajaxEditOptions);!n.url&&
+!b[d.p.id].useDataProxy&&(a.isFunction(d.p.dataProxy)?b[d.p.id].useDataProxy=!0:(l[0]=!1,l[1]+=" "+a.jgrid.errors.nourl));l[0]&&(b[d.p.id].useDataProxy?(g=d.p.dataProxy.call(d,n,"set_"+d.p.id),void 0===g&&(g=[!0,""]),!1===g[0]?(l[0]=!1,l[1]=g[1]||"Error deleting the selected row!"):(n.data.oper===h.addoper&&b[d.p.id].closeAfterAdd&&a.jgrid.hideModal("#"+a.jgrid.jqID(p.themodal),{gb:"#gbox_"+a.jgrid.jqID(q),jqm:c.jqModal,onClose:b[d.p.id].onClose}),n.data.oper===h.editoper&&b[d.p.id].closeAfterEdit&&
 a.jgrid.hideModal("#"+a.jgrid.jqID(p.themodal),{gb:"#gbox_"+a.jgrid.jqID(q),jqm:c.jqModal,onClose:b[d.p.id].onClose}))):a.ajax(n))}!1===l[0]&&(a("#FormError>td",k).html(l[1]),a("#FormError",k).show())}function m(a,c){var b=!1,d;for(d in a)if(a.hasOwnProperty(d)&&a[d]!=c[d]){b=!0;break}return b}function h(){var c=!0;a("#FormError",k).hide();if(b[d.p.id].checkOnUpdate&&(j={},e(),K=m(j,b[d.p.id]._savedData)))a("#"+f).data("disabled",!0),a(".confirm","#"+p.themodal).show(),c=!1;return c}function g(){var c;
-if("_empty"!==r&&void 0!==d.p.savedRow&&0<d.p.savedRow.length&&a.isFunction(a.fn.jqGrid.restoreRow))for(c=0;c<d.p.savedRow.length;c++)if(d.p.savedRow[c].id==r){a(d).jqGrid("restoreRow",r);break}}function n(c,b){var d=b[1].length-1;0===c?a("#pData",k+"_2").addClass("ui-state-disabled"):void 0!==b[1][c-1]&&a("#"+a.jgrid.jqID(b[1][c-1])).hasClass("ui-state-disabled")?a("#pData",k+"_2").addClass("ui-state-disabled"):a("#pData",k+"_2").removeClass("ui-state-disabled");c==d?a("#nData",k+"_2").addClass("ui-state-disabled"):
+if("_empty"!==r&&void 0!==d.p.savedRow&&0<d.p.savedRow.length&&a.isFunction(a.fn.jqGrid.restoreRow))for(c=0;c<d.p.savedRow.length;c++)if(d.p.savedRow[c].id==r){a(d).jqGrid("restoreRow",r);break}}function n(c,b){var d=b[1].length-1;0===c?a("#pData",k+"_2").addClass("ui-state-disabled"):void 0!==b[1][c-1]&&a("#"+a.jgrid.jqID(b[1][c-1])).hasClass("ui-state-disabled")?a("#pData",k+"_2").addClass("ui-state-disabled"):a("#pData",k+"_2").removeClass("ui-state-disabled");c===d?a("#nData",k+"_2").addClass("ui-state-disabled"):
 void 0!==b[1][c+1]&&a("#"+a.jgrid.jqID(b[1][c+1])).hasClass("ui-state-disabled")?a("#nData",k+"_2").addClass("ui-state-disabled"):a("#nData",k+"_2").removeClass("ui-state-disabled")}function x(){var c=a(d).jqGrid("getDataIDs"),b=a("#id_g",k).val();return[a.inArray(b,c),c]}var d=this;if(d.grid&&r){var q=d.p.id,f="FrmGrid_"+q,o="TblGrid_"+q,k="#"+a.jgrid.jqID(o),p={themodal:"editmod"+q,modalhead:"edithd"+q,modalcontent:"editcnt"+q,scrollelm:f},y=a.isFunction(b[d.p.id].beforeShowForm)?b[d.p.id].beforeShowForm:
 !1,A=a.isFunction(b[d.p.id].afterShowForm)?b[d.p.id].afterShowForm:!1,w=a.isFunction(b[d.p.id].beforeInitData)?b[d.p.id].beforeInitData:!1,B=a.isFunction(b[d.p.id].onInitializeForm)?b[d.p.id].onInitializeForm:!1,l=!0,z=1,F=0,j,K,v,f=a.jgrid.jqID(f);"new"===r?(r="_empty",v="add",c.caption=b[d.p.id].addCaption):(c.caption=b[d.p.id].editCaption,v="edit");!0===c.recreateForm&&void 0!==a("#"+a.jgrid.jqID(p.themodal))[0]&&a("#"+a.jgrid.jqID(p.themodal)).remove();var G=!0;c.checkOnUpdate&&c.jqModal&&!c.modal&&
 (G=!1);if(void 0!==a("#"+a.jgrid.jqID(p.themodal))[0]){l=a(d).triggerHandler("jqGridAddEditBeforeInitData",[a("#"+a.jgrid.jqID(f)),v]);void 0===l&&(l=!0);l&&w&&(l=w.call(d,a("#"+f),v));if(!1===l)return;g();a(".ui-jqdialog-title","#"+a.jgrid.jqID(p.modalhead)).html(c.caption);a("#FormError",k).hide();b[d.p.id].topinfo?(a(".topinfo",k).html(b[d.p.id].topinfo),a(".tinfo",k).show()):a(".tinfo",k).hide();b[d.p.id].bottominfo?(a(".bottominfo",k+"_2").html(b[d.p.id].bottominfo),a(".binfo",k+"_2").show()):
-a(".binfo",k+"_2").hide();t(r,d,f);"_empty"==r||!b[d.p.id].viewPagerButtons?a("#pData, #nData",k+"_2").hide():a("#pData, #nData",k+"_2").show();!0===b[d.p.id].processing&&(b[d.p.id].processing=!1,a("#sData",k+"_2").removeClass("ui-state-active"));!0===a("#"+f).data("disabled")&&(a(".confirm","#"+a.jgrid.jqID(p.themodal)).hide(),a("#"+f).data("disabled",!1));a(d).triggerHandler("jqGridAddEditBeforeShowForm",[a("#"+f),v]);y&&y.call(d,a("#"+f),v);a("#"+a.jgrid.jqID(p.themodal)).data("onClose",b[d.p.id].onClose);
+a(".binfo",k+"_2").hide();t(r,d,f);"_empty"===r||!b[d.p.id].viewPagerButtons?a("#pData, #nData",k+"_2").hide():a("#pData, #nData",k+"_2").show();!0===b[d.p.id].processing&&(b[d.p.id].processing=!1,a("#sData",k+"_2").removeClass("ui-state-active"));!0===a("#"+f).data("disabled")&&(a(".confirm","#"+a.jgrid.jqID(p.themodal)).hide(),a("#"+f).data("disabled",!1));a(d).triggerHandler("jqGridAddEditBeforeShowForm",[a("#"+f),v]);y&&y.call(d,a("#"+f),v);a("#"+a.jgrid.jqID(p.themodal)).data("onClose",b[d.p.id].onClose);
 a.jgrid.viewModal("#"+a.jgrid.jqID(p.themodal),{gbox:"#gbox_"+a.jgrid.jqID(q),jqm:c.jqModal,jqM:!1,overlay:c.overlay,modal:c.modal,overlayClass:c.overlayClass});G||a("."+a.jgrid.jqID(c.overlayClass)).click(function(){if(!h())return false;a.jgrid.hideModal("#"+a.jgrid.jqID(p.themodal),{gb:"#gbox_"+a.jgrid.jqID(q),jqm:c.jqModal,onClose:b[d.p.id].onClose});return false});a(d).triggerHandler("jqGridAddEditAfterShowForm",[a("#"+f),v]);A&&A.call(d,a("#"+f),v)}else{var E=isNaN(c.dataheight)?c.dataheight:
 c.dataheight+"px",l=isNaN(c.datawidth)?c.datawidth:c.datawidth+"px",E=a("<form name='FormPost' id='"+f+"' class='FormGrid' onSubmit='return false;' style='width:"+l+";overflow:auto;position:relative;height:"+E+";'></form>").data("disabled",!1),C=a("<table id='"+o+"' class='EditTable' cellspacing='0' cellpadding='0' border='0'><tbody></tbody></table>"),l=a(d).triggerHandler("jqGridAddEditBeforeInitData",[a("#"+f),v]);void 0===l&&(l=!0);l&&w&&(l=w.call(d,a("#"+f,v)));if(!1===l)return;g();a(d.p.colModel).each(function(){var a=
-this.formoptions;z=Math.max(z,a?a.colpos||0:0);F=Math.max(F,a?a.rowpos||0:0)});a(E).append(C);w=a("<tr id='FormError' style='display:none'><td class='ui-state-error' colspan='"+2*z+"'></td></tr>");w[0].rp=0;a(C).append(w);w=a("<tr style='display:none' class='tinfo'><td class='topinfo' colspan='"+2*z+"'>"+b[d.p.id].topinfo+"</td></tr>");w[0].rp=0;a(C).append(w);var l=(w="rtl"==d.p.direction?!0:!1)?"nData":"pData",D=w?"pData":"nData";i(r,d,C,z);var l="<a href='javascript:void(0)' id='"+l+"' class='fm-button ui-state-default ui-corner-left'><span class='ui-icon ui-icon-triangle-1-w'></span></a>",
+this.formoptions;z=Math.max(z,a?a.colpos||0:0);F=Math.max(F,a?a.rowpos||0:0)});a(E).append(C);w=a("<tr id='FormError' style='display:none'><td class='ui-state-error' colspan='"+2*z+"'></td></tr>");w[0].rp=0;a(C).append(w);w=a("<tr style='display:none' class='tinfo'><td class='topinfo' colspan='"+2*z+"'>"+b[d.p.id].topinfo+"</td></tr>");w[0].rp=0;a(C).append(w);var l=(w="rtl"===d.p.direction?!0:!1)?"nData":"pData",D=w?"pData":"nData";i(r,d,C,z);var l="<a href='javascript:void(0)' id='"+l+"' class='fm-button ui-state-default ui-corner-left'><span class='ui-icon ui-icon-triangle-1-w'></span></a>",
 D="<a href='javascript:void(0)' id='"+D+"' class='fm-button ui-state-default ui-corner-right'><span class='ui-icon ui-icon-triangle-1-e'></span></a>",H="<a href='javascript:void(0)' id='sData' class='fm-button ui-state-default ui-corner-all'>"+c.bSubmit+"</a>",I="<a href='javascript:void(0)' id='cData' class='fm-button ui-state-default ui-corner-all'>"+c.bCancel+"</a>",o="<table border='0' cellspacing='0' cellpadding='0' class='EditTable' id='"+o+"_2'><tbody><tr><td colspan='2'><hr class='ui-widget-content' style='margin:1px'/></td></tr><tr id='Act_Buttons'><td class='navButton'>"+
 (w?D+l:l+D)+"</td><td class='EditButton'>"+H+I+"</td></tr>"+("<tr style='display:none' class='binfo'><td class='bottominfo' colspan='2'>"+b[d.p.id].bottominfo+"</td></tr>"),o=o+"</tbody></table>";if(0<F){var J=[];a.each(a(C)[0].rows,function(a,c){J[a]=c});J.sort(function(a,c){return a.rp>c.rp?1:a.rp<c.rp?-1:0});a.each(J,function(c,b){a("tbody",C).append(b)})}c.gbox="#gbox_"+a.jgrid.jqID(q);var L=!1;!0===c.closeOnEscape&&(c.closeOnEscape=!1,L=!0);o=a("<div></div>").append(E).append(o);a.jgrid.createModal(p,
-o,c,"#gview_"+a.jgrid.jqID(d.p.id),a("#gbox_"+a.jgrid.jqID(d.p.id))[0]);w&&(a("#pData, #nData",k+"_2").css("float","right"),a(".EditButton",k+"_2").css("text-align","left"));b[d.p.id].topinfo&&a(".tinfo",k).show();b[d.p.id].bottominfo&&a(".binfo",k+"_2").show();o=o=null;a("#"+a.jgrid.jqID(p.themodal)).keydown(function(e){var l=e.target;if(a("#"+f).data("disabled")===true)return false;if(b[d.p.id].savekey[0]===true&&e.which==b[d.p.id].savekey[1]&&l.tagName!="TEXTAREA"){a("#sData",k+"_2").trigger("click");
-return false}if(e.which===27){if(!h())return false;L&&a.jgrid.hideModal("#"+a.jgrid.jqID(p.themodal),{gb:c.gbox,jqm:c.jqModal,onClose:b[d.p.id].onClose});return false}if(b[d.p.id].navkeys[0]===true){if(a("#id_g",k).val()=="_empty")return true;if(e.which==b[d.p.id].navkeys[1]){a("#pData",k+"_2").trigger("click");return false}if(e.which==b[d.p.id].navkeys[2]){a("#nData",k+"_2").trigger("click");return false}}});c.checkOnUpdate&&(a("a.ui-jqdialog-titlebar-close span","#"+a.jgrid.jqID(p.themodal)).removeClass("jqmClose"),
-a("a.ui-jqdialog-titlebar-close","#"+a.jgrid.jqID(p.themodal)).unbind("click").click(function(){if(!h())return false;a.jgrid.hideModal("#"+a.jgrid.jqID(p.themodal),{gb:"#gbox_"+a.jgrid.jqID(q),jqm:c.jqModal,onClose:b[d.p.id].onClose});return false}));c.saveicon=a.extend([!0,"left","ui-icon-disk"],c.saveicon);c.closeicon=a.extend([!0,"left","ui-icon-close"],c.closeicon);!0===c.saveicon[0]&&a("#sData",k+"_2").addClass("right"==c.saveicon[1]?"fm-button-icon-right":"fm-button-icon-left").append("<span class='ui-icon "+
-c.saveicon[2]+"'></span>");!0===c.closeicon[0]&&a("#cData",k+"_2").addClass("right"==c.closeicon[1]?"fm-button-icon-right":"fm-button-icon-left").append("<span class='ui-icon "+c.closeicon[2]+"'></span>");if(b[d.p.id].checkOnSubmit||b[d.p.id].checkOnUpdate)H="<a href='javascript:void(0)' id='sNew' class='fm-button ui-state-default ui-corner-all' style='z-index:1002'>"+c.bYes+"</a>",D="<a href='javascript:void(0)' id='nNew' class='fm-button ui-state-default ui-corner-all' style='z-index:1002'>"+c.bNo+
+o,c,"#gview_"+a.jgrid.jqID(d.p.id),a("#gbox_"+a.jgrid.jqID(d.p.id))[0]);w&&(a("#pData, #nData",k+"_2").css("float","right"),a(".EditButton",k+"_2").css("text-align","left"));b[d.p.id].topinfo&&a(".tinfo",k).show();b[d.p.id].bottominfo&&a(".binfo",k+"_2").show();o=o=null;a("#"+a.jgrid.jqID(p.themodal)).keydown(function(e){var l=e.target;if(a("#"+f).data("disabled")===true)return false;if(b[d.p.id].savekey[0]===true&&e.which===b[d.p.id].savekey[1]&&l.tagName!=="TEXTAREA"){a("#sData",k+"_2").trigger("click");
+return false}if(e.which===27){if(!h())return false;L&&a.jgrid.hideModal("#"+a.jgrid.jqID(p.themodal),{gb:c.gbox,jqm:c.jqModal,onClose:b[d.p.id].onClose});return false}if(b[d.p.id].navkeys[0]===true){if(a("#id_g",k).val()==="_empty")return true;if(e.which===b[d.p.id].navkeys[1]){a("#pData",k+"_2").trigger("click");return false}if(e.which===b[d.p.id].navkeys[2]){a("#nData",k+"_2").trigger("click");return false}}});c.checkOnUpdate&&(a("a.ui-jqdialog-titlebar-close span","#"+a.jgrid.jqID(p.themodal)).removeClass("jqmClose"),
+a("a.ui-jqdialog-titlebar-close","#"+a.jgrid.jqID(p.themodal)).unbind("click").click(function(){if(!h())return false;a.jgrid.hideModal("#"+a.jgrid.jqID(p.themodal),{gb:"#gbox_"+a.jgrid.jqID(q),jqm:c.jqModal,onClose:b[d.p.id].onClose});return false}));c.saveicon=a.extend([!0,"left","ui-icon-disk"],c.saveicon);c.closeicon=a.extend([!0,"left","ui-icon-close"],c.closeicon);!0===c.saveicon[0]&&a("#sData",k+"_2").addClass("right"===c.saveicon[1]?"fm-button-icon-right":"fm-button-icon-left").append("<span class='ui-icon "+
+c.saveicon[2]+"'></span>");!0===c.closeicon[0]&&a("#cData",k+"_2").addClass("right"===c.closeicon[1]?"fm-button-icon-right":"fm-button-icon-left").append("<span class='ui-icon "+c.closeicon[2]+"'></span>");if(b[d.p.id].checkOnSubmit||b[d.p.id].checkOnUpdate)H="<a href='javascript:void(0)' id='sNew' class='fm-button ui-state-default ui-corner-all' style='z-index:1002'>"+c.bYes+"</a>",D="<a href='javascript:void(0)' id='nNew' class='fm-button ui-state-default ui-corner-all' style='z-index:1002'>"+c.bNo+
 "</a>",I="<a href='javascript:void(0)' id='cNew' class='fm-button ui-state-default ui-corner-all' style='z-index:1002'>"+c.bExit+"</a>",o=c.zIndex||999,o++,a("<div class='"+c.overlayClass+" jqgrid-overlay confirm' style='z-index:"+o+";display:none;'>&#160;</div><div class='confirm ui-widget-content ui-jqconfirm' style='z-index:"+(o+1)+"'>"+c.saveData+"<br/><br/>"+H+D+I+"</div>").insertAfter("#"+f),a("#sNew","#"+a.jgrid.jqID(p.themodal)).click(function(){s();a("#"+f).data("disabled",false);a(".confirm",
 "#"+a.jgrid.jqID(p.themodal)).hide();return false}),a("#nNew","#"+a.jgrid.jqID(p.themodal)).click(function(){a(".confirm","#"+a.jgrid.jqID(p.themodal)).hide();a("#"+f).data("disabled",false);setTimeout(function(){a(":input:visible","#"+f)[0].focus()},0);return false}),a("#cNew","#"+a.jgrid.jqID(p.themodal)).click(function(){a(".confirm","#"+a.jgrid.jqID(p.themodal)).hide();a("#"+f).data("disabled",false);a.jgrid.hideModal("#"+a.jgrid.jqID(p.themodal),{gb:"#gbox_"+a.jgrid.jqID(q),jqm:c.jqModal,onClose:b[d.p.id].onClose});
-return false});a(d).triggerHandler("jqGridAddEditInitializeForm",[a("#"+f),v]);B&&B.call(d,a("#"+f),v);"_empty"==r||!b[d.p.id].viewPagerButtons?a("#pData,#nData",k+"_2").hide():a("#pData,#nData",k+"_2").show();a(d).triggerHandler("jqGridAddEditBeforeShowForm",[a("#"+f),v]);y&&y.call(d,a("#"+f),v);a("#"+a.jgrid.jqID(p.themodal)).data("onClose",b[d.p.id].onClose);a.jgrid.viewModal("#"+a.jgrid.jqID(p.themodal),{gbox:"#gbox_"+a.jgrid.jqID(q),jqm:c.jqModal,overlay:c.overlay,modal:c.modal,overlayClass:c.overlayClass});
+return false});a(d).triggerHandler("jqGridAddEditInitializeForm",[a("#"+f),v]);B&&B.call(d,a("#"+f),v);"_empty"===r||!b[d.p.id].viewPagerButtons?a("#pData,#nData",k+"_2").hide():a("#pData,#nData",k+"_2").show();a(d).triggerHandler("jqGridAddEditBeforeShowForm",[a("#"+f),v]);y&&y.call(d,a("#"+f),v);a("#"+a.jgrid.jqID(p.themodal)).data("onClose",b[d.p.id].onClose);a.jgrid.viewModal("#"+a.jgrid.jqID(p.themodal),{gbox:"#gbox_"+a.jgrid.jqID(q),jqm:c.jqModal,overlay:c.overlay,modal:c.modal,overlayClass:c.overlayClass});
 G||a("."+a.jgrid.jqID(c.overlayClass)).click(function(){if(!h())return false;a.jgrid.hideModal("#"+a.jgrid.jqID(p.themodal),{gb:"#gbox_"+a.jgrid.jqID(q),jqm:c.jqModal,onClose:b[d.p.id].onClose});return false});a(d).triggerHandler("jqGridAddEditAfterShowForm",[a("#"+f),v]);A&&A.call(d,a("#"+f),v);a(".fm-button","#"+a.jgrid.jqID(p.themodal)).hover(function(){a(this).addClass("ui-state-hover")},function(){a(this).removeClass("ui-state-hover")});a("#sData",k+"_2").click(function(){j={};a("#FormError",
-k).hide();e();if(j[d.p.id+"_id"]=="_empty")s();else if(c.checkOnSubmit===true)if(K=m(j,b[d.p.id]._savedData)){a("#"+f).data("disabled",true);a(".confirm","#"+a.jgrid.jqID(p.themodal)).show()}else s();else s();return false});a("#cData",k+"_2").click(function(){if(!h())return false;a.jgrid.hideModal("#"+a.jgrid.jqID(p.themodal),{gb:"#gbox_"+a.jgrid.jqID(q),jqm:c.jqModal,onClose:b[d.p.id].onClose});return false});a("#nData",k+"_2").click(function(){if(!h())return false;a("#FormError",k).hide();var b=
+k).hide();e();if(j[d.p.id+"_id"]==="_empty")s();else if(c.checkOnSubmit===true)if(K=m(j,b[d.p.id]._savedData)){a("#"+f).data("disabled",true);a(".confirm","#"+a.jgrid.jqID(p.themodal)).show()}else s();else s();return false});a("#cData",k+"_2").click(function(){if(!h())return false;a.jgrid.hideModal("#"+a.jgrid.jqID(p.themodal),{gb:"#gbox_"+a.jgrid.jqID(q),jqm:c.jqModal,onClose:b[d.p.id].onClose});return false});a("#nData",k+"_2").click(function(){if(!h())return false;a("#FormError",k).hide();var b=
 x();b[0]=parseInt(b[0],10);if(b[0]!==-1&&b[1][b[0]+1]){a(d).triggerHandler("jqGridAddEditClickPgButtons",["next",a("#"+f),b[1][b[0]]]);var e;if(a.isFunction(c.onclickPgButtons)){e=c.onclickPgButtons.call(d,"next",a("#"+f),b[1][b[0]]);if(e!==void 0&&e===false)return false}if(a("#"+a.jgrid.jqID(b[1][b[0]+1])).hasClass("ui-state-disabled"))return false;t(b[1][b[0]+1],d,f);a(d).jqGrid("setSelection",b[1][b[0]+1]);a(d).triggerHandler("jqGridAddEditAfterClickPgButtons",["next",a("#"+f),b[1][b[0]]]);a.isFunction(c.afterclickPgButtons)&&
 c.afterclickPgButtons.call(d,"next",a("#"+f),b[1][b[0]+1]);n(b[0]+1,b)}return false});a("#pData",k+"_2").click(function(){if(!h())return false;a("#FormError",k).hide();var b=x();if(b[0]!==-1&&b[1][b[0]-1]){a(d).triggerHandler("jqGridAddEditClickPgButtons",["prev",a("#"+f),b[1][b[0]]]);var e;if(a.isFunction(c.onclickPgButtons)){e=c.onclickPgButtons.call(d,"prev",a("#"+f),b[1][b[0]]);if(e!==void 0&&e===false)return false}if(a("#"+a.jgrid.jqID(b[1][b[0]-1])).hasClass("ui-state-disabled"))return false;
 t(b[1][b[0]-1],d,f);a(d).jqGrid("setSelection",b[1][b[0]-1]);a(d).triggerHandler("jqGridAddEditAfterClickPgButtons",["prev",a("#"+f),b[1][b[0]]]);a.isFunction(c.afterclickPgButtons)&&c.afterclickPgButtons.call(d,"prev",a("#"+f),b[1][b[0]-1]);n(b[0]-1,b)}return false})}y=x();n(y[0],y)}})},viewGridRow:function(r,c){c=a.extend(!0,{top:0,left:0,width:0,datawidth:"auto",height:"auto",dataheight:"auto",modal:!1,overlay:30,drag:!0,resize:!0,jqModal:!0,closeOnEscape:!1,labelswidth:"30%",closeicon:[],navkeys:[!1,
 38,40],onClose:null,beforeShowForm:null,beforeInitData:null,viewPagerButtons:!0,recreateForm:!1},a.jgrid.view,c||{});b[a(this)[0].p.id]=c;return this.each(function(){function e(){(!0===b[m.p.id].closeOnEscape||!0===b[m.p.id].navkeys[0])&&setTimeout(function(){a(".ui-jqdialog-titlebar-close","#"+a.jgrid.jqID(q.modalhead)).focus()},0)}function i(b,d,e,g){var f,h,i,k=0,p,m,n=[],r=!1,o,q="<td class='CaptionTD form-view-label ui-widget-content' width='"+c.labelswidth+"'>&#160;</td><td class='DataTD form-view-data ui-helper-reset ui-widget-content'>&#160;</td>",
-s="",t=["integer","number","currency"],w=0,u=0,y,x,A;for(o=1;o<=g;o++)s+=1==o?q:"<td class='CaptionTD form-view-label ui-widget-content'>&#160;</td><td class='DataTD form-view-data ui-widget-content'>&#160;</td>";a(d.p.colModel).each(function(){h=this.editrules&&!0===this.editrules.edithidden?!1:!0===this.hidden?!0:!1;!h&&"right"===this.align&&(this.formatter&&-1!==a.inArray(this.formatter,t)?w=Math.max(w,parseInt(this.width,10)):u=Math.max(u,parseInt(this.width,10)))});y=0!==w?w:0!==u?u:0;r=a(d).jqGrid("getInd",
-b);a(d.p.colModel).each(function(b){f=this.name;x=!1;m=(h=this.editrules&&!0===this.editrules.edithidden?!1:!0===this.hidden?!0:!1)?"style='display:none'":"";A="boolean"!==typeof this.viewable?!0:this.viewable;if("cb"!==f&&"subgrid"!==f&&"rn"!==f&&A){p=!1===r?"":f==d.p.ExpandColumn&&!0===d.p.treeGrid?a("td:eq("+b+")",d.rows[r]).text():a("td:eq("+b+")",d.rows[r]).html();x="right"===this.align&&0!==y?!0:!1;var c=a.extend({},{rowabove:!1,rowcontent:""},this.formoptions||{}),l=parseInt(c.rowpos,10)||
+s="",t=["integer","number","currency"],w=0,u=0,y,x,A;for(o=1;o<=g;o++)s+=1===o?q:"<td class='CaptionTD form-view-label ui-widget-content'>&#160;</td><td class='DataTD form-view-data ui-widget-content'>&#160;</td>";a(d.p.colModel).each(function(){h=this.editrules&&!0===this.editrules.edithidden?!1:!0===this.hidden?!0:!1;!h&&"right"===this.align&&(this.formatter&&-1!==a.inArray(this.formatter,t)?w=Math.max(w,parseInt(this.width,10)):u=Math.max(u,parseInt(this.width,10)))});y=0!==w?w:0!==u?u:0;r=a(d).jqGrid("getInd",
+b);a(d.p.colModel).each(function(b){f=this.name;x=!1;m=(h=this.editrules&&!0===this.editrules.edithidden?!1:!0===this.hidden?!0:!1)?"style='display:none'":"";A="boolean"!==typeof this.viewable?!0:this.viewable;if("cb"!==f&&"subgrid"!==f&&"rn"!==f&&A){p=!1===r?"":f===d.p.ExpandColumn&&!0===d.p.treeGrid?a("td:eq("+b+")",d.rows[r]).text():a("td:eq("+b+")",d.rows[r]).html();x="right"===this.align&&0!==y?!0:!1;var c=a.extend({},{rowabove:!1,rowcontent:""},this.formoptions||{}),l=parseInt(c.rowpos,10)||
 k+1,o=parseInt(2*(parseInt(c.colpos,10)||1),10);if(c.rowabove){var q=a("<tr><td class='contentinfo' colspan='"+2*g+"'>"+c.rowcontent+"</td></tr>");a(e).append(q);q[0].rp=l}i=a(e).find("tr[rowpos="+l+"]");0===i.length&&(i=a("<tr "+m+" rowpos='"+l+"'></tr>").addClass("FormData").attr("id","trv_"+f),a(i).append(s),a(e).append(i),i[0].rp=l);a("td:eq("+(o-2)+")",i[0]).html("<b>"+(void 0===c.label?d.p.colNames[b]:c.label)+"</b>");a("td:eq("+(o-1)+")",i[0]).append("<span>"+p+"</span>").attr("id","v_"+f);
 x&&a("td:eq("+(o-1)+") span",i[0]).css({"text-align":"right",width:y+"px"});n[k]=b;k++}});0<k&&(b=a("<tr class='FormData' style='display:none'><td class='CaptionTD'></td><td colspan='"+(2*g-1)+"' class='DataTD'><input class='FormElement' id='id_g' type='text' name='id' value='"+b+"'/></td></tr>"),b[0].rp=k+99,a(e).append(b));return n}function t(b,c){var d,e,g=0,f,h;if(h=a(c).jqGrid("getInd",b,!0))a("td",h).each(function(b){d=c.p.colModel[b].name;e=c.p.colModel[b].editrules&&!0===c.p.colModel[b].editrules.edithidden?
-!1:!0===c.p.colModel[b].hidden?!0:!1;"cb"!==d&&"subgrid"!==d&&"rn"!==d&&(f=d==c.p.ExpandColumn&&!0===c.p.treeGrid?a(this).text():a(this).html(),a.extend({},c.p.colModel[b].editoptions||{}),d=a.jgrid.jqID("v_"+d),a("#"+d+" span","#"+n).html(f),e&&a("#"+d,"#"+n).parents("tr:first").hide(),g++)}),0<g&&a("#id_g","#"+n).val(b)}function u(b,c){var d=c[1].length-1;0===b?a("#pData","#"+n+"_2").addClass("ui-state-disabled"):void 0!==c[1][b-1]&&a("#"+a.jgrid.jqID(c[1][b-1])).hasClass("ui-state-disabled")?a("#pData",
-n+"_2").addClass("ui-state-disabled"):a("#pData","#"+n+"_2").removeClass("ui-state-disabled");b==d?a("#nData","#"+n+"_2").addClass("ui-state-disabled"):void 0!==c[1][b+1]&&a("#"+a.jgrid.jqID(c[1][b+1])).hasClass("ui-state-disabled")?a("#nData",n+"_2").addClass("ui-state-disabled"):a("#nData","#"+n+"_2").removeClass("ui-state-disabled")}function s(){var b=a(m).jqGrid("getDataIDs"),c=a("#id_g","#"+n).val();return[a.inArray(c,b),b]}var m=this;if(m.grid&&r){var h=m.p.id,g="ViewGrid_"+a.jgrid.jqID(h),
-n="ViewTbl_"+a.jgrid.jqID(h),x="ViewGrid_"+h,d="ViewTbl_"+h,q={themodal:"viewmod"+h,modalhead:"viewhd"+h,modalcontent:"viewcnt"+h,scrollelm:g},f=a.isFunction(b[m.p.id].beforeInitData)?b[m.p.id].beforeInitData:!1,o=!0,k=1,p=0;!0===c.recreateForm&&void 0!==a("#"+a.jgrid.jqID(q.themodal))[0]&&a("#"+a.jgrid.jqID(q.themodal)).remove();if(void 0!==a("#"+a.jgrid.jqID(q.themodal))[0]){f&&(o=f.call(m,a("#"+g)),void 0===o&&(o=!0));if(!1===o)return;a(".ui-jqdialog-title","#"+a.jgrid.jqID(q.modalhead)).html(c.caption);
-a("#FormError","#"+n).hide();t(r,m);a.isFunction(b[m.p.id].beforeShowForm)&&b[m.p.id].beforeShowForm.call(m,a("#"+g));a.jgrid.viewModal("#"+a.jgrid.jqID(q.themodal),{gbox:"#gbox_"+a.jgrid.jqID(h),jqm:c.jqModal,jqM:!1,overlay:c.overlay,modal:c.modal});e()}else{var y=isNaN(c.dataheight)?c.dataheight:c.dataheight+"px",A=isNaN(c.datawidth)?c.datawidth:c.datawidth+"px",x=a("<form name='FormPost' id='"+x+"' class='FormGrid' style='width:"+A+";overflow:auto;position:relative;height:"+y+";'></form>"),w=a("<table id='"+
-d+"' class='EditTable' cellspacing='1' cellpadding='2' border='0' style='table-layout:fixed'><tbody></tbody></table>");f&&(o=f.call(m,a("#"+g)),void 0===o&&(o=!0));if(!1===o)return;a(m.p.colModel).each(function(){var a=this.formoptions;k=Math.max(k,a?a.colpos||0:0);p=Math.max(p,a?a.rowpos||0:0)});a(x).append(w);i(r,m,w,k);d="rtl"==m.p.direction?!0:!1;f="<a href='javascript:void(0)' id='"+(d?"nData":"pData")+"' class='fm-button ui-state-default ui-corner-left'><span class='ui-icon ui-icon-triangle-1-w'></span></a>";
-o="<a href='javascript:void(0)' id='"+(d?"pData":"nData")+"' class='fm-button ui-state-default ui-corner-right'><span class='ui-icon ui-icon-triangle-1-e'></span></a>";y="<a href='javascript:void(0)' id='cData' class='fm-button ui-state-default ui-corner-all'>"+c.bClose+"</a>";if(0<p){var B=[];a.each(a(w)[0].rows,function(a,b){B[a]=b});B.sort(function(a,b){return a.rp>b.rp?1:a.rp<b.rp?-1:0});a.each(B,function(b,c){a("tbody",w).append(c)})}c.gbox="#gbox_"+a.jgrid.jqID(h);x=a("<div></div>").append(x).append("<table border='0' class='EditTable' id='"+
-n+"_2'><tbody><tr id='Act_Buttons'><td class='navButton' width='"+c.labelswidth+"'>"+(d?o+f:f+o)+"</td><td class='EditButton'>"+y+"</td></tr></tbody></table>");a.jgrid.createModal(q,x,c,"#gview_"+a.jgrid.jqID(m.p.id),a("#gview_"+a.jgrid.jqID(m.p.id))[0]);d&&(a("#pData, #nData","#"+n+"_2").css("float","right"),a(".EditButton","#"+n+"_2").css("text-align","left"));c.viewPagerButtons||a("#pData, #nData","#"+n+"_2").hide();x=null;a("#"+q.themodal).keydown(function(d){if(d.which===27){b[m.p.id].closeOnEscape&&
-a.jgrid.hideModal("#"+a.jgrid.jqID(q.themodal),{gb:c.gbox,jqm:c.jqModal,onClose:c.onClose});return false}if(c.navkeys[0]===true){if(d.which===c.navkeys[1]){a("#pData","#"+n+"_2").trigger("click");return false}if(d.which===c.navkeys[2]){a("#nData","#"+n+"_2").trigger("click");return false}}});c.closeicon=a.extend([!0,"left","ui-icon-close"],c.closeicon);!0===c.closeicon[0]&&a("#cData","#"+n+"_2").addClass("right"==c.closeicon[1]?"fm-button-icon-right":"fm-button-icon-left").append("<span class='ui-icon "+
-c.closeicon[2]+"'></span>");a.isFunction(c.beforeShowForm)&&c.beforeShowForm.call(m,a("#"+g));a.jgrid.viewModal("#"+a.jgrid.jqID(q.themodal),{gbox:"#gbox_"+a.jgrid.jqID(h),jqm:c.jqModal,overlay:c.overlay,modal:c.modal});a(".fm-button:not(.ui-state-disabled)","#"+n+"_2").hover(function(){a(this).addClass("ui-state-hover")},function(){a(this).removeClass("ui-state-hover")});e();a("#cData","#"+n+"_2").click(function(){a.jgrid.hideModal("#"+a.jgrid.jqID(q.themodal),{gb:"#gbox_"+a.jgrid.jqID(h),jqm:c.jqModal,
-onClose:c.onClose});return false});a("#nData","#"+n+"_2").click(function(){a("#FormError","#"+n).hide();var b=s();b[0]=parseInt(b[0],10);if(b[0]!=-1&&b[1][b[0]+1]){a.isFunction(c.onclickPgButtons)&&c.onclickPgButtons.call(m,"next",a("#"+g),b[1][b[0]]);t(b[1][b[0]+1],m);a(m).jqGrid("setSelection",b[1][b[0]+1]);a.isFunction(c.afterclickPgButtons)&&c.afterclickPgButtons.call(m,"next",a("#"+g),b[1][b[0]+1]);u(b[0]+1,b)}e();return false});a("#pData","#"+n+"_2").click(function(){a("#FormError","#"+n).hide();
-var b=s();if(b[0]!=-1&&b[1][b[0]-1]){a.isFunction(c.onclickPgButtons)&&c.onclickPgButtons.call(m,"prev",a("#"+g),b[1][b[0]]);t(b[1][b[0]-1],m);a(m).jqGrid("setSelection",b[1][b[0]-1]);a.isFunction(c.afterclickPgButtons)&&c.afterclickPgButtons.call(m,"prev",a("#"+g),b[1][b[0]-1]);u(b[0]-1,b)}e();return false})}x=s();u(x[0],x)}})},delGridRow:function(r,c){c=a.extend(!0,{top:0,left:0,width:240,height:"auto",dataheight:"auto",modal:!1,overlay:30,drag:!0,resize:!0,url:"",mtype:"POST",reloadAfterSubmit:!0,
-beforeShowForm:null,beforeInitData:null,afterShowForm:null,beforeSubmit:null,onclickSubmit:null,afterSubmit:null,jqModal:!0,closeOnEscape:!1,delData:{},delicon:[],cancelicon:[],onClose:null,ajaxDelOptions:{},processing:!1,serializeDelData:null,useDataProxy:!1},a.jgrid.del,c||{});b[a(this)[0].p.id]=c;return this.each(function(){var e=this;if(e.grid&&r){var i=a.isFunction(b[e.p.id].beforeShowForm),t=a.isFunction(b[e.p.id].afterShowForm),u=a.isFunction(b[e.p.id].beforeInitData)?b[e.p.id].beforeInitData:
-!1,s=e.p.id,m={},h=!0,g="DelTbl_"+a.jgrid.jqID(s),n,x,d,q,f="DelTbl_"+s,o={themodal:"delmod"+s,modalhead:"delhd"+s,modalcontent:"delcnt"+s,scrollelm:g};a.isArray(r)&&(r=r.join());if(void 0!==a("#"+a.jgrid.jqID(o.themodal))[0]){u&&(h=u.call(e,a("#"+g)),void 0===h&&(h=!0));if(!1===h)return;a("#DelData>td","#"+g).text(r);a("#DelError","#"+g).hide();!0===b[e.p.id].processing&&(b[e.p.id].processing=!1,a("#dData","#"+g).removeClass("ui-state-active"));i&&b[e.p.id].beforeShowForm.call(e,a("#"+g));a.jgrid.viewModal("#"+
-a.jgrid.jqID(o.themodal),{gbox:"#gbox_"+a.jgrid.jqID(s),jqm:b[e.p.id].jqModal,jqM:!1,overlay:b[e.p.id].overlay,modal:b[e.p.id].modal})}else{var k=isNaN(b[e.p.id].dataheight)?b[e.p.id].dataheight:b[e.p.id].dataheight+"px",p=isNaN(c.datawidth)?c.datawidth:c.datawidth+"px",f="<div id='"+f+"' class='formdata' style='width:"+p+";overflow:auto;position:relative;height:"+k+";'><table class='DelTable'><tbody><tr id='DelError' style='display:none'><td class='ui-state-error'></td></tr>"+("<tr id='DelData' style='display:none'><td >"+
-r+"</td></tr>"),f=f+('<tr><td class="delmsg" style="white-space:pre;">'+b[e.p.id].msg+"</td></tr><tr><td >&#160;</td></tr>"),f=f+"</tbody></table></div>"+("<table cellspacing='0' cellpadding='0' border='0' class='EditTable' id='"+g+"_2'><tbody><tr><td><hr class='ui-widget-content' style='margin:1px'/></td></tr><tr><td class='DelButton EditButton'>"+("<a href='javascript:void(0)' id='dData' class='fm-button ui-state-default ui-corner-all'>"+c.bSubmit+"</a>")+"&#160;"+("<a href='javascript:void(0)' id='eData' class='fm-button ui-state-default ui-corner-all'>"+
-c.bCancel+"</a>")+"</td></tr></tbody></table>");c.gbox="#gbox_"+a.jgrid.jqID(s);a.jgrid.createModal(o,f,c,"#gview_"+a.jgrid.jqID(e.p.id),a("#gview_"+a.jgrid.jqID(e.p.id))[0]);u&&(h=u.call(e,a("#"+g)),void 0===h&&(h=!0));if(!1===h)return;a(".fm-button","#"+g+"_2").hover(function(){a(this).addClass("ui-state-hover")},function(){a(this).removeClass("ui-state-hover")});c.delicon=a.extend([!0,"left","ui-icon-scissors"],b[e.p.id].delicon);c.cancelicon=a.extend([!0,"left","ui-icon-cancel"],b[e.p.id].cancelicon);
-!0===c.delicon[0]&&a("#dData","#"+g+"_2").addClass("right"==c.delicon[1]?"fm-button-icon-right":"fm-button-icon-left").append("<span class='ui-icon "+c.delicon[2]+"'></span>");!0===c.cancelicon[0]&&a("#eData","#"+g+"_2").addClass("right"==c.cancelicon[1]?"fm-button-icon-right":"fm-button-icon-left").append("<span class='ui-icon "+c.cancelicon[2]+"'></span>");a("#dData","#"+g+"_2").click(function(){var f=[true,""],h,i=a("#DelData>td","#"+g).text();m={};a.isFunction(b[e.p.id].onclickSubmit)&&(m=b[e.p.id].onclickSubmit.call(e,
-b[e.p.id],i)||{});a.isFunction(b[e.p.id].beforeSubmit)&&(f=b[e.p.id].beforeSubmit.call(e,i));if(f[0]&&!b[e.p.id].processing){b[e.p.id].processing=true;d=e.p.prmNames;n=a.extend({},b[e.p.id].delData,m);q=d.oper;n[q]=d.deloper;x=d.id;i=(""+i).split(",");if(!i.length)return false;for(h in i)i.hasOwnProperty(h)&&(i[h]=a.jgrid.stripPref(e.p.idPrefix,i[h]));n[x]=i.join();a(this).addClass("ui-state-active");h=a.extend({url:b[e.p.id].url||a(e).jqGrid("getGridParam","editurl"),type:b[e.p.id].mtype,data:a.isFunction(b[e.p.id].serializeDelData)?
-b[e.p.id].serializeDelData.call(e,n):n,complete:function(d,h){var k;if(d.status>=300&&d.status!==304){f[0]=false;f[1]=a.isFunction(b[e.p.id].errorTextFormat)?b[e.p.id].errorTextFormat.call(e,d):h+" Status: '"+d.statusText+"'. Error code: "+d.status}else a.isFunction(b[e.p.id].afterSubmit)&&(f=b[e.p.id].afterSubmit.call(e,d,n));if(f[0]===false){a("#DelError>td","#"+g).html(f[1]);a("#DelError","#"+g).show()}else{if(b[e.p.id].reloadAfterSubmit&&e.p.datatype!="local")a(e).trigger("reloadGrid");else{if(e.p.treeGrid===
-true)try{a(e).jqGrid("delTreeNode",e.p.idPrefix+i[0])}catch(p){}else for(k=0;k<i.length;k++)a(e).jqGrid("delRowData",e.p.idPrefix+i[k]);e.p.selrow=null;e.p.selarrrow=[]}a.isFunction(b[e.p.id].afterComplete)&&setTimeout(function(){b[e.p.id].afterComplete.call(e,d,i)},500)}b[e.p.id].processing=false;a("#dData","#"+g+"_2").removeClass("ui-state-active");f[0]&&a.jgrid.hideModal("#"+a.jgrid.jqID(o.themodal),{gb:"#gbox_"+a.jgrid.jqID(s),jqm:c.jqModal,onClose:b[e.p.id].onClose})}},a.jgrid.ajaxOptions,b[e.p.id].ajaxDelOptions);
-if(!h.url&&!b[e.p.id].useDataProxy)if(a.isFunction(e.p.dataProxy))b[e.p.id].useDataProxy=true;else{f[0]=false;f[1]=f[1]+(" "+a.jgrid.errors.nourl)}if(f[0])if(b[e.p.id].useDataProxy){h=e.p.dataProxy.call(e,h,"del_"+e.p.id);h===void 0&&(h=[true,""]);if(h[0]===false){f[0]=false;f[1]=h[1]||"Error deleting the selected row!"}else a.jgrid.hideModal("#"+a.jgrid.jqID(o.themodal),{gb:"#gbox_"+a.jgrid.jqID(s),jqm:c.jqModal,onClose:b[e.p.id].onClose})}else a.ajax(h)}if(f[0]===false){a("#DelError>td","#"+g).html(f[1]);
+!1:!0===c.p.colModel[b].hidden?!0:!1;"cb"!==d&&"subgrid"!==d&&"rn"!==d&&(f=d===c.p.ExpandColumn&&!0===c.p.treeGrid?a(this).text():a(this).html(),d=a.jgrid.jqID("v_"+d),a("#"+d+" span","#"+n).html(f),e&&a("#"+d,"#"+n).parents("tr:first").hide(),g++)}),0<g&&a("#id_g","#"+n).val(b)}function u(b,c){var d=c[1].length-1;0===b?a("#pData","#"+n+"_2").addClass("ui-state-disabled"):void 0!==c[1][b-1]&&a("#"+a.jgrid.jqID(c[1][b-1])).hasClass("ui-state-disabled")?a("#pData",n+"_2").addClass("ui-state-disabled"):
+a("#pData","#"+n+"_2").removeClass("ui-state-disabled");b===d?a("#nData","#"+n+"_2").addClass("ui-state-disabled"):void 0!==c[1][b+1]&&a("#"+a.jgrid.jqID(c[1][b+1])).hasClass("ui-state-disabled")?a("#nData",n+"_2").addClass("ui-state-disabled"):a("#nData","#"+n+"_2").removeClass("ui-state-disabled")}function s(){var b=a(m).jqGrid("getDataIDs"),c=a("#id_g","#"+n).val();return[a.inArray(c,b),b]}var m=this;if(m.grid&&r){var h=m.p.id,g="ViewGrid_"+a.jgrid.jqID(h),n="ViewTbl_"+a.jgrid.jqID(h),x="ViewGrid_"+
+h,d="ViewTbl_"+h,q={themodal:"viewmod"+h,modalhead:"viewhd"+h,modalcontent:"viewcnt"+h,scrollelm:g},f=a.isFunction(b[m.p.id].beforeInitData)?b[m.p.id].beforeInitData:!1,o=!0,k=1,p=0;!0===c.recreateForm&&void 0!==a("#"+a.jgrid.jqID(q.themodal))[0]&&a("#"+a.jgrid.jqID(q.themodal)).remove();if(void 0!==a("#"+a.jgrid.jqID(q.themodal))[0]){f&&(o=f.call(m,a("#"+g)),void 0===o&&(o=!0));if(!1===o)return;a(".ui-jqdialog-title","#"+a.jgrid.jqID(q.modalhead)).html(c.caption);a("#FormError","#"+n).hide();t(r,
+m);a.isFunction(b[m.p.id].beforeShowForm)&&b[m.p.id].beforeShowForm.call(m,a("#"+g));a.jgrid.viewModal("#"+a.jgrid.jqID(q.themodal),{gbox:"#gbox_"+a.jgrid.jqID(h),jqm:c.jqModal,jqM:!1,overlay:c.overlay,modal:c.modal});e()}else{var y=isNaN(c.dataheight)?c.dataheight:c.dataheight+"px",A=isNaN(c.datawidth)?c.datawidth:c.datawidth+"px",x=a("<form name='FormPost' id='"+x+"' class='FormGrid' style='width:"+A+";overflow:auto;position:relative;height:"+y+";'></form>"),w=a("<table id='"+d+"' class='EditTable' cellspacing='1' cellpadding='2' border='0' style='table-layout:fixed'><tbody></tbody></table>");
+f&&(o=f.call(m,a("#"+g)),void 0===o&&(o=!0));if(!1===o)return;a(m.p.colModel).each(function(){var a=this.formoptions;k=Math.max(k,a?a.colpos||0:0);p=Math.max(p,a?a.rowpos||0:0)});a(x).append(w);i(r,m,w,k);d="rtl"===m.p.direction?!0:!1;f="<a href='javascript:void(0)' id='"+(d?"nData":"pData")+"' class='fm-button ui-state-default ui-corner-left'><span class='ui-icon ui-icon-triangle-1-w'></span></a>";o="<a href='javascript:void(0)' id='"+(d?"pData":"nData")+"' class='fm-button ui-state-default ui-corner-right'><span class='ui-icon ui-icon-triangle-1-e'></span></a>";
+y="<a href='javascript:void(0)' id='cData' class='fm-button ui-state-default ui-corner-all'>"+c.bClose+"</a>";if(0<p){var B=[];a.each(a(w)[0].rows,function(a,b){B[a]=b});B.sort(function(a,b){return a.rp>b.rp?1:a.rp<b.rp?-1:0});a.each(B,function(b,c){a("tbody",w).append(c)})}c.gbox="#gbox_"+a.jgrid.jqID(h);x=a("<div></div>").append(x).append("<table border='0' class='EditTable' id='"+n+"_2'><tbody><tr id='Act_Buttons'><td class='navButton' width='"+c.labelswidth+"'>"+(d?o+f:f+o)+"</td><td class='EditButton'>"+
+y+"</td></tr></tbody></table>");a.jgrid.createModal(q,x,c,"#gview_"+a.jgrid.jqID(m.p.id),a("#gview_"+a.jgrid.jqID(m.p.id))[0]);d&&(a("#pData, #nData","#"+n+"_2").css("float","right"),a(".EditButton","#"+n+"_2").css("text-align","left"));c.viewPagerButtons||a("#pData, #nData","#"+n+"_2").hide();x=null;a("#"+q.themodal).keydown(function(d){if(d.which===27){b[m.p.id].closeOnEscape&&a.jgrid.hideModal("#"+a.jgrid.jqID(q.themodal),{gb:c.gbox,jqm:c.jqModal,onClose:c.onClose});return false}if(c.navkeys[0]===
+true){if(d.which===c.navkeys[1]){a("#pData","#"+n+"_2").trigger("click");return false}if(d.which===c.navkeys[2]){a("#nData","#"+n+"_2").trigger("click");return false}}});c.closeicon=a.extend([!0,"left","ui-icon-close"],c.closeicon);!0===c.closeicon[0]&&a("#cData","#"+n+"_2").addClass("right"===c.closeicon[1]?"fm-button-icon-right":"fm-button-icon-left").append("<span class='ui-icon "+c.closeicon[2]+"'></span>");a.isFunction(c.beforeShowForm)&&c.beforeShowForm.call(m,a("#"+g));a.jgrid.viewModal("#"+
+a.jgrid.jqID(q.themodal),{gbox:"#gbox_"+a.jgrid.jqID(h),jqm:c.jqModal,overlay:c.overlay,modal:c.modal});a(".fm-button:not(.ui-state-disabled)","#"+n+"_2").hover(function(){a(this).addClass("ui-state-hover")},function(){a(this).removeClass("ui-state-hover")});e();a("#cData","#"+n+"_2").click(function(){a.jgrid.hideModal("#"+a.jgrid.jqID(q.themodal),{gb:"#gbox_"+a.jgrid.jqID(h),jqm:c.jqModal,onClose:c.onClose});return false});a("#nData","#"+n+"_2").click(function(){a("#FormError","#"+n).hide();var b=
+s();b[0]=parseInt(b[0],10);if(b[0]!==-1&&b[1][b[0]+1]){a.isFunction(c.onclickPgButtons)&&c.onclickPgButtons.call(m,"next",a("#"+g),b[1][b[0]]);t(b[1][b[0]+1],m);a(m).jqGrid("setSelection",b[1][b[0]+1]);a.isFunction(c.afterclickPgButtons)&&c.afterclickPgButtons.call(m,"next",a("#"+g),b[1][b[0]+1]);u(b[0]+1,b)}e();return false});a("#pData","#"+n+"_2").click(function(){a("#FormError","#"+n).hide();var b=s();if(b[0]!==-1&&b[1][b[0]-1]){a.isFunction(c.onclickPgButtons)&&c.onclickPgButtons.call(m,"prev",
+a("#"+g),b[1][b[0]]);t(b[1][b[0]-1],m);a(m).jqGrid("setSelection",b[1][b[0]-1]);a.isFunction(c.afterclickPgButtons)&&c.afterclickPgButtons.call(m,"prev",a("#"+g),b[1][b[0]-1]);u(b[0]-1,b)}e();return false})}x=s();u(x[0],x)}})},delGridRow:function(r,c){c=a.extend(!0,{top:0,left:0,width:240,height:"auto",dataheight:"auto",modal:!1,overlay:30,drag:!0,resize:!0,url:"",mtype:"POST",reloadAfterSubmit:!0,beforeShowForm:null,beforeInitData:null,afterShowForm:null,beforeSubmit:null,onclickSubmit:null,afterSubmit:null,
+jqModal:!0,closeOnEscape:!1,delData:{},delicon:[],cancelicon:[],onClose:null,ajaxDelOptions:{},processing:!1,serializeDelData:null,useDataProxy:!1},a.jgrid.del,c||{});b[a(this)[0].p.id]=c;return this.each(function(){var e=this;if(e.grid&&r){var i=a.isFunction(b[e.p.id].beforeShowForm),t=a.isFunction(b[e.p.id].afterShowForm),u=a.isFunction(b[e.p.id].beforeInitData)?b[e.p.id].beforeInitData:!1,s=e.p.id,m={},h=!0,g="DelTbl_"+a.jgrid.jqID(s),n,x,d,q,f="DelTbl_"+s,o={themodal:"delmod"+s,modalhead:"delhd"+
+s,modalcontent:"delcnt"+s,scrollelm:g};a.isArray(r)&&(r=r.join());if(void 0!==a("#"+a.jgrid.jqID(o.themodal))[0]){u&&(h=u.call(e,a("#"+g)),void 0===h&&(h=!0));if(!1===h)return;a("#DelData>td","#"+g).text(r);a("#DelError","#"+g).hide();!0===b[e.p.id].processing&&(b[e.p.id].processing=!1,a("#dData","#"+g).removeClass("ui-state-active"));i&&b[e.p.id].beforeShowForm.call(e,a("#"+g));a.jgrid.viewModal("#"+a.jgrid.jqID(o.themodal),{gbox:"#gbox_"+a.jgrid.jqID(s),jqm:b[e.p.id].jqModal,jqM:!1,overlay:b[e.p.id].overlay,
+modal:b[e.p.id].modal})}else{var k=isNaN(b[e.p.id].dataheight)?b[e.p.id].dataheight:b[e.p.id].dataheight+"px",p=isNaN(c.datawidth)?c.datawidth:c.datawidth+"px",f="<div id='"+f+"' class='formdata' style='width:"+p+";overflow:auto;position:relative;height:"+k+";'><table class='DelTable'><tbody><tr id='DelError' style='display:none'><td class='ui-state-error'></td></tr>"+("<tr id='DelData' style='display:none'><td >"+r+"</td></tr>"),f=f+('<tr><td class="delmsg" style="white-space:pre;">'+b[e.p.id].msg+
+"</td></tr><tr><td >&#160;</td></tr>"),f=f+"</tbody></table></div>"+("<table cellspacing='0' cellpadding='0' border='0' class='EditTable' id='"+g+"_2'><tbody><tr><td><hr class='ui-widget-content' style='margin:1px'/></td></tr><tr><td class='DelButton EditButton'>"+("<a href='javascript:void(0)' id='dData' class='fm-button ui-state-default ui-corner-all'>"+c.bSubmit+"</a>")+"&#160;"+("<a href='javascript:void(0)' id='eData' class='fm-button ui-state-default ui-corner-all'>"+c.bCancel+"</a>")+"</td></tr></tbody></table>");
+c.gbox="#gbox_"+a.jgrid.jqID(s);a.jgrid.createModal(o,f,c,"#gview_"+a.jgrid.jqID(e.p.id),a("#gview_"+a.jgrid.jqID(e.p.id))[0]);u&&(h=u.call(e,a("#"+g)),void 0===h&&(h=!0));if(!1===h)return;a(".fm-button","#"+g+"_2").hover(function(){a(this).addClass("ui-state-hover")},function(){a(this).removeClass("ui-state-hover")});c.delicon=a.extend([!0,"left","ui-icon-scissors"],b[e.p.id].delicon);c.cancelicon=a.extend([!0,"left","ui-icon-cancel"],b[e.p.id].cancelicon);!0===c.delicon[0]&&a("#dData","#"+g+"_2").addClass("right"===
+c.delicon[1]?"fm-button-icon-right":"fm-button-icon-left").append("<span class='ui-icon "+c.delicon[2]+"'></span>");!0===c.cancelicon[0]&&a("#eData","#"+g+"_2").addClass("right"===c.cancelicon[1]?"fm-button-icon-right":"fm-button-icon-left").append("<span class='ui-icon "+c.cancelicon[2]+"'></span>");a("#dData","#"+g+"_2").click(function(){var f=[true,""],h,i=a("#DelData>td","#"+g).text();m={};a.isFunction(b[e.p.id].onclickSubmit)&&(m=b[e.p.id].onclickSubmit.call(e,b[e.p.id],i)||{});a.isFunction(b[e.p.id].beforeSubmit)&&
+(f=b[e.p.id].beforeSubmit.call(e,i));if(f[0]&&!b[e.p.id].processing){b[e.p.id].processing=true;d=e.p.prmNames;n=a.extend({},b[e.p.id].delData,m);q=d.oper;n[q]=d.deloper;x=d.id;i=(""+i).split(",");if(!i.length)return false;for(h in i)i.hasOwnProperty(h)&&(i[h]=a.jgrid.stripPref(e.p.idPrefix,i[h]));n[x]=i.join();a(this).addClass("ui-state-active");h=a.extend({url:b[e.p.id].url||a(e).jqGrid("getGridParam","editurl"),type:b[e.p.id].mtype,data:a.isFunction(b[e.p.id].serializeDelData)?b[e.p.id].serializeDelData.call(e,
+n):n,complete:function(d,h){var k;if(d.status>=300&&d.status!==304){f[0]=false;f[1]=a.isFunction(b[e.p.id].errorTextFormat)?b[e.p.id].errorTextFormat.call(e,d):h+" Status: '"+d.statusText+"'. Error code: "+d.status}else a.isFunction(b[e.p.id].afterSubmit)&&(f=b[e.p.id].afterSubmit.call(e,d,n));if(f[0]===false){a("#DelError>td","#"+g).html(f[1]);a("#DelError","#"+g).show()}else{if(b[e.p.id].reloadAfterSubmit&&e.p.datatype!=="local")a(e).trigger("reloadGrid");else{if(e.p.treeGrid===true)try{a(e).jqGrid("delTreeNode",
+e.p.idPrefix+i[0])}catch(p){}else for(k=0;k<i.length;k++)a(e).jqGrid("delRowData",e.p.idPrefix+i[k]);e.p.selrow=null;e.p.selarrrow=[]}a.isFunction(b[e.p.id].afterComplete)&&setTimeout(function(){b[e.p.id].afterComplete.call(e,d,i)},500)}b[e.p.id].processing=false;a("#dData","#"+g+"_2").removeClass("ui-state-active");f[0]&&a.jgrid.hideModal("#"+a.jgrid.jqID(o.themodal),{gb:"#gbox_"+a.jgrid.jqID(s),jqm:c.jqModal,onClose:b[e.p.id].onClose})}},a.jgrid.ajaxOptions,b[e.p.id].ajaxDelOptions);if(!h.url&&
+!b[e.p.id].useDataProxy)if(a.isFunction(e.p.dataProxy))b[e.p.id].useDataProxy=true;else{f[0]=false;f[1]=f[1]+(" "+a.jgrid.errors.nourl)}if(f[0])if(b[e.p.id].useDataProxy){h=e.p.dataProxy.call(e,h,"del_"+e.p.id);h===void 0&&(h=[true,""]);if(h[0]===false){f[0]=false;f[1]=h[1]||"Error deleting the selected row!"}else a.jgrid.hideModal("#"+a.jgrid.jqID(o.themodal),{gb:"#gbox_"+a.jgrid.jqID(s),jqm:c.jqModal,onClose:b[e.p.id].onClose})}else a.ajax(h)}if(f[0]===false){a("#DelError>td","#"+g).html(f[1]);
 a("#DelError","#"+g).show()}return false});a("#eData","#"+g+"_2").click(function(){a.jgrid.hideModal("#"+a.jgrid.jqID(o.themodal),{gb:"#gbox_"+a.jgrid.jqID(s),jqm:b[e.p.id].jqModal,onClose:b[e.p.id].onClose});return false});i&&b[e.p.id].beforeShowForm.call(e,a("#"+g));a.jgrid.viewModal("#"+a.jgrid.jqID(o.themodal),{gbox:"#gbox_"+a.jgrid.jqID(s),jqm:b[e.p.id].jqModal,overlay:b[e.p.id].overlay,modal:b[e.p.id].modal})}t&&b[e.p.id].afterShowForm.call(e,a("#"+g));!0===b[e.p.id].closeOnEscape&&setTimeout(function(){a(".ui-jqdialog-titlebar-close",
 "#"+a.jgrid.jqID(o.modalhead)).focus()},0)}})},navGrid:function(b,c,e,i,t,u,s){c=a.extend({edit:!0,editicon:"ui-icon-pencil",add:!0,addicon:"ui-icon-plus",del:!0,delicon:"ui-icon-trash",search:!0,searchicon:"ui-icon-search",refresh:!0,refreshicon:"ui-icon-refresh",refreshstate:"firstpage",view:!1,viewicon:"ui-icon-document",position:"left",closeOnEscape:!0,beforeRefresh:null,afterRefresh:null,cloneToTop:!1,alertwidth:200,alertheight:"auto",alerttop:null,alertleft:null,alertzIndex:null},a.jgrid.nav,
 c||{});return this.each(function(){if(!this.nav){var m={themodal:"alertmod_"+this.p.id,modalhead:"alerthd_"+this.p.id,modalcontent:"alertcnt_"+this.p.id},h=this,g;if(h.grid&&"string"===typeof b){void 0===a("#"+m.themodal)[0]&&(!c.alerttop&&!c.alertleft&&(void 0!==window.innerWidth?(c.alertleft=window.innerWidth,c.alerttop=window.innerHeight):void 0!==document.documentElement&&void 0!==document.documentElement.clientWidth&&0!==document.documentElement.clientWidth?(c.alertleft=document.documentElement.clientWidth,
 c.alerttop=document.documentElement.clientHeight):(c.alertleft=1024,c.alerttop=768),c.alertleft=c.alertleft/2-parseInt(c.alertwidth,10)/2,c.alerttop=c.alerttop/2-25),a.jgrid.createModal(m,"<div>"+c.alerttext+"</div><span tabindex='0'><span tabindex='-1' id='jqg_alrt'></span></span>",{gbox:"#gbox_"+a.jgrid.jqID(h.p.id),jqModal:!0,drag:!0,resize:!0,caption:c.alertcap,top:c.alerttop,left:c.alertleft,width:c.alertwidth,height:c.alertheight,closeOnEscape:c.closeOnEscape,zIndex:c.alertzIndex},"#gview_"+
-a.jgrid.jqID(h.p.id),a("#gbox_"+a.jgrid.jqID(h.p.id))[0],!0));var n=1,x,d=function(){a(this).hasClass("ui-state-disabled")||a(this).addClass("ui-state-hover")},q=function(){a(this).removeClass("ui-state-hover")};c.cloneToTop&&h.p.toppager&&(n=2);for(x=0;x<n;x++){var f=a("<table cellspacing='0' cellpadding='0' border='0' class='ui-pg-table navtable' style='float:left;table-layout:auto;'><tbody><tr></tr></tbody></table>"),o,k;0===x?(o=b,k=h.p.id,o==h.p.toppager&&(k+="_top",n=1)):(o=h.p.toppager,k=h.p.id+
-"_top");"rtl"==h.p.direction&&a(f).attr("dir","rtl").css("float","right");c.add&&(i=i||{},g=a("<td class='ui-pg-button ui-corner-all'></td>"),a(g).append("<div class='ui-pg-div'><span class='ui-icon "+c.addicon+"'></span>"+c.addtext+"</div>"),a("tr",f).append(g),a(g,f).attr({title:c.addtitle||"",id:i.id||"add_"+k}).click(function(){a(this).hasClass("ui-state-disabled")||(a.isFunction(c.addfunc)?c.addfunc.call(h):a(h).jqGrid("editGridRow","new",i));return false}).hover(d,q),g=null);c.edit&&(g=a("<td class='ui-pg-button ui-corner-all'></td>"),
-e=e||{},a(g).append("<div class='ui-pg-div'><span class='ui-icon "+c.editicon+"'></span>"+c.edittext+"</div>"),a("tr",f).append(g),a(g,f).attr({title:c.edittitle||"",id:e.id||"edit_"+k}).click(function(){if(!a(this).hasClass("ui-state-disabled")){var b=h.p.selrow;if(b)a.isFunction(c.editfunc)?c.editfunc.call(h,b):a(h).jqGrid("editGridRow",b,e);else{a.jgrid.viewModal("#"+m.themodal,{gbox:"#gbox_"+a.jgrid.jqID(h.p.id),jqm:true});a("#jqg_alrt").focus()}}return false}).hover(d,q),g=null);c.view&&(g=a("<td class='ui-pg-button ui-corner-all'></td>"),
-s=s||{},a(g).append("<div class='ui-pg-div'><span class='ui-icon "+c.viewicon+"'></span>"+c.viewtext+"</div>"),a("tr",f).append(g),a(g,f).attr({title:c.viewtitle||"",id:s.id||"view_"+k}).click(function(){if(!a(this).hasClass("ui-state-disabled")){var b=h.p.selrow;if(b)a.isFunction(c.viewfunc)?c.viewfunc.call(h,b):a(h).jqGrid("viewGridRow",b,s);else{a.jgrid.viewModal("#"+m.themodal,{gbox:"#gbox_"+a.jgrid.jqID(h.p.id),jqm:true});a("#jqg_alrt").focus()}}return false}).hover(d,q),g=null);c.del&&(g=a("<td class='ui-pg-button ui-corner-all'></td>"),
-t=t||{},a(g).append("<div class='ui-pg-div'><span class='ui-icon "+c.delicon+"'></span>"+c.deltext+"</div>"),a("tr",f).append(g),a(g,f).attr({title:c.deltitle||"",id:t.id||"del_"+k}).click(function(){if(!a(this).hasClass("ui-state-disabled")){var b;if(h.p.multiselect){b=h.p.selarrrow;b.length===0&&(b=null)}else b=h.p.selrow;if(b)a.isFunction(c.delfunc)?c.delfunc.call(h,b):a(h).jqGrid("delGridRow",b,t);else{a.jgrid.viewModal("#"+m.themodal,{gbox:"#gbox_"+a.jgrid.jqID(h.p.id),jqm:true});a("#jqg_alrt").focus()}}return false}).hover(d,
-q),g=null);(c.add||c.edit||c.del||c.view)&&a("tr",f).append("<td class='ui-pg-button ui-state-disabled' style='width:4px;'><span class='ui-separator'></span></td>");c.search&&(g=a("<td class='ui-pg-button ui-corner-all'></td>"),u=u||{},a(g).append("<div class='ui-pg-div'><span class='ui-icon "+c.searchicon+"'></span>"+c.searchtext+"</div>"),a("tr",f).append(g),a(g,f).attr({title:c.searchtitle||"",id:u.id||"search_"+k}).click(function(){a(this).hasClass("ui-state-disabled")||(a.isFunction(c.searchfunc)?
-c.searchfunc.call(h,u):a(h).jqGrid("searchGrid",u));return false}).hover(d,q),u.showOnLoad&&!0===u.showOnLoad&&a(g,f).click(),g=null);c.refresh&&(g=a("<td class='ui-pg-button ui-corner-all'></td>"),a(g).append("<div class='ui-pg-div'><span class='ui-icon "+c.refreshicon+"'></span>"+c.refreshtext+"</div>"),a("tr",f).append(g),a(g,f).attr({title:c.refreshtitle||"",id:"refresh_"+k}).click(function(){if(!a(this).hasClass("ui-state-disabled")){a.isFunction(c.beforeRefresh)&&c.beforeRefresh.call(h);h.p.search=
-false;try{var b=h.p.id;h.p.postData.filters="";try{a("#fbox_"+a.jgrid.jqID(b)).jqFilter("resetFilter")}catch(d){}a.isFunction(h.clearToolbar)&&h.clearToolbar.call(h,false)}catch(e){}switch(c.refreshstate){case "firstpage":a(h).trigger("reloadGrid",[{page:1}]);break;case "current":a(h).trigger("reloadGrid",[{current:true}])}a.isFunction(c.afterRefresh)&&c.afterRefresh.call(h)}return false}).hover(d,q),g=null);g=a(".ui-jqgrid").css("font-size")||"11px";a("body").append("<div id='testpg2' class='ui-jqgrid ui-widget ui-widget-content' style='font-size:"+
-g+";visibility:hidden;' ></div>");g=a(f).clone().appendTo("#testpg2").width();a("#testpg2").remove();a(o+"_"+c.position,o).append(f);h.p._nvtd&&(g>h.p._nvtd[0]&&(a(o+"_"+c.position,o).width(g),h.p._nvtd[0]=g),h.p._nvtd[1]=g);f=g=g=null;this.nav=!0}}}})},navButtonAdd:function(b,c){c=a.extend({caption:"newButton",title:"",buttonicon:"ui-icon-newwin",onClickButton:null,position:"last",cursor:"pointer"},c||{});return this.each(function(){if(this.grid){"string"===typeof b&&0!==b.indexOf("#")&&(b="#"+a.jgrid.jqID(b));
-var e=a(".navtable",b)[0],i=this;if(e&&!(c.id&&void 0!==a("#"+a.jgrid.jqID(c.id),e)[0])){var t=a("<td></td>");"NONE"==c.buttonicon.toString().toUpperCase()?a(t).addClass("ui-pg-button ui-corner-all").append("<div class='ui-pg-div'>"+c.caption+"</div>"):a(t).addClass("ui-pg-button ui-corner-all").append("<div class='ui-pg-div'><span class='ui-icon "+c.buttonicon+"'></span>"+c.caption+"</div>");c.id&&a(t).attr("id",c.id);"first"==c.position?0===e.rows[0].cells.length?a("tr",e).append(t):a("tr td:eq(0)",
-e).before(t):a("tr",e).append(t);a(t,e).attr("title",c.title||"").click(function(b){a(this).hasClass("ui-state-disabled")||a.isFunction(c.onClickButton)&&c.onClickButton.call(i,b);return!1}).hover(function(){a(this).hasClass("ui-state-disabled")||a(this).addClass("ui-state-hover")},function(){a(this).removeClass("ui-state-hover")})}}})},navSeparatorAdd:function(b,c){c=a.extend({sepclass:"ui-separator",sepcontent:"",position:"last"},c||{});return this.each(function(){if(this.grid){"string"===typeof b&&
-0!==b.indexOf("#")&&(b="#"+a.jgrid.jqID(b));var e=a(".navtable",b)[0];if(e){var i="<td class='ui-pg-button ui-state-disabled' style='width:4px;'><span class='"+c.sepclass+"'></span>"+c.sepcontent+"</td>";"first"===c.position?0===e.rows[0].cells.length?a("tr",e).append(i):a("tr td:eq(0)",e).before(i):a("tr",e).append(i)}}})},GridToForm:function(b,c){return this.each(function(){var e=this,i;if(e.grid){var t=a(e).jqGrid("getRowData",b);if(t)for(i in t)t.hasOwnProperty(i)&&(a("[name="+a.jgrid.jqID(i)+
-"]",c).is("input:radio")||a("[name="+a.jgrid.jqID(i)+"]",c).is("input:checkbox")?a("[name="+a.jgrid.jqID(i)+"]",c).each(function(){if(a(this).val()==t[i])a(this)[e.p.useProp?"prop":"attr"]("checked",!0);else a(this)[e.p.useProp?"prop":"attr"]("checked",!1)}):a("[name="+a.jgrid.jqID(i)+"]",c).val(t[i]))}})},FormToGrid:function(b,c,e,i){return this.each(function(){if(this.grid){e||(e="set");i||(i="first");var t=a(c).serializeArray(),u={};a.each(t,function(a,b){u[b.name]=b.value});"add"==e?a(this).jqGrid("addRowData",
-b,u,i):"set"==e&&a(this).jqGrid("setRowData",b,u)}})}})})(jQuery);
+a.jgrid.jqID(h.p.id),a("#gbox_"+a.jgrid.jqID(h.p.id))[0],!0));var n=1,x,d=function(){a(this).hasClass("ui-state-disabled")||a(this).addClass("ui-state-hover")},q=function(){a(this).removeClass("ui-state-hover")};c.cloneToTop&&h.p.toppager&&(n=2);for(x=0;x<n;x++){var f=a("<table cellspacing='0' cellpadding='0' border='0' class='ui-pg-table navtable' style='float:left;table-layout:auto;'><tbody><tr></tr></tbody></table>"),o,k;0===x?(o=b,k=h.p.id,o===h.p.toppager&&(k+="_top",n=1)):(o=h.p.toppager,k=
+h.p.id+"_top");"rtl"===h.p.direction&&a(f).attr("dir","rtl").css("float","right");c.add&&(i=i||{},g=a("<td class='ui-pg-button ui-corner-all'></td>"),a(g).append("<div class='ui-pg-div'><span class='ui-icon "+c.addicon+"'></span>"+c.addtext+"</div>"),a("tr",f).append(g),a(g,f).attr({title:c.addtitle||"",id:i.id||"add_"+k}).click(function(){a(this).hasClass("ui-state-disabled")||(a.isFunction(c.addfunc)?c.addfunc.call(h):a(h).jqGrid("editGridRow","new",i));return false}).hover(d,q),g=null);c.edit&&
+(g=a("<td class='ui-pg-button ui-corner-all'></td>"),e=e||{},a(g).append("<div class='ui-pg-div'><span class='ui-icon "+c.editicon+"'></span>"+c.edittext+"</div>"),a("tr",f).append(g),a(g,f).attr({title:c.edittitle||"",id:e.id||"edit_"+k}).click(function(){if(!a(this).hasClass("ui-state-disabled")){var b=h.p.selrow;if(b)a.isFunction(c.editfunc)?c.editfunc.call(h,b):a(h).jqGrid("editGridRow",b,e);else{a.jgrid.viewModal("#"+m.themodal,{gbox:"#gbox_"+a.jgrid.jqID(h.p.id),jqm:true});a("#jqg_alrt").focus()}}return false}).hover(d,
+q),g=null);c.view&&(g=a("<td class='ui-pg-button ui-corner-all'></td>"),s=s||{},a(g).append("<div class='ui-pg-div'><span class='ui-icon "+c.viewicon+"'></span>"+c.viewtext+"</div>"),a("tr",f).append(g),a(g,f).attr({title:c.viewtitle||"",id:s.id||"view_"+k}).click(function(){if(!a(this).hasClass("ui-state-disabled")){var b=h.p.selrow;if(b)a.isFunction(c.viewfunc)?c.viewfunc.call(h,b):a(h).jqGrid("viewGridRow",b,s);else{a.jgrid.viewModal("#"+m.themodal,{gbox:"#gbox_"+a.jgrid.jqID(h.p.id),jqm:true});
+a("#jqg_alrt").focus()}}return false}).hover(d,q),g=null);c.del&&(g=a("<td class='ui-pg-button ui-corner-all'></td>"),t=t||{},a(g).append("<div class='ui-pg-div'><span class='ui-icon "+c.delicon+"'></span>"+c.deltext+"</div>"),a("tr",f).append(g),a(g,f).attr({title:c.deltitle||"",id:t.id||"del_"+k}).click(function(){if(!a(this).hasClass("ui-state-disabled")){var b;if(h.p.multiselect){b=h.p.selarrrow;b.length===0&&(b=null)}else b=h.p.selrow;if(b)a.isFunction(c.delfunc)?c.delfunc.call(h,b):a(h).jqGrid("delGridRow",
+b,t);else{a.jgrid.viewModal("#"+m.themodal,{gbox:"#gbox_"+a.jgrid.jqID(h.p.id),jqm:true});a("#jqg_alrt").focus()}}return false}).hover(d,q),g=null);(c.add||c.edit||c.del||c.view)&&a("tr",f).append("<td class='ui-pg-button ui-state-disabled' style='width:4px;'><span class='ui-separator'></span></td>");c.search&&(g=a("<td class='ui-pg-button ui-corner-all'></td>"),u=u||{},a(g).append("<div class='ui-pg-div'><span class='ui-icon "+c.searchicon+"'></span>"+c.searchtext+"</div>"),a("tr",f).append(g),a(g,
+f).attr({title:c.searchtitle||"",id:u.id||"search_"+k}).click(function(){a(this).hasClass("ui-state-disabled")||(a.isFunction(c.searchfunc)?c.searchfunc.call(h,u):a(h).jqGrid("searchGrid",u));return false}).hover(d,q),u.showOnLoad&&!0===u.showOnLoad&&a(g,f).click(),g=null);c.refresh&&(g=a("<td class='ui-pg-button ui-corner-all'></td>"),a(g).append("<div class='ui-pg-div'><span class='ui-icon "+c.refreshicon+"'></span>"+c.refreshtext+"</div>"),a("tr",f).append(g),a(g,f).attr({title:c.refreshtitle||
+"",id:"refresh_"+k}).click(function(){if(!a(this).hasClass("ui-state-disabled")){a.isFunction(c.beforeRefresh)&&c.beforeRefresh.call(h);h.p.search=false;try{var b=h.p.id;h.p.postData.filters="";try{a("#fbox_"+a.jgrid.jqID(b)).jqFilter("resetFilter")}catch(d){}a.isFunction(h.clearToolbar)&&h.clearToolbar.call(h,false)}catch(e){}switch(c.refreshstate){case "firstpage":a(h).trigger("reloadGrid",[{page:1}]);break;case "current":a(h).trigger("reloadGrid",[{current:true}])}a.isFunction(c.afterRefresh)&&
+c.afterRefresh.call(h)}return false}).hover(d,q),g=null);g=a(".ui-jqgrid").css("font-size")||"11px";a("body").append("<div id='testpg2' class='ui-jqgrid ui-widget ui-widget-content' style='font-size:"+g+";visibility:hidden;' ></div>");g=a(f).clone().appendTo("#testpg2").width();a("#testpg2").remove();a(o+"_"+c.position,o).append(f);h.p._nvtd&&(g>h.p._nvtd[0]&&(a(o+"_"+c.position,o).width(g),h.p._nvtd[0]=g),h.p._nvtd[1]=g);f=g=g=null;this.nav=!0}}}})},navButtonAdd:function(b,c){c=a.extend({caption:"newButton",
+title:"",buttonicon:"ui-icon-newwin",onClickButton:null,position:"last",cursor:"pointer"},c||{});return this.each(function(){if(this.grid){"string"===typeof b&&0!==b.indexOf("#")&&(b="#"+a.jgrid.jqID(b));var e=a(".navtable",b)[0],i=this;if(e&&!(c.id&&void 0!==a("#"+a.jgrid.jqID(c.id),e)[0])){var t=a("<td></td>");"NONE"===c.buttonicon.toString().toUpperCase()?a(t).addClass("ui-pg-button ui-corner-all").append("<div class='ui-pg-div'>"+c.caption+"</div>"):a(t).addClass("ui-pg-button ui-corner-all").append("<div class='ui-pg-div'><span class='ui-icon "+
+c.buttonicon+"'></span>"+c.caption+"</div>");c.id&&a(t).attr("id",c.id);"first"===c.position?0===e.rows[0].cells.length?a("tr",e).append(t):a("tr td:eq(0)",e).before(t):a("tr",e).append(t);a(t,e).attr("title",c.title||"").click(function(b){a(this).hasClass("ui-state-disabled")||a.isFunction(c.onClickButton)&&c.onClickButton.call(i,b);return!1}).hover(function(){a(this).hasClass("ui-state-disabled")||a(this).addClass("ui-state-hover")},function(){a(this).removeClass("ui-state-hover")})}}})},navSeparatorAdd:function(b,
+c){c=a.extend({sepclass:"ui-separator",sepcontent:"",position:"last"},c||{});return this.each(function(){if(this.grid){"string"===typeof b&&0!==b.indexOf("#")&&(b="#"+a.jgrid.jqID(b));var e=a(".navtable",b)[0];if(e){var i="<td class='ui-pg-button ui-state-disabled' style='width:4px;'><span class='"+c.sepclass+"'></span>"+c.sepcontent+"</td>";"first"===c.position?0===e.rows[0].cells.length?a("tr",e).append(i):a("tr td:eq(0)",e).before(i):a("tr",e).append(i)}}})},GridToForm:function(b,c){return this.each(function(){var e=
+this,i;if(e.grid){var t=a(e).jqGrid("getRowData",b);if(t)for(i in t)t.hasOwnProperty(i)&&(a("[name="+a.jgrid.jqID(i)+"]",c).is("input:radio")||a("[name="+a.jgrid.jqID(i)+"]",c).is("input:checkbox")?a("[name="+a.jgrid.jqID(i)+"]",c).each(function(){if(a(this).val()==t[i])a(this)[e.p.useProp?"prop":"attr"]("checked",!0);else a(this)[e.p.useProp?"prop":"attr"]("checked",!1)}):a("[name="+a.jgrid.jqID(i)+"]",c).val(t[i]))}})},FormToGrid:function(b,c,e,i){return this.each(function(){if(this.grid){e||(e=
+"set");i||(i="first");var t=a(c).serializeArray(),u={};a.each(t,function(a,b){u[b.name]=b.value});"add"===e?a(this).jqGrid("addRowData",b,u,i):"set"===e&&a(this).jqGrid("setRowData",b,u)}})}})})(jQuery);
 (function(a){a.fn.jqFilter=function(d){if("string"===typeof d){var l=a.fn.jqFilter[d];if(!l)throw"jqFilter - No such method: "+d;var v=a.makeArray(arguments).slice(1);return l.apply(this,v)}var n=a.extend(!0,{filter:null,columns:[],onChange:null,afterRedraw:null,checkValues:null,error:!1,errmsg:"",errorcheck:!0,showQuery:!0,sopt:null,ops:[],operands:null,numopts:"eq,ne,lt,le,gt,ge,nu,nn,in,ni".split(","),stropts:"eq,ne,bw,bn,ew,en,cn,nc,nu,nn,in,ni".split(","),strarr:["text","string","blob"],groupOps:[{op:"AND",
 text:"AND"},{op:"OR",text:"OR"}],groupButton:!0,ruleButtons:!0,direction:"ltr"},a.jgrid.filter,d||{});return this.each(function(){if(!this.filter){this.p=n;if(null===this.p.filter||void 0===this.p.filter)this.p.filter={groupOp:this.p.groupOps[0].op,rules:[],groups:[]};var d,l=this.p.columns.length,f,t=/msie/i.test(navigator.userAgent)&&!window.opera;this.p.initFilter=a.extend(!0,{},this.p.filter);if(l){for(d=0;d<l;d++)if(f=this.p.columns[d],f.stype?f.inputtype=f.stype:f.inputtype||(f.inputtype="text"),
 f.sorttype?f.searchtype=f.sorttype:f.searchtype||(f.searchtype="string"),void 0===f.hidden&&(f.hidden=!1),f.label||(f.label=f.name),f.index&&(f.name=f.index),f.hasOwnProperty("searchoptions")||(f.searchoptions={}),!f.hasOwnProperty("searchrules"))f.searchrules={};this.p.showQuery&&a(this).append("<table class='queryresult ui-widget ui-widget-content' style='display:block;max-width:440px;border:0px none;' dir='"+this.p.direction+"'><tbody><tr><td class='query'></td></tr></tbody></table>");var u=function(){return a("#"+
@@ -383,7 +385,7 @@ this.p.ops[c].oper;break}for(c=0;c<this.p.columns.length;c++)if(this.p.columns[c
 b.rules)for(f=0;f<b.rules.length;f++){1<c.length&&(c="OR"===b.groupOp?c+" || ":c+" && ");var e=b.rules[f];if(d.p.errorcheck){for(var h=void 0,l=void 0,h=0;h<d.p.columns.length;h++)if(d.p.columns[h].name===e.field){l=d.p.columns[h];break}l&&r(e.data,l)}c+=e.op+"(item."+e.field+",'"+e.data+"')"}c+=")";return"()"===c?"":c}var d=this;return a(this.p.filter)};this.reDraw();if(this.p.showQuery)this.onchange();this.filter=!0}}})};a.extend(a.fn.jqFilter,{toSQLString:function(){var a="";this.each(function(){a=
 this.toUserFriendlyString()});return a},filterData:function(){var a;this.each(function(){a=this.p.filter});return a},getParameter:function(a){return void 0!==a&&this.p.hasOwnProperty(a)?this.p[a]:this.p},resetFilter:function(){return this.each(function(){this.resetFilter()})},addFilter:function(d){"string"===typeof d&&(d=a.jgrid.parse(d));this.each(function(){this.p.filter=d;this.reDraw();this.onchange()})}})})(jQuery);
 (function(a){a.jgrid.inlineEdit=a.jgrid.inlineEdit||{};a.jgrid.extend({editRow:function(c,b,e,o,l,g,n,h,f){var j={},d=a.makeArray(arguments).slice(1);if("object"===a.type(d[0]))j=d[0];else if(void 0!==b&&(j.keys=b),a.isFunction(e)&&(j.oneditfunc=e),a.isFunction(o)&&(j.successfunc=o),void 0!==l&&(j.url=l),void 0!==g&&(j.extraparam=g),a.isFunction(n)&&(j.aftersavefunc=n),a.isFunction(h)&&(j.errorfunc=h),a.isFunction(f))j.afterrestorefunc=f;j=a.extend(!0,{keys:!1,oneditfunc:null,successfunc:null,url:null,
-extraparam:{},aftersavefunc:null,errorfunc:null,afterrestorefunc:null,restoreAfterError:!0,mtype:"POST"},a.jgrid.inlineEdit,j);return this.each(function(){var d=this,b,f,e=0,h=null,l={},g,k;if(d.grid&&(g=a(d).jqGrid("getInd",c,!0),!1!==g&&"0"==(a(g).attr("editable")||"0")&&!a(g).hasClass("not-editable-row")))k=d.p.colModel,a('td[role="gridcell"]',g).each(function(g){b=k[g].name;var j=!0===d.p.treeGrid&&b===d.p.ExpandColumn;if(j)f=a("span:first",this).html();else try{f=a.unformat.call(d,this,{rowId:c,
+extraparam:{},aftersavefunc:null,errorfunc:null,afterrestorefunc:null,restoreAfterError:!0,mtype:"POST"},a.jgrid.inlineEdit,j);return this.each(function(){var d=this,b,f,e=0,h=null,l={},g,k;if(d.grid&&(g=a(d).jqGrid("getInd",c,!0),!1!==g&&"0"===(a(g).attr("editable")||"0")&&!a(g).hasClass("not-editable-row")))k=d.p.colModel,a('td[role="gridcell"]',g).each(function(g){b=k[g].name;var j=!0===d.p.treeGrid&&b===d.p.ExpandColumn;if(j)f=a("span:first",this).html();else try{f=a.unformat.call(d,this,{rowId:c,
 colModel:k[g]},g)}catch(o){f=k[g].edittype&&"textarea"===k[g].edittype?a(this).text():a(this).html()}if("cb"!==b&&"subgrid"!==b&&"rn"!==b&&(d.p.autoencode&&(f=a.jgrid.htmlDecode(f)),l[b]=f,!0===k[g].editable)){null===h&&(h=g);j?a("span:first",this).html(""):a(this).html("");var x=a.extend({},k[g].editoptions||{},{id:c+"_"+b,name:b});k[g].edittype||(k[g].edittype="text");if("&nbsp;"===f||"&#160;"===f||1===f.length&&160===f.charCodeAt(0))f="";var v=a.jgrid.createEl.call(d,k[g].edittype,x,f,!0,a.extend({},
 a.jgrid.ajaxOptions,d.p.ajaxSelectOptions||{}));a(v).addClass("editable");j?a("span:first",this).append(v):a(this).append(v);a.jgrid.bindEv.call(d,v,x);"select"===k[g].edittype&&void 0!==k[g].editoptions&&!0===k[g].editoptions.multiple&&void 0===k[g].editoptions.dataUrl&&a.jgrid.msie&&a(v).width(a(v).width());e++}}),0<e&&(l.id=c,d.p.savedRow.push(l),a(g).attr("editable","1"),a("td:eq("+h+") input",g).focus(),!0===j.keys&&a(g).bind("keydown",function(f){if(27===f.keyCode){a(d).jqGrid("restoreRow",
 c,j.afterrestorefunc);if(d.p._inlinenav)try{a(d).jqGrid("showAddEditButtons")}catch(b){}return!1}if(13===f.keyCode){if("TEXTAREA"===f.target.tagName)return!0;if(a(d).jqGrid("saveRow",c,j)&&d.p._inlinenav)try{a(d).jqGrid("showAddEditButtons")}catch(g){}return!1}}),a(d).triggerHandler("jqGridInlineEditRow",[c,j]),a.isFunction(j.oneditfunc)&&j.oneditfunc.call(d,c))})},saveRow:function(c,b,e,o,l,g,n){var h=a.makeArray(arguments).slice(1),f={};if("object"===a.type(h[0]))f=h[0];else if(a.isFunction(b)&&
@@ -391,8 +393,8 @@ c,j.afterrestorefunc);if(d.p._inlinenav)try{a(d).jqGrid("showAddEditButtons")}ca
 if("1"===h){var k;a('td[role="gridcell"]',q).each(function(c){k=d.p.colModel[c];m=k.name;if("cb"!==m&&"subgrid"!==m&&!0===k.editable&&"rn"!==m&&!a(this).hasClass("not-editable-cell")){switch(k.edittype){case "checkbox":var b=["Yes","No"];k.editoptions&&(b=k.editoptions.value.split(":"));i[m]=a("input",this).is(":checked")?b[0]:b[1];break;case "text":case "password":case "textarea":case "button":i[m]=a("input, textarea",this).val();break;case "select":if(k.editoptions.multiple){var b=a("select",this),
 g=[];i[m]=a(b).val();i[m]=i[m]?i[m].join(","):"";a("select option:selected",this).each(function(d,c){g[d]=a(c).text()});w[m]=g.join(",")}else i[m]=a("select option:selected",this).val(),w[m]=a("select option:selected",this).text();k.formatter&&"select"===k.formatter&&(w={});break;case "custom":try{if(k.editoptions&&a.isFunction(k.editoptions.custom_value)){if(i[m]=k.editoptions.custom_value.call(d,a(".customelement",this),"get"),void 0===i[m])throw"e2";}else throw"e1";}catch(e){"e1"===e&&a.jgrid.info_dialog(a.jgrid.errors.errcap,
 "function 'custom_value' "+a.jgrid.edit.msg.nodefined,a.jgrid.edit.bClose),"e2"===e?a.jgrid.info_dialog(a.jgrid.errors.errcap,"function 'custom_value' "+a.jgrid.edit.msg.novalue,a.jgrid.edit.bClose):a.jgrid.info_dialog(a.jgrid.errors.errcap,e.message,a.jgrid.edit.bClose)}}s=a.jgrid.checkValues.call(d,i[m],c);if(!1===s[0])return s[1]=i[m]+" "+s[1],!1;d.p.autoencode&&(i[m]=a.jgrid.htmlEncode(i[m]));"clientArray"!==f.url&&k.editoptions&&!0===k.editoptions.NullIfEmpty&&""===i[m]&&(r[m]="null")}});if(!1===
-s[0]){try{var u=d.rows.namedItem(c),p=a.jgrid.findPos(u);a.jgrid.info_dialog(a.jgrid.errors.errcap,s[1],a.jgrid.edit.bClose,{left:p[0],top:p[1]+a(u).outerHeight()})}catch(y){alert(s[1])}return j}h=d.p.prmNames;u=c;p=!1===d.p.keyIndex?h.id:d.p.colModel[d.p.keyIndex+(!0===d.p.rownumbers?1:0)+(!0===d.p.multiselect?1:0)+(!0===d.p.subGrid?1:0)].name;if(i){i[h.oper]=h.editoper;if(void 0===i[p])i[p]=c;else if(q.id!==d.p.idPrefix+i[p]&&(h=a.jgrid.stripPref(d.p.idPrefix,c),void 0!==d.p._index[h]&&(d.p._index[i[p]]=
-d.p._index[h],delete d.p._index[h]),c=d.p.idPrefix+i[p],a(q).attr("id",c),d.p.selrow===u&&(d.p.selrow=c),a.isArray(d.p.selarrrow)&&(h=a.inArray(u,d.p.selarrrow),0<=h&&(d.p.selarrrow[h]=c)),d.p.multiselect))h="jqg_"+d.p.id+"_"+c,a("input.cbox",q).attr("id",h).attr("name",h);void 0===d.p.inlineData&&(d.p.inlineData={});i=a.extend({},i,d.p.inlineData,f.extraparam)}if("clientArray"===f.url){i=a.extend({},i,w);d.p.autoencode&&a.each(i,function(d,c){i[d]=a.jgrid.htmlDecode(c)});h=a(d).jqGrid("setRowData",
+s[0]){try{var u=d.rows.namedItem(c),p=a.jgrid.findPos(u);a.jgrid.info_dialog(a.jgrid.errors.errcap,s[1],a.jgrid.edit.bClose,{left:p[0],top:p[1]+a(u).outerHeight()})}catch(y){alert(s[1])}return j}h=d.p.prmNames;u=c;p=!1===d.p.keyIndex?h.id:d.p.colModel[d.p.keyIndex+(!0===d.p.rownumbers?1:0)+(!0===d.p.multiselect?1:0)+(!0===d.p.subGrid?1:0)].name;if(i){i[h.oper]=h.editoper;if(void 0===i[p]||""===i[p])i[p]=c;else if(q.id!==d.p.idPrefix+i[p]&&(h=a.jgrid.stripPref(d.p.idPrefix,c),void 0!==d.p._index[h]&&
+(d.p._index[i[p]]=d.p._index[h],delete d.p._index[h]),c=d.p.idPrefix+i[p],a(q).attr("id",c),d.p.selrow===u&&(d.p.selrow=c),a.isArray(d.p.selarrrow)&&(h=a.inArray(u,d.p.selarrrow),0<=h&&(d.p.selarrrow[h]=c)),d.p.multiselect))h="jqg_"+d.p.id+"_"+c,a("input.cbox",q).attr("id",h).attr("name",h);void 0===d.p.inlineData&&(d.p.inlineData={});i=a.extend({},i,d.p.inlineData,f.extraparam)}if("clientArray"===f.url){i=a.extend({},i,w);d.p.autoencode&&a.each(i,function(d,c){i[d]=a.jgrid.htmlDecode(c)});h=a(d).jqGrid("setRowData",
 c,i);a(q).attr("editable","0");for(p=0;p<d.p.savedRow.length;p++)if(""+d.p.savedRow[p].id===""+u){t=p;break}0<=t&&d.p.savedRow.splice(t,1);a(d).triggerHandler("jqGridInlineAfterSaveRow",[c,h,i,f]);a.isFunction(f.aftersavefunc)&&f.aftersavefunc.call(d,c,h,f);j=!0;a(q).removeClass("jqgrid-new-row").unbind("keydown")}else a("#lui_"+a.jgrid.jqID(d.p.id)).show(),r=a.extend({},i,r),r[p]=a.jgrid.stripPref(d.p.idPrefix,r[p]),a.ajax(a.extend({url:f.url,data:a.isFunction(d.p.serializeRowData)?d.p.serializeRowData.call(d,
 r):r,type:f.mtype,async:!1,complete:function(b,g){a("#lui_"+a.jgrid.jqID(d.p.id)).hide();if("success"===g){var e=!0,h;h=a(d).triggerHandler("jqGridInlineSuccessSaveRow",[b,c,f]);a.isArray(h)||(h=[!0,i]);h[0]&&a.isFunction(f.successfunc)&&(h=f.successfunc.call(d,b));a.isArray(h)?(e=h[0],i=h[1]||i):e=h;if(!0===e){d.p.autoencode&&a.each(i,function(d,c){i[d]=a.jgrid.htmlDecode(c)});i=a.extend({},i,w);a(d).jqGrid("setRowData",c,i);a(q).attr("editable","0");for(e=0;e<d.p.savedRow.length;e++)if(""+d.p.savedRow[e].id===
 ""+c){t=e;break}0<=t&&d.p.savedRow.splice(t,1);a(d).triggerHandler("jqGridInlineAfterSaveRow",[c,b,i,f]);a.isFunction(f.aftersavefunc)&&f.aftersavefunc.call(d,c,b);j=!0;a(q).removeClass("jqgrid-new-row").unbind("keydown")}else a(d).triggerHandler("jqGridInlineErrorSaveRow",[c,b,g,null,f]),a.isFunction(f.errorfunc)&&f.errorfunc.call(d,c,b,g,null),!0===f.restoreAfterError&&a(d).jqGrid("restoreRow",c,f.afterrestorefunc)}},error:function(b,e,g){a("#lui_"+a.jgrid.jqID(d.p.id)).hide();a(d).triggerHandler("jqGridInlineErrorSaveRow",
@@ -400,7 +402,7 @@ r):r,type:f.mtype,async:!1,complete:function(b,g){a("#lui_"+a.jgrid.jqID(d.p.id)
 (o.afterrestorefunc=b);o=a.extend(!0,{},a.jgrid.inlineEdit,o);return this.each(function(){var b=this,e,n,h={},f;if(b.grid){n=a(b).jqGrid("getInd",c,true);if(n!==false){for(f=0;f<b.p.savedRow.length;f++)if(""+b.p.savedRow[f].id===""+c){e=f;break}if(e>=0){if(a.isFunction(a.fn.datepicker))try{a("input.hasDatepicker","#"+a.jgrid.jqID(n.id)).datepicker("hide")}catch(j){}a.each(b.p.colModel,function(){this.editable===true&&b.p.savedRow[e].hasOwnProperty(this.name)&&(h[this.name]=b.p.savedRow[e][this.name])});
 a(b).jqGrid("setRowData",c,h);a(n).attr("editable","0").unbind("keydown");b.p.savedRow.splice(e,1);a("#"+a.jgrid.jqID(c),"#"+a.jgrid.jqID(b.p.id)).hasClass("jqgrid-new-row")&&setTimeout(function(){a(b).jqGrid("delRowData",c);a(b).jqGrid("showAddEditButtons")},0)}a(b).triggerHandler("jqGridInlineAfterRestoreRow",[c]);a.isFunction(o.afterrestorefunc)&&o.afterrestorefunc.call(b,c)}}})},addRow:function(c){c=a.extend(!0,{rowID:null,initdata:{},position:"first",useDefValues:!0,useFormatter:!1,addRowParams:{extraparam:{}}},
 c||{});return this.each(function(){if(this.grid){var b=this;c.rowID=a.isFunction(c.rowID)?c.rowID.call(b,c):null!=c.rowID?c.rowID:a.jgrid.randId();!0===c.useDefValues&&a(b.p.colModel).each(function(){if(this.editoptions&&this.editoptions.defaultValue){var e=this.editoptions.defaultValue,e=a.isFunction(e)?e.call(b):e;c.initdata[this.name]=e}});a(b).jqGrid("addRowData",c.rowID,c.initdata,c.position);c.rowID=b.p.idPrefix+c.rowID;a("#"+a.jgrid.jqID(c.rowID),"#"+a.jgrid.jqID(b.p.id)).addClass("jqgrid-new-row");
-if(c.useFormatter)a("#"+a.jgrid.jqID(c.rowID)+" .ui-inline-edit","#"+a.jgrid.jqID(b.p.id)).click();else{var e=b.p.prmNames;c.addRowParams.extraparam[e.oper]=e.addoper;a(b).jqGrid("editRow",c.rowID,c.addRowParams);a(b).jqGrid("setSelection",c.rowID)}}})},inlineNav:function(c,b){b=a.extend({edit:!0,editicon:"ui-icon-pencil",add:!0,addicon:"ui-icon-plus",save:!0,saveicon:"ui-icon-disk",cancel:!0,cancelicon:"ui-icon-cancel",addParams:{addRowParams:{extraparam:{}}},editParams:{},restoreAfterSelect:!0},
+if(c.useFormatter)a("#"+a.jgrid.jqID(c.rowID)+" .ui-inline-edit","#"+a.jgrid.jqID(b.p.id)).click();else{var e=b.p.prmNames;c.addRowParams.extraparam[e.oper]=e.addoper;a(b).jqGrid("editRow",c.rowID,c.addRowParams);a(b).jqGrid("setSelection",c.rowID)}}})},inlineNav:function(c,b){b=a.extend(!0,{edit:!0,editicon:"ui-icon-pencil",add:!0,addicon:"ui-icon-plus",save:!0,saveicon:"ui-icon-disk",cancel:!0,cancelicon:"ui-icon-cancel",addParams:{addRowParams:{extraparam:{}}},editParams:{},restoreAfterSelect:!0},
 a.jgrid.nav,b||{});return this.each(function(){if(this.grid){var e=this,o,l=a.jgrid.jqID(e.p.id);e.p._inlinenav=!0;if(!0===b.addParams.useFormatter){var g=e.p.colModel,n;for(n=0;n<g.length;n++)if(g[n].formatter&&"actions"===g[n].formatter){g[n].formatoptions&&(g=a.extend({keys:!1,onEdit:null,onSuccess:null,afterSave:null,onError:null,afterRestore:null,extraparam:{},url:null},g[n].formatoptions),b.addParams.addRowParams={keys:g.keys,oneditfunc:g.onEdit,successfunc:g.onSuccess,url:g.url,extraparam:g.extraparam,
 aftersavefunc:g.afterSave,errorfunc:g.onError,afterrestorefunc:g.afterRestore});break}}b.add&&a(e).jqGrid("navButtonAdd",c,{caption:b.addtext,title:b.addtitle,buttonicon:b.addicon,id:e.p.id+"_iladd",onClickButton:function(){a(e).jqGrid("addRow",b.addParams);b.addParams.useFormatter||(a("#"+l+"_ilsave").removeClass("ui-state-disabled"),a("#"+l+"_ilcancel").removeClass("ui-state-disabled"),a("#"+l+"_iladd").addClass("ui-state-disabled"),a("#"+l+"_iledit").addClass("ui-state-disabled"))}});b.edit&&a(e).jqGrid("navButtonAdd",
 c,{caption:b.edittext,title:b.edittitle,buttonicon:b.editicon,id:e.p.id+"_iledit",onClickButton:function(){var c=a(e).jqGrid("getGridParam","selrow");c?(a(e).jqGrid("editRow",c,b.editParams),a("#"+l+"_ilsave").removeClass("ui-state-disabled"),a("#"+l+"_ilcancel").removeClass("ui-state-disabled"),a("#"+l+"_iladd").addClass("ui-state-disabled"),a("#"+l+"_iledit").addClass("ui-state-disabled")):(a.jgrid.viewModal("#alertmod",{gbox:"#gbox_"+l,jqm:!0}),a("#jqg_alrt").focus())}});b.save&&(a(e).jqGrid("navButtonAdd",
@@ -408,27 +410,27 @@ c,{caption:b.savetext||"",title:b.savetitle||"Save row",buttonicon:b.saveicon,id
 {gbox:"#gbox_"+l,jqm:!0}),a("#jqg_alrt").focus()}}),a("#"+l+"_ilsave").addClass("ui-state-disabled"));b.cancel&&(a(e).jqGrid("navButtonAdd",c,{caption:b.canceltext||"",title:b.canceltitle||"Cancel row editing",buttonicon:b.cancelicon,id:e.p.id+"_ilcancel",onClickButton:function(){var c=e.p.savedRow[0].id,f={};if(c){f=a("#"+a.jgrid.jqID(c),"#"+l).hasClass("jqgrid-new-row")?b.addParams.addRowParams:b.editParams;a(e).jqGrid("restoreRow",c,f);a(e).jqGrid("showAddEditButtons")}else{a.jgrid.viewModal("#alertmod",
 {gbox:"#gbox_"+l,jqm:true});a("#jqg_alrt").focus()}}}),a("#"+l+"_ilcancel").addClass("ui-state-disabled"));!0===b.restoreAfterSelect&&(o=a.isFunction(e.p.beforeSelectRow)?e.p.beforeSelectRow:!1,e.p.beforeSelectRow=function(c,f){var g=true;if(e.p.savedRow.length>0&&e.p._inlinenav===true&&c!==e.p.selrow&&e.p.selrow!==null){e.p.selrow===b.addParams.rowID?a(e).jqGrid("delRowData",e.p.selrow):a(e).jqGrid("restoreRow",e.p.selrow,b.editParams);a(e).jqGrid("showAddEditButtons")}o&&(g=o.call(e,c,f));return g})}})},
 showAddEditButtons:function(){return this.each(function(){if(this.grid){var c=a.jgrid.jqID(this.p.id);a("#"+c+"_ilsave").addClass("ui-state-disabled");a("#"+c+"_ilcancel").addClass("ui-state-disabled");a("#"+c+"_iladd").removeClass("ui-state-disabled");a("#"+c+"_iledit").removeClass("ui-state-disabled")}})}})})(jQuery);
-(function(b){b.jgrid.extend({editCell:function(d,f,a){return this.each(function(){var c=this,g,e,h,i;if(c.grid&&!0===c.p.cellEdit){f=parseInt(f,10);c.p.selrow=c.rows[d].id;c.p.knv||b(c).jqGrid("GridNav");if(0<c.p.savedRow.length){if(!0===a&&d==c.p.iRow&&f==c.p.iCol)return;b(c).jqGrid("saveCell",c.p.savedRow[0].id,c.p.savedRow[0].ic)}else window.setTimeout(function(){b("#"+b.jgrid.jqID(c.p.knv)).attr("tabindex","-1").focus()},0);i=c.p.colModel[f];g=i.name;if(!("subgrid"==g||"cb"==g||"rn"==g)){h=b("td:eq("+
-f+")",c.rows[d]);if(!0===i.editable&&!0===a&&!h.hasClass("not-editable-cell")){0<=parseInt(c.p.iCol,10)&&0<=parseInt(c.p.iRow,10)&&(b("td:eq("+c.p.iCol+")",c.rows[c.p.iRow]).removeClass("edit-cell ui-state-highlight"),b(c.rows[c.p.iRow]).removeClass("selected-row ui-state-hover"));b(h).addClass("edit-cell ui-state-highlight");b(c.rows[d]).addClass("selected-row ui-state-hover");try{e=b.unformat.call(c,h,{rowId:c.rows[d].id,colModel:i},f)}catch(k){e=i.edittype&&"textarea"==i.edittype?b(h).text():b(h).html()}c.p.autoencode&&
-(e=b.jgrid.htmlDecode(e));i.edittype||(i.edittype="text");c.p.savedRow.push({id:d,ic:f,name:g,v:e});if("&nbsp;"===e||"&#160;"===e||1===e.length&&160===e.charCodeAt(0))e="";if(b.isFunction(c.p.formatCell)){var j=c.p.formatCell.call(c,c.rows[d].id,g,e,d,f);void 0!==j&&(e=j)}var j=b.extend({},i.editoptions||{},{id:d+"_"+g,name:g}),n=b.jgrid.createEl.call(c,i.edittype,j,e,!0,b.extend({},b.jgrid.ajaxOptions,c.p.ajaxSelectOptions||{}));b(c).triggerHandler("jqGridBeforeEditCell",[c.rows[d].id,g,e,d,f]);
-b.isFunction(c.p.beforeEditCell)&&c.p.beforeEditCell.call(c,c.rows[d].id,g,e,d,f);b(h).html("").append(n).attr("tabindex","0");b.jgrid.bindEv.call(c,n,j);window.setTimeout(function(){b(n).focus()},0);b("input, select, textarea",h).bind("keydown",function(a){a.keyCode===27&&(b("input.hasDatepicker",h).length>0?b(".ui-datepicker").is(":hidden")?b(c).jqGrid("restoreCell",d,f):b("input.hasDatepicker",h).datepicker("hide"):b(c).jqGrid("restoreCell",d,f));if(a.keyCode===13){b(c).jqGrid("saveCell",d,f);
-return false}if(a.keyCode===9){if(c.grid.hDiv.loading)return false;a.shiftKey?b(c).jqGrid("prevCell",d,f):b(c).jqGrid("nextCell",d,f)}a.stopPropagation()});b(c).triggerHandler("jqGridAfterEditCell",[c.rows[d].id,g,e,d,f]);b.isFunction(c.p.afterEditCell)&&c.p.afterEditCell.call(c,c.rows[d].id,g,e,d,f)}else 0<=parseInt(c.p.iCol,10)&&0<=parseInt(c.p.iRow,10)&&(b("td:eq("+c.p.iCol+")",c.rows[c.p.iRow]).removeClass("edit-cell ui-state-highlight"),b(c.rows[c.p.iRow]).removeClass("selected-row ui-state-hover")),
+(function(b){b.jgrid.extend({editCell:function(d,f,a){return this.each(function(){var c=this,g,e,h,i;if(c.grid&&!0===c.p.cellEdit){f=parseInt(f,10);c.p.selrow=c.rows[d].id;c.p.knv||b(c).jqGrid("GridNav");if(0<c.p.savedRow.length){if(!0===a&&d==c.p.iRow&&f==c.p.iCol)return;b(c).jqGrid("saveCell",c.p.savedRow[0].id,c.p.savedRow[0].ic)}else window.setTimeout(function(){b("#"+b.jgrid.jqID(c.p.knv)).attr("tabindex","-1").focus()},0);i=c.p.colModel[f];g=i.name;if(!("subgrid"===g||"cb"===g||"rn"===g)){h=
+b("td:eq("+f+")",c.rows[d]);if(!0===i.editable&&!0===a&&!h.hasClass("not-editable-cell")){0<=parseInt(c.p.iCol,10)&&0<=parseInt(c.p.iRow,10)&&(b("td:eq("+c.p.iCol+")",c.rows[c.p.iRow]).removeClass("edit-cell ui-state-highlight"),b(c.rows[c.p.iRow]).removeClass("selected-row ui-state-hover"));b(h).addClass("edit-cell ui-state-highlight");b(c.rows[d]).addClass("selected-row ui-state-hover");try{e=b.unformat.call(c,h,{rowId:c.rows[d].id,colModel:i},f)}catch(k){e=i.edittype&&"textarea"===i.edittype?b(h).text():
+b(h).html()}c.p.autoencode&&(e=b.jgrid.htmlDecode(e));i.edittype||(i.edittype="text");c.p.savedRow.push({id:d,ic:f,name:g,v:e});if("&nbsp;"===e||"&#160;"===e||1===e.length&&160===e.charCodeAt(0))e="";if(b.isFunction(c.p.formatCell)){var j=c.p.formatCell.call(c,c.rows[d].id,g,e,d,f);void 0!==j&&(e=j)}var j=b.extend({},i.editoptions||{},{id:d+"_"+g,name:g}),n=b.jgrid.createEl.call(c,i.edittype,j,e,!0,b.extend({},b.jgrid.ajaxOptions,c.p.ajaxSelectOptions||{}));b(c).triggerHandler("jqGridBeforeEditCell",
+[c.rows[d].id,g,e,d,f]);b.isFunction(c.p.beforeEditCell)&&c.p.beforeEditCell.call(c,c.rows[d].id,g,e,d,f);b(h).html("").append(n).attr("tabindex","0");b.jgrid.bindEv.call(c,n,j);window.setTimeout(function(){b(n).focus()},0);b("input, select, textarea",h).bind("keydown",function(a){a.keyCode===27&&(b("input.hasDatepicker",h).length>0?b(".ui-datepicker").is(":hidden")?b(c).jqGrid("restoreCell",d,f):b("input.hasDatepicker",h).datepicker("hide"):b(c).jqGrid("restoreCell",d,f));if(a.keyCode===13){b(c).jqGrid("saveCell",
+d,f);return false}if(a.keyCode===9){if(c.grid.hDiv.loading)return false;a.shiftKey?b(c).jqGrid("prevCell",d,f):b(c).jqGrid("nextCell",d,f)}a.stopPropagation()});b(c).triggerHandler("jqGridAfterEditCell",[c.rows[d].id,g,e,d,f]);b.isFunction(c.p.afterEditCell)&&c.p.afterEditCell.call(c,c.rows[d].id,g,e,d,f)}else 0<=parseInt(c.p.iCol,10)&&0<=parseInt(c.p.iRow,10)&&(b("td:eq("+c.p.iCol+")",c.rows[c.p.iRow]).removeClass("edit-cell ui-state-highlight"),b(c.rows[c.p.iRow]).removeClass("selected-row ui-state-hover")),
 h.addClass("edit-cell ui-state-highlight"),b(c.rows[d]).addClass("selected-row ui-state-hover"),e=h.html().replace(/\&#160\;/ig,""),b(c).triggerHandler("jqGridSelectCell",[c.rows[d].id,g,e,d,f]),b.isFunction(c.p.onSelectCell)&&c.p.onSelectCell.call(c,c.rows[d].id,g,e,d,f);c.p.iCol=f;c.p.iRow=d}}})},saveCell:function(d,f){return this.each(function(){var a=this,c;if(a.grid&&!0===a.p.cellEdit){c=1<=a.p.savedRow.length?0:null;if(null!==c){var g=b("td:eq("+f+")",a.rows[d]),e,h,i=a.p.colModel[f],k=i.name,
 j=b.jgrid.jqID(k);switch(i.edittype){case "select":if(i.editoptions.multiple){var j=b("#"+d+"_"+j,a.rows[d]),n=[];(e=b(j).val())?e.join(","):e="";b("option:selected",j).each(function(a,c){n[a]=b(c).text()});h=n.join(",")}else e=b("#"+d+"_"+j+" option:selected",a.rows[d]).val(),h=b("#"+d+"_"+j+" option:selected",a.rows[d]).text();i.formatter&&(h=e);break;case "checkbox":var l=["Yes","No"];i.editoptions&&(l=i.editoptions.value.split(":"));h=e=b("#"+d+"_"+j,a.rows[d]).is(":checked")?l[0]:l[1];break;
-case "password":case "text":case "textarea":case "button":h=e=b("#"+d+"_"+j,a.rows[d]).val();break;case "custom":try{if(i.editoptions&&b.isFunction(i.editoptions.custom_value)){e=i.editoptions.custom_value.call(a,b(".customelement",g),"get");if(void 0===e)throw"e2";h=e}else throw"e1";}catch(o){"e1"==o&&b.jgrid.info_dialog(b.jgrid.errors.errcap,"function 'custom_value' "+b.jgrid.edit.msg.nodefined,b.jgrid.edit.bClose),"e2"==o?b.jgrid.info_dialog(b.jgrid.errors.errcap,"function 'custom_value' "+b.jgrid.edit.msg.novalue,
+case "password":case "text":case "textarea":case "button":h=e=b("#"+d+"_"+j,a.rows[d]).val();break;case "custom":try{if(i.editoptions&&b.isFunction(i.editoptions.custom_value)){e=i.editoptions.custom_value.call(a,b(".customelement",g),"get");if(void 0===e)throw"e2";h=e}else throw"e1";}catch(o){"e1"===o&&b.jgrid.info_dialog(b.jgrid.errors.errcap,"function 'custom_value' "+b.jgrid.edit.msg.nodefined,b.jgrid.edit.bClose),"e2"===o?b.jgrid.info_dialog(b.jgrid.errors.errcap,"function 'custom_value' "+b.jgrid.edit.msg.novalue,
 b.jgrid.edit.bClose):b.jgrid.info_dialog(b.jgrid.errors.errcap,o.message,b.jgrid.edit.bClose)}}if(h!==a.p.savedRow[c].v){if(c=b(a).triggerHandler("jqGridBeforeSaveCell",[a.rows[d].id,k,e,d,f]))h=e=c;if(b.isFunction(a.p.beforeSaveCell)&&(c=a.p.beforeSaveCell.call(a,a.rows[d].id,k,e,d,f)))h=e=c;var p=b.jgrid.checkValues.call(a,e,f);if(!0===p[0]){c=b(a).triggerHandler("jqGridBeforeSubmitCell",[a.rows[d].id,k,e,d,f])||{};b.isFunction(a.p.beforeSubmitCell)&&((c=a.p.beforeSubmitCell.call(a,a.rows[d].id,
-k,e,d,f))||(c={}));0<b("input.hasDatepicker",g).length&&b("input.hasDatepicker",g).datepicker("hide");if("remote"==a.p.cellsubmit)if(a.p.cellurl){var m={};a.p.autoencode&&(e=b.jgrid.htmlEncode(e));m[k]=e;l=a.p.prmNames;i=l.id;j=l.oper;m[i]=b.jgrid.stripPref(a.p.idPrefix,a.rows[d].id);m[j]=l.editoper;m=b.extend(c,m);b("#lui_"+b.jgrid.jqID(a.p.id)).show();a.grid.hDiv.loading=!0;b.ajax(b.extend({url:a.p.cellurl,data:b.isFunction(a.p.serializeCellData)?a.p.serializeCellData.call(a,m):m,type:"POST",complete:function(c,
-i){b("#lui_"+a.p.id).hide();a.grid.hDiv.loading=false;if(i=="success"){var j=b(a).triggerHandler("jqGridAfterSubmitCell",[a,c,m.id,k,e,d,f])||[true,""];j[0]===true&&b.isFunction(a.p.afterSubmitCell)&&(j=a.p.afterSubmitCell.call(a,c,m.id,k,e,d,f));if(j[0]===true){b(g).empty();b(a).jqGrid("setCell",a.rows[d].id,f,h,false,false,true);b(g).addClass("dirty-cell");b(a.rows[d]).addClass("edited");b(a).triggerHandler("jqGridAfterSaveCell",[a.rows[d].id,k,e,d,f]);b.isFunction(a.p.afterSaveCell)&&a.p.afterSaveCell.call(a,
+k,e,d,f))||(c={}));0<b("input.hasDatepicker",g).length&&b("input.hasDatepicker",g).datepicker("hide");if("remote"===a.p.cellsubmit)if(a.p.cellurl){var m={};a.p.autoencode&&(e=b.jgrid.htmlEncode(e));m[k]=e;l=a.p.prmNames;i=l.id;j=l.oper;m[i]=b.jgrid.stripPref(a.p.idPrefix,a.rows[d].id);m[j]=l.editoper;m=b.extend(c,m);b("#lui_"+b.jgrid.jqID(a.p.id)).show();a.grid.hDiv.loading=!0;b.ajax(b.extend({url:a.p.cellurl,data:b.isFunction(a.p.serializeCellData)?a.p.serializeCellData.call(a,m):m,type:"POST",complete:function(c,
+i){b("#lui_"+a.p.id).hide();a.grid.hDiv.loading=false;if(i==="success"){var j=b(a).triggerHandler("jqGridAfterSubmitCell",[a,c,m.id,k,e,d,f])||[true,""];j[0]===true&&b.isFunction(a.p.afterSubmitCell)&&(j=a.p.afterSubmitCell.call(a,c,m.id,k,e,d,f));if(j[0]===true){b(g).empty();b(a).jqGrid("setCell",a.rows[d].id,f,h,false,false,true);b(g).addClass("dirty-cell");b(a.rows[d]).addClass("edited");b(a).triggerHandler("jqGridAfterSaveCell",[a.rows[d].id,k,e,d,f]);b.isFunction(a.p.afterSaveCell)&&a.p.afterSaveCell.call(a,
 a.rows[d].id,k,e,d,f);a.p.savedRow.splice(0,1)}else{b.jgrid.info_dialog(b.jgrid.errors.errcap,j[1],b.jgrid.edit.bClose);b(a).jqGrid("restoreCell",d,f)}}},error:function(c,e,h){b("#lui_"+b.jgrid.jqID(a.p.id)).hide();a.grid.hDiv.loading=false;b(a).triggerHandler("jqGridErrorCell",[c,e,h]);b.isFunction(a.p.errorCell)?a.p.errorCell.call(a,c,e,h):b.jgrid.info_dialog(b.jgrid.errors.errcap,c.status+" : "+c.statusText+"<br/>"+e,b.jgrid.edit.bClose);b(a).jqGrid("restoreCell",d,f)}},b.jgrid.ajaxOptions,a.p.ajaxCellOptions||
-{}))}else try{b.jgrid.info_dialog(b.jgrid.errors.errcap,b.jgrid.errors.nourl,b.jgrid.edit.bClose),b(a).jqGrid("restoreCell",d,f)}catch(q){}"clientArray"==a.p.cellsubmit&&(b(g).empty(),b(a).jqGrid("setCell",a.rows[d].id,f,h,!1,!1,!0),b(g).addClass("dirty-cell"),b(a.rows[d]).addClass("edited"),b(a).triggerHandler("jqGridAfterSaveCell",[a.rows[d].id,k,e,d,f]),b.isFunction(a.p.afterSaveCell)&&a.p.afterSaveCell.call(a,a.rows[d].id,k,e,d,f),a.p.savedRow.splice(0,1))}else try{window.setTimeout(function(){b.jgrid.info_dialog(b.jgrid.errors.errcap,
+{}))}else try{b.jgrid.info_dialog(b.jgrid.errors.errcap,b.jgrid.errors.nourl,b.jgrid.edit.bClose),b(a).jqGrid("restoreCell",d,f)}catch(q){}"clientArray"===a.p.cellsubmit&&(b(g).empty(),b(a).jqGrid("setCell",a.rows[d].id,f,h,!1,!1,!0),b(g).addClass("dirty-cell"),b(a.rows[d]).addClass("edited"),b(a).triggerHandler("jqGridAfterSaveCell",[a.rows[d].id,k,e,d,f]),b.isFunction(a.p.afterSaveCell)&&a.p.afterSaveCell.call(a,a.rows[d].id,k,e,d,f),a.p.savedRow.splice(0,1))}else try{window.setTimeout(function(){b.jgrid.info_dialog(b.jgrid.errors.errcap,
 e+" "+p[1],b.jgrid.edit.bClose)},100),b(a).jqGrid("restoreCell",d,f)}catch(r){}}else b(a).jqGrid("restoreCell",d,f)}window.setTimeout(function(){b("#"+b.jgrid.jqID(a.p.knv)).attr("tabindex","-1").focus()},0)}})},restoreCell:function(d,f){return this.each(function(){var a=this,c;if(a.grid&&!0===a.p.cellEdit){c=1<=a.p.savedRow.length?0:null;if(null!==c){var g=b("td:eq("+f+")",a.rows[d]);if(b.isFunction(b.fn.datepicker))try{b("input.hasDatepicker",g).datepicker("hide")}catch(e){}b(g).empty().attr("tabindex",
 "-1");b(a).jqGrid("setCell",a.rows[d].id,f,a.p.savedRow[c].v,!1,!1,!0);b(a).triggerHandler("jqGridAfterRestoreCell",[a.rows[d].id,a.p.savedRow[c].v,d,f]);b.isFunction(a.p.afterRestoreCell)&&a.p.afterRestoreCell.call(a,a.rows[d].id,a.p.savedRow[c].v,d,f);a.p.savedRow.splice(0,1)}window.setTimeout(function(){b("#"+a.p.knv).attr("tabindex","-1").focus()},0)}})},nextCell:function(d,f){return this.each(function(){var a=!1,c;if(this.grid&&!0===this.p.cellEdit){for(c=f+1;c<this.p.colModel.length;c++)if(!0===
-this.p.colModel[c].editable){a=c;break}!1!==a?b(this).jqGrid("editCell",d,a,!0):0<this.p.savedRow.length&&b(this).jqGrid("saveCell",d,f)}})},prevCell:function(d,f){return this.each(function(){var a=!1,c;if(this.grid&&!0===this.p.cellEdit){for(c=f-1;0<=c;c--)if(!0===this.p.colModel[c].editable){a=c;break}!1!==a?b(this).jqGrid("editCell",d,a,!0):0<this.p.savedRow.length&&b(this).jqGrid("saveCell",d,f)}})},GridNav:function(){return this.each(function(){function d(c,d,e){if("v"==e.substr(0,1)){var f=
-b(a.grid.bDiv)[0].clientHeight,g=b(a.grid.bDiv)[0].scrollTop,l=a.rows[c].offsetTop+a.rows[c].clientHeight,o=a.rows[c].offsetTop;"vd"==e&&l>=f&&(b(a.grid.bDiv)[0].scrollTop=b(a.grid.bDiv)[0].scrollTop+a.rows[c].clientHeight);"vu"==e&&o<g&&(b(a.grid.bDiv)[0].scrollTop=b(a.grid.bDiv)[0].scrollTop-a.rows[c].clientHeight)}"h"==e&&(e=b(a.grid.bDiv)[0].clientWidth,f=b(a.grid.bDiv)[0].scrollLeft,g=a.rows[c].cells[d].offsetLeft,a.rows[c].cells[d].offsetLeft+a.rows[c].cells[d].clientWidth>=e+parseInt(f,10)?
-b(a.grid.bDiv)[0].scrollLeft=b(a.grid.bDiv)[0].scrollLeft+a.rows[c].cells[d].clientWidth:g<f&&(b(a.grid.bDiv)[0].scrollLeft=b(a.grid.bDiv)[0].scrollLeft-a.rows[c].cells[d].clientWidth))}function f(b,c){var d,e;if("lft"==c){d=b+1;for(e=b;0<=e;e--)if(!0!==a.p.colModel[e].hidden){d=e;break}}if("rgt"==c){d=b-1;for(e=b;e<a.p.colModel.length;e++)if(!0!==a.p.colModel[e].hidden){d=e;break}}return d}var a=this;if(a.grid&&!0===a.p.cellEdit){a.p.knv=a.p.id+"_kn";var c=b("<div style='position:fixed;top:0px;width:1px;height:1px;' tabindex='0'><div tabindex='-1' style='width:1px;height:1px;' id='"+
-a.p.knv+"'></div></div>"),g,e;b(c).insertBefore(a.grid.cDiv);b("#"+a.p.knv).focus().keydown(function(c){e=c.keyCode;"rtl"==a.p.direction&&(37===e?e=39:39===e&&(e=37));switch(e){case 38:0<a.p.iRow-1&&(d(a.p.iRow-1,a.p.iCol,"vu"),b(a).jqGrid("editCell",a.p.iRow-1,a.p.iCol,!1));break;case 40:a.p.iRow+1<=a.rows.length-1&&(d(a.p.iRow+1,a.p.iCol,"vd"),b(a).jqGrid("editCell",a.p.iRow+1,a.p.iCol,!1));break;case 37:0<=a.p.iCol-1&&(g=f(a.p.iCol-1,"lft"),d(a.p.iRow,g,"h"),b(a).jqGrid("editCell",a.p.iRow,g,!1));
-break;case 39:a.p.iCol+1<=a.p.colModel.length-1&&(g=f(a.p.iCol+1,"rgt"),d(a.p.iRow,g,"h"),b(a).jqGrid("editCell",a.p.iRow,g,!1));break;case 13:0<=parseInt(a.p.iCol,10)&&0<=parseInt(a.p.iRow,10)&&b(a).jqGrid("editCell",a.p.iRow,a.p.iCol,!0);break;default:return!0}return!1})}})},getChangedCells:function(d){var f=[];d||(d="all");this.each(function(){var a=this,c;a.grid&&!0===a.p.cellEdit&&b(a.rows).each(function(g){var e={};b(this).hasClass("edited")&&(b("td",this).each(function(f){c=a.p.colModel[f].name;
-if("cb"!==c&&"subgrid"!==c)if("dirty"==d){if(b(this).hasClass("dirty-cell"))try{e[c]=b.unformat.call(a,this,{rowId:a.rows[g].id,colModel:a.p.colModel[f]},f)}catch(i){e[c]=b.jgrid.htmlDecode(b(this).html())}}else try{e[c]=b.unformat.call(a,this,{rowId:a.rows[g].id,colModel:a.p.colModel[f]},f)}catch(k){e[c]=b.jgrid.htmlDecode(b(this).html())}}),e.id=this.id,f.push(e))})});return f}})})(jQuery);
+this.p.colModel[c].editable){a=c;break}!1!==a?b(this).jqGrid("editCell",d,a,!0):0<this.p.savedRow.length&&b(this).jqGrid("saveCell",d,f)}})},prevCell:function(d,f){return this.each(function(){var a=!1,c;if(this.grid&&!0===this.p.cellEdit){for(c=f-1;0<=c;c--)if(!0===this.p.colModel[c].editable){a=c;break}!1!==a?b(this).jqGrid("editCell",d,a,!0):0<this.p.savedRow.length&&b(this).jqGrid("saveCell",d,f)}})},GridNav:function(){return this.each(function(){function d(c,d,e){if("v"===e.substr(0,1)){var f=
+b(a.grid.bDiv)[0].clientHeight,g=b(a.grid.bDiv)[0].scrollTop,l=a.rows[c].offsetTop+a.rows[c].clientHeight,o=a.rows[c].offsetTop;"vd"===e&&l>=f&&(b(a.grid.bDiv)[0].scrollTop=b(a.grid.bDiv)[0].scrollTop+a.rows[c].clientHeight);"vu"===e&&o<g&&(b(a.grid.bDiv)[0].scrollTop=b(a.grid.bDiv)[0].scrollTop-a.rows[c].clientHeight)}"h"===e&&(e=b(a.grid.bDiv)[0].clientWidth,f=b(a.grid.bDiv)[0].scrollLeft,g=a.rows[c].cells[d].offsetLeft,a.rows[c].cells[d].offsetLeft+a.rows[c].cells[d].clientWidth>=e+parseInt(f,
+10)?b(a.grid.bDiv)[0].scrollLeft=b(a.grid.bDiv)[0].scrollLeft+a.rows[c].cells[d].clientWidth:g<f&&(b(a.grid.bDiv)[0].scrollLeft=b(a.grid.bDiv)[0].scrollLeft-a.rows[c].cells[d].clientWidth))}function f(b,c){var d,e;if("lft"===c){d=b+1;for(e=b;0<=e;e--)if(!0!==a.p.colModel[e].hidden){d=e;break}}if("rgt"===c){d=b-1;for(e=b;e<a.p.colModel.length;e++)if(!0!==a.p.colModel[e].hidden){d=e;break}}return d}var a=this;if(a.grid&&!0===a.p.cellEdit){a.p.knv=a.p.id+"_kn";var c=b("<div style='position:fixed;top:0px;width:1px;height:1px;' tabindex='0'><div tabindex='-1' style='width:1px;height:1px;' id='"+
+a.p.knv+"'></div></div>"),g,e;b(c).insertBefore(a.grid.cDiv);b("#"+a.p.knv).focus().keydown(function(c){e=c.keyCode;"rtl"===a.p.direction&&(37===e?e=39:39===e&&(e=37));switch(e){case 38:0<a.p.iRow-1&&(d(a.p.iRow-1,a.p.iCol,"vu"),b(a).jqGrid("editCell",a.p.iRow-1,a.p.iCol,!1));break;case 40:a.p.iRow+1<=a.rows.length-1&&(d(a.p.iRow+1,a.p.iCol,"vd"),b(a).jqGrid("editCell",a.p.iRow+1,a.p.iCol,!1));break;case 37:0<=a.p.iCol-1&&(g=f(a.p.iCol-1,"lft"),d(a.p.iRow,g,"h"),b(a).jqGrid("editCell",a.p.iRow,g,
+!1));break;case 39:a.p.iCol+1<=a.p.colModel.length-1&&(g=f(a.p.iCol+1,"rgt"),d(a.p.iRow,g,"h"),b(a).jqGrid("editCell",a.p.iRow,g,!1));break;case 13:0<=parseInt(a.p.iCol,10)&&0<=parseInt(a.p.iRow,10)&&b(a).jqGrid("editCell",a.p.iRow,a.p.iCol,!0);break;default:return!0}return!1})}})},getChangedCells:function(d){var f=[];d||(d="all");this.each(function(){var a=this,c;a.grid&&!0===a.p.cellEdit&&b(a.rows).each(function(g){var e={};b(this).hasClass("edited")&&(b("td",this).each(function(f){c=a.p.colModel[f].name;
+if("cb"!==c&&"subgrid"!==c)if("dirty"===d){if(b(this).hasClass("dirty-cell"))try{e[c]=b.unformat.call(a,this,{rowId:a.rows[g].id,colModel:a.p.colModel[f]},f)}catch(i){e[c]=b.jgrid.htmlDecode(b(this).html())}}else try{e[c]=b.unformat.call(a,this,{rowId:a.rows[g].id,colModel:a.p.colModel[f]},f)}catch(k){e[c]=b.jgrid.htmlDecode(b(this).html())}}),e.id=this.id,f.push(e))})});return f}})})(jQuery);
 (function(c){c.fn.jqm=function(a){var i={overlay:50,closeoverlay:!0,overlayClass:"jqmOverlay",closeClass:"jqmClose",trigger:".jqModal",ajax:d,ajaxText:"",target:d,modal:d,toTop:d,onShow:d,onHide:d,onLoad:d};return this.each(function(){if(this._jqm)return j[this._jqm].c=c.extend({},j[this._jqm].c,a);l++;this._jqm=l;j[l]={c:c.extend(i,c.jqm.params,a),a:d,w:c(this).addClass("jqmID"+l),s:l};i.trigger&&c(this).jqmAddTrigger(i.trigger)})};c.fn.jqmAddClose=function(a){return o(this,a,"jqmHide")};c.fn.jqmAddTrigger=
 function(a){return o(this,a,"jqmShow")};c.fn.jqmShow=function(a){return this.each(function(){c.jqm.open(this._jqm,a)})};c.fn.jqmHide=function(a){return this.each(function(){c.jqm.close(this._jqm,a)})};c.jqm={hash:{},open:function(a,i){var b=j[a],e=b.c,h="."+e.closeClass,f=parseInt(b.w.css("z-index")),f=0<f?f:3E3,g=c("<div></div>").css({height:"100%",width:"100%",position:"fixed",left:0,top:0,"z-index":f-1,opacity:e.overlay/100});if(b.a)return d;b.t=i;b.a=!0;b.w.css("z-index",f);e.modal?(k[0]||setTimeout(function(){p("bind")},
 1),k.push(a)):0<e.overlay?e.closeoverlay&&b.w.jqmAddClose(g):g=d;b.o=g?g.addClass(e.overlayClass).prependTo("body"):d;e.ajax?(f=e.target||b.w,g=e.ajax,f="string"==typeof f?c(f,b.w):c(f),g="@"==g.substr(0,1)?c(i).attr(g.substring(1)):g,f.html(e.ajaxText).load(g,function(){e.onLoad&&e.onLoad.call(this,b);h&&b.w.jqmAddClose(c(h,b.w));m(b)})):h&&b.w.jqmAddClose(c(h,b.w));e.toTop&&b.o&&b.w.before('<span id="jqmP'+b.w[0]._jqm+'"></span>').insertAfter(b.o);e.onShow?e.onShow(b):b.w.show();m(b);return d},
@@ -464,32 +466,33 @@ r}for(o=0;o<t;o++)if(x[o]){n="";e.groupCollapse&&!e.showSummaryOnHide&&(n=' styl
 y);try{v=a.formatter("",this.v,p,this)}catch(b){v=this.v}z="<td "+a.formatCol(p,1,"")+">"+d.jgrid.format(A,v)+"</td>";return!1}});h+=z}h+="</tr>"}t=r}});d("#"+d.jgrid.jqID(a.p.id)+" tbody:first").append(h);h=null})},groupingGroupBy:function(b,g){return this.each(function(){"string"===typeof b&&(b=[b]);var f=this.p.groupingView;this.p.grouping=!0;void 0===f.visibiltyOnNextGrouping&&(f.visibiltyOnNextGrouping=[]);var a;for(a=0;a<f.groupField.length;a++)!f.groupColumnShow[a]&&f.visibiltyOnNextGrouping[a]&&
 d(this).jqGrid("showCol",f.groupField[a]);for(a=0;a<b.length;a++)f.visibiltyOnNextGrouping[a]=d("#"+d.jgrid.jqID(this.p.id)+"_"+d.jgrid.jqID(b[a])).is(":visible");this.p.groupingView=d.extend(this.p.groupingView,g||{});f.groupField=b;d(this).trigger("reloadGrid")})},groupingRemove:function(b){return this.each(function(){void 0===b&&(b=!0);this.p.grouping=!1;if(!0===b){var g=this.p.groupingView,f;for(f=0;f<g.groupField.length;f++)!g.groupColumnShow[f]&&g.visibiltyOnNextGrouping[f]&&d(this).jqGrid("showCol",
 g.groupField);d("tr.jqgroup, tr.jqfoot","#"+d.jgrid.jqID(this.p.id)+" tbody:first").remove();d("tr.jqgrow:hidden","#"+d.jgrid.jqID(this.p.id)+" tbody:first").show()}else d(this).trigger("reloadGrid")})},groupingCalculations:{handler:function(b,d,f,a,e,h){var c={sum:function(){return parseFloat(d||0)+parseFloat(h[f]||0)},min:function(){return""===d?parseFloat(h[f]||0):Math.min(parseFloat(d),parseFloat(h[f]||0))},max:function(){return""===d?parseFloat(h[f]||0):Math.max(parseFloat(d),parseFloat(h[f]||
-0))},count:function(){""===d&&(d=0);return h.hasOwnProperty(f)?d+1:0},avg:function(){return c.sum()}};if(!c[b])throw"jqGrid Grouping No such method: "+b;b=c[b]();null!=a&&("fixed"==e?b=b.toFixed(a):(a=Math.pow(10,a),b=Math.round(b*a)/a));return b}}})})(jQuery);
-(function(d){d.jgrid.extend({setTreeNode:function(b,c){return this.each(function(){var a=this;if(a.grid&&a.p.treeGrid)for(var h=a.p.expColInd,e=a.p.treeReader.expanded_field,i=a.p.treeReader.leaf_field,g=a.p.treeReader.level_field,f=a.p.treeReader.icon_field,l=a.p.treeReader.loaded,k,m,n,j;b<c;)j=a.p.data[a.p._index[a.rows[b].id]],"nested"==a.p.treeGridModel&&!j[i]&&(k=parseInt(j[a.p.treeReader.left_field],10),m=parseInt(j[a.p.treeReader.right_field],10),j[i]=m===k+1?"true":"false",a.rows[b].cells[a.p._treeleafpos].innerHTML=
-j[i]),k=parseInt(j[g],10),0===a.p.tree_root_level?(n=k+1,m=k):(n=k,m=k-1),n="<div class='tree-wrap tree-wrap-"+a.p.direction+"' style='width:"+18*n+"px;'>",n+="<div style='"+("rtl"==a.p.direction?"right:":"left:")+18*m+"px;' class='ui-icon ",void 0!==j[l]&&(j[l]="true"==j[l]||!0===j[l]?!0:!1),"true"==j[i]||!0===j[i]?(n+=(void 0!==j[f]&&""!==j[f]?j[f]:a.p.treeIcons.leaf)+" tree-leaf treeclick",j[i]=!0,m="leaf"):(j[i]=!1,m=""),j[e]=("true"==j[e]||!0===j[e]?!0:!1)&&(j[l]||void 0===j[l]),n=!1===j[e]?
-n+(!0===j[i]?"'":a.p.treeIcons.plus+" tree-plus treeclick'"):n+(!0===j[i]?"'":a.p.treeIcons.minus+" tree-minus treeclick'"),n+="></div></div>",d(a.rows[b].cells[h]).wrapInner("<span class='cell-wrapper"+m+"'></span>").prepend(n),k!==parseInt(a.p.tree_root_level,10)&&((j=(j=d(a).jqGrid("getNodeParent",j))&&j.hasOwnProperty(e)?j[e]:!0)||d(a.rows[b]).css("display","none")),d(a.rows[b].cells[h]).find("div.treeclick").bind("click",function(b){b=d(b.target||b.srcElement,a.rows).closest("tr.jqgrow")[0].id;
-b=a.p._index[b];if(!a.p.data[b][i])if(a.p.data[b][e]){d(a).jqGrid("collapseRow",a.p.data[b]);d(a).jqGrid("collapseNode",a.p.data[b])}else{d(a).jqGrid("expandRow",a.p.data[b]);d(a).jqGrid("expandNode",a.p.data[b])}return false}),!0===a.p.ExpandColClick&&d(a.rows[b].cells[h]).find("span.cell-wrapper").css("cursor","pointer").bind("click",function(b){var b=d(b.target||b.srcElement,a.rows).closest("tr.jqgrow")[0].id,c=a.p._index[b];if(!a.p.data[c][i])if(a.p.data[c][e]){d(a).jqGrid("collapseRow",a.p.data[c]);
-d(a).jqGrid("collapseNode",a.p.data[c])}else{d(a).jqGrid("expandRow",a.p.data[c]);d(a).jqGrid("expandNode",a.p.data[c])}d(a).jqGrid("setSelection",b);return false}),b++})},setTreeGrid:function(){return this.each(function(){var b=this,c=0,a=!1,h,e,i,g=[];if(b.p.treeGrid){b.p.treedatatype||d.extend(b.p,{treedatatype:b.p.datatype});b.p.subGrid=!1;b.p.altRows=!1;b.p.pgbuttons=!1;b.p.pginput=!1;b.p.gridview=!0;null===b.p.rowTotal&&(b.p.rowNum=1E4);b.p.multiselect=!1;b.p.rowList=[];b.p.expColInd=0;b.p.treeIcons=
-d.extend({plus:"ui-icon-triangle-1-"+("rtl"==b.p.direction?"w":"e"),minus:"ui-icon-triangle-1-s",leaf:"ui-icon-radio-off"},b.p.treeIcons||{});"nested"==b.p.treeGridModel?b.p.treeReader=d.extend({level_field:"level",left_field:"lft",right_field:"rgt",leaf_field:"isLeaf",expanded_field:"expanded",loaded:"loaded",icon_field:"icon"},b.p.treeReader):"adjacency"==b.p.treeGridModel&&(b.p.treeReader=d.extend({level_field:"level",parent_id_field:"parent",leaf_field:"isLeaf",expanded_field:"expanded",loaded:"loaded",
-icon_field:"icon"},b.p.treeReader));for(e in b.p.colModel)if(b.p.colModel.hasOwnProperty(e))for(i in h=b.p.colModel[e].name,h==b.p.ExpandColumn&&!a&&(a=!0,b.p.expColInd=c),c++,b.p.treeReader)b.p.treeReader.hasOwnProperty(i)&&b.p.treeReader[i]==h&&g.push(h);d.each(b.p.treeReader,function(a,e){if(e&&d.inArray(e,g)===-1){if(a==="leaf_field")b.p._treeleafpos=c;c++;b.p.colNames.push(e);b.p.colModel.push({name:e,width:1,hidden:true,sortable:false,resizable:false,hidedlg:true,editable:true,search:false})}})}})},
-expandRow:function(b){this.each(function(){var c=this;if(c.grid&&c.p.treeGrid){var a=d(c).jqGrid("getNodeChildren",b),h=c.p.treeReader.expanded_field,e=c.rows;d(a).each(function(){var a=d.jgrid.getAccessor(this,c.p.localReader.id);d(e.namedItem(a)).css("display","");this[h]&&d(c).jqGrid("expandRow",this)})}})},collapseRow:function(b){this.each(function(){var c=this;if(c.grid&&c.p.treeGrid){var a=d(c).jqGrid("getNodeChildren",b),h=c.p.treeReader.expanded_field,e=c.rows;d(a).each(function(){var a=d.jgrid.getAccessor(this,
-c.p.localReader.id);d(e.namedItem(a)).css("display","none");this[h]&&d(c).jqGrid("collapseRow",this)})}})},getRootNodes:function(){var b=[];this.each(function(){var c=this;if(c.grid&&c.p.treeGrid)switch(c.p.treeGridModel){case "nested":var a=c.p.treeReader.level_field;d(c.p.data).each(function(){parseInt(this[a],10)===parseInt(c.p.tree_root_level,10)&&b.push(this)});break;case "adjacency":var h=c.p.treeReader.parent_id_field;d(c.p.data).each(function(){(null===this[h]||"null"==(""+this[h]).toLowerCase())&&
-b.push(this)})}});return b},getNodeDepth:function(b){var c=null;this.each(function(){if(this.grid&&this.p.treeGrid)switch(this.p.treeGridModel){case "nested":c=parseInt(b[this.p.treeReader.level_field],10)-parseInt(this.p.tree_root_level,10);break;case "adjacency":c=d(this).jqGrid("getNodeAncestors",b).length}});return c},getNodeParent:function(b){var c=null;this.each(function(){var a=this;if(a.grid&&a.p.treeGrid)switch(a.p.treeGridModel){case "nested":var h=a.p.treeReader.left_field,e=a.p.treeReader.right_field,
-i=a.p.treeReader.level_field,g=parseInt(b[h],10),f=parseInt(b[e],10),l=parseInt(b[i],10);d(this.p.data).each(function(){if(parseInt(this[i],10)===l-1&&parseInt(this[h],10)<g&&parseInt(this[e],10)>f)return c=this,!1});break;case "adjacency":var k=a.p.treeReader.parent_id_field,m=a.p.localReader.id;d(this.p.data).each(function(){if(this[m]===d.jgrid.stripPref(a.p.idPrefix,b[k]))return c=this,!1})}});return c},getNodeChildren:function(b){var c=[];this.each(function(){var a=this;if(a.grid&&a.p.treeGrid)switch(a.p.treeGridModel){case "nested":var h=
-a.p.treeReader.left_field,e=a.p.treeReader.right_field,i=a.p.treeReader.level_field,g=parseInt(b[h],10),f=parseInt(b[e],10),l=parseInt(b[i],10);d(this.p.data).each(function(){parseInt(this[i],10)===l+1&&parseInt(this[h],10)>g&&parseInt(this[e],10)<f&&c.push(this)});break;case "adjacency":var k=a.p.treeReader.parent_id_field,m=a.p.localReader.id;d(this.p.data).each(function(){this[k]===d.jgrid.stripPref(a.p.idPrefix,b[m])&&c.push(this)})}});return c},getFullTreeNode:function(b){var c=[];this.each(function(){var a=
-this,h;if(a.grid&&a.p.treeGrid)switch(a.p.treeGridModel){case "nested":var e=a.p.treeReader.left_field,i=a.p.treeReader.right_field,g=a.p.treeReader.level_field,f=parseInt(b[e],10),l=parseInt(b[i],10),k=parseInt(b[g],10);d(this.p.data).each(function(){parseInt(this[g],10)>=k&&parseInt(this[e],10)>=f&&parseInt(this[e],10)<=l&&c.push(this)});break;case "adjacency":if(b){c.push(b);var m=a.p.treeReader.parent_id_field,n=a.p.localReader.id;d(this.p.data).each(function(b){h=c.length;for(b=0;b<h;b++)if(d.jgrid.stripPref(a.p.idPrefix,
-c[b][n])===this[m]){c.push(this);break}})}}});return c},getNodeAncestors:function(b){var c=[];this.each(function(){if(this.grid&&this.p.treeGrid)for(var a=d(this).jqGrid("getNodeParent",b);a;)c.push(a),a=d(this).jqGrid("getNodeParent",a)});return c},isVisibleNode:function(b){var c=!0;this.each(function(){if(this.grid&&this.p.treeGrid){var a=d(this).jqGrid("getNodeAncestors",b),h=this.p.treeReader.expanded_field;d(a).each(function(){c=c&&this[h];if(!c)return!1})}});return c},isNodeLoaded:function(b){var c;
-this.each(function(){if(this.grid&&this.p.treeGrid){var a=this.p.treeReader.leaf_field;c=void 0!==b?void 0!==b.loaded?b.loaded:b[a]||0<d(this).jqGrid("getNodeChildren",b).length?!0:!1:!1}});return c},expandNode:function(b){return this.each(function(){if(this.grid&&this.p.treeGrid){var c=this.p.treeReader.expanded_field,a=this.p.treeReader.parent_id_field,h=this.p.treeReader.loaded,e=this.p.treeReader.level_field,i=this.p.treeReader.left_field,g=this.p.treeReader.right_field;if(!b[c]){var f=d.jgrid.getAccessor(b,
-this.p.localReader.id),l=d("#"+d.jgrid.jqID(f),this.grid.bDiv)[0],k=this.p._index[f];d(this).jqGrid("isNodeLoaded",this.p.data[k])?(b[c]=!0,d("div.treeclick",l).removeClass(this.p.treeIcons.plus+" tree-plus").addClass(this.p.treeIcons.minus+" tree-minus")):this.grid.hDiv.loading||(b[c]=!0,d("div.treeclick",l).removeClass(this.p.treeIcons.plus+" tree-plus").addClass(this.p.treeIcons.minus+" tree-minus"),this.p.treeANode=l.rowIndex,this.p.datatype=this.p.treedatatype,"nested"==this.p.treeGridModel?
-d(this).jqGrid("setGridParam",{postData:{nodeid:f,n_left:b[i],n_right:b[g],n_level:b[e]}}):d(this).jqGrid("setGridParam",{postData:{nodeid:f,parentid:b[a],n_level:b[e]}}),d(this).trigger("reloadGrid"),b[h]=!0,"nested"==this.p.treeGridModel?d(this).jqGrid("setGridParam",{postData:{nodeid:"",n_left:"",n_right:"",n_level:""}}):d(this).jqGrid("setGridParam",{postData:{nodeid:"",parentid:"",n_level:""}}))}}})},collapseNode:function(b){return this.each(function(){if(this.grid&&this.p.treeGrid){var c=this.p.treeReader.expanded_field;
-b[c]&&(b[c]=!1,c=d.jgrid.getAccessor(b,this.p.localReader.id),c=d("#"+d.jgrid.jqID(c),this.grid.bDiv)[0],d("div.treeclick",c).removeClass(this.p.treeIcons.minus+" tree-minus").addClass(this.p.treeIcons.plus+" tree-plus"))}})},SortTree:function(b,c,a,h){return this.each(function(){if(this.grid&&this.p.treeGrid){var e,i,g,f=[],l=this,k;e=d(this).jqGrid("getRootNodes");e=d.jgrid.from(e);e.orderBy(b,c,a,h);k=e.select();e=0;for(i=k.length;e<i;e++)g=k[e],f.push(g),d(this).jqGrid("collectChildrenSortTree",
-f,g,b,c,a,h);d.each(f,function(a){var b=d.jgrid.getAccessor(this,l.p.localReader.id);d("#"+d.jgrid.jqID(l.p.id)+" tbody tr:eq("+a+")").after(d("tr#"+d.jgrid.jqID(b),l.grid.bDiv))});f=k=e=null}})},collectChildrenSortTree:function(b,c,a,h,e,i){return this.each(function(){if(this.grid&&this.p.treeGrid){var g,f,l,k;g=d(this).jqGrid("getNodeChildren",c);g=d.jgrid.from(g);g.orderBy(a,h,e,i);k=g.select();g=0;for(f=k.length;g<f;g++)l=k[g],b.push(l),d(this).jqGrid("collectChildrenSortTree",b,l,a,h,e,i)}})},
-setTreeRow:function(b,c){var a=!1;this.each(function(){this.grid&&this.p.treeGrid&&(a=d(this).jqGrid("setRowData",b,c))});return a},delTreeNode:function(b){return this.each(function(){var c=this.p.localReader.id,a,h=this.p.treeReader.left_field,e=this.p.treeReader.right_field,i,g,f;if(this.grid&&this.p.treeGrid&&(a=this.p._index[b],void 0!==a)){i=parseInt(this.p.data[a][e],10);g=i-parseInt(this.p.data[a][h],10)+1;var l=d(this).jqGrid("getFullTreeNode",this.p.data[a]);if(0<l.length)for(a=0;a<l.length;a++)d(this).jqGrid("delRowData",
-l[a][c]);if("nested"===this.p.treeGridModel){c=d.jgrid.from(this.p.data).greater(h,i,{stype:"integer"}).select();if(c.length)for(f in c)c.hasOwnProperty(f)&&(c[f][h]=parseInt(c[f][h],10)-g);c=d.jgrid.from(this.p.data).greater(e,i,{stype:"integer"}).select();if(c.length)for(f in c)c.hasOwnProperty(f)&&(c[f][e]=parseInt(c[f][e],10)-g)}}})},addChildNode:function(b,c,a,h){var e=this[0];if(a){var i=e.p.treeReader.expanded_field,g=e.p.treeReader.leaf_field,f=e.p.treeReader.level_field,l=e.p.treeReader.parent_id_field,
-k=e.p.treeReader.left_field,m=e.p.treeReader.right_field,n=e.p.treeReader.loaded,j,r,q,t,p;j=0;var s=c,u;void 0===h&&(h=!1);if(void 0===b||null===b){p=e.p.data.length-1;if(0<=p)for(;0<=p;)j=Math.max(j,parseInt(e.p.data[p][e.p.localReader.id],10)),p--;b=j+1}var v=d(e).jqGrid("getInd",c);u=!1;if(void 0===c||null===c||""===c)s=c=null,j="last",t=e.p.tree_root_level,p=e.p.data.length+1;else if(j="after",r=e.p._index[c],q=e.p.data[r],c=q[e.p.localReader.id],t=parseInt(q[f],10)+1,p=d(e).jqGrid("getFullTreeNode",
-q),p.length?(s=p=p[p.length-1][e.p.localReader.id],p=d(e).jqGrid("getInd",s)+1):p=d(e).jqGrid("getInd",c)+1,q[g])u=!0,q[i]=!0,d(e.rows[v]).find("span.cell-wrapperleaf").removeClass("cell-wrapperleaf").addClass("cell-wrapper").end().find("div.tree-leaf").removeClass(e.p.treeIcons.leaf+" tree-leaf").addClass(e.p.treeIcons.minus+" tree-minus"),e.p.data[r][g]=!1,q[n]=!0;r=p+1;void 0===a[i]&&(a[i]=!1);void 0===a[n]&&(a[n]=!1);a[f]=t;void 0===a[g]&&(a[g]=!0);"adjacency"===e.p.treeGridModel&&(a[l]=c);if("nested"===
-e.p.treeGridModel){var o;if(null!==c){g=parseInt(q[m],10);f=d.jgrid.from(e.p.data);f=f.greaterOrEquals(m,g,{stype:"integer"});f=f.select();if(f.length)for(o in f)f.hasOwnProperty(o)&&(f[o][k]=f[o][k]>g?parseInt(f[o][k],10)+2:f[o][k],f[o][m]=f[o][m]>=g?parseInt(f[o][m],10)+2:f[o][m]);a[k]=g;a[m]=g+1}else{g=parseInt(d(e).jqGrid("getCol",m,!1,"max"),10);f=d.jgrid.from(e.p.data).greater(k,g,{stype:"integer"}).select();if(f.length)for(o in f)f.hasOwnProperty(o)&&(f[o][k]=parseInt(f[o][k],10)+2);f=d.jgrid.from(e.p.data).greater(m,
-g,{stype:"integer"}).select();if(f.length)for(o in f)f.hasOwnProperty(o)&&(f[o][m]=parseInt(f[o][m],10)+2);a[k]=g+1;a[m]=g+2}}if(null===c||d(e).jqGrid("isNodeLoaded",q)||u)d(e).jqGrid("addRowData",b,a,j,s),d(e).jqGrid("setTreeNode",p,r);q&&!q[i]&&h&&d(e.rows[v]).find("div.treeclick").click()}}})})(jQuery);
+0))},count:function(){""===d&&(d=0);return h.hasOwnProperty(f)?d+1:0},avg:function(){return c.sum()}};if(!c[b])throw"jqGrid Grouping No such method: "+b;b=c[b]();null!=a&&("fixed"===e?b=b.toFixed(a):(a=Math.pow(10,a),b=Math.round(b*a)/a));return b}}})})(jQuery);
+(function(d){d.jgrid.extend({setTreeNode:function(b,c){return this.each(function(){var a=this;if(a.grid&&a.p.treeGrid)for(var h=a.p.expColInd,e=a.p.treeReader.expanded_field,i=a.p.treeReader.leaf_field,g=a.p.treeReader.level_field,f=a.p.treeReader.icon_field,l=a.p.treeReader.loaded,k,m,n,j;b<c;)j=d.jgrid.stripPref(a.p.idPrefix,a.rows[b].id),j=a.p.data[a.p._index[j]],"nested"===a.p.treeGridModel&&!j[i]&&(k=parseInt(j[a.p.treeReader.left_field],10),m=parseInt(j[a.p.treeReader.right_field],10),j[i]=
+m===k+1?"true":"false",a.rows[b].cells[a.p._treeleafpos].innerHTML=j[i]),k=parseInt(j[g],10),0===a.p.tree_root_level?(n=k+1,m=k):(n=k,m=k-1),n="<div class='tree-wrap tree-wrap-"+a.p.direction+"' style='width:"+18*n+"px;'>",n+="<div style='"+("rtl"===a.p.direction?"right:":"left:")+18*m+"px;' class='ui-icon ",void 0!==j[l]&&(j[l]="true"===j[l]||!0===j[l]?!0:!1),"true"===j[i]||!0===j[i]?(n+=(void 0!==j[f]&&""!==j[f]?j[f]:a.p.treeIcons.leaf)+" tree-leaf treeclick",j[i]=!0,m="leaf"):(j[i]=!1,m=""),j[e]=
+("true"===j[e]||!0===j[e]?!0:!1)&&(j[l]||void 0===j[l]),n=!1===j[e]?n+(!0===j[i]?"'":a.p.treeIcons.plus+" tree-plus treeclick'"):n+(!0===j[i]?"'":a.p.treeIcons.minus+" tree-minus treeclick'"),n+="></div></div>",d(a.rows[b].cells[h]).wrapInner("<span class='cell-wrapper"+m+"'></span>").prepend(n),k!==parseInt(a.p.tree_root_level,10)&&((j=(j=d(a).jqGrid("getNodeParent",j))&&j.hasOwnProperty(e)?j[e]:!0)||d(a.rows[b]).css("display","none")),d(a.rows[b].cells[h]).find("div.treeclick").bind("click",function(b){b=
+d.jgrid.stripPref(a.p.idPrefix,d(b.target||b.srcElement,a.rows).closest("tr.jqgrow")[0].id);b=a.p._index[b];if(!a.p.data[b][i])if(a.p.data[b][e]){d(a).jqGrid("collapseRow",a.p.data[b]);d(a).jqGrid("collapseNode",a.p.data[b])}else{d(a).jqGrid("expandRow",a.p.data[b]);d(a).jqGrid("expandNode",a.p.data[b])}return false}),!0===a.p.ExpandColClick&&d(a.rows[b].cells[h]).find("span.cell-wrapper").css("cursor","pointer").bind("click",function(b){var b=d.jgrid.stripPref(a.p.idPrefix,d(b.target||b.srcElement,
+a.rows).closest("tr.jqgrow")[0].id),c=a.p._index[b];if(!a.p.data[c][i])if(a.p.data[c][e]){d(a).jqGrid("collapseRow",a.p.data[c]);d(a).jqGrid("collapseNode",a.p.data[c])}else{d(a).jqGrid("expandRow",a.p.data[c]);d(a).jqGrid("expandNode",a.p.data[c])}d(a).jqGrid("setSelection",b);return false}),b++})},setTreeGrid:function(){return this.each(function(){var b=this,c=0,a=!1,h,e,i,g=[];if(b.p.treeGrid){b.p.treedatatype||d.extend(b.p,{treedatatype:b.p.datatype});b.p.subGrid=!1;b.p.altRows=!1;b.p.pgbuttons=
+!1;b.p.pginput=!1;b.p.gridview=!0;null===b.p.rowTotal&&(b.p.rowNum=1E4);b.p.multiselect=!1;b.p.rowList=[];b.p.expColInd=0;b.p.treeIcons=d.extend({plus:"ui-icon-triangle-1-"+("rtl"===b.p.direction?"w":"e"),minus:"ui-icon-triangle-1-s",leaf:"ui-icon-radio-off"},b.p.treeIcons||{});"nested"===b.p.treeGridModel?b.p.treeReader=d.extend({level_field:"level",left_field:"lft",right_field:"rgt",leaf_field:"isLeaf",expanded_field:"expanded",loaded:"loaded",icon_field:"icon"},b.p.treeReader):"adjacency"===b.p.treeGridModel&&
+(b.p.treeReader=d.extend({level_field:"level",parent_id_field:"parent",leaf_field:"isLeaf",expanded_field:"expanded",loaded:"loaded",icon_field:"icon"},b.p.treeReader));for(e in b.p.colModel)if(b.p.colModel.hasOwnProperty(e))for(i in h=b.p.colModel[e].name,h===b.p.ExpandColumn&&!a&&(a=!0,b.p.expColInd=c),c++,b.p.treeReader)b.p.treeReader.hasOwnProperty(i)&&b.p.treeReader[i]===h&&g.push(h);d.each(b.p.treeReader,function(a,e){if(e&&d.inArray(e,g)===-1){if(a==="leaf_field")b.p._treeleafpos=c;c++;b.p.colNames.push(e);
+b.p.colModel.push({name:e,width:1,hidden:true,sortable:false,resizable:false,hidedlg:true,editable:true,search:false})}})}})},expandRow:function(b){this.each(function(){var c=this;if(c.grid&&c.p.treeGrid){var a=d(c).jqGrid("getNodeChildren",b),h=c.p.treeReader.expanded_field,e=c.rows;d(a).each(function(){var a=c.p.idPrefix+d.jgrid.getAccessor(this,c.p.localReader.id);d(e.namedItem(a)).css("display","");this[h]&&d(c).jqGrid("expandRow",this)})}})},collapseRow:function(b){this.each(function(){var c=
+this;if(c.grid&&c.p.treeGrid){var a=d(c).jqGrid("getNodeChildren",b),h=c.p.treeReader.expanded_field,e=c.rows;d(a).each(function(){var a=c.p.idPrefix+d.jgrid.getAccessor(this,c.p.localReader.id);d(e.namedItem(a)).css("display","none");this[h]&&d(c).jqGrid("collapseRow",this)})}})},getRootNodes:function(){var b=[];this.each(function(){var c=this;if(c.grid&&c.p.treeGrid)switch(c.p.treeGridModel){case "nested":var a=c.p.treeReader.level_field;d(c.p.data).each(function(){parseInt(this[a],10)===parseInt(c.p.tree_root_level,
+10)&&b.push(this)});break;case "adjacency":var h=c.p.treeReader.parent_id_field;d(c.p.data).each(function(){(null===this[h]||"null"===(""+this[h]).toLowerCase())&&b.push(this)})}});return b},getNodeDepth:function(b){var c=null;this.each(function(){if(this.grid&&this.p.treeGrid)switch(this.p.treeGridModel){case "nested":c=parseInt(b[this.p.treeReader.level_field],10)-parseInt(this.p.tree_root_level,10);break;case "adjacency":c=d(this).jqGrid("getNodeAncestors",b).length}});return c},getNodeParent:function(b){var c=
+null;this.each(function(){var a=this;if(a.grid&&a.p.treeGrid)switch(a.p.treeGridModel){case "nested":var h=a.p.treeReader.left_field,e=a.p.treeReader.right_field,i=a.p.treeReader.level_field,g=parseInt(b[h],10),f=parseInt(b[e],10),l=parseInt(b[i],10);d(this.p.data).each(function(){if(parseInt(this[i],10)===l-1&&parseInt(this[h],10)<g&&parseInt(this[e],10)>f)return c=this,!1});break;case "adjacency":var k=a.p.treeReader.parent_id_field,m=a.p.localReader.id;d(this.p.data).each(function(){if(this[m]===
+d.jgrid.stripPref(a.p.idPrefix,b[k]))return c=this,!1})}});return c},getNodeChildren:function(b){var c=[];this.each(function(){var a=this;if(a.grid&&a.p.treeGrid)switch(a.p.treeGridModel){case "nested":var h=a.p.treeReader.left_field,e=a.p.treeReader.right_field,i=a.p.treeReader.level_field,g=parseInt(b[h],10),f=parseInt(b[e],10),l=parseInt(b[i],10);d(this.p.data).each(function(){parseInt(this[i],10)===l+1&&parseInt(this[h],10)>g&&parseInt(this[e],10)<f&&c.push(this)});break;case "adjacency":var k=
+a.p.treeReader.parent_id_field,m=a.p.localReader.id;d(this.p.data).each(function(){this[k]==d.jgrid.stripPref(a.p.idPrefix,b[m])&&c.push(this)})}});return c},getFullTreeNode:function(b){var c=[];this.each(function(){var a=this,h;if(a.grid&&a.p.treeGrid)switch(a.p.treeGridModel){case "nested":var e=a.p.treeReader.left_field,i=a.p.treeReader.right_field,g=a.p.treeReader.level_field,f=parseInt(b[e],10),l=parseInt(b[i],10),k=parseInt(b[g],10);d(this.p.data).each(function(){parseInt(this[g],10)>=k&&parseInt(this[e],
+10)>=f&&parseInt(this[e],10)<=l&&c.push(this)});break;case "adjacency":if(b){c.push(b);var m=a.p.treeReader.parent_id_field,n=a.p.localReader.id;d(this.p.data).each(function(b){h=c.length;for(b=0;b<h;b++)if(d.jgrid.stripPref(a.p.idPrefix,c[b][n])===this[m]){c.push(this);break}})}}});return c},getNodeAncestors:function(b){var c=[];this.each(function(){if(this.grid&&this.p.treeGrid)for(var a=d(this).jqGrid("getNodeParent",b);a;)c.push(a),a=d(this).jqGrid("getNodeParent",a)});return c},isVisibleNode:function(b){var c=
+!0;this.each(function(){if(this.grid&&this.p.treeGrid){var a=d(this).jqGrid("getNodeAncestors",b),h=this.p.treeReader.expanded_field;d(a).each(function(){c=c&&this[h];if(!c)return!1})}});return c},isNodeLoaded:function(b){var c;this.each(function(){if(this.grid&&this.p.treeGrid){var a=this.p.treeReader.leaf_field;c=void 0!==b?void 0!==b.loaded?b.loaded:b[a]||0<d(this).jqGrid("getNodeChildren",b).length?!0:!1:!1}});return c},expandNode:function(b){return this.each(function(){if(this.grid&&this.p.treeGrid){var c=
+this.p.treeReader.expanded_field,a=this.p.treeReader.parent_id_field,h=this.p.treeReader.loaded,e=this.p.treeReader.level_field,i=this.p.treeReader.left_field,g=this.p.treeReader.right_field;if(!b[c]){var f=d.jgrid.getAccessor(b,this.p.localReader.id),l=d("#"+this.p.idPrefix+d.jgrid.jqID(f),this.grid.bDiv)[0],k=this.p._index[f];d(this).jqGrid("isNodeLoaded",this.p.data[k])?(b[c]=!0,d("div.treeclick",l).removeClass(this.p.treeIcons.plus+" tree-plus").addClass(this.p.treeIcons.minus+" tree-minus")):
+this.grid.hDiv.loading||(b[c]=!0,d("div.treeclick",l).removeClass(this.p.treeIcons.plus+" tree-plus").addClass(this.p.treeIcons.minus+" tree-minus"),this.p.treeANode=l.rowIndex,this.p.datatype=this.p.treedatatype,"nested"===this.p.treeGridModel?d(this).jqGrid("setGridParam",{postData:{nodeid:f,n_left:b[i],n_right:b[g],n_level:b[e]}}):d(this).jqGrid("setGridParam",{postData:{nodeid:f,parentid:b[a],n_level:b[e]}}),d(this).trigger("reloadGrid"),b[h]=!0,"nested"===this.p.treeGridModel?d(this).jqGrid("setGridParam",
+{postData:{nodeid:"",n_left:"",n_right:"",n_level:""}}):d(this).jqGrid("setGridParam",{postData:{nodeid:"",parentid:"",n_level:""}}))}}})},collapseNode:function(b){return this.each(function(){if(this.grid&&this.p.treeGrid){var c=this.p.treeReader.expanded_field;b[c]&&(b[c]=!1,c=d.jgrid.getAccessor(b,this.p.localReader.id),c=d("#"+this.p.idPrefix+d.jgrid.jqID(c),this.grid.bDiv)[0],d("div.treeclick",c).removeClass(this.p.treeIcons.minus+" tree-minus").addClass(this.p.treeIcons.plus+" tree-plus"))}})},
+SortTree:function(b,c,a,h){return this.each(function(){if(this.grid&&this.p.treeGrid){var e,i,g,f=[],l=this,k;e=d(this).jqGrid("getRootNodes");e=d.jgrid.from(e);e.orderBy(b,c,a,h);k=e.select();e=0;for(i=k.length;e<i;e++)g=k[e],f.push(g),d(this).jqGrid("collectChildrenSortTree",f,g,b,c,a,h);d.each(f,function(a){var b=d.jgrid.getAccessor(this,l.p.localReader.id);d("#"+d.jgrid.jqID(l.p.id)+" tbody tr:eq("+a+")").after(d("tr#"+d.jgrid.jqID(b),l.grid.bDiv))});f=k=e=null}})},collectChildrenSortTree:function(b,
+c,a,h,e,i){return this.each(function(){if(this.grid&&this.p.treeGrid){var g,f,l,k;g=d(this).jqGrid("getNodeChildren",c);g=d.jgrid.from(g);g.orderBy(a,h,e,i);k=g.select();g=0;for(f=k.length;g<f;g++)l=k[g],b.push(l),d(this).jqGrid("collectChildrenSortTree",b,l,a,h,e,i)}})},setTreeRow:function(b,c){var a=!1;this.each(function(){this.grid&&this.p.treeGrid&&(a=d(this).jqGrid("setRowData",b,c))});return a},delTreeNode:function(b){return this.each(function(){var c=this.p.localReader.id,a,h=this.p.treeReader.left_field,
+e=this.p.treeReader.right_field,i,g,f;if(this.grid&&this.p.treeGrid&&(a=this.p._index[b],void 0!==a)){i=parseInt(this.p.data[a][e],10);g=i-parseInt(this.p.data[a][h],10)+1;var l=d(this).jqGrid("getFullTreeNode",this.p.data[a]);if(0<l.length)for(a=0;a<l.length;a++)d(this).jqGrid("delRowData",l[a][c]);if("nested"===this.p.treeGridModel){c=d.jgrid.from(this.p.data).greater(h,i,{stype:"integer"}).select();if(c.length)for(f in c)c.hasOwnProperty(f)&&(c[f][h]=parseInt(c[f][h],10)-g);c=d.jgrid.from(this.p.data).greater(e,
+i,{stype:"integer"}).select();if(c.length)for(f in c)c.hasOwnProperty(f)&&(c[f][e]=parseInt(c[f][e],10)-g)}}})},addChildNode:function(b,c,a,h){var e=this[0];if(a){var i=e.p.treeReader.expanded_field,g=e.p.treeReader.leaf_field,f=e.p.treeReader.level_field,l=e.p.treeReader.parent_id_field,k=e.p.treeReader.left_field,m=e.p.treeReader.right_field,n=e.p.treeReader.loaded,j,r,q,t,p;j=0;var s=c,u;void 0===h&&(h=!1);if(void 0===b||null===b){p=e.p.data.length-1;if(0<=p)for(;0<=p;)j=Math.max(j,parseInt(e.p.data[p][e.p.localReader.id],
+10)),p--;b=j+1}var v=d(e).jqGrid("getInd",c);u=!1;if(void 0===c||null===c||""===c)s=c=null,j="last",t=e.p.tree_root_level,p=e.p.data.length+1;else if(j="after",r=e.p._index[c],q=e.p.data[r],c=q[e.p.localReader.id],t=parseInt(q[f],10)+1,p=d(e).jqGrid("getFullTreeNode",q),p.length?(s=p=p[p.length-1][e.p.localReader.id],p=d(e).jqGrid("getInd",s)+1):p=d(e).jqGrid("getInd",c)+1,q[g])u=!0,q[i]=!0,d(e.rows[v]).find("span.cell-wrapperleaf").removeClass("cell-wrapperleaf").addClass("cell-wrapper").end().find("div.tree-leaf").removeClass(e.p.treeIcons.leaf+
+" tree-leaf").addClass(e.p.treeIcons.minus+" tree-minus"),e.p.data[r][g]=!1,q[n]=!0;r=p+1;void 0===a[i]&&(a[i]=!1);void 0===a[n]&&(a[n]=!1);a[f]=t;void 0===a[g]&&(a[g]=!0);"adjacency"===e.p.treeGridModel&&(a[l]=c);if("nested"===e.p.treeGridModel){var o;if(null!==c){g=parseInt(q[m],10);f=d.jgrid.from(e.p.data);f=f.greaterOrEquals(m,g,{stype:"integer"});f=f.select();if(f.length)for(o in f)f.hasOwnProperty(o)&&(f[o][k]=f[o][k]>g?parseInt(f[o][k],10)+2:f[o][k],f[o][m]=f[o][m]>=g?parseInt(f[o][m],10)+
+2:f[o][m]);a[k]=g;a[m]=g+1}else{g=parseInt(d(e).jqGrid("getCol",m,!1,"max"),10);f=d.jgrid.from(e.p.data).greater(k,g,{stype:"integer"}).select();if(f.length)for(o in f)f.hasOwnProperty(o)&&(f[o][k]=parseInt(f[o][k],10)+2);f=d.jgrid.from(e.p.data).greater(m,g,{stype:"integer"}).select();if(f.length)for(o in f)f.hasOwnProperty(o)&&(f[o][m]=parseInt(f[o][m],10)+2);a[k]=g+1;a[m]=g+2}}if(null===c||d(e).jqGrid("isNodeLoaded",q)||u)d(e).jqGrid("addRowData",b,a,j,s),d(e).jqGrid("setTreeNode",p,r);q&&!q[i]&&
+h&&d(e.rows[v]).find("div.treeclick").click()}}})})(jQuery);
 (function(c){c.jgrid.extend({jqGridImport:function(a){a=c.extend({imptype:"xml",impstring:"",impurl:"",mtype:"GET",impData:{},xmlGrid:{config:"roots>grid",data:"roots>rows"},jsonGrid:{config:"grid",data:"data"},ajaxOptions:{}},a||{});return this.each(function(){var d=this,f=function(a,b){var e=c(b.xmlGrid.config,a)[0],h=c(b.xmlGrid.data,a)[0],f,g;if(xmlJsonClass.xml2json&&c.jgrid.parse){e=xmlJsonClass.xml2json(e," ");e=c.jgrid.parse(e);for(g in e)e.hasOwnProperty(g)&&(f=e[g]);h?(h=e.grid.datatype,
 e.grid.datatype="xmlstring",e.grid.datastr=a,c(d).jqGrid(f).jqGrid("setGridParam",{datatype:h})):c(d).jqGrid(f)}else alert("xml2json or parse are not present")},b=function(a,b){if(a&&"string"===typeof a){var e=!1;c.jgrid.useJSON&&(c.jgrid.useJSON=!1,e=!0);var f=c.jgrid.parse(a);e&&(c.jgrid.useJSON=!0);e=f[b.jsonGrid.config];if(f=f[b.jsonGrid.data]){var g=e.datatype;e.datatype="jsonstring";e.datastr=f;c(d).jqGrid(e).jqGrid("setGridParam",{datatype:g})}else c(d).jqGrid(e)}};switch(a.imptype){case "xml":c.ajax(c.extend({url:a.impurl,
 type:a.mtype,data:a.impData,dataType:"xml",complete:function(b,g){"success"===g&&(f(b.responseXML,a),c(d).triggerHandler("jqGridImportComplete",[b,a]),c.isFunction(a.importComplete)&&a.importComplete(b))}},a.ajaxOptions));break;case "xmlstring":if(a.impstring&&"string"===typeof a.impstring){var g=c.parseXML(a.impstring);g&&(f(g,a),c(d).triggerHandler("jqGridImportComplete",[g,a]),c.isFunction(a.importComplete)&&a.importComplete(g),a.impstring=null);g=null}break;case "json":c.ajax(c.extend({url:a.impurl,
@@ -520,9 +523,9 @@ e).css("height",a.height);g.css("height",a.height-10)}var i=c.jqGrid("getGridPar
 this;if(d.grid&&!d.p.treeGrid&&b.fn.sortable){a=b.extend({cursor:"move",axis:"y",items:".jqgrow"},a||{});if(a.start&&b.isFunction(a.start)){a._start_=a.start;delete a.start}else a._start_=false;if(a.update&&b.isFunction(a.update)){a._update_=a.update;delete a.update}else a._update_=false;a.start=function(c,e){b(e.item).css("border-width","0px");b("td",e.item).each(function(b){this.style.width=d.grid.cols[b].style.width});if(d.p.subGrid){var g=b(e.item).attr("id");try{b(d).jqGrid("collapseSubGridRow",
 g)}catch(i){}}a._start_&&a._start_.apply(this,[c,e])};a.update=function(c,e){b(e.item).css("border-width","");d.p.rownumbers===true&&b("td.jqgrid-rownum",d.rows).each(function(a){b(this).html(a+1+(parseInt(d.p.page,10)-1)*parseInt(d.p.rowNum,10))});a._update_&&a._update_.apply(this,[c,e])};b("tbody:first",d).sortable(a);b("tbody:first",d).disableSelection()}})},gridDnD:function(a){return this.each(function(){function d(){var a=b.data(c,"dnd");b("tr.jqgrow:not(.ui-draggable)",c).draggable(b.isFunction(a.drag)?
 a.drag.call(b(c),a):a.drag)}var c=this,e,g;if(c.grid&&!c.p.treeGrid&&b.fn.draggable&&b.fn.droppable){b("#jqgrid_dnd")[0]===void 0&&b("body").append("<table id='jqgrid_dnd' class='ui-jqgrid-dnd'></table>");if(typeof a==="string"&&a==="updateDnD"&&c.p.jqgdnd===true)d();else{a=b.extend({drag:function(a){return b.extend({start:function(e,d){var f;if(c.p.subGrid){f=b(d.helper).attr("id");try{b(c).jqGrid("collapseSubGridRow",f)}catch(g){}}for(f=0;f<b.data(c,"dnd").connectWith.length;f++)b(b.data(c,"dnd").connectWith[f]).jqGrid("getGridParam",
-"reccount")=="0"&&b(b.data(c,"dnd").connectWith[f]).jqGrid("addRowData","jqg_empty_row",{});d.helper.addClass("ui-state-highlight");b("td",d.helper).each(function(b){this.style.width=c.grid.headers[b].width+"px"});a.onstart&&b.isFunction(a.onstart)&&a.onstart.call(b(c),e,d)},stop:function(e,d){var f;if(d.helper.dropped&&!a.dragcopy){f=b(d.helper).attr("id");f===void 0&&(f=b(this).attr("id"));b(c).jqGrid("delRowData",f)}for(f=0;f<b.data(c,"dnd").connectWith.length;f++)b(b.data(c,"dnd").connectWith[f]).jqGrid("delRowData",
+"reccount")===0&&b(b.data(c,"dnd").connectWith[f]).jqGrid("addRowData","jqg_empty_row",{});d.helper.addClass("ui-state-highlight");b("td",d.helper).each(function(b){this.style.width=c.grid.headers[b].width+"px"});a.onstart&&b.isFunction(a.onstart)&&a.onstart.call(b(c),e,d)},stop:function(e,d){var f;if(d.helper.dropped&&!a.dragcopy){f=b(d.helper).attr("id");f===void 0&&(f=b(this).attr("id"));b(c).jqGrid("delRowData",f)}for(f=0;f<b.data(c,"dnd").connectWith.length;f++)b(b.data(c,"dnd").connectWith[f]).jqGrid("delRowData",
 "jqg_empty_row");a.onstop&&b.isFunction(a.onstop)&&a.onstop.call(b(c),e,d)}},a.drag_opts||{})},drop:function(a){return b.extend({accept:function(a){if(!b(a).hasClass("jqgrow"))return a;a=b(a).closest("table.ui-jqgrid-btable");if(a.length>0&&b.data(a[0],"dnd")!==void 0){a=b.data(a[0],"dnd").connectWith;return b.inArray("#"+b.jgrid.jqID(this.id),a)!==-1?true:false}return false},drop:function(e,d){if(b(d.draggable).hasClass("jqgrow")){var f=b(d.draggable).attr("id"),f=d.draggable.parent().parent().jqGrid("getRowData",
 f);if(!a.dropbyname){var g=0,j={},h,l,p=b("#"+b.jgrid.jqID(this.id)).jqGrid("getGridParam","colModel");try{for(l in f)if(f.hasOwnProperty(l)){h=p[g].name;h==="cb"||h==="rn"||h==="subgrid"||f.hasOwnProperty(l)&&p[g]&&(j[h]=f[l]);g++}f=j}catch(o){}}d.helper.dropped=true;if(a.beforedrop&&b.isFunction(a.beforedrop)){h=a.beforedrop.call(this,e,d,f,b("#"+b.jgrid.jqID(c.p.id)),b(this));h!==void 0&&h!==null&&typeof h==="object"&&(f=h)}if(d.helper.dropped){var k;if(a.autoid)if(b.isFunction(a.autoid))k=a.autoid.call(this,
 f);else{k=Math.ceil(Math.random()*1E3);k=a.autoidprefix+k}b("#"+b.jgrid.jqID(this.id)).jqGrid("addRowData",k,f,a.droppos)}a.ondrop&&b.isFunction(a.ondrop)&&a.ondrop.call(this,e,d,f)}}},a.drop_opts||{})},onstart:null,onstop:null,beforedrop:null,ondrop:null,drop_opts:{activeClass:"ui-state-active",hoverClass:"ui-state-hover"},drag_opts:{revert:"invalid",helper:"clone",cursor:"move",appendTo:"#jqgrid_dnd",zIndex:5E3},dragcopy:false,dropbyname:false,droppos:"first",autoid:true,autoidprefix:"dnd_"},a||
-{});if(a.connectWith){a.connectWith=a.connectWith.split(",");a.connectWith=b.map(a.connectWith,function(a){return b.trim(a)});b.data(c,"dnd",a);c.p.reccount!="0"&&!c.p.jqgdnd&&d();c.p.jqgdnd=true;for(e=0;e<a.connectWith.length;e++){g=a.connectWith[e];b(g).droppable(b.isFunction(a.drop)?a.drop.call(b(c),a):a.drop)}}}}})},gridResize:function(a){return this.each(function(){var d=this,c=b.jgrid.jqID(d.p.id);if(d.grid&&b.fn.resizable){a=b.extend({},a||{});if(a.alsoResize){a._alsoResize_=a.alsoResize;delete a.alsoResize}else a._alsoResize_=
+{});if(a.connectWith){a.connectWith=a.connectWith.split(",");a.connectWith=b.map(a.connectWith,function(a){return b.trim(a)});b.data(c,"dnd",a);c.p.reccount!==0&&!c.p.jqgdnd&&d();c.p.jqgdnd=true;for(e=0;e<a.connectWith.length;e++){g=a.connectWith[e];b(g).droppable(b.isFunction(a.drop)?a.drop.call(b(c),a):a.drop)}}}}})},gridResize:function(a){return this.each(function(){var d=this,c=b.jgrid.jqID(d.p.id);if(d.grid&&b.fn.resizable){a=b.extend({},a||{});if(a.alsoResize){a._alsoResize_=a.alsoResize;delete a.alsoResize}else a._alsoResize_=
 false;if(a.stop&&b.isFunction(a.stop)){a._stop_=a.stop;delete a.stop}else a._stop_=false;a.stop=function(e,g){b(d).jqGrid("setGridParam",{height:b("#gview_"+c+" .ui-jqgrid-bdiv").height()});b(d).jqGrid("setGridWidth",g.size.width,a.shrinkToFit);a._stop_&&a._stop_.call(d,e,g)};a.alsoResize=a._alsoResize_?eval("("+("{'#gview_"+c+" .ui-jqgrid-bdiv':true,'"+a._alsoResize_+"':true}")+")"):b(".ui-jqgrid-bdiv","#gview_"+c);delete a._alsoResize_;b("#gbox_"+c).resizable(a)}})}})})(jQuery);

+ 51 - 14
main/inc/lib/link.lib.php

@@ -22,16 +22,18 @@
 
 class Link extends Model
 {
-    var $table;
-    var $is_course_model = true;
-    var $columns = array('id', 'c_id','url','title','description','category_id', 'display_order', 'on_homepage', 'target', 'session_id');
-    var $required = array('url', 'title');
+    public $table;
+    public $is_course_model = true;
+    public $columns = array('id', 'c_id','url','title','description','category_id', 'display_order', 'on_homepage', 'target', 'session_id');
+    public $required = array('url', 'title');
 
-    public function __construct() {
+    public function __construct()
+    {
         $this->table =  Database::get_course_table(TABLE_LINK);
 	}
 
-    public function save($params, $show_query = null) {
+    public function save($params, $show_query = null)
+    {
         $course_info = api_get_course_info();
         $params['session_id'] = api_get_session_id();
         $params['category_id'] = isset($params['category_id']) ? $params['category_id'] : 0;
@@ -51,7 +53,8 @@ class Link extends Model
  * @todo replace strings by constants
  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  */
-function addlinkcategory($type) {
+function addlinkcategory($type)
+{
 	global $catlinkstatus;
 	global $msgErr;
 
@@ -238,7 +241,8 @@ function addlinkcategory($type) {
  * Used to delete a link or a category
  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  */
-function deletelinkcategory($type) {
+function deletelinkcategory($type)
+{
 	global $catlinkstatus;
     $_course = api_get_course_info();
 	$tbl_link              = Database :: get_course_table(TABLE_LINK);
@@ -283,7 +287,8 @@ function deletelinkcategory($type) {
  * @param string $course_id Course code
  * @param int $document_id Document id to delete
  */
-function delete_link_from_search_engine($course_id, $link_id) {
+function delete_link_from_search_engine($course_id, $link_id)
+{
 	// Remove from search engine if enabled.
 	if (api_get_setting('search_enabled') == 'true') {
 		$tbl_se_ref = Database :: get_main_table(TABLE_MAIN_SEARCH_ENGINE_REF);
@@ -315,7 +320,8 @@ function delete_link_from_search_engine($course_id, $link_id) {
  *
  * */
 
-function get_link_info($id) {
+function get_link_info($id)
+{
      $tbl_link      = Database :: get_course_table(TABLE_LINK);
      $course_id     = api_get_course_int_id();
      $sql           = "SELECT * FROM " . $tbl_link . " WHERE c_id = $course_id AND id='" . intval($id) . "' ";
@@ -336,7 +342,8 @@ function get_link_info($id) {
  * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  * @todo replace the globals with the appropriate $_POST or $_GET values
  */
-function editlinkcategory($type) {
+function editlinkcategory($type)
+{
 
 	global $catlinkstatus;
 	global $id;
@@ -927,7 +934,8 @@ function import_link($linkdata) {
  * CSV file import functions
  * @author René Haentjens , Ghent University
  */
-function import_csvfile() {
+function import_csvfile()
+{
 
 	global $catlinkstatus; // Feedback message to user.
 
@@ -980,18 +988,47 @@ function import_csvfile() {
 	}
 }
 
+/**
+ * This function checks if the url is a vimeo link
+ * @author Julio Montoya
+ * @version 1.0
+ */
+function isVimeoLink($url)
+{
+	$isLink = strrpos($url, "vimeo.com");
+    return $isLink;
+}
+
+function getVimeoLinkId($url)
+{
+    $possibleUrls = array(
+        'http://www.vimeo.com/',
+        'http://vimeo.com/',
+        'https://www.vimeo.com/',
+        'https://vimeo.com/'
+    );
+    $url = str_replace($possibleUrls, '', $url);
+
+    if (is_numeric($url)) {
+        return $url;
+    }
+    return false;
+}
+
 /**
  * This function checks if the url is a youtube link
  * @author Jorge Frisancho
  * @author Julio Montoya - Fixing code
  * @version 1.0
  */
-function is_youtube_link($url) {
+function is_youtube_link($url)
+{
 	$is_youtube_link = strrpos($url, "youtube") || strrpos($url, "youtu.be");
     return $is_youtube_link;
 }
 
-function get_youtube_video_id($url) {
+function get_youtube_video_id($url)
+{
     // This is the length of YouTube's video IDs
 	$len = 11;
 

+ 6 - 7
main/inc/lib/login.lib.php

@@ -105,7 +105,7 @@ class Login
         $email_admin = api_get_setting('emailAdministrator');
 
         if (api_mail_html('', $email_to, $email_subject, $email_body, $sender_name, $email_admin) == 1) {
-            return get_lang('your_password_has_been_reset');
+            return get_lang('YourPasswordHasBeenReset');
         } else {
             $admin_email = Display :: encrypted_mailto_link(api_get_setting('emailAdministrator'), api_get_person_name(api_get_setting('administratorName'), api_get_setting('administratorSurname')));
             return sprintf(get_lang('ThisPlatformWasUnableToSendTheEmailPleaseContactXForMoreInformation'), $admin_email);
@@ -167,8 +167,7 @@ class Login
      */
     public static function get_secret_word($add)
     {
-        global $_configuration;
-        return $secret_word = md5($_configuration['security_key'] . $add);
+        return $secret_word = sha1($add);
     }
 
     /**
@@ -189,12 +188,12 @@ class Login
             return get_lang('CouldNotResetPassword');
         }
 
-        if (self::get_secret_word($user['email']) == $secret) { // OK, secret word is good. Now change password and mail it.
+        if (self::get_secret_word($user['email']) == $secret) {
+            // OK, secret word is good. Now change password and mail it.
             $user['password'] = api_generate_password();
-            $crypted = $user['password'];
-            $crypted = api_get_encrypted_password($crypted);
+            $crypted = api_get_encrypted_password($user['password']);
             $sql = "UPDATE " . $tbl_user . " SET password='$crypted' WHERE user_id = $id";
-            $result = Database::query($sql);
+            Database::query($sql);
             return self::send_password_to_user($user, $by_username);
         } else {
             return get_lang('NotAllowed');

+ 1 - 1
main/inc/lib/pclzip/pclzip.lib.php

@@ -61,7 +61,7 @@ if (!function_exists('gzopen') && function_exists('gzopen64')) {
   //define( 'PCLZIP_SEPARATOR', ' ' );
   // Recommanded values for smart separation of filenames.
   if (!defined('PCLZIP_SEPARATOR')) {
-    define( 'PCLZIP_SEPARATOR', ',' );
+    define( 'PCLZIP_SEPARATOR', '|' );
   }
 
   // ----- Error configuration

+ 388 - 0
main/inc/lib/pear/Exception.php

@@ -0,0 +1,388 @@
+<?php
+/* vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker: */
+/**
+ * PEAR_Exception
+ *
+ * PHP version 5
+ *
+ * @category   pear
+ * @package    PEAR_Exception
+ * @author     Tomas V. V. Cox <cox@idecnet.com>
+ * @author     Hans Lellelid <hans@velum.net>
+ * @author     Bertrand Mansion <bmansion@mamasam.com>
+ * @author     Greg Beaver <cellog@php.net>
+ * @copyright  1997-2009 The Authors
+ * @license    http://opensource.org/licenses/bsd-license.php New BSD License
+ * @link       http://pear.php.net/package/PEAR_Exception
+ * @since      File available since Release 1.0.0
+ */
+
+
+/**
+ * Base PEAR_Exception Class
+ *
+ * 1) Features:
+ *
+ * - Nestable exceptions (throw new PEAR_Exception($msg, $prev_exception))
+ * - Definable triggers, shot when exceptions occur
+ * - Pretty and informative error messages
+ * - Added more context info available (like class, method or cause)
+ * - cause can be a PEAR_Exception or an array of mixed
+ *   PEAR_Exceptions/PEAR_ErrorStack warnings
+ * - callbacks for specific exception classes and their children
+ *
+ * 2) Ideas:
+ *
+ * - Maybe a way to define a 'template' for the output
+ *
+ * 3) Inherited properties from PHP Exception Class:
+ *
+ * protected $message
+ * protected $code
+ * protected $line
+ * protected $file
+ * private   $trace
+ *
+ * 4) Inherited methods from PHP Exception Class:
+ *
+ * __clone
+ * __construct
+ * getMessage
+ * getCode
+ * getFile
+ * getLine
+ * getTraceSafe
+ * getTraceSafeAsString
+ * __toString
+ *
+ * 5) Usage example
+ *
+ * <code>
+ *  require_once 'PEAR/Exception.php';
+ *
+ *  class Test {
+ *     function foo() {
+ *         throw new PEAR_Exception('Error Message', ERROR_CODE);
+ *     }
+ *  }
+ *
+ *  function myLogger($pear_exception) {
+ *     echo $pear_exception->getMessage();
+ *  }
+ *  // each time a exception is thrown the 'myLogger' will be called
+ *  // (its use is completely optional)
+ *  PEAR_Exception::addObserver('myLogger');
+ *  $test = new Test;
+ *  try {
+ *     $test->foo();
+ *  } catch (PEAR_Exception $e) {
+ *     print $e;
+ *  }
+ * </code>
+ *
+ * @category   pear
+ * @package    PEAR_Exception
+ * @author     Tomas V.V.Cox <cox@idecnet.com>
+ * @author     Hans Lellelid <hans@velum.net>
+ * @author     Bertrand Mansion <bmansion@mamasam.com>
+ * @author     Greg Beaver <cellog@php.net>
+ * @copyright  1997-2009 The Authors
+ * @license    http://opensource.org/licenses/bsd-license.php New BSD License
+ * @version    Release: @package_version@
+ * @link       http://pear.php.net/package/PEAR_Exception
+ * @since      Class available since Release 1.0.0
+ *
+ */
+class PEAR_Exception extends Exception
+{
+    const OBSERVER_PRINT = -2;
+    const OBSERVER_TRIGGER = -4;
+    const OBSERVER_DIE = -8;
+    protected $cause;
+    private static $_observers = array();
+    private static $_uniqueid = 0;
+    private $_trace;
+
+    /**
+     * Supported signatures:
+     *  - PEAR_Exception(string $message);
+     *  - PEAR_Exception(string $message, int $code);
+     *  - PEAR_Exception(string $message, Exception $cause);
+     *  - PEAR_Exception(string $message, Exception $cause, int $code);
+     *  - PEAR_Exception(string $message, PEAR_Error $cause);
+     *  - PEAR_Exception(string $message, PEAR_Error $cause, int $code);
+     *  - PEAR_Exception(string $message, array $causes);
+     *  - PEAR_Exception(string $message, array $causes, int $code);
+     * @param string exception message
+     * @param int|Exception|PEAR_Error|array|null exception cause
+     * @param int|null exception code or null
+     */
+    public function __construct($message, $p2 = null, $p3 = null)
+    {
+        if (is_int($p2)) {
+            $code = $p2;
+            $this->cause = null;
+        } elseif (is_object($p2) || is_array($p2)) {
+            // using is_object allows both Exception and PEAR_Error
+            if (is_object($p2) && !($p2 instanceof Exception)) {
+                if (!class_exists('PEAR_Error') || !($p2 instanceof PEAR_Error)) {
+                    throw new PEAR_Exception('exception cause must be Exception, ' .
+                        'array, or PEAR_Error');
+                }
+            }
+            $code = $p3;
+            if (is_array($p2) && isset($p2['message'])) {
+                // fix potential problem of passing in a single warning
+                $p2 = array($p2);
+            }
+            $this->cause = $p2;
+        } else {
+            $code = null;
+            $this->cause = null;
+        }
+        parent::__construct($message, $code);
+        $this->signal();
+    }
+
+    /**
+     * @param mixed $callback  - A valid php callback, see php func is_callable()
+     *                         - A PEAR_Exception::OBSERVER_* constant
+     *                         - An array(const PEAR_Exception::OBSERVER_*,
+     *                           mixed $options)
+     * @param string $label    The name of the observer. Use this if you want
+     *                         to remove it later with removeObserver()
+     */
+    public static function addObserver($callback, $label = 'default')
+    {
+        self::$_observers[$label] = $callback;
+    }
+
+    public static function removeObserver($label = 'default')
+    {
+        unset(self::$_observers[$label]);
+    }
+
+    /**
+     * @return int unique identifier for an observer
+     */
+    public static function getUniqueId()
+    {
+        return self::$_uniqueid++;
+    }
+
+    private function signal()
+    {
+        foreach (self::$_observers as $func) {
+            if (is_callable($func)) {
+                call_user_func($func, $this);
+                continue;
+            }
+            settype($func, 'array');
+            switch ($func[0]) {
+                case self::OBSERVER_PRINT :
+                    $f = (isset($func[1])) ? $func[1] : '%s';
+                    printf($f, $this->getMessage());
+                    break;
+                case self::OBSERVER_TRIGGER :
+                    $f = (isset($func[1])) ? $func[1] : E_USER_NOTICE;
+                    trigger_error($this->getMessage(), $f);
+                    break;
+                case self::OBSERVER_DIE :
+                    $f = (isset($func[1])) ? $func[1] : '%s';
+                    die(printf($f, $this->getMessage()));
+                    break;
+                default:
+                    trigger_error('invalid observer type', E_USER_WARNING);
+            }
+        }
+    }
+
+    /**
+     * Return specific error information that can be used for more detailed
+     * error messages or translation.
+     *
+     * This method may be overridden in child exception classes in order
+     * to add functionality not present in PEAR_Exception and is a placeholder
+     * to define API
+     *
+     * The returned array must be an associative array of parameter => value like so:
+     * <pre>
+     * array('name' => $name, 'context' => array(...))
+     * </pre>
+     * @return array
+     */
+    public function getErrorData()
+    {
+        return array();
+    }
+
+    /**
+     * Returns the exception that caused this exception to be thrown
+     * @access public
+     * @return Exception|array The context of the exception
+     */
+    public function getCause()
+    {
+        return $this->cause;
+    }
+
+    /**
+     * Function must be public to call on caused exceptions
+     * @param array
+     */
+    public function getCauseMessage(&$causes)
+    {
+        $trace = $this->getTraceSafe();
+        $cause = array('class'   => get_class($this),
+                       'message' => $this->message,
+                       'file' => 'unknown',
+                       'line' => 'unknown');
+        if (isset($trace[0])) {
+            if (isset($trace[0]['file'])) {
+                $cause['file'] = $trace[0]['file'];
+                $cause['line'] = $trace[0]['line'];
+            }
+        }
+        $causes[] = $cause;
+        if ($this->cause instanceof PEAR_Exception) {
+            $this->cause->getCauseMessage($causes);
+        } elseif ($this->cause instanceof Exception) {
+            $causes[] = array('class'   => get_class($this->cause),
+                              'message' => $this->cause->getMessage(),
+                              'file' => $this->cause->getFile(),
+                              'line' => $this->cause->getLine());
+        } elseif (class_exists('PEAR_Error') && $this->cause instanceof PEAR_Error) {
+            $causes[] = array('class' => get_class($this->cause),
+                              'message' => $this->cause->getMessage(),
+                              'file' => 'unknown',
+                              'line' => 'unknown');
+        } elseif (is_array($this->cause)) {
+            foreach ($this->cause as $cause) {
+                if ($cause instanceof PEAR_Exception) {
+                    $cause->getCauseMessage($causes);
+                } elseif ($cause instanceof Exception) {
+                    $causes[] = array('class'   => get_class($cause),
+                                   'message' => $cause->getMessage(),
+                                   'file' => $cause->getFile(),
+                                   'line' => $cause->getLine());
+                } elseif (class_exists('PEAR_Error') && $cause instanceof PEAR_Error) {
+                    $causes[] = array('class' => get_class($cause),
+                                      'message' => $cause->getMessage(),
+                                      'file' => 'unknown',
+                                      'line' => 'unknown');
+                } elseif (is_array($cause) && isset($cause['message'])) {
+                    // PEAR_ErrorStack warning
+                    $causes[] = array(
+                        'class' => $cause['package'],
+                        'message' => $cause['message'],
+                        'file' => isset($cause['context']['file']) ?
+                                            $cause['context']['file'] :
+                                            'unknown',
+                        'line' => isset($cause['context']['line']) ?
+                                            $cause['context']['line'] :
+                                            'unknown',
+                    );
+                }
+            }
+        }
+    }
+
+    public function getTraceSafe()
+    {
+        if (!isset($this->_trace)) {
+            $this->_trace = $this->getTrace();
+            if (empty($this->_trace)) {
+                $backtrace = debug_backtrace();
+                $this->_trace = array($backtrace[count($backtrace)-1]);
+            }
+        }
+        return $this->_trace;
+    }
+
+    public function getErrorClass()
+    {
+        $trace = $this->getTraceSafe();
+        return $trace[0]['class'];
+    }
+
+    public function getErrorMethod()
+    {
+        $trace = $this->getTraceSafe();
+        return $trace[0]['function'];
+    }
+
+    public function __toString()
+    {
+        if (isset($_SERVER['REQUEST_URI'])) {
+            return $this->toHtml();
+        }
+        return $this->toText();
+    }
+
+    public function toHtml()
+    {
+        $trace = $this->getTraceSafe();
+        $causes = array();
+        $this->getCauseMessage($causes);
+        $html =  '<table style="border: 1px" cellspacing="0">' . "\n";
+        foreach ($causes as $i => $cause) {
+            $html .= '<tr><td colspan="3" style="background: #ff9999">'
+               . str_repeat('-', $i) . ' <b>' . $cause['class'] . '</b>: '
+               . htmlspecialchars($cause['message']) . ' in <b>' . $cause['file'] . '</b> '
+               . 'on line <b>' . $cause['line'] . '</b>'
+               . "</td></tr>\n";
+        }
+        $html .= '<tr><td colspan="3" style="background-color: #aaaaaa; text-align: center; font-weight: bold;">Exception trace</td></tr>' . "\n"
+               . '<tr><td style="text-align: center; background: #cccccc; width:20px; font-weight: bold;">#</td>'
+               . '<td style="text-align: center; background: #cccccc; font-weight: bold;">Function</td>'
+               . '<td style="text-align: center; background: #cccccc; font-weight: bold;">Location</td></tr>' . "\n";
+
+        foreach ($trace as $k => $v) {
+            $html .= '<tr><td style="text-align: center;">' . $k . '</td>'
+                   . '<td>';
+            if (!empty($v['class'])) {
+                $html .= $v['class'] . $v['type'];
+            }
+            $html .= $v['function'];
+            $args = array();
+            if (!empty($v['args'])) {
+                foreach ($v['args'] as $arg) {
+                    if (is_null($arg)) $args[] = 'null';
+                    elseif (is_array($arg)) $args[] = 'Array';
+                    elseif (is_object($arg)) $args[] = 'Object('.get_class($arg).')';
+                    elseif (is_bool($arg)) $args[] = $arg ? 'true' : 'false';
+                    elseif (is_int($arg) || is_double($arg)) $args[] = $arg;
+                    else {
+                        $arg = (string)$arg;
+                        $str = htmlspecialchars(substr($arg, 0, 16));
+                        if (strlen($arg) > 16) $str .= '&hellip;';
+                        $args[] = "'" . $str . "'";
+                    }
+                }
+            }
+            $html .= '(' . implode(', ',$args) . ')'
+                   . '</td>'
+                   . '<td>' . (isset($v['file']) ? $v['file'] : 'unknown')
+                   . ':' . (isset($v['line']) ? $v['line'] : 'unknown')
+                   . '</td></tr>' . "\n";
+        }
+        $html .= '<tr><td style="text-align: center;">' . ($k+1) . '</td>'
+               . '<td>{main}</td>'
+               . '<td>&nbsp;</td></tr>' . "\n"
+               . '</table>';
+        return $html;
+    }
+
+    public function toText()
+    {
+        $causes = array();
+        $this->getCauseMessage($causes);
+        $causeMsg = '';
+        foreach ($causes as $i => $cause) {
+            $causeMsg .= str_repeat(' ', $i) . $cause['class'] . ': '
+                   . $cause['message'] . ' in ' . $cause['file']
+                   . ' on line ' . $cause['line'] . "\n";
+        }
+        return $causeMsg . $this->getTraceAsString();
+    }
+}

+ 50 - 0
main/inc/lib/pear/HTML/QuickForm/Rule/CAPTCHA.php

@@ -0,0 +1,50 @@
+<?php
+/* vim: set expandtab tabstop=4 shiftwidth=4: */
+
+/**
+ * Rule for HTML_QuickForm to display a CAPTCHA image
+ *
+ * This package requires the use of a PHP session.
+ *
+ * PHP versions 4 and 5
+ *
+ * @category  HTML
+ * @package   HTML_QuickForm_CAPTCHA
+ * @author    Philippe Jausions <Philippe.Jausions@11abacus.com>
+ * @copyright 2006-2008 by Philippe Jausions / 11abacus
+ * @license   http://www.opensource.org/licenses/bsd-license.php New BSD
+ * @version   CVS: $Id: CAPTCHA.php,v 1.1 2008/04/26 23:27:30 jausions Exp $
+ * @link      http://pear.php.net/package/HTML_QuickForm_CAPTCHA
+ */
+
+require_once 'HTML/QuickForm/Rule.php';
+
+/**
+ * Rule to compare a field with a CAPTCHA image
+ *
+ * @category  HTML
+ * @package   HTML_QuickForm_CAPTCHA
+ * @author    Philippe Jausions <Philippe.Jausions@11abacus.com>
+ * @copyright 2006-2008 by Philippe Jausions / 11abacus
+ * @license   http://www.opensource.org/licenses/bsd-license.php New BSD
+ * @version   Release: 0.3.0
+ * @link      http://pear.php.net/package/HTML_QuickForm_CAPTCHA
+ */
+class HTML_QuickForm_Rule_CAPTCHA extends HTML_QuickForm_Rule
+{
+    /**
+     * Validates the data entered matches the CAPTCHA image that was
+     * displayed
+     *
+     * @param string                        $value   data to validate
+     * @param HTML_QuickForm_CAPTCHA_Common $captcha element to check against
+     *
+     * @return boolean TRUE if valid, FALSE otherwise
+     * @access public
+     * @static
+     */
+    function validate($value, $captcha)
+    {
+        return ($value == $captcha->getValue());
+    }
+}

+ 58 - 53
main/inc/lib/promotion.lib.php

@@ -13,28 +13,28 @@ require_once 'career.lib.php';
 require_once 'fckeditor/fckeditor.php';
 
 define ('PROMOTION_STATUS_ACTIVE',  1);
-define ('PROMOTION_STATUS_INACTIVE',0);
+define ('PROMOTION_STATUS_INACTIVE',0);   
 /**
  * @package chamilo.library
  */
 class Promotion extends Model {
-
+    
     var $table;
     var $columns = array('id','name','description','career_id','status','created_at','updated_at');
-
+    
 	public function __construct() {
         $this->table =  Database::get_main_table(TABLE_PROMOTION);
 	}
-
+    
      /**
      * Get the count of elements
      */
-    public function get_count() {
+    public function get_count() {        
         $row = Database::select('count(*) as count', $this->table, array(),'first');
         return $row['count'];
     }
-
-
+    
+	
 	/**
 	* Copies the promotion to a new one
 	* @param   integer     Promotion ID
@@ -44,7 +44,7 @@ class Promotion extends Model {
 	*/
 	public function copy($id, $career_id = null, $copy_sessions = false) {
 		$pid = false;
-		$promotion = $this->get($id);
+		$promotion = $this->get($id);		
 		if (!empty($promotion)) {
 			$new = array();
 			foreach ($promotion as $key => $val) {
@@ -53,7 +53,7 @@ class Promotion extends Model {
 					case 'updated_at':
 						break;
 					case 'name':
-						$val .= ' '.get_lang('Copy');
+						$val .= ' '.get_lang('CopyLabelSuffix');
 						$new[$key] = $val;
 						break;
 					case 'created_at':
@@ -70,26 +70,26 @@ class Promotion extends Model {
 					break;
 				}
 			}
-
+			
 			if ($copy_sessions) {
 				/**
 				 * When copying a session we do:
 				 * 1. Copy a new session from the source
 				 * 2. Copy all courses from the session (no user data, no user list)
 				 * 3. Create the promotion
-				 */
+				 */				
 				$session_list   = SessionManager::get_all_sessions_by_promotion($id);
-
+				
 				if (!empty($session_list)) {
-					$pid = $this->save($new);
+					$pid = $this->save($new);				
 					if (!empty($pid)) {
                         $new_session_list = array();
-
+                        
 						foreach($session_list as $item) {
-							$sid = SessionManager::copy_session($item['id'], true, false, true, true);
+							$sid = SessionManager::copy_session($item['id'], true, false, false, true);						
                             $new_session_list[] = $sid;
 						}
-
+                        
                         if (!empty($new_session_list)) {
                             SessionManager::suscribe_sessions_to_promotion($pid, $new_session_list);
                         }
@@ -101,20 +101,20 @@ class Promotion extends Model {
 		}
 		return $pid;
 	}
-
+	
     /**
      * Gets all promotions by career id
      * @param   int     career id
      * @return  array   results
      */
-    public function get_all_promotions_by_career_id($career_id, $order = false) {
+    public function get_all_promotions_by_career_id($career_id, $order = false) {        
         return Database::select('*', $this->table, array('where'=>array('career_id = ?'=>$career_id),'order' =>$order));
     }
-
+    
     public function get_status_list() {
     	return array(PROMOTION_STATUS_ACTIVE => get_lang('Active'), PROMOTION_STATUS_INACTIVE => get_lang('Inactive'));
-    }
-
+    } 
+   
     /**
      * Displays the title + grid
      * @return  string  html code
@@ -123,44 +123,44 @@ class Promotion extends Model {
 		// action links
 		echo '<div class="actions" style="margin-bottom:20px">';
         echo '<a href="career_dashboard.php">'.Display::return_icon('back.png',get_lang('Back'),'','32').'</a>';
-		echo '<a href="'.api_get_self().'?action=add">'.Display::return_icon('new_promotion.png',get_lang('Add'),'','32').'</a>';
+		echo '<a href="'.api_get_self().'?action=add">'.Display::return_icon('new_promotion.png',get_lang('Add'),'','32').'</a>';			
 		echo '<a href="'.api_get_path(WEB_CODE_PATH).'session/session_add.php">'.Display::return_icon('new_session.png',get_lang('AddSession'),'','32').'</a>';
 		echo '</div>';
-        echo Display::grid_html('promotions');
+        echo Display::grid_html('promotions');  
 	}
-
+    
     /**
      * Update all session status by promotion
      * @param   int     promotion id
      * @param   int     status (1, 0)
     */
     public function update_all_sessions_status_by_promotion_id($promotion_id, $status) {
-        $session_list   = SessionManager::get_all_sessions_by_promotion($promotion_id);
+        $session_list   = SessionManager::get_all_sessions_by_promotion($promotion_id);    
         if (!empty($session_list)) {
             foreach($session_list  as $item) {
-                SessionManager::set_session_status($item['id'], $status);
+                SessionManager::set_session_status($item['id'], $status);            
             }
         }
     }
-
-
+    
+        
     /**
      * Returns a Form validator Obj
      * @todo the form should be auto generated
      * @param   string  url
      * @param   string  header name
-     * @return  obj     form validator obj
+     * @return  obj     form validator obj 
      */
-
+     
     function return_form($url, $action = 'add') {
-
+    	
 		$oFCKeditor = new FCKeditor('description') ;
 		$oFCKeditor->ToolbarSet = 'careers';
 		$oFCKeditor->Width		= '100%';
 		$oFCKeditor->Height		= '200';
 		$oFCKeditor->Value		= '';
-		$oFCKeditor->CreateHtml();
-
+		$oFCKeditor->CreateHtml();		
+		
 		$form = new FormValidator('promotion', 'post', $url);
         // Settting the form elements
         $header = get_lang('Add');
@@ -168,31 +168,31 @@ class Promotion extends Model {
         	$header = get_lang('Modify');
         }
         $id = isset($_GET['id']) ? intval($_GET['id']) : '';
-
+        
         $form->addElement('header', '', $header);
         $form->addElement('hidden', 'id', $id);
-        $form->addElement('text', 'name', get_lang('Name'), array('size' => '70','id' => 'name'));
-        $form->add_html_editor('description', get_lang('Description'), false, false, array('ToolbarSet' => 'careers','Width' => '100%', 'Height' => '250'));
+        $form->addElement('text', 'name', get_lang('Name'), array('size' => '70','id' => 'name'));        
+        $form->add_html_editor('description', get_lang('Description'), false, false, array('ToolbarSet' => 'careers','Width' => '100%', 'Height' => '250'));       
         $career = new Career();
         $careers = $career->get_all();
-        $career_list = array();
-        foreach($careers as $item) {
+        $career_list = array();    
+        foreach($careers as $item) {        
             $career_list[$item['id']] = $item['name'];
         }
         $form->addElement('select', 'career_id', get_lang('Career'), $career_list);
-
-        $status_list = $this->get_status_list();
+        
+        $status_list = $this->get_status_list();         
         $form->addElement('select', 'status', get_lang('Status'), $status_list);
         if ($action == 'edit') {
             $form->addElement('text', 'created_at', get_lang('CreatedAt'));
             $form->freeze('created_at');
-        }
+        }         
       	if ($action == 'edit') {
         	$form->addElement('style_submit_button', 'submit', get_lang('Modify'), 'class="save"');
         } else {
         	$form->addElement('style_submit_button', 'submit', get_lang('Add'), 'class="save"');
         }
-
+    
         // Setting the defaults
         $defaults = $this->get($id);
         if (!empty($defaults['created_at'])) {
@@ -200,27 +200,32 @@ class Promotion extends Model {
         }
         if (!empty($defaults['updated_at'])) {
         	$defaults['updated_at'] = api_convert_and_format_date($defaults['updated_at']);
-        }
+        }            
         $form->setDefaults($defaults);
-
+    
         // Setting the rules
         $form->addRule('name', get_lang('ThisFieldIsRequired'), 'required');
-
+        
         return $form;
     }
-
+    
     public function save($params, $show_query = false) {
     	$id = parent::save($params, $show_query);
     	if (!empty($id)) {
     		event_system(LOG_PROMOTION_CREATE, LOG_PROMOTION_ID, $id, api_get_utc_datetime(), api_get_user_id());
     	}
-    	return $id;
+    	return $id;	
     }
-
-    public function delete($id) {
-    	parent::delete($id);
-    	event_system(LOG_PROMOTION_DELETE, LOG_PROMOTION_ID, $id, api_get_utc_datetime(), api_get_user_id());
+    
+    public function delete($id) 
+    {
+    	if (parent::delete($id)) {
+            SessionManager::clear_session_ref_promotion($id);
+    	    event_system(LOG_PROMOTION_DELETE, LOG_PROMOTION_ID, $id, api_get_utc_datetime(), api_get_user_id());    	
+        } else {
+            return false;
+        }   	
     }
-
-
+   
+    
 }

+ 460 - 2
main/inc/lib/sessionmanager.lib.php

@@ -2051,7 +2051,7 @@ class SessionManager
      * @param  int ID of the URL we want to filter on (optional)
      * @return int Number of sessions
      */
-    public function count_sessions($access_url_id=null) {
+    public static function count_sessions($access_url_id=null) {
         $session_table = Database::get_main_table(TABLE_MAIN_SESSION);
         $access_url_rel_session_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
         $sql = "SELECT count(id) FROM $session_table s";
@@ -2093,7 +2093,8 @@ class SessionManager
      * @param $courseId
      * @return array
      */
-    static function get_session_by_course($courseId) {
+    static function get_session_by_course($courseId) 
+    {
         $table_session_course = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
         $table_session = Database::get_main_table(TABLE_MAIN_SESSION);
         $courseId = Database::escape_string($courseId);
@@ -2103,6 +2104,463 @@ class SessionManager
         return Database::store_result($result);
     }
 
+    public static function get_sessions_by_user($user_id, $ignore_visibility_for_admins = false)
+    {
+       $session_categories = UserManager::get_sessions_by_category($user_id, false, $ignore_visibility_for_admins);
+       $session_array = array();
+       if (!empty($session_categories)) {
+           foreach ($session_categories as $category) {
+               if (isset($category['sessions'])) {
+                   foreach ($category['sessions'] as $session) {
+                       $session_array[] = $session;
+                   }
+               }
+           }
+       }
+       return $session_array;
+    }
+
+    /**
+     * @param string $file
+     * @param bool $updatesession options:
+     * true: if the session exists it will be updated
+     * false: if session exists a new session will be created adding a counter session1, session2, etc
+     * @param int $user_id
+     * @param $logger
+     * @param array convert a file row to an extra field. Example in CSV file there's a SessionID then it will
+     * converted to extra_external_session_id if you set this: array('SessionId' => 'extra_external_session_id')
+     * @param array extra fields
+     * @param string extra field id
+     * @param int $daysCoachAccessBeforeBeginning
+     * @param int $daysCoachAccessAfterBeginning
+     * @param int $sessionVisibility
+     * @return array
+     */
+    static function importCSV(
+        $file,
+        $updatesession,
+        $defaultUserId = null,
+        $logger = null,
+        $extraFields = array(),
+        $extraFieldId = null,
+        $daysCoachAccessBeforeBeginning = null,
+        $daysCoachAccessAfterBeginning = null,
+        $sessionVisibility = 1
+    )
+    {
+        $content = file($file);
+
+        $error_message = null;
+        $session_counter = 0;
+
+        if (empty($defaultUserId)) {
+            $defaultUserId = api_get_user_id();
+        }
+
+        $eol = PHP_EOL;
+        if (PHP_SAPI !='cli') {
+            $eol = '<br />';
+        }
+
+        $debug = false;
+        if (isset($logger)) {
+            $debug = true;
+        }
+
+        $extraParameters = null;
+
+        if (!empty($daysCoachAccessBeforeBeginning) && !empty($daysCoachAccessAfterBeginning)) {
+            $extraParameters .= ' , nb_days_access_before_beginning = '.intval($daysCoachAccessBeforeBeginning);
+            $extraParameters .= ' , nb_days_access_after_end = '.intval($daysCoachAccessAfterBeginning);
+        }
+
+        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
+        $tbl_session_user           = Database::get_main_table(TABLE_MAIN_SESSION_USER);
+        $tbl_session_course         = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
+        $tbl_session_course_user    = Database::get_main_table(TABLE_MAIN_SESSION_COURSE_USER);
+
+        $sessions = array();
+
+        if (!api_strstr($content[0], ';')) {
+            $error_message = get_lang('NotCSV');
+        } else {
+            $tag_names = array();
+
+            foreach ($content as $key => $enreg) {
+
+                $enreg = explode(';', trim($enreg));
+                if ($key) {
+                    foreach ($tag_names as $tag_key => $tag_name) {
+                        $sessions[$key - 1][$tag_name] = $enreg[$tag_key];
+                    }
+                } else {
+                    foreach ($enreg as $tag_name) {
+                        $tag_names[] = api_preg_replace('/[^a-zA-Z0-9_\-]/', '', $tag_name);
+                    }
+                    if (!in_array('SessionName', $tag_names) || !in_array('DateStart', $tag_names) || !in_array('DateEnd', $tag_names)) {
+                        $error_message = get_lang('NoNeededData');
+                        break;
+                    }
+                }
+            }
+
+            // Looping the sessions.
+            foreach ($sessions as $enreg) {
+                $user_counter = 0;
+                $course_counter = 0;
+
+                if (isset($extraFields) && !empty($extraFields)) {
+                    foreach ($extraFields as $original => $to) {
+                        $enreg[$to] = $enreg[$original];
+                    }
+                }
+
+                $session_name           = Database::escape_string($enreg['SessionName']);
+                $date_start             = $enreg['DateStart'];
+                $date_end               = $enreg['DateEnd'];
+                $visibility             = isset($enreg['Visibility']) ? $enreg['Visibility'] : $sessionVisibility;
+                $session_category_id    = $enreg['SessionCategory'];
+
+                // Searching a coach.
+                if (!empty($enreg['Coach'])) {
+                    $coach_id = UserManager::get_user_id_from_username($enreg['Coach']);
+                    if ($coach_id === false) {
+                        // If the coach-user does not exist - I'm the coach.
+                        $coach_id = $defaultUserId;
+                    }
+                } else {
+                    $coach_id = $defaultUserId;
+                }
+
+                if (!$updatesession) {
+                    // Always create a session.
+                    $unique_name = false; // This MUST be initializead.
+                    $i = 0;
+                    // Change session name, verify that session doesn't exist.
+                    while (!$unique_name) {
+                        if ($i > 1) {
+                            $suffix = ' - '.$i;
+                        }
+                        $sql = 'SELECT 1 FROM '.$tbl_session.' WHERE name="'.$session_name.$suffix.'"';
+                        $rs = Database::query($sql);
+
+                        if (Database::result($rs, 0, 0)) {
+                            $i++;
+                        } else {
+                            $unique_name = true;
+                            $session_name .= $suffix;
+                        }
+                    }
+
+                    // Creating the session.
+                    $sql_session = "INSERT IGNORE INTO $tbl_session SET
+                            name = '".$session_name."',
+                            id_coach = '$coach_id',
+                            date_start = '$date_start',
+                            date_end = '$date_end',
+                            visibility = '$visibility',
+                            session_category_id = '$session_category_id',
+                            session_admin_id=".intval($defaultUserId).$extraParameters;
+                    Database::query($sql_session);
+                    $session_id = Database::insert_id();
+
+                    if ($debug) {
+                        if ($session_id) {
+
+                            foreach ($enreg as $key => $value) {
+                                if (substr($key, 0, 6) == 'extra_') { //an extra field
+                                    self::update_session_extra_field_value($session_id, substr($key, 6), $value);
+                                }
+                            }
+
+                            $logger->addInfo("Sessions - Session created: #$session_id - $session_name");
+                        } else {
+                            $logger->addError("Sessions - Session NOT created: $session_name");
+                        }
+                    }
+                    $session_counter++;
+                } else {
+                    $sessionId = null;
+
+                    if (isset($extraFields) && !empty($extraFields)) {
+                        $sessionId = self::get_session_id_from_original_id($enreg['extra_'.$extraFieldId], $extraFieldId);
+
+                        if (empty($sessionId)) {
+                            $my_session_result = false;
+                        } else {
+                            $my_session_result = true;
+                        }
+                    } else {
+                        $my_session_result = self::get_session_by_name($session_name);
+                    }
+
+                    if ($my_session_result === false) {
+
+                        // Creating a session.
+                        $sql_session = "INSERT IGNORE INTO $tbl_session SET
+                                name = '$session_name',
+                                id_coach = '$coach_id',
+                                date_start = '$date_start',
+                                date_end = '$date_end',
+                                visibility = '$visibility',
+                                session_category_id = '$session_category_id'".$extraParameters;
+
+                        Database::query($sql_session);
+                        // We get the last insert id.
+                        $my_session_result = SessionManager::get_session_by_name($session_name);
+                        $session_id = $my_session_result['id'];
+
+                        if ($debug) {
+                            if ($session_id) {
+                                foreach ($enreg as $key => $value) {
+                                    if (substr($key, 0, 6) == 'extra_') { //an extra field
+                                        self::update_session_extra_field_value($session_id, substr($key, 6), $value);
+                                    }
+                                }
+                                $logger->addInfo("Sessions - #$session_id created: $session_name");
+                            } else {
+                                $logger->addError("Sessions - Session NOT created: $session_name");
+                            }
+                        }
+                    } else {
+
+                        if (isset($sessionId) && !empty($sessionId)) {
+                            // The session already exists, update it then.
+                            $sql_session = "UPDATE $tbl_session SET
+                                    id_coach = '$coach_id',
+                                    date_start = '$date_start',
+                                    date_end = '$date_end',
+                                    visibility = '$visibility',
+                                    session_category_id = '$session_category_id'
+                                WHERE id = '$sessionId'";
+                            //name = '$session_name'
+                            Database::query($sql_session);
+                            $session_id = $sessionId;
+                        } else {
+
+                            // The session already exists, update it then.
+                            $sql_session = "UPDATE $tbl_session SET
+                                    id_coach = '$coach_id',
+                                    date_start = '$date_start',
+                                    date_end = '$date_end',
+                                    visibility = '$visibility',
+                                    session_category_id = '$session_category_id'
+                                WHERE name = '$session_name'";
+                            Database::query($sql_session);
+                            $row = Database::query("SELECT id FROM $tbl_session WHERE name='$session_name'");
+                            list($session_id) = Database::fetch_array($row);
+                        }
+
+                        foreach ($enreg as $key => $value) {
+                            if (substr($key, 0, 6) == 'extra_') { //an extra field
+                                self::update_session_extra_field_value($session_id, substr($key, 6), $value);
+                            }
+                        }
+
+                        Database::query("DELETE FROM $tbl_session_user WHERE id_session='$session_id'");
+                        Database::query("DELETE FROM $tbl_session_course WHERE id_session='$session_id'");
+                        Database::query("DELETE FROM $tbl_session_course_user WHERE id_session='$session_id'");
+                    }
+                    $session_counter++;
+                }
+
+                $users = explode('|', $enreg['Users']);
+
+                // Adding the relationship "Session - User".
+                if (is_array($users)) {
+                    foreach ($users as $user) {
+                        $user_id = UserManager::get_user_id_from_username($user);
+                        if ($user_id !== false) {
+                            // Insert new users.
+                            $sql = "INSERT IGNORE INTO $tbl_session_user SET
+                                    id_user = '$user_id',
+                                    id_session = '$session_id'";
+                            Database::query($sql);
+                            if ($debug) {
+                                $logger->addInfo("Sessions - Adding User #$user_id ($user) to session #$session_id");
+                            }
+                            $user_counter++;
+                        }
+                    }
+                }
+
+                $courses = explode('|', $enreg['Courses']);
+
+                foreach ($courses as $course) {
+                    $course_code = api_strtoupper(api_substr($course, 0, api_strpos($course, '[')));
+
+                    if (CourseManager::course_exists($course_code)) {
+
+                        $coach = api_strstr($course, '[');
+                        $coach = api_substr($coach, 1, api_strpos($coach,']') - 1);
+
+                        if (!empty($coach)) {
+                            $coach_id = UserManager::get_user_id_from_username($coach);
+                            if ($coach_id === false) {
+                                $coach_id = '';
+                            }
+                        } else {
+                            $coach = '';
+                        }
+
+                        // Adding the course to a session.
+                        $sql_course = "INSERT IGNORE INTO $tbl_session_course SET
+                                course_code = '$course_code',
+                                id_session='$session_id'";
+                        Database::query($sql_course);
+
+                        if ($debug) {
+                            $logger->addInfo("Sessions - Adding course '$course_code' to session #$session_id");
+                        }
+                        $course_counter++;
+
+                        $pattern = "/\[(.*?)\]/";
+                        preg_match_all($pattern, $course, $matches);
+
+                        if (isset($matches[1])) {
+                            $course_coaches = $matches[1][0];
+                            $course_users   = $matches[1][1];
+                        }
+
+                        $course_users   = explode(',', $course_users);
+                        $course_coaches = explode(',', $course_coaches);
+
+                        // Adding coaches to session course user
+                        if (!empty($course_coaches)) {
+                            foreach ($course_coaches as $course_coach) {
+                                $coach_id = UserManager::get_user_id_from_username($course_coach);
+                                if ($coach_id !== false) {
+                                    $sql = "INSERT IGNORE INTO $tbl_session_course_user SET
+                                            id_user='$coach_id',
+                                            course_code='$course_code',
+                                            id_session = '$session_id',
+                                            status = 2 ";
+                                    Database::query($sql);
+                                    if ($debug) {
+                                        $logger->addInfo("Sessions - Adding course coach: user #$coach_id ($course_coach) to course: '$course_code' and session #$session_id");
+                                    }
+                                } else {
+                                    $error_message .= get_lang('UserDoesNotExist').' : '.$course_coach.$eol;
+                                }
+                            }
+                        }
+
+                        $users_in_course_counter = 0;
+
+                        // Adding the relationship "Session - Course - User".
+
+                        foreach ($course_users as $user) {
+                            $user_id = UserManager::get_user_id_from_username($user);
+
+                            if ($user_id !== false) {
+                                $sql = "INSERT IGNORE INTO $tbl_session_course_user SET
+                                        id_user='$user_id',
+                                        course_code='$course_code',
+                                        id_session = '$session_id'";
+                                Database::query($sql);
+                                if ($debug) {
+                                    $logger->addInfo("Sessions - Adding student: user #$user_id ($user) to course: '$course_code' and session #$session_id");
+                                }
+                                $users_in_course_counter++;
+                            } else {
+                                $error_message .= get_lang('UserDoesNotExist').': '.$user.$eol;
+                            }
+                        }
+
+                        $sql = "UPDATE $tbl_session_course SET nbr_users='$users_in_course_counter' WHERE course_code='$course_code'";
+                        Database::query($sql);
+
+                        $course_info = CourseManager::get_course_information($course_code);
+                        $inserted_in_course[$course_code] = $course_info['title'];
+                    } else {
+                        // TODO: We should create the course as in the XML import.
+                    }
+
+
+                    if (CourseManager::course_exists($course_code, true)) {
+
+                        $list = CourseManager :: get_courses_info_from_visual_code($course_code);
+
+                        foreach ($list as $vcourse) {
+
+                            if ($vcourse['code'] == $course_code) {
+                                // Ignore, this has already been inserted.
+                            } else {
+
+                                $coach = api_strstr($course, '[');
+                                $coach = api_substr($coach, 1, api_strpos($coach,']') - 1);
+
+                                // Adding the relationship "Session - Course".
+                                $sql_course = "INSERT IGNORE INTO $tbl_session_course SET
+                                                course_code = '".$vcourse['code']."',
+                                                id_session='$session_id'";
+
+                                Database::query($sql_course);
+
+                                if ($debug) {
+                                    $logger->addInfo("Sessions - Adding course to session: course: '".$vcourse['code']."' and session #$session_id");
+                                }
+
+                                // Adding coachs to session course user
+                                foreach ($course_coaches as $course_coach) {
+                                    $coach_id = UserManager::get_user_id_from_username($course_coach);
+                                    if ($coach_id !== false) {
+                                        $sql = "INSERT IGNORE INTO $tbl_session_course_user SET
+                                                id_user='$coach_id',
+                                                course_code='{$vcourse['code']}',
+                                                id_session = '$session_id',
+                                                status = 2 ";
+                                        Database::query($sql);
+
+                                        if ($debug) {
+                                            $logger->addInfo("Sessions - Adding coach to session: user #$coach_id ($course_coach) course: '".$vcourse['code']."' and session #$session_id");
+                                        }
+
+                                    } else {
+                                        $error_message .= get_lang('UserDoesNotExist').' : '.$course_coach.$eol;
+                                    }
+                                }
+
+
+                                $users_in_course_counter = 0;
+                                // Adding the relationship "Session - Course - User".
+                                foreach ($course_users as $user) {
+                                    $user_id = UserManager::get_user_id_from_username($user);
+                                    if ($user_id !== false) {
+                                        $sql = "INSERT IGNORE INTO $tbl_session_course_user SET
+                                                id_user='$user_id',
+                                                course_code='{$vcourse['code']}',
+                                                id_session = '$session_id'";
+                                        Database::query($sql);
+
+                                        if ($debug) {
+                                            $logger->addInfo("Sessions - Adding user to session: user #$user_id ($user) course: '".$vcourse['code']."' and session #$session_id");
+                                        }
+
+                                        $users_in_course_counter++;
+                                    } else {
+                                        $error_message .= get_lang('UserDoesNotExist').' : '.$user.$eol;
+                                    }
+                                }
+                                Database::query("UPDATE $tbl_session_course SET nbr_users='$users_in_course_counter' WHERE course_code='".$vcourse['code']."'");
+                            }
+                        }
+                        $inserted_in_course[$vcourse['code']] = $vcourse['title'];
+                    }
+                }
+                $access_url_id = api_get_current_access_url_id();
+                UrlManager::add_session_to_url($session_id, $access_url_id);
+                $sql_update_users = "UPDATE $tbl_session SET nbr_users='$user_counter', nbr_courses='$course_counter' WHERE id='$session_id'";
+                Database::query($sql_update_users);
+            }
+        }
+
+        return array(
+            'error_message' => $error_message,
+            'session_counter' =>  $session_counter
+        );
+    }
+
     /**
      *  @todo Add constatns in a DB table
      */

+ 1 - 1
main/inc/lib/social.lib.php

@@ -585,7 +585,7 @@ class SocialManager extends UserManager {
                        // Do something?
                     if ($user_id != api_get_user_id()) {
                         if ($current_user_info['user_is_online_in_chat'] == 1) {
-                            $message = Security::remove_XSS(sprintf(get_lang("YouHaveToAddXAsAFriendFirst", $user_name)));
+                            $message = Security::remove_XSS(sprintf(get_lang("YouHaveToAddXAsAFriendFirst"), $user_name));
                             $options = array('onclick' => "javascript:chatNotYetWith('".$message."')");
                             $chat_icon = $user_info['user_is_online_in_chat'] ? Display::return_icon('online.png', get_lang('Online')) : Display::return_icon('offline.png', get_lang('Offline'));
                             $html .= Display::tag('li', Display::url($chat_icon.'&nbsp;&nbsp;'.get_lang('Chat'), 'javascript:void(0);', $options));

+ 0 - 3
main/inc/lib/usermanager.lib.php

@@ -4252,7 +4252,4 @@ class UserManager
         }
         return $users;
     }
-
-
-
 }

+ 6 - 0
main/lang/arabic/admin.inc.php

@@ -750,4 +750,10 @@ $CannotMakeFieldChangeable = "لايمكن جعل الحقل قابلا للتغ
 $CannotMakeFieldUnchangeable = "لايمكن جعل الحقل قابلا للتغيير";
 $FieldDeleted = "تم حذف الحقل";
 $CannotDeleteField = "لا يستطيع حذف الحقل";
+$GoToCourseAfterLoginTitle = "الذهاب الي المقرر يعد التسجيل";
+$GoToCourseAfterLoginComment = "الذهاب الي المقرر يعد تسجيل المستخدم";
+$GroupList = "قائمة المجموعات";
+$MessagesSent = "عدد الرسائل المرسلة";
+$MessagesReceived = "عدد الرسائل المستقبلة";
+$phone = "الهاتف";
 ?>

+ 7 - 0
main/lang/arabic/agenda.inc.php

@@ -60,5 +60,12 @@ $RepeatType = "كرر النوع";
 $RepeatDaily = "يوميا";
 $RepeatWeekly = "أسبوعيا";
 $RepeatMonthlyByDate = "شهريا، حسب التاريخ";
+$RepeatMonthlyByDay = "شهري او يومي";
+$RepeatMonthlyByDayR = "شهري, يومي او محظور";
+$RepeatYearly = "سنوي";
+$RepeatEnd = "تكرار تاريخ الانتهاء";
+$RepeatedEventViewOriginalEvent = "اظهار الحدث الاصلي";
+$ICalFileImport = "استيراد لبربد Outlook";
 $AllUsersOfThePlatform = "جميع مستخدمي البرنامج";
+$AllEvents = "كل الاحداث";
 ?>

+ 3 - 0
main/lang/arabic/announcements.inc.php

@@ -56,4 +56,7 @@ $AnnounceSentToUserSelection = "الإعلانات أرسلت للمستخدمي
 $SendAnnouncement = "إرسال إعلان";
 $ModifyAnnouncement = "تعديل إعلان";
 $ButtonPublishAnnouncement = "إرسال إعلان";
+$YourAccountIsActiveYouCanLoginAndCheckYourCourses = "عزيزي الطالب تم تفعيل الحساب الخاص بك فضلا ادخل علي حسابك واسنمتع يالمقررات المتاحة";
+$AddAsAnnouncement = "اضف كاعلان";
+$AnnouncementForGroup = "اعلان للمجموعة";
 ?>

+ 1 - 0
main/lang/arabic/course_home.inc.php

@@ -25,4 +25,5 @@ $Authoring = " التحرير";
 $Administration = " الإدارة";
 $IntroductionTextUpdated = " تم تحديث النص التوضيحي";
 $IntroductionTextDeleted = "تم حذف نص المقدمة";
+$ToolSearch = "بحث";
 ?>

+ 2 - 0
main/lang/arabic/courses.inc.php

@@ -2,6 +2,7 @@
 /*
 for more information: see languages.txt in the lang folder.
 */
+$AlreadyRegisteredToCourse = "لقد تم التسجيل من قيل";
 $lang_already_enrolled = " مسجل مسبقا";
 $lang_my_personnal_course_list = " قائمة مقرراتي الخاصة";
 $lang_course_enrollment = " مقررات المستخدمين";
@@ -70,4 +71,5 @@ $SubmitRegistrationCode = " ارسل رمز التسجيل";
 $CourseCategoryDeleted = " تم حذف تصنيف المقرر";
 $CategorySortingDone = " تم ترتيب التصنيف";
 $CourseCategoryEditStored = " تم تحديث التصنيف";
+$Compose = "انشاء رسالة";
 ?>

+ 1 - 1
main/lang/arabic/document.inc.php

@@ -213,7 +213,7 @@ $HelpDefaultDirDocuments = "ـ المعلومات مرئية للمعلم فقط
 $TemplateImage = "أيقونة قالب";
 $MoveElement = "أنقل العنصر";
 $CertificateName = "الاسم";
-$CopyToMyFiles = "انسخ الى منطقة الملفات الخاصة التي لي";
+$CopyToMyFiles = "انسخ الى منطقة الملفات خاصتي";
 $Export2PDF = "صدِّر الى هيئة بي دي اف";
 $ResourceShared = "مورد مشترك";
 $CopyAlreadyDone = "هناك ملف بنفس الاسم في منطقة الملفات الخاصة بك. هل تريد استبداله؟";

Энэ ялгаанд хэт олон файл өөрчлөгдсөн тул зарим файлыг харуулаагүй болно