diff options
author | prashant | 2016-01-30 12:25:22 +0530 |
---|---|---|
committer | prashantsinalkar | 2016-01-30 13:05:18 +0530 |
commit | 205c03ca3b0c7caaf42ba2e7649edd4ee06ccc44 (patch) | |
tree | 7e4b74e141452039fe6d5618cd058d2a2e696e75 | |
parent | 96743e5f2674f353030512da2a58db05658912c2 (diff) | |
download | DWSIM_textbook_companion-205c03ca3b0c7caaf42ba2e7649edd4ee06ccc44.tar.gz DWSIM_textbook_companion-205c03ca3b0c7caaf42ba2e7649edd4ee06ccc44.tar.bz2 DWSIM_textbook_companion-205c03ca3b0c7caaf42ba2e7649edd4ee06ccc44.zip |
Done minor changes and added submit all code notification for tbc reviver interface
-rwxr-xr-x | README | 2 | ||||
-rwxr-xr-x | cheque_contact.inc | 378 | ||||
-rwxr-xr-x | cheque_manage.inc | 44 | ||||
-rwxr-xr-x | code.inc | 1035 | ||||
-rwxr-xr-x | code_approval.inc | 2204 | ||||
-rwxr-xr-x | css/jquery-ui.css | 1178 | ||||
-rwxr-xr-x | css/textbook_companion.css | 120 | ||||
-rwxr-xr-x | dependency.inc | 1414 | ||||
-rwxr-xr-x | dependency_approval.inc | 395 | ||||
-rwxr-xr-x | download.inc | 421 | ||||
-rwxr-xr-x | editcode.inc | 1666 | ||||
-rwxr-xr-x | editcodeadmin.inc | 1258 | ||||
-rwxr-xr-x | full_download.inc | 325 | ||||
-rwxr-xr-x | general.inc | 558 | ||||
-rwxr-xr-x | js/jquery-1.9.1.js | 9598 | ||||
-rwxr-xr-x | js/jquery-ui.js | 15004 | ||||
-rwxr-xr-x | js/jquery.js | 6 | ||||
-rwxr-xr-x | js/textbook_companion.js | 210 | ||||
-rwxr-xr-x | latex.inc | 423 | ||||
-rwxr-xr-x | latex/Initial_body | 112 | ||||
-rwxr-xr-x | manage_proposal.inc | 3055 | ||||
-rwxr-xr-x | notes.inc | 257 | ||||
-rwxr-xr-x | pdf/generate_pdf.inc | 240 | ||||
-rwxr-xr-x | pdf/images/dwsim_logo.png | bin | 0 -> 6200 bytes | |||
-rwxr-xr-x | pdf/list_all_certificates.inc | 202 | ||||
-rwxr-xr-x | run.inc | 870 | ||||
-rwxr-xr-x | search.inc | 648 | ||||
-rwxr-xr-x | settings.inc | 158 | ||||
-rwxr-xr-x | textbook_companion.info | 6 | ||||
-rwxr-xr-x | textbook_companion.install | 991 | ||||
-rwxr-xr-x | textbook_companion.module | 6062 |
31 files changed, 13108 insertions, 35732 deletions
@@ -1,2 +1,2 @@ -Textbook Companion project for IIT Bombay written in Drupal 6 +Textbook Companion project Module for IIT Bombay written in Drupal 7 diff --git a/cheque_contact.inc b/cheque_contact.inc index 335ee42..65208fd 100755 --- a/cheque_contact.inc +++ b/cheque_contact.inc @@ -6,12 +6,19 @@ function paper_submission_form($form_state, $proposal_id) $proposal_id = arg(2); /* get current proposal */ - $preference4_q = db_query("SELECT * FROM {textbook_companion_paper} WHERE proposal_id=".$proposal_id); + + /*$preference4_q = db_query("SELECT * FROM {textbook_companion_paper} WHERE proposal_id=".$proposal_id);*/ + + $query = db_select('textbook_companion_paper'); + $query->fields('textbook_companion_paper'); + $query->condition('proposal_id', $proposal_id); + $preference4_q = $query->execute(); + $form1=0; $form2=0; $form3=0; $form4=0; - if($data = db_fetch_object($preference4_q)) + if($data = $preference4_q->fetchObject()) { $form1 = $data->internship_form; $form2 = $data->copyright_form; @@ -20,8 +27,11 @@ function paper_submission_form($form_state, $proposal_id) } else { - $query = "insert into {textbook_companion_paper} (proposal_id) values(".$proposal_id.")"; - db_query($query); + $query = "Insert into {textbook_companion_paper} (proposal_id) values (:proposal_id)"; + $args = array( + ":proposal_id"=>$proposal_id, + ); + $result = db_query($query, $args, array('return' => Database::RETURN_INSERT_ID)); } $form['proposal_id'] =array( '#type' => 'hidden', @@ -65,8 +75,18 @@ function paper_submission_form($form_state, $proposal_id) function paper_submission_form_submit($form, &$form_state) { - $query ="UPDATE {textbook_companion_paper} SET internship_form = ".$form_state['values']['internshipform'].", copyright_form = ".$form_state['values']['copyrighttransferform'].", undertaking_form= ".$form_state['values']['undertakingform'].", reciept_form= ".$form_state['values']['recieptform']." WHERE proposal_id = ".$form_state['values']['proposal_id']; - db_query($query); + /*$query ="UPDATE {textbook_companion_paper} SET internship_form = ".$form_state['values']['internshipform'].", copyright_form = ".$form_state['values']['copyrighttransferform'].", undertaking_form= ".$form_state['values']['undertakingform'].", reciept_form= ".$form_state['values']['recieptform']." WHERE proposal_id = ".$form_state['values']['proposal_id']; + db_query($query);*/ + + $query = db_update('textbook_companion_paper'); + $query->fields(array( + 'internship_form' => $form_state[ values ][ internshipform ], + 'copyright_form' => $form_state[ values ][ copyrighttransferform ], + 'undertaking_form' => $form_state[ values ][ undertakingform ], + 'reciept_form' => $form_state[ values ][ recieptform ], + )); + $query->condition('proposal_id', $form_state['values']['proposal_id']); + $num_updated = $query->execute(); /************************************************ Check For the Internship Form is checked or not @@ -204,8 +224,14 @@ function cheque_contct_form() { global $user; - $preference4_q = db_query("SELECT id FROM {textbook_companion_proposal} WHERE uid=".$user->uid); - $data = db_fetch_object($preference4_q); + /*$preference4_q = db_query("SELECT id FROM {textbook_companion_proposal} WHERE uid=".$user->uid);*/ + + $query = db_select('textbook_companion_proposal'); + $query->fields('id', array('')); + $query->condition('uid', $user->uid); + $result = $query->execute(); + $data = $result->fetchObject(); + $form1 = $data->id; if($user->uid) @@ -234,20 +260,26 @@ function cheque_contct_form() '#attributes' => array('id' => 'perm_report'), ); - $search_q = db_query("SELECT * FROM textbook_companion_proposal p,textbook_companion_cheque c WHERE c.address_con = 'Submitted' AND (p.id = c.proposal_id)"); + /*$search_q = db_query("SELECT * FROM textbook_companion_proposal p,textbook_companion_cheque c WHERE c.address_con = 'Submitted' AND (p.id = c.proposal_id)");*/ + $query = db_select('textbook_companion_proposal', 'p'); + $query->join('textbook_companion_cheque','c','p.id = c.proposal_id'); + $query->fields('p',array('textbook_companion_proposal')); + $query->fields('c',array('textbook_companion_cheque')); + $query->condition('c.address_con','Submitted'); + $result = $query->execute(); - while ($search_data = db_fetch_object($search_q)) + while ($search_data = $result->fetchObject()) { $search_rows[] = array(l($search_data->full_name, 'cheque_contct/status/' . $search_data->proposal_id),$search_data->address_con,$search_data->cheque_no,$search_data->cheque_dispatch_date); } if ($search_rows) { $search_header = array('Name Of The Student', 'Application Form Status', 'Cheque No', 'Cheque Clearance Date'); - $output .= theme_table($search_header, $search_rows); + $output .= theme('table',array('headers'=>$search_header, 'rows'=>$search_rows)); $form['search_results'] = array( '#type' => 'item', '#title' => $_POST['search'] , - '#value' => $output, + '#markup' => $output, ); } else @@ -255,7 +287,7 @@ function cheque_contct_form() $form['search_results'] = array( '#type' => 'item', '#title' => t('Search results for "') . $_POST['search'] . '"', - '#value' => 'No results found', + '#markup' => 'No results found', ); } if ($_POST) @@ -263,19 +295,29 @@ function cheque_contct_form() $output = ''; $search_rows = array(); $search_quert = ''; - $search_q = db_query("SELECT * FROM textbook_companion_proposal p,textbook_companion_cheque c WHERE c.address_con = 'Submitted' AND (p.id = c.proposal_id) AND (p.full_name LIKE '%%%s%%')", $_POST['search']); - while ($search_data = db_fetch_object($search_q)) + + /*$search_q = db_query("SELECT * FROM textbook_companion_proposal p,textbook_companion_cheque c WHERE c.address_con = 'Submitted' AND (p.id = c.proposal_id) AND (p.full_name LIKE '%%%s%%')", $_POST['search']);*/ + $query = db_select('textbook_companion_proposal', 'p'); + $query->join('textbook_companion_cheque','c','p.id = c.proposal_id'); + $query->fields('p',array('textbook_companion_proposal')); + $query->fields('c',array('textbook_companion_cheque')); + $query->condition('c.address_con', 'Submitted'); + $query->condition('p.full_name', '%%'.$_POST['search'].'%%', 'LIKE'); + $result = $query->execute(); + + + while ($search_data = $result->fetchObject()) { $search_rows[] = array(l($search_data->full_name, 'cheque_contct/status/' . $search_data->proposal_id),$search_data->address_con,$search_data->cheque_no,$search_data->cheque_dispatch_date); } if ($search_rows) { $search_header = array('Name Of The Student', 'Application Form Status', 'Cheque No', 'Cheque Clearance Date'); - $output .= theme_table($search_header, $search_rows); + $output .= theme('table',array('headers'=>$search_header,'rows'=>$search_rows)); $form['search_results'] = array( '#type' => 'item', '#title' => t('Search results for "') . $_POST['search'] . '"', - '#value' => $output, + '#markup' => $output, ); } else @@ -283,7 +325,7 @@ function cheque_contct_form() $form['search_results'] = array( '#type' => 'item', '#title' => t('Search results for "') . $_POST['search'] . '"', - '#value' => 'No results found', + '#markup' => 'No results found', ); } } @@ -291,14 +333,28 @@ function cheque_contct_form() } else { - $preference5_q = db_query("SELECT * FROM {textbook_companion_paper} WHERE proposal_id=".$form1); - $data1 = db_fetch_object($preference5_q); + /*$preference5_q = db_query("SELECT * FROM {textbook_companion_paper} WHERE proposal_id=".$form1); + $data1 = db_fetch_object($preference5_q);*/ + $query = db_select('textbook_companion_paper'); + $query->fields('textbook_companion_paper'); + $query->condition('proposal_id', $form1); + $result = $query->execute(); + $data1=$result->fetchObject(); + $form2 = $data1->internship_form; $form3 = $data1->copyright_form; $form4 = $data1->undertaking_form; $form5 = $data1->reciept_form; - $chq_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id=".$form1); - $data_chq = db_fetch_object($chq_q); + + /*$chq_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id=".$form1); + $data_chq = db_fetch_object($chq_q);*/ + + $query = db_select('textbook_companion_proposal'); + $query->fields('textbook_companion_proposal'); + $query->condition('id', $form1); + $result = $query->execute(); + $data_chq=$result->fetchObject(); + $form9 = $data_chq->full_name; $form8 = $data->how_project; $form10 = $data_chq->mobile; @@ -324,7 +380,7 @@ function cheque_contct_form() $form['how_project'] = array( '#type' => 'select', '#title' => t('How did you come to know about this project'), - '#options' => array('Scilab Website' => 'Scilab Website', + '#options' => array('eSim Website' => 'eSim Website', 'Friend' => 'Friend', 'Professor/Teacher' => 'Professor/Teacher', 'Mailing List' => 'Mailing List', @@ -402,10 +458,21 @@ function cheque_status_form($form_state, $proposal_id) /* get current proposal */ $proposal_id = arg(2); - $proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id =".$proposal_id); - $proposal_q1 = db_query("SELECT * FROM {textbook_companion_cheque} WHERE proposal_id =".$proposal_id); - $proposal_data1 = db_fetch_object($proposal_q1); - if (!$proposal_data = db_fetch_object($proposal_q)) + /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id =".$proposal_id);*/ + $query = db_select('textbook_companion_proposal'); + $query->fields('textbook_companion_proposal'); + $query->condition('id', $proposal_id); + $proposal_q = $query->execute(); + + /*$proposal_q1 = db_query("SELECT * FROM {textbook_companion_cheque} WHERE proposal_id =".$proposal_id);*/ + $query = db_select('textbook_companion_cheque'); + $query->fields('textbook_companion_cheque'); + $query->condition('proposal_id', $proposal_id); + $proposal_q1 = $query->execute(); + + + $proposal_data1 = $proposal_q1->fetchObject(); + if (!$proposal_data = $proposal_q->fetchObject()) { drupal_set_message(t('Invalid proposal selected. Please try again.'), 'error'); drupal_goto('manage_proposal'); @@ -415,10 +482,22 @@ function cheque_status_form($form_state, $proposal_id) '#type' => 'hidden', '#default_value' => $proposal_id, ); - $empty = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = ".$proposal_id); + + /*$empty = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = ".$proposal_id);*/ + $query = db_select('textbook_companion_proposal'); + $query->fields('textbook_companion_proposal'); + $query->condition('id', $proposal_id); + $empty = $query->execute(); + if(!$empty) { - $prop =db_query("insert into {textbook_companion_cheque} (proposal_id) values(%d)",$proposal_id); + /*$prop =db_query("insert into {textbook_companion_cheque} (proposal_id) values(%d)",$proposal_id);*/ + + $query = "insert into {textbook_companion_cheque} (proposal_id) values (:proposal_id)"; + $args = array( + ":proposal_id"=>$proposal_id, + ); + $result = db_query($query, $args, array('return' => Database::RETURN_INSERT_ID)); } $form['candidate_detail'] = array( '#type' => 'fieldset', @@ -429,31 +508,44 @@ function cheque_status_form($form_state, $proposal_id) ); $form['candidate_detail']['full_name'] = array( '#type' => 'item', - '#value' => $proposal_data->full_name, + '#markup' => $proposal_data->full_name, '#title' => t('Contributor Name'), ); $form['candidate_detail']['email'] = array( '#type' => 'item', - '#value' => user_load($proposal_data->uid)->mail, + '#markup' => user_load($proposal_data->uid)->mail, '#title' => t('Email'), ); $form['candidate_detail']['mobile'] = array( '#type' => 'item', - '#value' => $proposal_data->mobile, + '#markup' => $proposal_data->mobile, '#title' => t('Mobile'), ); $form['candidate_detail']['alt_mobile'] = array( '#type' => 'item', - '#value' => $proposal_data1->alt_mobno, + '#markup' => $proposal_data1->alt_mobno, '#title' => t('Alternate Mobile No.'), ); - $form_q=db_query("SELECT * FROM {textbook_companion_paper} WHERE proposal_id =".$proposal_id); - $form_data=db_fetch_object($form_q); + /*$form_q=db_query("SELECT * FROM {textbook_companion_paper} WHERE proposal_id =".$proposal_id); + $form_data=db_fetch_object($form_q);*/ + + $query = db_select('textbook_companion_paper'); + $query->fields('textbook_companion_paper'); + $query->condition('proposal_id', $proposal_id); + $result = $query->execute(); + $form_data=$result->fetchObject(); /* get book preference */ $preference_html = '<ul>'; - $preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d ORDER BY pref_number ASC", $proposal_id); - while ($preference_data = db_fetch_object($preference_q)) + + /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d ORDER BY pref_number ASC", $proposal_id);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('proposal_id', $proposal_id); + $query->orderBy('pref_number', 'ASC'); + $preference_q = $query->execute(); + + while ($preference_data = $preference_q->fetchObject()) { if ($preference_data->approval_status == 1) $preference_html .= '<li><strong>' . $preference_data->book . ' (Written by ' . $preference_data->author . ') - Approved Book</strong></li>'; @@ -470,11 +562,18 @@ function cheque_status_form($form_state, $proposal_id) ); $form['book_preference_f']['book_preference'] = array( '#type' => 'item', - '#value' => $preference_html, + '#markup' => $preference_html, '#title' => t('Book Preferences'), ); - $chq_q=db_query("SELECT * FROM {textbook_companion_cheque} WHERE proposal_id = %d", $proposal_id); - $chq_data=db_fetch_object($chq_q); + + /*$chq_q=db_query("SELECT * FROM {textbook_companion_cheque} WHERE proposal_id = %d", $proposal_id); + $chq_data=db_fetch_object($chq_q);*/ + $query = db_select('textbook_companion_cheque'); + $query->fields('textbook_companion_cheque'); + $query->condition('proposal_id', $proposal_id); + $result = $query->execute(); + $chq_data=$result->fetchObject(); + $form_html .= '<ul>'; if($form_data->internship_form) { @@ -503,7 +602,7 @@ function cheque_status_form($form_state, $proposal_id) $form_html .= '</ul>'; $form['book_preference_f']['formsubmit'] = array( '#type' => 'item', - '#value' => $form_html, + '#markup' => $form_html, '#title' => t('Application Form Status'), ); $form['stu_cheque_details'] = array( @@ -548,7 +647,11 @@ function cheque_status_form($form_state, $proposal_id) '#collapsed' => FALSE, '#attributes' => array('id' => 'commentf'), ); - $chq4_q = db_query("SELECT * FROM {textbook_companion_cheque} WHERE proposal_id=".$proposal_id); + /*$chq4_q = db_query("SELECT * FROM {textbook_companion_cheque} WHERE proposal_id=".$proposal_id);*/ + $query = db_select('textbook_companion_cheque'); + $query->fields('textbook_companion_cheque'); + $query->condition('proposal_id', $proposal_id); + $chq4_q = $query->execute(); $chq1 = ''; $chq2 = ''; @@ -567,7 +670,7 @@ function cheque_status_form($form_state, $proposal_id) $chq15 = ''; $chq16 = ''; $chq17 = ''; - if($chqe = db_fetch_object($chq4_q)) + if($chqe = $chq4_q->fetchObject()) { $chq1 = $chqe->cheque_no; $chq2 = $chqe->address; @@ -772,8 +875,16 @@ function cheque_status_form($form_state, $proposal_id) '#type' => 'hidden', '#value' => $proposal_id, ); - $preference1_p = db_query("SELECT * FROM {textbook_companion_paper} WHERE proposal_id = %d ORDER BY id ASC", $proposal_id); - if (!($proposal_data1 = db_fetch_object($preference1_p))) + + /*$preference1_p = db_query("SELECT * FROM {textbook_companion_paper} WHERE proposal_id = %d ORDER BY id ASC", $proposal_id); */ + + $query = db_select('textbook_companion_paper'); + $query->fields('textbook_companion_paper'); + $query->condition('proposal_id', $proposal_id); + $query->orderBy('id', 'ASC'); + $preference1_p = $query->execute(); + + if (!($proposal_data1 = $preference1_p->fetchObject())) { drupal_set_message(t('Invalid proposal selected. Please try again.'), 'error'); drupal_goto('manage_proposal'); @@ -821,7 +932,7 @@ function cheque_status_form_submit($form, &$form_state) $proposal_id=arg(2); - $query ="UPDATE {textbook_companion_cheque} SET + /*$query ="UPDATE {textbook_companion_cheque} SET cheque_no = ".$form_state['values']['cheque_no'].", cheque_amt = ".$form_state['values']['cheq_amt'].", alt_mobno = '".$form_state['values']['mobileno2']."', @@ -838,12 +949,41 @@ function cheque_status_form_submit($form, &$form_state) t_cheque_amt = ".$form_state['values']['cheq_amt_t']." WHERE proposal_id = ".$proposal_id; - db_query($query); + db_query($query);*/ + + $query = db_update('textbook_companion_cheque'); + $query->fields(array( + 'cheque_no' => $form_state[ values ][ cheque_no ], + 'cheque_amt' => $form_state[ values ][ cheq_amt ], + 'alt_mobno' => $form_state[ values ][ mobileno2 ], + 'address' => $form_state[ values ][ chq_address ], + 'perm_city' => $form_state[ values ][ perm_city ], + 'perm_state' => $form_state[ values ][ perm_state ], + 'perm_pincode' => $form_state[ values ][ perm_pincode ], + 'temp_chq_address' => $form_state[ values ][ temp_chq_address ], + 'temp_city' => $form_state[ values ][ temp_city ], + 'temp_state' => $form_state[ values ][ temp_state ], + 'temp_pincode' => $form_state[ values ][ temp_pincode ], + 'commentf' => $form_state[ values ][ comment_cheque ], + 't_cheque_no' => $form_state[ values ][ cheque_no_t ], + 't_cheque_amt' => $form_state[ values ][ cheq_amt_t ], + )); + $query->condition('proposal_id', $proposal_id); + $num_updated = $query->execute(); + if ($form_state['values']['cheque_sent'] == 1) { /* sending email */ - $query ="UPDATE {textbook_companion_cheque} SET cheque_sent = ".$form_state['values']['cheque_sent']." WHERE proposal_id = ".$proposal_id; - db_query($query); + /*$query ="UPDATE {textbook_companion_cheque} SET cheque_sent = ".$form_state['values']['cheque_sent']." WHERE proposal_id = ".$proposal_id; + db_query($query);*/ + + $query = db_update('textbook_companion_cheque'); + $query->fields(array( + 'cheque_sent' => $form_state[ values ][ cheque_sent ], + )); + $query->condition('proposal_id', $proposal_id); + $num_updated = $query->execute(); + $book_user = user_load($proposal_data->uid); $param['proposal_completed']['proposal_id'] = $proposal_id; $param['proposal_completed']['user_id'] = $proposal_data->uid; @@ -856,13 +996,28 @@ function cheque_status_form_submit($form, &$form_state) if ($form_state['values']['cheque_cleared'] == 1) { - $query ="UPDATE {textbook_companion_cheque} SET cheque_cleared = ".$form_state['values']['cheque_cleared']." WHERE proposal_id = ".$proposal_id; - db_query($query); + /*$query ="UPDATE {textbook_companion_cheque} SET cheque_cleared = ".$form_state['values']['cheque_cleared']." WHERE proposal_id = ".$proposal_id; + db_query($query);*/ + + $query = db_update('textbook_companion_cheque'); + $query->fields(array( + 'cheque_cleared' => $form_state[ values ][ cheque_cleared ], + )); + $query->condition('proposal_id', $proposal_id); + $num_updated = $query->execute(); + $curtime = MySQL_NOW(); echo $curtime; drupal_set_message('Cheque Has Been Debited into User Account.', 'status'); - $queryc ="UPDATE {textbook_companion_cheque} SET cheque_dispatch_date = NOW() WHERE proposal_id = ".$form_state['values']['proposal_id'].""; - db_query($queryc); + /*$queryc ="UPDATE {textbook_companion_cheque} SET cheque_dispatch_date = NOW() WHERE proposal_id = ".$form_state['values']['proposal_id'].""; + db_query($queryc);*/ + + $query = db_update('textbook_companion_cheque'); + $query->fields(array( + 'cheque_dispatch_date' => 'NOW', + )); + $query->condition('proposal_id', $form_state['values']['proposal_id']); + $num_updated = $query->execute(); } /************************************************ @@ -895,15 +1050,30 @@ function contact_details($form_state) drupal_set_message('<strong>Caution</strong>:Please update Contact Detail carefully as this will be used for future reference during <strong>Payment</strong></li></ul>', 'error'); $x = $user->uid; - $query2 = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid=".$x); - $data2 = db_fetch_object($query2); + /*$query2 = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid=".$x); + $data2 = db_fetch_object($query2);*/ + + $query = db_select('textbook_companion_proposal'); + $query->fields('textbook_companion_proposal'); + $query->condition('uid', $x); + $result = $query->execute(); + $data2=$result->fetchObject(); + + if(!$data2) { drupal_set_message('Fill Up The <a href="proposal">Book Proposal Form</a>', 'error'); return ''; } - $query3 = db_query("SELECT * FROM {textbook_companion_preference} WHERE approval_status=1 AND proposal_id=".$data2->id); - $data3 = db_fetch_object($query3); + /*$query3 = db_query("SELECT * FROM {textbook_companion_preference} WHERE approval_status=1 AND proposal_id=".$data2->id); + $data3 = db_fetch_object($query3);*/ + + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('approval_status', 1); + $query->condition('proposal_id', $data2->id); + $result = $query->execute(); + $data3=$result->fetchObject(); if(!$data3->approval_status) { @@ -912,12 +1082,26 @@ function contact_details($form_state) } $proposal_id = $data2->id; - $comment_qx = db_query("SELECT * FROM textbook_companion_cheque c WHERE proposal_id =".$proposal_id); - $commentv = db_fetch_object($comment_qx); + + /*$comment_qx = db_query("SELECT * FROM textbook_companion_cheque c WHERE proposal_id =".$proposal_id); + $commentv = db_fetch_object($comment_qx);*/ + + $query = db_select('textbook_companion_cheque', 'c'); + $query->fields('c'); + $query->condition('proposal_id', $proposal_id); + $result = $query->execute(); + $commentv=$result->fetchObject(); + $form16 = $commentv->commentf; $mob_no = $data2->mobile; $full_name = $data2->full_name; - $query1 = db_query("SELECT * FROM {textbook_companion_cheque} WHERE proposal_id=".$proposal_id); + + /*$query1 = db_query("SELECT * FROM {textbook_companion_cheque} WHERE proposal_id=".$proposal_id);*/ + $query = db_select('textbook_companion_cheque'); + $query->fields('textbook_companion_cheque'); + $query->condition('proposal_id', $proposal_id); + $result = $query->execute(); + $form1 = 0; $form2 = 0; $form3 = 0; @@ -934,7 +1118,7 @@ function contact_details($form_state) $form14 = 0; $form15 = 0; - if($data = db_fetch_object($query1)) + if($data = $result->fetchObject()) { $form1 = $data->address; $form8 = $data->alt_mobno; @@ -948,7 +1132,13 @@ function contact_details($form_state) } else { - db_query("insert into {textbook_companion_cheque} (proposal_id) values(%d)",$proposal_id); + /*db_query("insert into {textbook_companion_cheque} (proposal_id) values(%d)",$proposal_id);*/ + + $query = "insert into {textbook_companion_cheque} (proposal_id) values (:proposal_id)"; + $args = array( + ":proposal_id"=>$proposal_id, + ); + $result = db_query($query, $args, array('return' => Database::RETURN_INSERT_ID)); } $form['candidate_detail'] = array( '#type' => 'fieldset', @@ -986,11 +1176,26 @@ function contact_details($form_state) '#size' => 48, '#default_value' => $form8, ); - $chq_q=db_query("SELECT * FROM {textbook_companion_cheque} WHERE proposal_id=".$proposal_id); - $chq_data=db_fetch_object($chq_q); + + /*$chq_q=db_query("SELECT * FROM {textbook_companion_cheque} WHERE proposal_id=".$proposal_id); + $chq_data=db_fetch_object($chq_q);*/ + + $query = db_select('textbook_companion_cheque'); + $query->fields('textbook_companion_cheque'); + $query->condition('proposal_id', $proposal_id); + $result = $query->execute(); + $chq_data=$result->fetchObject(); - $q_form = db_query("SELECT * FROM {textbook_companion_paper} WHERE proposal_id=".$proposal_id); - $q_data = db_fetch_object($q_form); + + /*$q_form = db_query("SELECT * FROM {textbook_companion_paper} WHERE proposal_id=".$proposal_id); + $q_data = db_fetch_object($q_form);*/ + + $query = db_select('textbook_companion_paper'); + $query->fields('textbook_companion_paper'); + $query->condition('proposal_id', $proposal_id); + $result = $query->execute(); + $q_data=$result->fetchObject(); + $form_html .= '<ul>'; if($q_data->internship_form) { @@ -1120,11 +1325,18 @@ function contact_details_submit($form, &$form_state) global $user; $x = $user->uid; - $query2 = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid=".$x); - $data2 = db_fetch_object($query2); + /*$query2 = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid=".$x); + $data2 = db_fetch_object($query2);*/ - $query ="UPDATE {textbook_companion_cheque} SET + $query = db_select('textbook_companion_proposal'); + $query->fields('textbook_companion_proposal'); + $query->condition('uid', $x); + $result = $query->execute(); + $data2=$result->fetchObject(); + + + /*$query ="UPDATE {textbook_companion_cheque} SET alt_mobno = '".$form_state['values']['mobileno2']."' , address = '".$form_state['values']['chq_address']."', perm_city = '".$form_state['values']['perm_city']."', @@ -1136,8 +1348,23 @@ function contact_details_submit($form, &$form_state) temp_pincode = '".$form_state['values']['temp_pincode']."' , address_con = 'Submitted' WHERE proposal_id = ".$data2->id; + db_query($query);*/ - db_query($query); + $query = db_update('textbook_companion_cheque'); + $query->fields(array( + 'alt_mobno' => $form_state[ values ][ mobileno2 ], + 'address' => $form_state[ values ][ chq_address ], + 'perm_city' => $form_state[ values ][ perm_city ], + 'perm_state' => $form_state[ values ][ perm_state ], + 'perm_pincode' => $form_state[ values ][ perm_pincode ], + 'temp_chq_address' => $form_state[ values ][ temp_chq_address ], + 'temp_city' => $form_state[ values ][ temp_city ], + 'temp_state' => $form_state[ values ][ temp_state ], + 'temp_pincode' => $form_state[ values ][ temp_pincode ], + 'address_con' => 'Submitted', + )); + $query->condition('proposal_id', $data2->id); + $num_updated = $query->execute(); drupal_set_message('Contact Details Has Been Updated.....!', 'status'); drupal_goto('mycontact', array('msg' => 0 ), $fragment = NULL, $http_response_code = 302); @@ -1174,9 +1401,16 @@ function copy_address() function cheque_report_form() { - $search_qx = db_query("SELECT * FROM textbook_companion_proposal p,textbook_companion_cheque c WHERE c.address_con = 'Submitted' AND (p.id = c.proposal_id)"); + /*$search_qx = db_query("SELECT * FROM textbook_companion_proposal p,textbook_companion_cheque c WHERE c.address_con = 'Submitted' AND (p.id = c.proposal_id)");*/ + + $query = db_select('textbook_companion_proposal', 'p'); + $query->join('textbook_companion_cheque','c','p.id = c.proposal_id'); + $query->fields('p',array('textbook_companion_proposal')); + $query->fields('c',array('textbook_companion_cheque')); + $query->condition('c.address_con', 'Submitted'); + $search_qx = $query->execute(); - while ($search_datax = db_fetch_object($search_qx)) + while ($search_datax = $search_qx->fetchObject()) { $result = array($search_datax->full_name,$search_datax->address_con,$search_datax->cheque_no,$search_datax->cheque_dispatch_date); } diff --git a/cheque_manage.inc b/cheque_manage.inc index 750874f..8ddeffb 100755 --- a/cheque_manage.inc +++ b/cheque_manage.inc @@ -22,16 +22,42 @@ function cheque_proposal_all() $count=20; /* get pending proposals to be approved */ $proposal_rows = array(); - $proposal_q = "SELECT * FROM {textbook_companion_proposal} ORDER BY id DESC"; - $pagerquery = pager_query($proposal_q, $count); - while ($proposal_data = db_fetch_object($pagerquery)) + + /*$proposal_q = "SELECT * FROM {textbook_companion_proposal} ORDER BY id DESC";*/ + $query = db_select('textbook_companion_proposal'); + $query->fields('textbook_companion_proposal'); + $query->orderBy('id', 'DESC'); + + + /*$pagerquery = pager_query($proposal_q, $count); */ + $pagerquery = $query->extend('PagerDefault')->limit($count)->execute(); + + while ($proposal_data = $pagerquery->fetchObject()) { /* get preference */ - $preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND approval_status = 1 LIMIT 1", $proposal_data->id); - $preference_data = db_fetch_object($preference_q); - $preference_q1 = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid = %d AND approval_status = 1 LIMIT 1", $proposal_data->id); - $preference_data1 = db_fetch_object($preference_q1); + /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND approval_status = 1 LIMIT 1", $proposal_data->id); + $preference_data = db_fetch_object($preference_q);*/ + + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('proposal_id', $proposal_data->id); + $query->condition('approval_status', 1); + $query->range(0, 1); + $result = $query->execute(); + $preference_data =$result->fetchObject(); + + /*$preference_q1 = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid = %d AND approval_status = 1 LIMIT 1", $proposal_data->id); + $preference_data1 = db_fetch_object($preference_q1);*/ + + $query = db_select('textbook_companion_proposal'); + $query->fields('textbook_companion_proposal'); + $query->condition('uid', $proposal_data->id); + $query->condition('proposal_status', 1); + $query->range(0, 1); + $result = $query->execute(); + $preference_data1=$result->fetchObject(); + $proposal_status = ''; switch ($proposal_data->proposal_status) @@ -53,8 +79,8 @@ function cheque_proposal_all() } $proposal_header = array('Date of Submission', 'Contributor Name', 'Expected Date of Completion', 'Status'); - $output = theme_table($proposal_header, $proposal_rows, $proposal_rows1); - return $output . theme('pager', $count); + $output = theme('table',array('header' =>$proposal_header,'rows'=>$proposal_rows)); + return $output . theme_pager($count); } return $form; @@ -1,519 +1,626 @@ <?php // $Id$ - function upload_examples() -{ - return drupal_get_form('upload_examples_form'); -} - -function upload_examples_form($form_state) -{ - global $user; - - /************************ start approve book details ************************/ - $proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid = %d ORDER BY id DESC LIMIT 1", $user->uid); - $proposal_data = db_fetch_object($proposal_q); - if (!$proposal_data) { - drupal_set_message("Please submit a " . l('proposal', 'proposal') . ".", 'error'); - drupal_goto(''); + return drupal_get_form('upload_examples_form'); } - if ($proposal_data->proposal_status != 1) +function upload_examples_form($form, $form_state) { - switch ($proposal_data->proposal_status ) - { - case 0: - drupal_set_message(t('We have already received your proposal. We will get back to you soon.'), 'status'); - drupal_goto(''); - return; - break; - case 2: - drupal_set_message(t('Your proposal has been dis-approved. Please create another proposal ' . l('here', 'proposal') . '.'), 'error'); - drupal_goto(''); - return; - break; - case 3: - drupal_set_message(t('Congratulations! You have completed your last book proposal. You have to create another proposal ' . l('here', 'proposal') . '.'), 'status'); + global $user; + /************************ start approve book details ************************/ + /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid = %d ORDER BY id DESC LIMIT 1", $user->uid); + $proposal_data = db_fetch_object($proposal_q);*/ + $query = db_select('textbook_companion_proposal'); + $query->fields('textbook_companion_proposal'); + $query->condition('uid', $user->uid); + $query->orderBy('id', 'DESC'); + $query->range(0, 1); + $result = $query->execute(); + $proposal_data = $result->fetchObject(); + if (!$proposal_data) + { + drupal_set_message("Please submit a " . l('proposal', 'textbook-companion/proposal') . ".", 'error'); + drupal_goto(''); + } + if ($proposal_data->proposal_status != 1 && $proposal_data->proposal_status != 4) + { + switch ($proposal_data->proposal_status) + { + case 0: + drupal_set_message(t('We have already received your proposal. We will get back to you soon.'), 'status'); + drupal_goto(''); + return; + break; + case 2: + drupal_set_message(t('Your proposal has been dis-approved. Please create another proposal ' . l('here', 'textbook-companion/proposal') . '.'), 'error'); + drupal_goto(''); + return; + break; + case 3: + drupal_set_message(t('Congratulations! You have completed your last book proposal. You have to create another proposal ' . l('here', 'textbook-companion/proposal') . '.'), 'status'); + drupal_goto(''); + return; + break; +case 5: + drupal_set_message(t('You have submitted your all codes.'), 'status'); drupal_goto(''); return; - break; - default: - drupal_set_message(t('Invalid proposal state. Please contact site administrator for further information.'), 'error'); - drupal_goto(''); - return; - break; - } - } - - $preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND approval_status = 1 LIMIT 1", $proposal_data->id); - $preference_data = db_fetch_object($preference_q); - if (!$preference_data) - { - drupal_set_message(t('Invalid Book Preference status. Please contact site administrator for further information.'), 'error'); - drupal_goto(''); - return; - } - /************************ end approve book details **************************/ - - /* add javascript for automatic book title, check if example uploaded, dependency selection effects */ - $chapter_name_js = " $(document).ready(function() { - $('#edit-number').change(function() { - $.get('" . base_path() . "textbook_companion/ajax/chapter_title/' + $('#edit-number').val() + '/' + " . $preference_data->id . ", function(data) { - data = data.toString().replace('\t', ''); - $('#edit-name').val(data); - }); - }); - $('#edit-example-number').change(function() { - $.get('" . base_path() . "textbook_companion/ajax/example_exists/' + $('#edit-number').val() + '/' + " . $preference_data->id . " + '/' + $('#edit-example-number').val(), function(data) { - if (!data) { - alert(data); - } - }); - }); - $('#edit-existing-depfile-dep-book-title').change(function() { - var dep_selected = ''; - /* showing and hiding relevant files */ - $('.form-checkboxes .option').hide(); - $('.form-checkboxes .option').each(function(index) { - var activeClass = $('#edit-existing-depfile-dep-book-title').val(); - if ($(this).children().hasClass(activeClass)) { - $(this).show(); - } - if ($(this).children().attr('checked') == true) { - dep_selected += $(this).children().next().text() + '<br />'; + default: + drupal_set_message(t('Invalid proposal state. Please contact site administrator for further information.'), 'error'); + drupal_goto(''); + return; + break; } - }); - /* showing list of already existing dependencies */ - $('#existing_depfile_selected').html(dep_selected); - }); - - $('.form-checkboxes .option').change(function() { - $('#edit-existing-depfile-dep-book-title').trigger('change'); - }); - $('#edit-existing-depfile-dep-book-title').trigger('change'); - });"; - drupal_add_js($chapter_name_js, 'inline', 'header'); - - $form['#attributes'] = array('enctype' => "multipart/form-data"); - - $form['book_details']['book'] = array( - '#type' => 'item', - '#value' => $preference_data->book, - '#title' => t('Title of the Book'), - ); - $form['contributor_name'] = array( - '#type' => 'item', - '#value' => $proposal_data->full_name, - '#title' => t('Contributor Name'), + } + /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND approval_status = 1 LIMIT 1", $proposal_data->id); + $preference_data = db_fetch_object($preference_q);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('proposal_id', $proposal_data->id); + $query->condition('approval_status', 1); + $query->range(0, 1); + $result = $query->execute(); + $preference_data = $result->fetchObject(); + if (!$preference_data) + { + drupal_set_message(t('Invalid Book Preference status. Please contact site administrator for further information.'), 'error'); + drupal_goto(''); + return; + } + $form['#attributes'] = array( + 'enctype' => "multipart/form-data" + ); +$form['book_details']['pref_id'] = array( + '#type' => 'hidden', + '#value' => $preference_data->id, ); - - $form['number'] = array( + $form['book_details']['book'] = array( + '#type' => 'item', + '#markup' => $preference_data->book, + '#title' => t('Title of the Book') + ); + $form['contributor_name'] = array( + '#type' => 'item', + '#markup' => $proposal_data->full_name, + '#title' => t('Contributor Name') + ); + $options = array( + '' => '(Select)' + ); + for ($i = 1; $i <= 100; $i++) + { + $options[$i] = $i; + } + $form['number'] = array( '#type' => 'select', '#title' => t('Chapter No'), - '#options' => array('' => '(Select)', '1' => '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', - '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', - '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', - '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', - '41', '42', '43', '44', '45', '46', '47', '48', '49', '50'), + '#options' => $options, '#multiple' => FALSE, '#size' => 1, - '#required' => TRUE, - ); + '#required' => TRUE, + '#ajax' => array( + 'callback' => 'ajax_chapter_name_callback', + ), + ); $form['name'] = array( '#type' => 'textfield', '#title' => t('Title of the Chapter'), '#size' => 40, '#maxlength' => 255, - '#required' => TRUE, - ); - $form['example_number'] = array( - '#type' => 'textfield', - '#title' => t('Example No'), - '#size' => 5, - '#maxlength' => 10, - '#description' => t("Example number should be separated by dots only.<br />Example: 1.1.a or 1.1.1"), - '#required' => TRUE, + '#required' => TRUE, + '#prefix' => '<div id="ajax-chapter-name-replace">', + '#suffix' => '</div>', ); - $form['example_caption'] = array( - '#type' => 'textfield', - '#title' => t('Caption'), - '#size' => 40, - '#maxlength' => 255, - '#description' => t('Example caption should contain only alphabets, numbers and spaces.'), - '#required' => TRUE, - ); - $form['example_warning'] = array( - '#type' => 'item', - '#title' => t('You should upload all the files as zip (main or source files, result files, executable file if any)'), - '#prefix' => '<div style="color:red">', - '#suffix' => '</div>', - ); - - $form['sourcefile'] = array( - '#type' => 'fieldset', - '#title' => t('Main or Source Files'), - '#collapsible' => FALSE, - '#collapsed' => FALSE, - ); - $form['sourcefile']['sourcefile1'] = array( - '#type' => 'file', - '#title' => t('Upload main or source file'), - '#size' => 48, - '#description' => t('Separate filenames with underscore. No spaces or any special characters allowed in filename.') . '<br />' . - t('<span style="color:red;">Allowed file extensions : ') . variable_get('textbook_companion_source_extensions', '').'</span>', - ); - $form['submit'] = array( - '#type' => 'submit', - '#value' => t('Submit') - ); - - $form['cancel'] = array( - '#type' => 'markup', - '#value' => l(t('Cancel'), 'textbook_companion/code'), - ); - return $form; -} - + $form['example_number'] = array( + '#type' => 'textfield', + '#title' => t('Example No'), + '#size' => 5, + '#maxlength' => 10, + '#description' => t("Example number should be separated by dots only.<br />Example: 1.1.a or 1.1.1"), + '#required' => TRUE + ); + $form['example_caption'] = array( + '#type' => 'textfield', + '#title' => t('Caption'), + '#size' => 40, + '#maxlength' => 255, + '#description' => t('Example caption should contain only alphabets, numbers and spaces.'), + '#required' => TRUE + ); + $form['example_warning'] = array( + '#type' => 'item', + '#title' => t('You should upload all the files as zip (main or source files, result files, executable file if any): '), + '#prefix' => '<div style="color:red">', + '#suffix' => '</div>' + ); + $form['sourcefile'] = array( + '#type' => 'fieldset', + '#title' => t('Main or Source Files'), + '#collapsible' => FALSE, + '#collapsed' => FALSE + ); + $form['sourcefile']['sourcefile1'] = array( + '#type' => 'file', + '#title' => t('Upload main or source file'), + '#size' => 48, + '#description' => t('Separate filenames with underscore. No spaces or any special characters allowed in filename.') . '<br />' . t('<span style="color:red;">Allowed file extensions : ') . variable_get('textbook_companion_source_extensions', '') . '</span>' + ); + $form['submit'] = array( + '#type' => 'submit', + '#value' => t('Submit') + ); + $form['cancel'] = array( + '#type' => 'markup', + '#value' => l(t('Cancel'), 'textbook-companion/code') + ); + return $form; + } function upload_examples_form_validate($form, &$form_state) -{ - if (!check_name($form_state['values']['name'])) - form_set_error('name', t('Title of the Chapter can contain only alphabets, numbers and spaces.')); - - if (!check_name($form_state['values']['example_caption'])) - form_set_error('example_caption', t('Example Caption can contain only alphabets, numbers and spaces.')); - - if (!check_chapter_number($form_state['values']['example_number'])) - form_set_error('example_number', t('Invalid Example Number. Example Number can contain only alphabets and numbers sepereated by dot.')); - - if (isset($_FILES['files'])) { - /* check if atleast one source or result file is uploaded */ - if ( ! ($_FILES['files']['name']['sourcefile1'])) - form_set_error('sourcefile1', t('Please upload source file.')); - /* check for valid filename extensions */ - foreach ($_FILES['files']['name'] as $file_form_name => $file_name) - { - if ($file_name) + if (!check_name($form_state['values']['name'])) + form_set_error('name', t('Title of the Chapter can contain only alphabets, numbers and spaces.')); + if (!check_name($form_state['values']['example_caption'])) + form_set_error('example_caption', t('Example Caption can contain only alphabets, numbers and spaces.')); + if (!check_chapter_number($form_state['values']['example_number'])) + form_set_error('example_number', t('Invalid Example Number. Example Number can contain only alphabets and numbers sepereated by dot.')); + if (isset($_FILES['files'])) { - $allowed_extensions_str = variable_get('textbook_companion_source_extensions', ''); - - $allowed_extensions = explode(',' , $allowed_extensions_str); - $temp_extension = end(explode('.', strtolower($_FILES['files']['name'][$file_form_name]))); - //$temp_extension = substr($_FILES['files']['name'][$file_form_name], strripos($_FILES['files']['name'][$file_form_name], '.')); // get file name - //var_dump($temp_extension); die; - if (!in_array($temp_extension, $allowed_extensions)) - form_set_error($file_form_name, t('Only file with ' . $allowed_extensions_str . ' extensions can be uploaded.')); - if ($_FILES['files']['size'][$file_form_name] <= 0) - form_set_error($file_form_name, t('File size cannot be zero.')); - - /* check if valid file name - if (!textbook_companion_check_valid_filename($_FILES['files']['name'][$file_form_name])) - form_set_error($file_form_name, t('Invalid file name specified. Only alphabets, numbers and underscore is allowed as a valid filename.'));*/ + /* check if atleast one source or result file is uploaded */ + if (!($_FILES['files']['name']['sourcefile1'])) + form_set_error('sourcefile1', t('Please upload source file.')); + /* check for valid filename extensions */ + foreach ($_FILES['files']['name'] as $file_form_name => $file_name) + { + if ($file_name) + { + $allowed_extensions_str = variable_get('textbook_companion_source_extensions', ''); + $allowed_extensions = explode(',', $allowed_extensions_str); + $temp_ext = explode('.', strtolower($_FILES['files']['name'][$file_form_name])); + $temp_extension = end($temp_ext); + //$temp_extension = substr($_FILES['files']['name'][$file_form_name], strripos($_FILES['files']['name'][$file_form_name], '.')); // get file name + //var_dump($temp_extension); die; + if (!in_array($temp_extension, $allowed_extensions)) + form_set_error($file_form_name, t('Only file with ' . $allowed_extensions_str . ' extensions can be uploaded.')); + if ($_FILES['files']['size'][$file_form_name] <= 0) + form_set_error($file_form_name, t('File size cannot be zero.')); + /* check if valid file name + if (!textbook_companion_check_valid_filename($_FILES['files']['name'][$file_form_name])) + form_set_error($file_form_name, t('Invalid file name specified. Only alphabets, numbers and underscore is allowed as a valid filename.'));*/ + } + } } - } - } - - /* add javascript again for automatic book title, check if example uploaded, dependency selection effects */ - $chapter_name_js = " $(document).ready(function() { - $('#edit-number').change(function() { - $.get('" . base_path() . "textbook_companion/ajax/chapter_title/' + $('#edit-number').val() + '/' + " . $row->pre_id . ", function(data) { - $('#edit-name').val(data); - }); - }); - $('#edit-example-number').change(function() { - $.get('" . base_path() . "textbook_companion/ajax/example_exists/' + $('#edit-number').val() + '/' + $('#edit-example-number').val(), function(data) { - if (data) { - alert(data); - } - }); - }); - $('#edit-existing-depfile-dep-book-title').change(function() { - var dep_selected = ''; - /* showing and hiding relevant files */ - $('.form-checkboxes .option').hide(); - $('.form-checkboxes .option').each(function(index) { - var activeClass = $('#edit-existing-depfile-dep-book-title').val(); - if ($(this).children().hasClass(activeClass)) { - $(this).show(); - } - if ($(this).children().attr('checked') == true) { - dep_selected += $(this).children().next().text() + '<br />'; - } - }); - /* showing list of already existing dependencies */ - $('#existing_depfile_selected').html(dep_selected); - }); - - $('.form-checkboxes .option').change(function() { - $('#edit-existing-depfile-dep-book-title').trigger('change'); - }); - $('#edit-existing-depfile-dep-book-title').trigger('change'); - });"; - drupal_add_js($chapter_name_js, 'inline', 'header'); -} - -function upload_examples_form_submit($form, &$form_state) { - global $user; - - $root_path = textbook_companion_path(); - - /************************ start approve book details ************************/ - $proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid = %d ORDER BY id DESC LIMIT 1", $user->uid); - $proposal_data = db_fetch_object($proposal_q); - if (!$proposal_data) +function upload_examples_form_submit($form, &$form_state) { - drupal_set_message("Please submit a " . l('proposal', 'proposal') . ".", 'error'); - drupal_goto(''); - } - if ($proposal_data->proposal_status != 1) - { - switch ($proposal_data->proposal_status ) - { - case 0: - drupal_set_message(t('We have already received your proposal. We will get back to you soon.'), 'status'); - drupal_goto(''); - return; - break; - case 2: - drupal_set_message(t('Your proposal has been dis-approved. Please create another proposal ' . l('here', 'proposal') . '.'), 'error'); - drupal_goto(''); - return; - break; - case 3: - drupal_set_message(t('Congratulations! You have completed your last book proposal. You have to create another proposal ' . l('here', 'textbook_companion/proposal') . '.'), 'status'); + global $user; + $root_path = textbook_companion_path(); + /************************ start approve book details ************************/ + /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid = %d ORDER BY id DESC LIMIT 1", $user->uid); + $proposal_data = db_fetch_object($proposal_q);*/ + $query = db_select('textbook_companion_proposal'); + $query->fields('textbook_companion_proposal'); + $query->condition('uid', $user->uid); + $query->orderBy('id', 'DESC'); + $query->range(0, 1); + $result = $query->execute(); + $proposal_data = $result->fetchObject(); + if (!$proposal_data) + { + drupal_set_message("Please submit a " . l('proposal', 'textbook-companion/proposal') . ".", 'error'); + drupal_goto(''); + } + if ($proposal_data->proposal_status != 1 && $proposal_data->proposal_status != 4) + { + switch ($proposal_data->proposal_status) + { + case 0: + drupal_set_message(t('We have already received your proposal. We will get back to you soon.'), 'status'); + drupal_goto(''); + return; + break; + case 2: + drupal_set_message(t('Your proposal has been dis-approved. Please create another proposal ' . l('here', 'textbook-companion/proposal') . '.'), 'error'); + drupal_goto(''); + return; + break; + case 3: + drupal_set_message(t('Congratulations! You have completed your last book proposal. You have to create another proposal ' . l('here', 'textbook-companion/proposal') . '.'), 'status'); + drupal_goto(''); + return; + break; +case 5: + drupal_set_message(t('You have submmited your all codes'), 'status'); drupal_goto(''); return; break; - default: - drupal_set_message(t('Invalid proposal state. Please contact site administrator for further information.'), 'error'); - drupal_goto(''); - return; - break; - } - } - - $preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND approval_status = 1 LIMIT 1", $proposal_data->id); - $preference_data = db_fetch_object($preference_q); - if (!$preference_data) - { - drupal_set_message(t('Invalid Book Preference status. Please contact site administrator for further information.'), 'error'); - drupal_goto(''); - return; - } - /************************ end approve book details **************************/ - - $preference_id = $preference_data->id; - - $dest_path = $preference_id . '/'; - if (!is_dir($root_path . $dest_path)) - mkdir($root_path . $dest_path); - - /* inserting chapter details */ - $chapter_id = 0; - $chapter_result = db_query("SELECT * FROM {textbook_companion_chapter} WHERE preference_id = %d AND number = %d", $preference_id, $form_state['values']['number']); - if (!$chapter_row = db_fetch_object($chapter_result)) - { - db_query("INSERT INTO {textbook_companion_chapter} (preference_id, number, name) VALUES (%d, '%s', '%s')", - $preference_id, - $form_state['values']['number'], - $form_state['values']['name'] - ); - $chapter_id = db_last_insert_id('textbook_companion_chapter', 'id'); - } else { - $chapter_id = $chapter_row->id; - db_query("UPDATE {textbook_companion_chapter} SET name = '%s' WHERE id = %d", $form_state['values']['name'], $chapter_id); - } - - /* get example details - dont allow if already example present */ - $cur_example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE chapter_id = %d AND number = '%s'", $chapter_id, $form_state['values']['example_number']); - if ($cur_example_d = db_fetch_object($cur_example_q)) - { - if ($cur_example_d->approval_status == 1) - { - drupal_set_message(t("Example already approved. Cannot overwrite it."), 'error'); - drupal_goto('textbook_companion/code'); - return; - } else if ($cur_example_d->approval_status == 0) { - drupal_set_message(t("Example is under pending review. Delete the example and reupload it."), 'error'); - drupal_goto('textbook_companion/code'); - return; - } else { - drupal_set_message(t("Error uploading example. Please contact administrator."), 'error'); - drupal_goto('textbook_companion/code'); - return; - } - } - - /* creating directories */ - $dest_path .= 'CH' . $form_state['values']['number'] . '/'; - if (!is_dir($root_path . $dest_path)) - mkdir($root_path . $dest_path); - - $dest_path .= 'EX' . $form_state['values']['example_number'] . '/'; - if (!is_dir($root_path . $dest_path)) - mkdir($root_path . $dest_path); - - /* creating example database entry */ - db_query("INSERT INTO {textbook_companion_example} (chapter_id, number, caption, approval_status, timestamp) VALUES (%d, '%s', '%s', %d, %d)", + default: + drupal_set_message(t('Invalid proposal state. Please contact site administrator for further information.'), 'error'); + drupal_goto(''); + return; + break; + } + } + /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND approval_status = 1 LIMIT 1", $proposal_data->id); + $preference_data = db_fetch_object($preference_q);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('proposal_id', $proposal_data->id); + $query->condition('approval_status', 1); + $query->range(0, 1); + $result = $query->execute(); + $preference_data = $result->fetchObject(); + if (!$preference_data) + { + drupal_set_message(t('Invalid Book Preference status. Please contact site administrator for further information.'), 'error'); + drupal_goto(''); + return; + } + /************************ end approve book details **************************/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('proposal_id', $proposal_data->id); + $query->condition('approval_status', 1); + $result = $query->execute()->rowCount(); + if ($result > 1) + { + drupal_set_message(t('You cannot upload your code. This name of book directory alrady preasent in directory folder, please contact to administrator.'), 'error'); + return; + } + $proposal_directory = $preference_data->directory_name; + $dest_path = $proposal_directory . '/'; + if (!is_dir($root_path . $dest_path)){ + if(!mkdir($root_path . $dest_path)) + { + drupal_set_message(t('You cannot upload your code. Error in creating directory'), 'error'); + } + } + /* inserting chapter details */ + $chapter_id = 0; + /*$chapter_result = db_query("SELECT * FROM {textbook_companion_chapter} WHERE preference_id = %d AND number = %d", $preference_id, $form_state['values']['number']);*/ + $preference_id = $preference_data->id; + $query = db_select('textbook_companion_chapter'); + $query->fields('textbook_companion_chapter'); + $query->condition('preference_id', $preference_id); + $query->condition('number', $form_state['values']['number']); + $chapter_result = $query->execute(); + if (!$chapter_row = $chapter_result->fetchObject()) + { + /*db_query("INSERT INTO {textbook_companion_chapter} (preference_id, number, name) VALUES (%d, '%s', '%s')", + $preference_id, + $form_state['values']['number'], + $form_state['values']['name'] + ); + $chapter_id = db_last_insert_id('textbook_companion_chapter', 'id'); */ + $query = "INSERT INTO {textbook_companion_chapter} (preference_id, number, name) VALUES(:preference_id, :number, :name)"; + $args = array( + ":preference_id" => $preference_id, + ":number" => $form_state['values']['number'], + ":name" => $form_state['values']['name'] + ); + $result = db_query($query, $args, array( + 'return' => Database::RETURN_INSERT_ID + )); + $chapter_id = $result; + } + else + { + $chapter_id = $chapter_row->id; + /*db_query("UPDATE {textbook_companion_chapter} SET name = '%s' WHERE id = %d", $form_state['values']['name'], $chapter_id);*/ + $query = db_update('textbook_companion_chapter'); + $query->fields(array( + 'name' => $form_state['values']['name'] + )); + $query->condition('id', $chapter_id); + $num_updated = $query->execute(); + } + /* get example details - dont allow if already example present */ + /*$cur_example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE chapter_id = %d AND number = '%s'", $chapter_id, $form_state['values']['example_number']);*/ + $query = db_select('textbook_companion_example'); + $query->fields('textbook_companion_example'); + $query->condition('chapter_id', $chapter_id); + $query->condition('number', $form_state['values']['example_number']); + $cur_example_q = $query->execute(); + if ($cur_example_d = $cur_example_q->fetchObject()) + { + if ($cur_example_d->approval_status == 1) + { + drupal_set_message(t("Example already approved. Cannot overwrite it."), 'error'); + drupal_goto('textbook-companion/code'); + return; + } + else if ($cur_example_d->approval_status == 0) + { + drupal_set_message(t("Example is under pending review. Delete the example and reupload it."), 'error'); + drupal_goto('textbook-companion/code'); + return; + } + else + { + drupal_set_message(t("Error uploading example. Please contact administrator."), 'error'); + drupal_goto('textbook-companion/code'); + return; + } + } + /* creating directories */ + $dest_path .= 'CH' . $form_state['values']['number'] . '/'; + if (!is_dir($root_path . $dest_path)) + mkdir($root_path . $dest_path); + $dest_path .= 'EX' . $form_state['values']['example_number'] . '/'; + if (!is_dir($root_path . $dest_path)) + mkdir($root_path . $dest_path); + $filepath = 'CH' . $form_state['values']['number'] . '/' . 'EX' . $form_state['values']['example_number'] . '/'; + /* creating example database entry */ + /*db_query("INSERT INTO {textbook_companion_example} (chapter_id, number, caption, approval_status, timestamp) VALUES (%d, '%s', '%s', %d, %d)", $chapter_id, $form_state['values']['example_number'], $form_state['values']['example_caption'], 0, time() - ); - $example_id = db_last_insert_id('textbook_companion_example', 'id'); - - /* uploading files */ - foreach ($_FILES['files']['name'] as $file_form_name => $file_name) - { - if ($file_name) + ); + $example_id = db_last_insert_id('textbook_companion_example', 'id');*/ + $query = "INSERT INTO {textbook_companion_example} (chapter_id, number, caption, approval_date, approval_status, timestamp) VALUES (:chapter_id, :number, :caption, :approval_date,:approval_status, :timestamp)"; + $args = array( + ":chapter_id" => $chapter_id, + ":number" => $form_state['values']['example_number'], + ":caption" => $form_state['values']['example_caption'], + ":approval_date" => time(), + ":approval_status" => 0, + ":timestamp" => time() + ); + $result = db_query($query, $args, array( + 'return' => Database::RETURN_INSERT_ID + )); + $example_id = $result; + /* linking existing dependencies */ + /* foreach ($form_state['values']['existing_depfile']['dep_chapter_example_files'] as $row) { - /* checking file type */ - $file_type = 'S'; - - if (file_exists($root_path . $dest_path . $_FILES['files']['name'][$file_form_name])) - { - drupal_set_message(t("Error uploading file. File !filename already exists.", array('!filename' => $_FILES['files']['name'][$file_form_name])), 'error'); - return; - } - - /* uploading file */ - if (move_uploaded_file($_FILES['files']['tmp_name'][$file_form_name], $root_path . $dest_path . $_FILES['files']['name'][$file_form_name])) + if ($row > 0) + { + /* insterting into database */ + /*db_query("INSERT INTO {textbook_companion_example_dependency} (example_id, dependency_id, approval_status, timestamp) + VALUES (%d, %d, %d, %d)", + $example_id, + $row, + 0, + time() + );*/ + /*$query = "INSERT INTO {textbook_companion_example_dependency} (example_id, dependency_id, approval_status, timestamp) + VALUES (:example_id, :dependency_id, :approval_status, :timestamp)"; + $args = array( + ":example_id"=>$example_id, + ":dependency_id"=>$row, + ":approval_status"=> 0, + ":timestamp"=>time(), + ); + $result = db_query($query, $args, array('return' => Database::RETURN_INSERT_ID)); + } + }*/ + /* uploading files */ + foreach ($_FILES['files']['name'] as $file_form_name => $file_name) { - /* for uploaded files making an entry in the database */ - db_query("INSERT INTO {textbook_companion_example_files} (example_id, filename, filepath, filesize, filetype, timestamp) - VALUES (%d, '%s', '%s', %d, '%s', %d)", - $example_id, - $_FILES['files']['name'][$file_form_name], - $dest_path . $_FILES['files']['name'][$file_form_name], - $_FILES['files']['size'][$file_form_name], - $file_type, - time() - ); - drupal_set_message($file_name . ' uploaded successfully.', 'status'); - } else { - drupal_set_message('Error uploading file : ' . $dest_path . '/' . $file_name, 'error'); + if ($file_name) + { + /* checking file type */ + $file_type = 'S'; + if (file_exists($root_path . $dest_path . $_FILES['files']['name'][$file_form_name])) + { + drupal_set_message(t("Error uploading file. File !filename already exists.", array( + '!filename' => $_FILES['files']['name'][$file_form_name] + )), 'error'); + return; + } + /* uploading file */ + if (move_uploaded_file($_FILES['files']['tmp_name'][$file_form_name], $root_path . $dest_path . $_FILES['files']['name'][$file_form_name])) + { + /* for uploaded files making an entry in the database */ + /*db_query("INSERT INTO {textbook_companion_example_files} (example_id, filename, filepath, filemime, filesize, filetype, timestamp) + VALUES (%d, '%s', '%s', '%s', %d, '%s', %d)", + $example_id, + $_FILES['files']['name'][$file_form_name], + $dest_path . $_FILES['files']['name'][$file_form_name], + $_FILES['files']['type'][$file_form_name], + $_FILES['files']['size'][$file_form_name], + $file_type, + time() + );*/ + $query = "INSERT INTO {textbook_companion_example_files} (example_id, filename, filepath,filemime, filesize, filetype, timestamp) + VALUES (:example_id, :filename ,:filepath,:filemime, :filesize, :filetype, :timestamp)"; + $args = array( + ":example_id" => $example_id, + ":filename" => $_FILES['files']['name'][$file_form_name], + ":filepath" => $filepath . $_FILES['files']['name'][$file_form_name], + ":filemime" => 'application/zip', + ":filesize" => $_FILES['files']['size'][$file_form_name], + ":filetype" => $file_type, + ":timestamp" => time() + ); + $result = db_query($query, $args, array( + 'return' => Database::RETURN_INSERT_ID + )); + drupal_set_message($file_name . ' uploaded successfully.', 'status'); + } + else + { + drupal_set_message('Error uploading file : ' . $dest_path . '/' . $file_name, 'error'); + } + } } - } + drupal_set_message('Example uploaded successfully.', 'status'); + /* sending email */ + $email_to = $user->mail; + $param['example_uploaded']['example_id'] = $example_id; + $param['example_uploaded']['user_id'] = $user->uid; + if (!drupal_mail('textbook_companion', 'example_uploaded', $email_to, language_default(), $param, variable_get('textbook_companion_from_email', NULL), TRUE)) + drupal_set_message('Error sending email message.', 'error'); + drupal_goto('textbook-companion/code'); } - drupal_set_message('Example uploaded successfully.', 'status'); - - /* sending email */ - $email_to = $user->mail; - $param['example_uploaded']['example_id'] = $example_id; - $param['example_uploaded']['user_id'] = $user->uid; - if (!drupal_mail('textbook_companion', 'example_uploaded', $email_to, language_default(), $param, variable_get('textbook_companion_from_email', NULL), TRUE)) - drupal_set_message('Error sending email message.', 'error'); - - drupal_goto('textbook_companion/code'); -} - /******************************************************************************/ /***************************** DELETE EXAMPLE *********************************/ /******************************************************************************/ - function _upload_examples_delete() -{ - global $user; - $root_path = textbook_companion_path(); - $example_id = arg(3); - - /* check example */ - $example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE id = %d LIMIT 1", $example_id); - $example_data = db_fetch_object($example_q); - if (!$example_data) - { - drupal_set_message('Invalid example.', 'error'); - drupal_goto('textbook_companion/code'); - return; - } - if ($example_data->approval_status != 0) - { - drupal_set_message('You cannnot delete an example after it has been approved. Please contact site administrator if you want to delete this example.', 'error'); - drupal_goto('textbook_companion/code'); - return; - } - - $chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE id = %d LIMIT 1", $example_data->chapter_id); - $chapter_data = db_fetch_object($chapter_q); - if (!$chapter_data) - { - drupal_set_message('You do not have permission to delete this example.', 'error'); - drupal_goto('textbook_companion/code'); - return; - } - - $preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d LIMIT 1", $chapter_data->preference_id); - $preference_data = db_fetch_object($preference_q); - if (!$preference_data) - { - drupal_set_message('You do not have permission to delete this example.', 'error'); - drupal_goto('textbook_companion/code'); - return; - } - - $proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d AND uid = %d LIMIT 1", $preference_data->proposal_id, $user->uid); - $proposal_data = db_fetch_object($proposal_q); - if (!$proposal_data) { - drupal_set_message('You do not have permission to delete this example.', 'error'); - drupal_goto('textbook_companion/code'); + global $user; + $root_path = textbook_companion_path(); + $example_id = arg(3); + //var_dump($example_id);die; + /* check example */ + /*$example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE id = %d LIMIT 1", $example_id); + $example_data = db_fetch_object($example_q);*/ + $query = db_select('textbook_companion_example'); + $query->fields('textbook_companion_example'); + $query->condition('id', $example_id); + $query->range(0, 1); + $result = $query->execute(); + $example_data = $result->fetchObject(); + if (!$example_data) + { + drupal_set_message('Invalid example.', 'error'); + drupal_goto('textbook-companion/code'); + return; + } + if ($example_data->approval_status != 0) + { + drupal_set_message('You cannnot delete an example after it has been approved. Please contact site administrator if you want to delete this example.', 'error'); + drupal_goto('textbook-companion/code'); + return; + } + /*$chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE id = %d LIMIT 1", $example_data->chapter_id); + $chapter_data = db_fetch_object($chapter_q);*/ + $query = db_select('textbook_companion_chapter'); + $query->fields('textbook_companion_chapter'); + $query->condition('id', $example_data->chapter_id); + $query->range(0, 1); + $result = $query->execute(); + $chapter_data = $result->fetchObject(); + if (!$chapter_data) + { + drupal_set_message('You do not have permission to delete this example.', 'error'); + drupal_goto('textbook-companion/code'); + return; + } + /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d LIMIT 1", $chapter_data->preference_id); + $preference_data = db_fetch_object($preference_q);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('id', $chapter_data->preference_id); + $query->range(0, 1); + $result = $query->execute(); + $preference_data = $result->fetchObject(); + if (!$preference_data) + { + drupal_set_message('You do not have permission to delete this example.', 'error'); + drupal_goto('textbook-companion/code'); + return; + } + /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d AND uid = %d LIMIT 1", $preference_data->proposal_id, $user->uid); + $proposal_data = db_fetch_object($proposal_q);*/ + $query = db_select('textbook_companion_proposal'); + $query->fields('textbook_companion_proposal'); + $query->condition('id', $preference_data->proposal_id); + $query->condition('uid', $user->uid); + $query->range(0, 1); + $result = $query->execute(); + $proposal_data = $result->fetchObject(); + if (!$proposal_data) + { + drupal_set_message('You do not have permission to delete this example.', 'error'); + drupal_goto('textbook-companion/code'); + return; + } + /* deleting example files */ + if (delete_example($example_data->id)) + { + drupal_set_message('Example deleted.', 'status'); + /* sending email */ + $email_to = $user->mail; + $param['example_deleted_user']['book_title'] = $preference_data->book; + $param['example_deleted_user']['chapter_title'] = $chapter_data->name; + $param['example_deleted_user']['example_number'] = $example_data->number; + $param['example_deleted_user']['example_caption'] = $example_data->caption; + $param['example_deleted_user']['user_id'] = $user->uid; + if (!drupal_mail('textbook_companion', 'example_deleted_user', $email_to, language_default(), $param, variable_get('textbook_companion_from_email', NULL), TRUE)) + drupal_set_message('Error sending email message.', 'error'); + } + else + { + drupal_set_message('Error deleting example.', 'status'); + } + drupal_goto('textbook-companion/code'); return; } - - /* deleting example files */ - if (delete_example($example_data->id)) - { - drupal_set_message('Example deleted.', 'status'); - - /* sending email */ - $email_to = $user->mail; - $param['example_deleted_user']['book_title'] = $preference_data->book; - $param['example_deleted_user']['chapter_title'] = $chapter_data->name; - $param['example_deleted_user']['example_number'] = $example_data->number; - $param['example_deleted_user']['example_caption'] = $example_data->caption; - - $param['example_deleted_user']['user_id'] = $user->uid; - - if (!drupal_mail('textbook_companion', 'example_deleted_user', $email_to, language_default(), $param, variable_get('textbook_companion_from_email', NULL), TRUE)) - drupal_set_message('Error sending email message.', 'error'); - } else { - drupal_set_message('Error deleting example.', 'status'); - } - - drupal_goto('textbook_companion/code'); - return; -} - /******************************************************************************/ /************************** GENERAL FUNCTIONS *********************************/ /******************************************************************************/ - function _list_of_book_titles() -{ - $book_titles = array('0' => 'Please select...'); - $book_titles_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE approval_status = 1 OR approval_status = 3 ORDER BY book ASC"); - while ($book_titles_data = db_fetch_object($book_titles_q)) { - $book_titles[$book_titles_data->id] = $book_titles_data->book . ' (Written by ' . $book_titles_data->author . ')'; + $book_titles = array( + '0' => 'Please select...' + ); + /*$book_titles_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE approval_status = 1 OR approval_status = 3 ORDER BY book ASC");*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $or = db_or(); + $or->condition('approval_status', 1); + $or->condition('approval_status', 3); + $query->condition($or); + $query->orderBy('book', 'ASC'); + $book_titles_q = $query->execute(); + while ($book_titles_data = $book_titles_q->fetchObject()) + { + $book_titles[$book_titles_data->id] = $book_titles_data->book . ' (Written by ' . $book_titles_data->author . ')'; + } + return $book_titles; } - return $book_titles; -} - function _list_of_book_dependency_files() -{ - $book_dependency_files = array(); - $book_dependency_files_class = array(); - $book_dependency_files_q = db_query("SELECT * FROM {textbook_companion_dependency_files} ORDER BY filename ASC"); - - while ($book_dependency_files_data = db_fetch_object($book_dependency_files_q)) { - $temp_caption = ''; - if ($book_dependency_files_data->caption) - $temp_caption .= ' (' . $book_dependency_files_data->caption . ')'; - $book_dependency_files[$book_dependency_files_data->id] = l($book_dependency_files_data->filename . $temp_caption, 'download/dependency/' . $book_dependency_files_data->id); - $book_dependency_files_class[$book_dependency_files_data->id] = $book_dependency_files_data->preference_id; + $book_dependency_files = array(); + $book_dependency_files_class = array(); + /*$book_dependency_files_q = db_query("SELECT * FROM {textbook_companion_dependency_files} ORDER BY filename ASC");*/ + $query = db_select('textbook_companion_dependency_files'); + $query->fields('textbook_companion_dependency_files'); + $query->orderBy('filename', 'ASC'); + $book_dependency_files_q = $query->execute(); + while ($book_dependency_files_data = $book_dependency_files_q->fetchObject()) + { + $temp_caption = ''; + if ($book_dependency_files_data->caption) + $temp_caption .= ' (' . $book_dependency_files_data->caption . ')'; + $book_dependency_files[$book_dependency_files_data->id] = l($book_dependency_files_data->filename . $temp_caption, 'download/dependency/' . $book_dependency_files_data->id, array( + 'attributes' => array( + 'class' => $book_dependency_files_data->preference_id + ) + )); + $book_dependency_files_class[$book_dependency_files_data->id] = $book_dependency_files_data->preference_id; + } + return array( + $book_dependency_files, + $book_dependency_files_class + ); } - return array($book_dependency_files, $book_dependency_files_class); + +function ajax_chapter_name_callback($form, $form_state){ + + $pref_id = $form_state['values']['pref_id']; + $chapter_number = $form_state['values']['number']; + $query = "SELECT * FROM `textbook_companion_chapter` WHERE `preference_id` = :pref_id AND `number` = :number"; + $arg = array(':pref_id'=> $pref_id,':number' => $chapter_number); + $chapter_name_data = db_query($query, $arg); + + if ($chapter_name_data->rowCount() > 0) { + + //$form['name']['#default_value'] = $chapter_name_data->fetchObject()->name; + $form['name']['#value'] = $chapter_name_data->fetchObject()->name; + $form['name']['#readonly'] = TRUE; + $form['name']['#attributes']['readonly'] = 'readonly'; + $commands[] = ajax_command_replace("#ajax-chapter-name-replace", drupal_render($form['name'])); + + }else{ + $form['name']['#value'] = ' '; + $form['name']['#readonly'] = FALSE; + //$form['name']['#attributes']['readonly'] = 'readonly'; + $commands[] = ajax_command_replace("#ajax-chapter-name-replace", drupal_render($form['name'])); + + } + return array('#type' => 'ajax', '#commands' => $commands); + } diff --git a/code_approval.inc b/code_approval.inc index a669125..71c769e 100755 --- a/code_approval.inc +++ b/code_approval.inc @@ -1,700 +1,1596 @@ <?php // $Id$ - function code_approval() { - /* get a list of unapproved chapters */ - $pending_chapter_q = db_query("SELECT c.id as c_id, c.number as c_number, c.name as c_name, c.preference_id as c_preference_id FROM {textbook_companion_example} as e JOIN {textbook_companion_chapter} as c ON c.id = e.chapter_id WHERE e.approval_status = 0"); - if (!$pending_chapter_q) - { - drupal_set_message(t('There are no pending code approvals.'), 'status'); - return ''; - } - $rows = array(); - while ($row = db_fetch_object($pending_chapter_q)) - { - /* get preference data */ - $preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d", $row->c_preference_id); - $preference_data = db_fetch_object($preference_q); - /* get proposal data */ - $proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d", $preference_data->proposal_id); - $proposal_data = db_fetch_object($proposal_q); - /* setting table row information */ - $rows[] = array($preference_data->book, $row->c_number, $row->c_name, $proposal_data->full_name, l('Edit', 'code_approval/approve/' . $row->c_id)); - } - - /* check if there are any pending proposals */ - if (!$rows) - { - drupal_set_message(t('There are no pending proposals'), 'status'); - return ''; - } - - $header = array('Title of the Book', 'Chapter Number', 'Title of the Chapter', 'Contributor Name', 'Actions'); - $output = theme_table($header, $rows); - return $output; + /* get a list of unapproved chapters */ + /*$pending_chapter_q = db_query("SELECT c.id as c_id, c.number as c_number, c.name as c_name, c.preference_id as c_preference_id FROM {textbook_companion_example} as e JOIN {textbook_companion_chapter} as c ON c.id = e.chapter_id WHERE e.approval_status = 0");*/ + $query = db_select('textbook_companion_example', 'e'); + $query->fields('c', array( + 'id', + 'number', + 'name', + 'preference_id' + )); + $query->addField('c', 'id', 'c_id'); + $query->addField('c', 'number', 'c_number'); + $query->addField('c', 'name', 'c_name'); + $query->addField('c', 'preference_id', 'c_preference_id'); + $query->innerJoin('textbook_companion_chapter', 'c', 'c.id = e.chapter_id'); + $query->condition('e.approval_status', 0); + $pending_chapter_q = $query->execute(); + if (!$pending_chapter_q) { + drupal_set_message(t('There are no pending code approvals.'), 'status'); + return ''; + } + $rows = array(); + while ($row = $pending_chapter_q->fetchObject()) { + /* get preference data */ + /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d", $row->c_preference_id); + $preference_data = db_fetch_object($preference_q);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('id', $row->c_preference_id); + $result = $query->execute(); + $preference_data = $result->fetchObject(); + /* get proposal data */ + /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d", $preference_data->proposal_id); + $proposal_data = db_fetch_object($proposal_q);*/ + $query = db_select('textbook_companion_proposal'); + $query->fields('textbook_companion_proposal'); + $query->condition('id', $preference_data->proposal_id); + $result = $query->execute(); + $proposal_data = $result->fetchObject(); + /* setting table row information */ + $rows[] = array( + $preference_data->book, + $row->c_number, + $row->c_name, + $proposal_data->full_name, + l('Edit', 'textbook-companion/code-approval/approve/' . $row->c_id) + ); + } + /* check if there are any pending proposals */ + if (!$rows) { + drupal_set_message(t('There are no pending proposals'), 'status'); + return ''; + } + $header = array( + 'Title of the Book', + 'Chapter Number', + 'Title of the Chapter', + 'Contributor Name', + 'Actions' + ); + $output = theme('table', array( + 'header' => $header, + 'rows' => $rows + )); + return $output; } - -function code_approval_form($form_state) +function code_approval_form($form, $form_state) { - /* get a list of unapproved chapters */ - $chapter_id = arg(2); - $pending_chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE id = %d", $chapter_id); - if ($pending_chapter_data = db_fetch_object($pending_chapter_q)) - { - /* get preference data */ - $preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d", $pending_chapter_data->preference_id); - $preference_data = db_fetch_object($preference_q); - /* get proposal data */ - $proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d", $preference_data->proposal_id); - $proposal_data = db_fetch_object($proposal_q); - } else { - drupal_set_message(t('Invalid chapter selected.'), 'error'); - drupal_goto('code_approval'); - return; - } - - $form['#tree'] = TRUE; - - $form['contributor'] = array( - '#type' => 'item', - '#value' => $proposal_data->full_name, - '#title' => t('Contributor Name'), - ); - - $form['book_details']['book'] = array( - '#type' => 'item', - '#value' => $preference_data->book, - '#title' => t('Title of the Book'), - ); - - $form['book_details']['number'] = array( - '#type' => 'item', - '#value' => $pending_chapter_data->number, - '#title' => t('Chapter Number'), - ); - - $form['book_details']['name'] = array( - '#type' => 'item', - '#value' => $pending_chapter_data->name, - '#title' => t('Title of the Chapter'), - ); - - $form['book_details']['back_to_list'] = array( - '#type' => 'item', - '#value' => l('Back to Code Approval List', 'code_approval'), - ); - - /* get example data */ - $example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE chapter_id = %d AND approval_status = 0", $chapter_id); - while ($example_data = db_fetch_object($example_q)) - { - $form['example_details'][$example_data->id] = array( - '#type' => 'fieldset', - '#collapsible' => FALSE, - '#collapsed' => TRUE, - ); - $form['example_details'][$example_data->id]['example_number'] = array( - '#type' => 'item', - '#value' => $example_data->number, - '#title' => t('Example Number'), + /* get a list of unapproved chapters */ + $chapter_id = arg(3); + /*$pending_chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE id = %d", $chapter_id);*/ + $query = db_select('textbook_companion_chapter'); + $query->fields('textbook_companion_chapter'); + $query->condition('id', $chapter_id); + $pending_chapter_q = $query->execute(); + if ($pending_chapter_data = $pending_chapter_q->fetchObject()) { + /* get preference data */ + /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d", $pending_chapter_data->preference_id); + $preference_data = db_fetch_object($preference_q);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('id', $pending_chapter_data->preference_id); + $result = $query->execute(); + $preference_data = $result->fetchObject(); + /* get proposal data */ + /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d", $preference_data->proposal_id); + $proposal_data = db_fetch_object($proposal_q);*/ + $query = db_select('textbook_companion_proposal'); + $query->fields('textbook_companion_proposal'); + $query->condition('id', $preference_data->proposal_id); + $result = $query->execute(); + $proposal_data = $result->fetchObject(); + } else { + drupal_set_message(t('Invalid chapter selected.'), 'error'); + drupal_goto('textbook-companion/code-approval'); + return; + } + $form['#tree'] = TRUE; + $form['contributor'] = array( + '#type' => 'item', + '#markup' => $proposal_data->full_name, + '#title' => t('Contributor Name') ); - - $form['example_details'][$example_data->id]['example_caption'] = array( - '#type' => 'item', - '#value' => $example_data->caption, - '#title' => t('Example Caption'), + $form['book_details']['book'] = array( + '#type' => 'item', + '#markup' => $preference_data->book, + '#title' => t('Title of the Book') ); - - $form['example_details'][$example_data->id]['download'] = array( - '#type' => 'markup', - '#value' => l('Download Example', 'download/example/' . $example_data->id), + $form['book_details']['number'] = array( + '#type' => 'item', + '#markup' => $pending_chapter_data->number, + '#title' => t('Chapter Number') ); - - $form['example_details'][$example_data->id]['approved'] = array( - '#type' => 'radios', - '#options' => array('Approved', 'Dis-approved'), + $form['book_details']['name'] = array( + '#type' => 'item', + '#markup' => $pending_chapter_data->name, + '#title' => t('Title of the Chapter') ); - - $form['example_details'][$example_data->id]['message'] = array( - '#type' => 'textfield', - '#title' => t('Reason for dis-approval'), + $form['book_details']['back_to_list'] = array( + '#type' => 'item', + '#markup' => l('Back to Code Approval List', 'textbook-companion/code-approval') ); - - $form['example_details'][$example_data->id]['example_id'] = array( - '#type' => 'hidden', - '#value' => $example_data->id, + /* get example data */ + /*$example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE chapter_id = %d AND approval_status = 0", $chapter_id);*/ + $query = db_select('textbook_companion_example'); + $query->fields('textbook_companion_example'); + $query->condition('chapter_id', $chapter_id); + $query->condition('approval_status', 0); + $example_q = $query->execute(); + while ($example_data = $example_q->fetchObject()) { + $form['example_details'][$example_data->id] = array( + '#type' => 'fieldset', + '#collapsible' => FALSE, + '#collapsed' => TRUE + ); + $form['example_details'][$example_data->id]['example_number'] = array( + '#type' => 'item', + '#markup' => $example_data->number, + '#title' => t('Example Number') + ); + $form['example_details'][$example_data->id]['example_caption'] = array( + '#type' => 'item', + '#markup' => $example_data->caption, + '#title' => t('Example Caption') + ); + $form['example_details'][$example_data->id]['download'] = array( + '#type' => 'markup', + '#markup' => l('Download Example', 'textbook-companion/download/example/' . $example_data->id) + ); + $form['example_details'][$example_data->id]['approved'] = array( + '#type' => 'radios', + '#options' => array( + 'Approved', + 'Dis-approved' + ) + ); + $form['example_details'][$example_data->id]['message'] = array( + '#type' => 'textfield', + '#title' => t('Reason for dis-approval') + ); + $form['example_details'][$example_data->id]['example_id'] = array( + '#type' => 'hidden', + '#value' => $example_data->id + ); + } + $form['submit'] = array( + '#type' => 'submit', + '#value' => t('Submit') ); - } - - $form['submit'] = array( - '#type' => 'submit', - '#value' => t('Submit') - ); - return $form; + return $form; } - function code_approval_form_submit($form, &$form_state) { - global $user; - - foreach ($form_state['values']['example_details'] as $ex_id => $ex_data) - { - $example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE id = %d LIMIT 1", $ex_data['example_id']); - $example_data = db_fetch_object($example_q); - $chapter_data = db_fetch_object(db_query("SELECT * FROM {textbook_companion_chapter} WHERE id = %d LIMIT 1", $example_data->chapter_id)); - $preference_data = db_fetch_object(db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d LIMIT 1", $chapter_data->preference_id)); - $proposal_data = db_fetch_object(db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d LIMIT 1", $preference_data->proposal_id)); - $user_data = user_load($proposal_data->uid); - - del_book_pdf($preference_data->id); - - if ($ex_data['approved'] == "0") - { - db_query("UPDATE {textbook_companion_example} SET approval_status = 1, approver_uid = %d, approval_date = %d WHERE id = %d", $user->uid, time(), $ex_data['example_id']); - - /* sending email */ - $email_to = $user_data->mail; - $param['example_approved']['example_id'] = $ex_data['example_id']; - $param['example_approved']['user_id'] = $user_data->uid; - if (!drupal_mail('textbook_companion', 'example_approved', $email_to, language_default(), $param, variable_get('textbook_companion_from_email', NULL), TRUE)) - drupal_set_message('Error sending email message.', 'error'); - - } else if ($ex_data['approved'] == "1") { - if (delete_example($ex_data['example_id'])) - { - /* sending email */ - $email_to = $user_data->mail; - $param['example_disapproved']['example_number'] = $example_data->number; - $param['example_disapproved']['example_caption'] = $example_data->caption; - $param['example_disapproved']['user_id'] = $user_data->uid; - $param['example_disapproved']['message'] = $ex_data['message']; - if (!drupal_mail('textbook_companion', 'example_disapproved', $email_to, language_default(), $param, variable_get('textbook_companion_from_email', NULL), TRUE)) - drupal_set_message('Error sending email message.', 'error'); - } else { - drupal_set_message('Error disapproving and deleting example. Please contact administrator.', 'error'); - } + global $user; + foreach ($form_state['values']['example_details'] as $ex_id => $ex_data) { + /*$example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE id = %d LIMIT 1", $ex_data['example_id']); + $example_data = db_fetch_object($example_q);*/ + $query = db_select('textbook_companion_example'); + $query->fields('textbook_companion_example'); + $query->condition('id', $ex_data['example_id']); + $query->range(0, 1); + $result = $query->execute(); + $example_data = $result->fetchObject(); + /*$chapter_data = db_fetch_object(db_query("SELECT * FROM {textbook_companion_chapter} WHERE id = %d LIMIT 1", $example_data->chapter_id));*/ + $query = db_select('textbook_companion_chapter'); + $query->fields('textbook_companion_chapter'); + $query->condition('id', $example_data->chapter_id); + $query->range(0, 1); + $result = $query->execute(); + $chapter_data = $result->fetchObject(); + /*$preference_data = db_fetch_object(db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d LIMIT 1", $chapter_data->preference_id));*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('id', $chapter_data->preference_id); + $query->range(0, 1); + $result = $query->execute(); + $preference_data = $result->fetchObject(); + /*$proposal_data = db_fetch_object(db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d LIMIT 1", $preference_data->proposal_id));*/ + $query = db_select('textbook_companion_proposal'); + $query->fields('textbook_companion_proposal'); + $query->condition('id', $preference_data->proposal_id); + $query->range(0, 1); + $result = $query->execute(); + $proposal_data = $result->fetchObject(); + $user_data = user_load($proposal_data->uid); + del_book_pdf($preference_data->id); + if ($ex_data['approved'] == "0") { + /*db_query("UPDATE {textbook_companion_example} SET approval_status = 1, approver_uid = %d, approval_date = %d WHERE id = %d", $user->uid, time(), $ex_data['example_id']);*/ + $query = db_update('textbook_companion_example'); + $query->fields(array( + 'approval_status' => 1, + 'approver_uid' => $user->uid, + 'approval_date' => time() + )); + $query->condition('id', $ex_data['example_id']); + $num_updated = $query->execute(); + /* sending email */ + $email_to = $user_data->mail; + $from = variable_get('textbook_companion_from_email', ''); + $bcc = variable_get('textbook_companion_emails', ''); + $cc = variable_get('textbook_companion_cc_emails', ''); + $param['example_approved']['example_id'] = $ex_data['example_id']; + $param['example_approved']['user_id'] = $user_data->uid; + $param['example_approved']['headers'] = array( + 'From' => $from, + 'MIME-Version' => '1.0', + 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes', + 'Content-Transfer-Encoding' => '8Bit', + 'X-Mailer' => 'Drupal', + 'Cc' => $cc, + 'Bcc' => $bcc + ); + if (!drupal_mail('textbook_companion', 'example_approved', $email_to, language_default(), $param, $from, TRUE)) + drupal_set_message('Error sending email message.', 'error'); + } else if ($ex_data['approved'] == "1") { + if (delete_example($ex_data['example_id'])) { + /* sending email */ + $email_to = $user_data->mail; + $from = variable_get('textbook_companion_from_email', ''); + $bcc = variable_get('textbook_companion_emails', ''); + $cc = variable_get('textbook_companion_cc_emails', ''); + $param['example_disapproved']['preference_id'] = $chapter_data->preference_id; + $param['example_disapproved']['chapter_id'] = $example_data->chapter_id; + $param['example_disapproved']['example_number'] = $example_data->number; + $param['example_disapproved']['example_caption'] = $example_data->caption; + $param['example_disapproved']['user_id'] = $user_data->uid; + $param['example_disapproved']['message'] = $ex_data['message']; + $param['example_disapproved']['headers'] = array( + 'From' => $from, + 'MIME-Version' => '1.0', + 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes', + 'Content-Transfer-Encoding' => '8Bit', + 'X-Mailer' => 'Drupal', + 'Cc' => $cc, + 'Bcc' => $bcc + ); + if (!drupal_mail('textbook_companion', 'example_disapproved', $email_to, language_default(), $param, $from, TRUE)) + drupal_set_message('Error sending email message.', 'error'); + } else { + drupal_set_message('Error disapproving and deleting example. Please contact administrator.', 'error'); + } + } } - } - drupal_set_message('Updated successfully.', 'status'); - drupal_goto('code_approval'); + drupal_set_message('Updated successfully.', 'status'); + drupal_goto('textbook-companion/code-approval'); } - - /******************************************************************************/ /********************************* BULK APPROVAL ******************************/ /******************************************************************************/ - -function bulk_approval_form($form_state) +function bulk_approval_form($form, &$form_state) { - $form['#redirect'] = FALSE; - - //ahah_helper_register($form, $form_state); - - /* default value for ahah fields - if (!isset($form_state['storage']['run']['book'])) - { - $book_default_value = 0; - } else { - $book_default_value = $form_state['storage']['run']['book']; - } - - if (!isset($form_state['storage']['run']['chapter'])) - { - $chapter_default_value = 0; - } else { - if ($form_state['values']['run']['book_hidden'] != $form_state['values']['run']['book']) - $chapter_default_value = 0; - else - $chapter_default_value = $form_state['storage']['run']['chapter']; - } - - if (!isset($form_state['storage']['run']['example'])) - { - $example_default_value = 0; - } else { - if ($form_state['values']['run']['book_hidden'] != $form_state['values']['run']['book']) - $example_default_value = 0; - else if ($form_state['values']['run']['chapter_hidden'] != $form_state['values']['run']['chapter']) - $example_default_value = 0; - else - $example_default_value = $form_state['storage']['run']['example']; - }*/ - - $form['run'] = array( - '#type' => 'fieldset', - '#title' => t('Bulk Manage Code'), - '#collapsible' => FALSE, - '#collapsed' => FALSE, - '#prefix' => '<div id="run-wrapper">', - '#suffix' => '</div>', - '#tree' => TRUE, - ); - - $form['run']['book'] = array( - '#type' => 'select', - '#title' => t('Title of the Book'), - '#options' => _list_of_books(), - '#default_value' => $book_default_value, - '#tree' => TRUE, - // '#ahah' => array( - // 'event' => 'change', - // 'effect' => 'none', - // 'path' => ahah_helper_path(array('run')), - // 'wrapper' => 'run-wrapper', - // 'progress' => array( - // 'type' => 'throbber', - // 'message' => t(''), - // ), - // ), - ); - - /* hidden form elements */ - $form['run']['book_hidden'] = array( - '#type' => 'hidden', - '#value' => $form_state['values']['run']['book'], - ); - - /* hidden form elements */ - $form['run']['chapter_hidden'] = array( - '#type' => 'hidden', - '#value' => $form_state['values']['run']['chapter'], - ); - - // if ($book_default_value > 0) - // { - $form['run']['download_book'] = array( - '#type' => 'item', - '#value' => l('Download', 'full_download/book/' . $book_default_value) . ' ' . t('(Download all the approved and unapproved examples of the entire book)'), - ); - $form['run']['download_pdf'] = array( - '#type' => 'item', - '#value' => l('Download PDF', 'textbook_companion/generate_book/' . $book_default_value . '/1') . ' ' . t('(Download PDF of all the approved and unapproved examples of the entire book)'), - ); - $form['run']['regenrate_book'] = array( - '#type' => 'item', - '#value' => l('Regenerate PDF', 'textbook_companion/delete_book/' . $book_default_value) . ' ' . t('(Manually Regenerate PDF of the entire book)'), - ); - $form['run']['notes_book'] = array( - '#type' => 'item', - '#value' => l('Notes for Reviewers', 'code_approval/notes/' . $book_default_value), - ); - - $form['run']['approve_book'] = array( - '#type' => 'checkbox', - '#title' => t('Approve Entire Book'), - ); - $form['run']['unapprove_book'] = array( - '#type' => 'checkbox', - '#title' => t('Pending Review Entire Book'), - ); - $form['run']['disapprove_book'] = array( - '#type' => 'checkbox', - '#title' => t('Dis-Approve Entire Book (This will delete all the examples in the book)'), - '#prefix' => '<div style="color:red;"><strong>', - '#suffix' => '</strong></div>', - ); - $form['run']['delete_book_including_proposal'] = array( - '#type' => 'checkbox', - '#title' => t('Delete Entire Book Including Proposal'), - '#prefix' => '<div style="color:red;"><strong>', - '#suffix' => '</strong></div>', - ); - - $form['run']['chapter'] = array( - '#type' => 'select', - '#title' => t('Title of the Chapter'), - '#options' => _list_of_chapters($book_default_value), - '#default_value' => $chapter_default_value, - '#tree' => TRUE, - '#ahah' => array( - 'event' => 'change', - 'effect' => 'none', - 'path' => ahah_helper_path(array('run')), - 'wrapper' => 'run-wrapper', - 'progress' => array( - 'type' => 'throbber', - 'message' => t(''), + $options_first = _bulk_list_of_books(); + $options_two = _ajax_bulk_get_chapter_list(); + $selected = isset($form_state['values']['book']) ? $form_state['values']['book'] : key($options_first); + $select_two = isset($form_state['values']['chapter']) ? $form_state['values']['chapter'] : key($options_two); + $form['book'] = array( + '#type' => 'select', + '#title' => t('Title of the Book'), + '#options' => _bulk_list_of_books(), + '#default_value' => $selected, + '#tree' => TRUE, + '#ajax' => array( + 'callback' => 'ajax_bulk_chapter_list_callback' + ), + '#validated' => TRUE + ); + $form['download_book'] = array( + '#type' => 'item', + '#markup' => '<div id="ajax_selected_book"></div>' + ); + /*$form['download_pdf'] = array( + '#type' => 'item', + '#markup' => '<div id="ajax_selected_book_pdf"></div>', + ); + $form['regenrate_book'] = array( + '#type' => 'item', + '#markup' => '<div id="ajax_selected_book_regenerate_pdf"></div>', + );*/ + $form['notes_book'] = array( + '#type' => 'item', + '#markup' => '<div id="ajax_selected_book_notes"></div>' + ); + $form['book_actions'] = array( + '#type' => 'select', + '#title' => t('Please select action for selected book'), + '#options' => _bulk_list_book_actions(), + //'#default_value' => isset($form_state['values']['lab_actions']) ? $form_state['values']['lab_actions'] : 0, + '#prefix' => '<div id="ajax_selected_book_action" style="color:red;">', + '#suffix' => '</div>', + '#states' => array( + 'invisible' => array( + ':input[name="book"]' => array( + 'value' => 0 + ) + ) + ), + '#validated' => TRUE + ); + $form['chapter'] = array( + '#type' => 'select', + '#title' => t('Title of the Chapter'), + '#options' => _ajax_bulk_get_chapter_list($selected), + //'#default_value' => $chapter_default_value, + '#prefix' => '<div id="ajax_select_chapter_list">', + '#suffix' => '</div>', + '#validated' => TRUE, + '#tree' => TRUE, + '#ajax' => array( + 'callback' => 'ajax_bulk_example_list_callback' ), - ), + '#states' => array( + 'invisible' => array( + ':input[name="book"]' => array( + 'value' => 0 + ) + ) + ) ); - // if ($chapter_default_value > 0) - // { - $form['run']['download_chapter'] = array( + $form['download_chapter'] = array( '#type' => 'item', - '#value' => l('Download', 'full_download/chapter/' . $chapter_default_value) . ' ' . t('(Download all the approved and unapproved examples of the entire chapter)'), - ); - - $form['run']['approve_chapter'] = array( - '#type' => 'checkbox', - '#title' => t('Approve Entire Chapter'), - ); - $form['run']['unapprove_chapter'] = array( - '#type' => 'checkbox', - '#title' => t('Pending Review Entire Chapter'), - ); - $form['run']['disapprove_chapter'] = array( - '#type' => 'checkbox', - '#title' => t('Dis-Approve Entire Chapter (This will delete all the examples in the chapter)'), - '#prefix' => '<div style="color:red;"><strong>', - '#suffix' => '</strong></div>', - ); - - $form['run']['example'] = array( + '#markup' => '<div id="ajax_download_chapter"></div>' + ); + $form['chapter_actions'] = array( + '#type' => 'select', + '#title' => t('Please select action for selected chapter'), + '#options' => _bulk_list_chapter_actions(), + //'#default_value' => isset($form_state['values']['lab_actions']) ? $form_state['values']['lab_actions'] : 0, + '#prefix' => '<div id="ajax_selected_chapter_action" style="color:red;">', + '#suffix' => '</div>', + '#states' => array( + 'invisible' => array( + ':input[name="book"]' => array( + 'value' => 0 + ) + ) + ), + '#ajax' => array( + 'callback' => 'ajax_bulk_chapter_actions_callback' + ) + ); + $form['example'] = array( '#type' => 'select', '#title' => t('Example No. (Caption)'), - '#options' => _list_of_examples($chapter_default_value), - '#default_value' => $example_default_value, - '#tree' => TRUE, - '#ahah' => array( - 'event' => 'change', - 'effect' => 'none', - 'path' => ahah_helper_path(array('run')), - 'wrapper' => 'run-wrapper', - 'progress' => array( - 'type' => 'throbber', - 'message' => t(''), - ), + '#options' => _ajax_bulk_get_examples(), + // '#default_value' => $example_default_value, + '#validated' => TRUE, + '#prefix' => '<div id="ajax_selected_example">', + '#suffix' => '</div>', + '#states' => array( + 'invisible' => array( + ':input[name="book"]' => array( + 'value' => 0 + ) + ) ), - ); - //} - //} - - /************ START OF $_POST **************/ - if ($_POST) - { - if (($book_default_value > 0) && ($chapter_default_value > 0) && ($example_default_value > 0)) - { - $example_list_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE example_id = %d", $form_state['values']['run']['example']); - if ($example_list_q) - { - $example_files_rows = array(); - while ($example_list_data = db_fetch_object($example_list_q)) - { - $example_file_type = ''; - switch ($example_list_data->filetype) - { - case 'S' : $example_file_type = 'Source or Main file'; break; - case 'R' : $example_file_type = 'Result file'; break; - case 'X' : $example_file_type = 'xcos file'; break; - default : $example_file_type = 'Unknown'; break; - } - $example_files_rows[] = array(l($example_list_data->filename, 'download/file/' . $example_list_data->id), $example_file_type); + '#ajax' => array( + 'callback' => 'ajax_bulk_example_files_callback' + ) + ); + $form['download_example'] = array( + '#type' => 'item', + '#markup' => '<div id="ajax_download_selected_example"></div>' + ); + $form['edit_example'] = array( + '#type' => 'item', + '#markup' => '<div id="ajax_edit_selected_example"></div>' + ); + $form['example_files'] = array( + '#type' => 'item', + '#markup' => '', + '#prefix' => '<div id="ajax_example_files_list">', + '#suffix' => '</div>' + ); + $form['example_actions'] = array( + '#type' => 'select', + '#title' => t('Please select action for selected example'), + '#options' => _bulk_list_example_actions(), + //'#default_value' => isset($form_state['values']['lab_actions']) ? $form_state['values']['lab_actions'] : 0, + '#prefix' => '<div id="ajax_selected_example_action" style="color:red;">', + '#suffix' => '</div>', + '#states' => array( + 'invisible' => array( + ':input[name="book"]' => array( + 'value' => 0 + ) + ) + ) + ); + $form['message'] = array( + '#type' => 'textarea', + '#title' => t('If Dis-Approved please specify reason for Dis-Approval'), + '#states' => array( + 'visible' => array( + array( + array( + ':input[name="book_actions"]' => array( + 'value' => 3 + ) + ), + 'or', + array( + ':input[name="chapter_actions"]' => array( + 'value' => 3 + ) + ), + 'or', + array( + ':input[name="example_actions"]' => array( + 'value' => 3 + ) + ), + 'or', + array( + ':input[name="book_actions"]' => array( + 'value' => 4 + ) + ) + ) + ), + 'required' => array( + array( + array( + ':input[name="book_actions"]' => array( + 'value' => 3 + ) + ), + 'or', + array( + ':input[name="chapter_actions"]' => array( + 'value' => 3 + ) + ), + 'or', + array( + ':input[name="example_actions"]' => array( + 'value' => 3 + ) + ), + 'or', + array( + ':input[name="book_actions"]' => array( + 'value' => 4 + ) + ) + ) + ) + ) + ); + $form['submit'] = array( + '#type' => 'submit', + '#value' => t('Submit'), + '#states' => array( + 'invisible' => array( + ':input[name="book"]' => array( + 'value' => 0 + ) + ) + ) + ); + return $form; +} +function bulk_approval_form_submit($form, &$form_state) +{ + global $user; + $root_path = textbook_companion_path(); + if ($form_state['clicked_button']['#value'] == 'Submit') { + if ($form_state['values']['book']) + del_book_pdf($form_state['values']['book']); + if (user_access('bulk manage code')) { + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('id', $form_state['values']['book']); + $result = $query->execute(); + $pref_data = $result->fetchObject(); + $prop_id = $pref_data->proposal_id; + $query = db_select('textbook_companion_proposal'); + $query->fields('textbook_companion_proposal'); + $query->condition('id', $prop_id); + $user_query = $query->execute(); + $user_info = $user_query->fetchObject(); + $user_data = user_load($user_info->uid); + if (($form_state['values']['book_actions'] == 1) && ($form_state['values']['chapter_actions'] == 0) && ($form_state['values']['example_actions'] == 0)) { + /* approving entire book */ + /* $chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE preference_id = %d", + $form_state['values']['book']);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('id', $form_state['values']['book']); + $query->condition('approval_status', 1); + $result = $query->execute(); + $preference_data = $result->fetchObject(); + $query = db_select('textbook_companion_chapter'); + $query->fields('textbook_companion_chapter'); + $query->condition('preference_id', $form_state['values']['book']); + $chapter_q = $query->execute(); + while ($chapter_data = $chapter_q->fetchObject()) { + /*db_query("UPDATE {textbook_companion_example} SET approval_status = 1, approver_uid = %d WHERE chapter_id = %d AND approval_status = 0", $user->uid, $chapter_data->id);*/ + $query = db_update('textbook_companion_example'); + $query->fields(array( + 'approval_status' => 1, + 'approver_uid' => $user->uid + )); + $query->condition('chapter_id', $chapter_data->id); + $query->condition('approval_status', 0); + $num_updated = $query->execute(); + } + $query = db_update('textbook_companion_preference'); + $query->fields(array( + 'submited_all_examples_code' => 1 + )); + $query->condition('id', $form_state['values']['book']); + $num_updated = $query->execute(); + drupal_set_message(t('Approved Entire Book.'), 'status'); + /* email */ + //$email_subject = t('Your uploaded examples have been approved'); + //$email_body = array(0=>t('Your all the uploaded examples for the book have been approved.')); + $email_subject = t('[!site_name] Your uploaded Textbook Companion examples have been approved', array( + '!site_name' => variable_get('site_name', '') + )); + $email_body = array( + 0 => t(' + +Dear !user_name, + +Your all the uploaded examples for the book have been approved. + +Title of the book : ' . $preference_data->book . ' +Author name : ' . $preference_data->author . ' +ISBN No. : ' . $preference_data->isbn . ' +Publisher and Place : ' . $preference_data->publisher . ' +Edition : ' . $preference_data->edition . ' +Year of publication : ' . $preference_data->year . ' + +Best Wishes, + +!site_name Team, +FOSSEE,IIT Bombay', array( + '!site_name' => variable_get('site_name', ''), + '!user_name' => $user_data->name + )) + ); + } elseif (($form_state['values']['book_actions'] == 2) && ($form_state['values']['chapter_actions'] == 0) && ($form_state['values']['example_actions'] == 0)) { + /* pending entire book */ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('id', $form_state['values']['book']); + $query->condition('approval_status', 1); + $result = $query->execute(); + $preference_data = $result->fetchObject(); + /*$chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE preference_id = %d", $form_state['values']['book']);*/ + $query = db_select('textbook_companion_chapter'); + $query->fields('textbook_companion_chapter'); + $query->condition('preference_id', $form_state['values']['book']); + $chapter_q = $query->execute(); + while ($chapter_data = $chapter_q->fetchObject()) { + /*db_query("UPDATE {textbook_companion_example} SET approval_status = 0 WHERE chapter_id = %d", $chapter_data->id);*/ + $query = db_update('textbook_companion_example'); + $query->fields(array( + 'approval_status' => 0 + )); + $query->condition('chapter_id', $chapter_data->id); + $num_updated = $query->execute(); + } + drupal_set_message(t('Pending Review Entire Book.'), 'status'); + /* email */ + /*$email_subject = t('Your uploaded examples have been marked as pending'); + $email_body =array( t('Your all the uploaded examples for the book have been marked as pending to be review. You will be able to see the exmaples after they have been approved by one of our reviewers.'));*/ + $email_subject = t('[!site_name] Your uploaded Textbook Companion examples have been marked as pending', array( + '!site_name' => variable_get('site_name', '') + )); + $email_body = array( + 0 => t(' + +Dear !user_name, + +Your all the uploaded examples for the book have been marked as pending to be reviewed. +You will be able to see the examples after they have been approved by one of our reviewers. + +Title of the book : ' . $preference_data->book . ' +Author name : ' . $preference_data->author . ' +ISBN No. : ' . $preference_data->isbn . ' +Publisher and Place : ' . $preference_data->publisher . ' +Edition : ' . $preference_data->edition . ' +Year of publication : ' . $preference_data->year . ' + +Best Wishes, + +!site_name Team, +FOSSEE,IIT Bombay', array( + '!site_name' => variable_get('site_name', ''), + '!user_name' => $user_data->name + )) + ); + } elseif (($form_state['values']['book_actions'] == 3) && ($form_state['values']['chapter_actions'] == 0) && ($form_state['values']['example_actions'] == 0)) { + if (strlen(trim($form_state['values']['message'])) <= 30) { + form_set_error('message', t('')); + drupal_set_message("Please mention the reason for disapproval. Minimum 30 character required", 'error'); + return; + } + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('id', $form_state['values']['book']); + $query->condition('approval_status', 1); + $result = $query->execute(); + $preference_data = $result->fetchObject(); + if (!user_access('bulk delete code')) { + drupal_set_message(t('You do not have permission to Bulk Dis-Approved and Deleted Entire Book.'), 'error'); + return; + } + if (delete_book($form_state['values']['book'])) { + drupal_set_message(t('Dis-Approved and Deleted Entire Book.'), 'status'); + } else { + drupal_set_message(t('Error Dis-Approving and Deleting Entire Book.'), 'error'); + } + /* email */ + /*$email_subject = t('Your uploaded examples have been marked as dis-approved'); + $email_body =array( t('Your all the uploaded examples for the whole book have been marked as dis-approved. + + Reason for dis-approval: + + ' . $form_state['values']['message']));*/ + $email_subject = t('[!site_name] Your uploaded Textbook Companion examples have been marked as + dis-approved', array( + '!site_name' => variable_get('site_name', '') + )); + $email_body = array( + 0 => t(' + +Dear !user_name, + +Your all the uploaded examples for the whole book have been marked as dis-approved. + +Title of the book : ' . $preference_data->book . ' +Author name : ' . $preference_data->author . ' +ISBN No. : ' . $preference_data->isbn . ' +Publisher and Place : ' . $preference_data->publisher . ' +Edition : ' . $preference_data->edition . ' +Year of publication : ' . $preference_data->year . ' + + +Reason for dis-approval:' . $form_state['values']['message'] . ' + +Best Wishes, + +!site_name Team, +FOSSEE,IIT Bombay', array( + '!site_name' => variable_get('site_name', ''), + '!user_name' => $user_data->name + )) + ); + } elseif (($form_state['values']['book_actions'] == 4) && ($form_state['values']['chapter_actions'] == 0) && ($form_state['values']['example_actions'] == 0)) { + if (strlen(trim($form_state['values']['message'])) <= 30) { + form_set_error('message', t('')); + drupal_set_message("Please mention the reason for disapproval/deletion. Minimum 30 character required", 'error'); + return; + } + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('id', $form_state['values']['book']); + $query->condition('approval_status', 1); + $result = $query->execute(); + $pref_data = $result->fetchObject(); + if (!user_access('bulk delete code')) { + drupal_set_message(t('You do not have permission to Bulk Delete Entire Book Including Proposal.'), 'error'); + return; + } + /* check if dependency files are present */ + /*$dep_q = db_query("SELECT * FROM {textbook_companion_dependency_files} WHERE preference_id = %d", $form_state['values']['book']);*/ + /*$query = db_select('textbook_companion_dependency_files'); + $query->fields('textbook_companion_dependency_files'); + $query->condition('preference_id', $form_state['values']['book']); + $dep_q = $query->execute(); + + if ($dep_data =$dep_q->fetchObject()) + { + drupal_set_message(t("Cannot delete book since it has dependency files that can be used by others. First delete the dependency files before deleing the Book."), 'error'); + return; + }*/ + if (delete_book($form_state['values']['book'])) { + drupal_set_message(t('Dis-Approved and Deleted Entire Book examples.'), 'status'); + $dir_path = $root_path . $form_state['values']['book']; + if (is_dir($dir_path)) { + $res = rmdir($dir_path); + if (!$res) { + drupal_set_message(t("Cannot delete Book directory : " . $dir_path . ". Please contact administrator."), 'error'); + return; + } + } else { + drupal_set_message(t("Book directory not present : " . $dir_path . ". Skipping deleting book directory."), 'status'); + } + /* deleting preference and proposal */ + /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d", $form_state['values']['book']); + $preference_data = db_fetch_object($preference_q); + */ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('id', $form_state['values']['book']); + $result = $query->execute(); + $preference_data = $result->fetchObject(); + $proposal_id = $preference_data->proposal_id; + /*db_query("DELETE FROM {textbook_companion_preference} WHERE proposal_id = %d", $proposal_id);*/ + $query = db_delete('textbook_companion_preference'); + $query->condition('proposal_id', $proposal_id); + $num_deleted = $query->execute(); + /*db_query("DELETE FROM {textbook_companion_proposal} WHERE id = %d", $proposal_id);*/ + $query = db_delete('textbook_companion_proposal'); + $query->condition('id', $proposal_id); + $num_deleted = $query->execute(); + drupal_set_message(t('Deleted Book Proposal.'), 'status'); + /* email */ + /*$email_subject = t('Your uploaded examples including the book proposal have been deleted'); + $email_body = array(0=>t('Your all the uploaded examples including the book have been deleted permanently. + Reason for deletion: + ' . $form_state['values']['message']));*/ + $email_subject = t('[!site_name] Your uploaded Textbook Companion examples including the book proposal have been deleted', array( + '!site_name' => variable_get('site_name', '') + )); + $email_body = array( + 0 => t(' + +Dear !user_name, + +We regret to inform you that all the uploaded examples including the book with following details have been deleted permanently. + + +Title of the book : ' . $pref_data->book . ' +Author name : ' . $pref_data->author . ' +ISBN No. : ' . $pref_data->isbn . ' +Publisher and Place : ' . $pref_data->publisher . ' +Edition : ' . $pref_data->edition . ' +Year of publication : ' . $pref_data->year . ' + +Reason for deletion:' . $form_state['values']['message'] . ' + + +Best Wishes, + +!site_name Team, +FOSSEE,IIT Bombay', array( + '!site_name' => variable_get('site_name', ''), + '!user_name' => $user_data->name + )) + ); + } else { + drupal_set_message(t('Error Dis-Approving and Deleting Entire Book.'), 'error'); + } + } elseif (($form_state['values']['book_actions'] == 0) && ($form_state['values']['chapter_actions'] == 1) && ($form_state['values']['example_actions'] == 0)) { + /*db_query("UPDATE {textbook_companion_example} SET approval_status = 1, approver_uid = %d WHERE chapter_id = %d AND approval_status = 0", $user->uid, $form_state['values']['chapter']);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('id', $form_state['values']['book']); + $query->condition('approval_status', 1); + $result = $query->execute(); + $pref_data = $result->fetchObject(); + $query = db_select('textbook_companion_chapter'); + $query->fields('textbook_companion_chapter'); + $query->condition('preference_id', $form_state['values']['book']); + $query->condition('id', $form_state['values']['chapter']); + $result = $query->execute(); + $chap_data = $result->fetchObject(); + $query = db_update('textbook_companion_example'); + $query->fields(array( + 'approval_status' => 1, + 'approver_uid' => $user->uid + )); + $query->condition('chapter_id', $form_state['values']['chapter']); + $query->condition('approval_status', 0); + $num_updated = $query->execute(); + drupal_set_message(t('Approved Entire Chapter.'), 'status'); + /* email */ + /*$email_subject = t('Your uploaded examples have been approved'); + $email_body = array(0=>t('Your all the uploaded examples for the chapter have been approved.'));*/ + $email_subject = t('[!site_name] Your uploaded Textbook Companion examples have been approved', array( + '!site_name' => variable_get('site_name', '') + )); + $email_body = array( + 0 => t(' + +Dear !user_name, + +Your all the uploaded examples for the chapter have been approved. + +Title of the book : ' . $pref_data->book . ' +Title of the chapter : ' . $chap_data->name . ' + +Best Wishes, + +!site_name Team, +FOSSEE,IIT Bombay', array( + '!site_name' => variable_get('site_name', ''), + '!user_name' => $user_data->name + )) + ); + } elseif (($form_state['values']['book_actions'] == 0) && ($form_state['values']['chapter_actions'] == 2) && ($form_state['values']['example_actions'] == 0)) { + /*db_query("UPDATE {textbook_companion_example} SET approval_status = 0 WHERE chapter_id = %d", $form_state['values']['chapter']);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('id', $form_state['values']['book']); + $query->condition('approval_status', 1); + $result = $query->execute(); + $pref_data = $result->fetchObject(); + $query = db_select('textbook_companion_chapter'); + $query->fields('textbook_companion_chapter'); + $query->condition('preference_id', $form_state['values']['book']); + $query->condition('id', $form_state['values']['chapter']); + $result = $query->execute(); + $chap_data = $result->fetchObject(); + $query = db_update('textbook_companion_example'); + $query->fields(array( + 'approval_status' => 0 + )); + $query->condition('chapter_id', $form_state['values']['chapter']); + $num_updated = $query->execute(); + drupal_set_message(t('Entire Chapter marked as Pending Review.'), 'status'); + /* email */ + /*$email_subject = t('Your uploaded examples have been marked as pending'); + $email_body = array(0=>t('Your all the uploaded examples for the chapter have been marked as pending + to be review.'));*/ + $email_subject = t('[!site_name] Your uploaded Textbook Companion examples have been marked as pending', array( + '!site_name' => variable_get('site_name', '') + )); + $email_body = array( + 0 => t(' + +Dear !user_name, + +Your all the uploaded examples for the chapter have been marked as pending to be reviewed. + +Title of the book : ' . $pref_data->book . ' +Title of the chapter : ' . $chap_data->name . ' + +Best Wishes, + +!site_name Team, +FOSSEE,IIT Bombay', array( + '!site_name' => variable_get('site_name', ''), + '!user_name' => $user_data->name + )) + ); + } elseif (($form_state['values']['book_actions'] == 0) && ($form_state['values']['chapter_actions'] == 3) && ($form_state['values']['example_actions'] == 0)) { + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('id', $form_state['values']['book']); + $query->condition('approval_status', 1); + $result = $query->execute(); + $pref_data = $result->fetchObject(); + $query = db_select('textbook_companion_chapter'); + $query->fields('textbook_companion_chapter'); + $query->condition('preference_id', $form_state['values']['book']); + $query->condition('id', $form_state['values']['chapter']); + $result = $query->execute(); + $chap_data = $result->fetchObject(); + if (strlen(trim($form_state['values']['message'])) <= 30) { + form_set_error('message', t('')); + drupal_set_message("Please mention the reason for disapproval. Minimum 30 character required", 'error'); + return; + } + if (!user_access('bulk delete code')) { + drupal_set_message(t('You do not have permission to Bulk Dis-Approved and Deleted Entire Chapter.'), 'error'); + return; + } + if (delete_chapter($form_state['values']['chapter'])) { + drupal_set_message(t('Dis-Approved and Deleted Entire Chapter.'), 'status'); + } else { + drupal_set_message(t('Error Dis-Approving and Deleting Entire Chapter.'), 'error'); + } + /* email */ + /*$email_subject = t('Your uploaded example have been marked as dis-approved'); + $email_body = array(0=>t('Your uploaded example for the entire chapter have been marked as dis-approved. + Reason for dis-approval:' . $form_state['values']['message']));*/ + $email_subject = t('[!site_name] Your uploaded Textbook Companion example have been marked as dis-approved', array( + '!site_name' => variable_get('site_name', '') + )); + $email_body = array( + 0 => t(' + +Dear !user_name, + +Your uploaded example for the entire chapter have been marked as dis-approved. + +Title of the book : ' . $pref_data->book . ' +Title of the chapter : ' . $chap_data->name . ' + + +Reason for dis-approval:' . $form_state['values']['message'] . ' + +Best Wishes, + +!site_name Team, +FOSSEE,IIT Bombay', array( + '!site_name' => variable_get('site_name', ''), + '!user_name' => $user_data->name + )) + ); + } elseif (($form_state['values']['book_actions'] == 0) && ($form_state['values']['chapter_actions'] == 0) && ($form_state['values']['example_actions'] == 1)) { + /*db_query("UPDATE {textbook_companion_example} SET approval_status = 1, approver_uid = %d WHERE id = %d", $user->uid, $form_state['values']['example']);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('id', $form_state['values']['book']); + $query->condition('approval_status', 1); + $result = $query->execute(); + $pref_data = $result->fetchObject(); + $query = db_select('textbook_companion_chapter'); + $query->fields('textbook_companion_chapter'); + $query->condition('preference_id', $form_state['values']['book']); + $query->condition('id', $form_state['values']['chapter']); + $result = $query->execute(); + $chap_data = $result->fetchObject(); + $query = db_select('textbook_companion_example'); + $query->fields('textbook_companion_example'); + $query->condition('id', $form_state['values']['example']); + $result = $query->execute(); + $examp_data = $result->fetchObject(); + $query = db_update('textbook_companion_example'); + $query->fields(array( + 'approval_status' => 1, + 'approver_uid' => $user->uid + )); + $query->condition('id', $form_state['values']['example']); + $num_updated = $query->execute(); + drupal_set_message(t('Example approved.'), 'status'); + /* email */ + /*$email_subject = t('Your uploaded example has been approved'); + $email_body = array(0=>t('Your uploaded example has been approved.'));*/ + $email_subject = t('[!site_name] Your uploaded Textbook Companion example have been approved', array( + '!site_name' => variable_get('site_name', '') + )); + $email_body = array( + 0 => t(' + +Dear !user_name, + +Your example for DWSIM Textbook Companion with the following details is approved. + +Title of the book : ' . $pref_data->book . ' +Title of the chapter : ' . $chap_data->name . ' +Example number : ' . $examp_data->number . ' +Caption : ' . $examp_data->caption . ' + +Best Wishes, + +!site_name Team, +FOSSEE,IIT Bombay', array( + '!site_name' => variable_get('site_name', ''), + '!user_name' => $user_data->name + )) + ); + } elseif (($form_state['values']['book_actions'] == 0) && ($form_state['values']['chapter_actions'] == 0) && ($form_state['values']['example_actions'] == 2)) { + /*db_query("UPDATE {textbook_companion_example} SET approval_status = 0 WHERE id = %d", $form_state['values']['example']);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('id', $form_state['values']['book']); + $query->condition('approval_status', 1); + $result = $query->execute(); + $pref_data = $result->fetchObject(); + $query = db_select('textbook_companion_chapter'); + $query->fields('textbook_companion_chapter'); + $query->condition('preference_id', $form_state['values']['book']); + $query->condition('id', $form_state['values']['chapter']); + $result = $query->execute(); + $chap_data = $result->fetchObject(); + $query = db_select('textbook_companion_example'); + $query->fields('textbook_companion_example'); + $query->condition('id', $form_state['values']['example']); + $result = $query->execute(); + $examp_data = $result->fetchObject(); + $query = db_update('textbook_companion_example'); + $query->fields(array( + 'approval_status' => 0 + )); + $query->condition('id', $form_state['values']['example']); + $num_updated = $query->execute(); + drupal_set_message(t('Example marked as Pending Review.'), 'status'); + /* email */ + /*$email_subject = t('Your uploaded example has been marked as pending'); + $email_body = array(0=>t('Your uploaded example has been marked as pending to be review.'));*/ + $email_subject = t('[!site_name] Your uploaded Textbook Companion example has been marked as pending', array( + '!site_name' => variable_get('site_name', '') + )); + $email_body = array( + 0 => t(' + +Dear !user_name, + +Your uploaded example for DWSIM Textbook Companion with the following details has been marked as pending to be reviewed. + +Title of the book : ' . $pref_data->book . ' +Title of the chapter : ' . $chap_data->name . ' +Example number : ' . $examp_data->number . ' +Caption : ' . $examp_data->caption . ' + +Best Wishes, + +!site_name Team, +FOSSEE,IIT Bombay', array( + '!site_name' => variable_get('site_name', ''), + '!user_name' => $user_data->name + )) + ); + } elseif (($form_state['values']['book_actions'] == 0) && ($form_state['values']['chapter_actions'] == 0) && ($form_state['values']['example_actions'] == 3)) { + if (strlen(trim($form_state['values']['message'])) <= 30) { + form_set_error('message', t('')); + drupal_set_message("Please mention the reason for disapproval. Minimum 30 character required", 'error'); + return; + } + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('id', $form_state['values']['book']); + $query->condition('approval_status', 1); + $result = $query->execute(); + $pref_data = $result->fetchObject(); + $query = db_select('textbook_companion_chapter'); + $query->fields('textbook_companion_chapter'); + $query->condition('preference_id', $form_state['values']['book']); + $query->condition('id', $form_state['values']['chapter']); + $result = $query->execute(); + $chap_data = $result->fetchObject(); + $query = db_select('textbook_companion_example'); + $query->fields('textbook_companion_example'); + $query->condition('id', $form_state['values']['example']); + $result = $query->execute(); + $examp_data = $result->fetchObject(); + if (delete_example($form_state['values']['example'])) { + drupal_set_message(t('Example Dis-Approved and Deleted.'), 'status'); + } else { + drupal_set_message(t('Error Dis-Approving and Deleting Example.'), 'error'); + } + /* email */ + /*$email_subject = t('Your uploaded example has been marked as dis-approved'); + $email_body =array(0=> t('Your uploaded example has been marked as dis-approved. + Reason for dis-approval:' . $form_state['values']['message']));*/ + $email_subject = t('[!site_name] Your uploaded Textbook Companion example has been marked as + dis-approved', array( + '!site_name' => variable_get('site_name', '') + )); + $email_body = array( + 0 => t(' + +Dear !user_name, + +Your example for DWSIM Textbook Companion has been marked as dis-approved and deleted. + +Title of the book : ' . $pref_data->book . ' +Title of the chapter : ' . $chap_data->name . ' +Example number : ' . $examp_data->number . ' +Caption : ' . $examp_data->caption . ' + +Reason for dis-approval:' . $form_state['values']['message'] . ' + +Best Wishes, + +!site_name Team, +FOSSEE,IIT Bombay', array( + '!site_name' => variable_get('site_name', ''), + '!user_name' => $user_data->name + )) + ); + } else { + drupal_set_message(t('Please select only one action at a time'), 'error'); + return; + } + /****** sending email when everything done ******/ + if ($email_subject) { + $email_to = $user_data->mail; + $from = variable_get('textbook_companion_from_email', ''); + $bcc = variable_get('textbook_companion_emails', ''); + $cc = variable_get('textbook_companion_cc_emails', ''); + $param['standard']['subject'] = $email_subject; + $param['standard']['body'] = $email_body; + $param['standard']['headers'] = array( + 'From' => $from, + 'MIME-Version' => '1.0', + 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes', + 'Content-Transfer-Encoding' => '8Bit', + 'X-Mailer' => 'Drupal', + 'Cc' => $cc, + 'Bcc' => $bcc + ); + if (!drupal_mail('textbook_companion', 'standard', $email_to, language_default(), $param, $from, TRUE)) + drupal_set_message('Error sending email message.', 'error'); + } + } else { + drupal_set_message(t('You do not have permission to bulk manage code.'), 'error'); } - - /* dependency files */ - $dependency_list_q = db_query("SELECT dependency.id as dependency_id, dependency.filename as dependency_filename, dependency.caption as dependency_caption - FROM {textbook_companion_example_dependency} example_dependency LEFT JOIN {textbook_companion_dependency_files} dependency - ON example_dependency.dependency_id = dependency.id - WHERE example_dependency.example_id = %d", $form_state['values']['run']['example']); - while ($dependency_list_data = db_fetch_object($dependency_list_q)) - { + } +} +function _bulk_list_of_books() +{ + $book_titles = array( + '0' => 'Please select...' + ); + /*$book_titles_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE approval_status = 1 OR approval_status = 3 ORDER BY book ASC");*/ + $query = db_select('textbook_companion_preference', 'pp'); + $query->join('textbook_companion_proposal', 'p', 'pp.proposal_id=p.id'); + $query->join('users', 'u', 'p.uid=u.uid'); + $query->fields('u', array( + 'name' + )); + $query->fields('pp', array( + 'id', + 'book', + 'author' + )); + $or = db_or(); + $or->condition('approval_status', 1); + $or->condition('approval_status', 3); + $query->condition($or); + $query->orderBy('book', 'ASC'); + $book_titles_q = $query->execute(); + while ($book_titles_data = $book_titles_q->fetchObject()) { + $book_titles[$book_titles_data->id] = $book_titles_data->book . ' (Written by ' . $book_titles_data->author . ')' . ' (Proposed by ' . $book_titles_data->name . ')'; + } + return $book_titles; +} +function _ajax_bulk_get_chapter_list($preference_id = 0) +{ + $book_chapters = array( + '0' => 'Please select...' + ); + /*$book_chapters_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE preference_id = %d ORDER BY number ASC", $preference_id);*/ + $query = db_select('textbook_companion_chapter'); + $query->fields('textbook_companion_chapter'); + $query->condition('preference_id', $preference_id); + $query->orderBy('number', 'ASC'); + $book_chapters_q = $query->execute(); + while ($book_chapters_data = $book_chapters_q->fetchObject()) { + $book_chapters[$book_chapters_data->id] = $book_chapters_data->number . '. ' . $book_chapters_data->name; + } + return $book_chapters; +} +function _ajax_bulk_get_examples($chapter_id = 0) +{ + $book_examples = array( + '0' => 'Please select...' + ); + /*$book_examples_q = db_query("SELECT * FROM {textbook_companion_example} WHERE chapter_id = %d ORDER BY + CAST(SUBSTRING_INDEX(number, '.', 1) AS BINARY) ASC, + CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(number , '.', 2), '.', -1) AS UNSIGNED) ASC, + CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(number , '.', -1), '.', 1) AS UNSIGNED) ASC", $chapter_id);*/ + $query = db_select('textbook_companion_example'); + $query->fields('textbook_companion_example'); + $query->condition('chapter_id', $chapter_id); + //$query->orderBy('CAST', 'ASC'); + //$query->orderBy('CAST', 'ASC'); + //$query->orderBy('CAST', 'ASC'); + $book_examples_q = $query->execute(); + while ($book_examples_data = $book_examples_q->fetchObject()) { + $book_examples[$book_examples_data->id] = $book_examples_data->number . ' (' . $book_examples_data->caption . ')'; + } + return $book_examples; +} +function _bulk_list_book_actions() +{ + $book_actions = array( + '0' => 'Please select...' + ); + $book_actions[1] = 'Approve Entire Book'; + $book_actions[2] = 'Pending Review Entire Book'; + $book_actions[3] = 'Dis-Approve Entire Book (This will delete all the examples in the book)'; + $book_actions[4] = 'Delete Entire Book Including Proposal'; + return $book_actions; +} +function _bulk_list_chapter_actions() +{ + $chapter_actions = array( + '0' => 'Please select...' + ); + $chapter_actions[1] = 'Approve Entire Chapter'; + $chapter_actions[2] = 'Pending Review Entire Chapter'; + $chapter_actions[3] = 'Dis-Approve Entire Chapter (This will delete all the examples in the chapter)'; + return $chapter_actions; +} +function _bulk_list_example_actions() +{ + $example_actions = array( + '0' => 'Please select...' + ); + $example_actions[1] = 'Approve Approve Example'; + $example_actions[2] = 'Pending Review Example'; + $example_actions[3] = 'Dis-approve Example (This will delete the example)'; + return $example_actions; +} +/****************************** Ajax Callback function ***************************/ +function ajax_bulk_chapter_list_callback($form, $form_state) +{ + $commands = array(); + $book_default_value = $form_state['values']['book']; + if ($book_default_value > 0) { + $commands[] = ajax_command_html('#ajax_selected_book', l('Download', 'textbook-companion/full-download/book/' . $book_default_value) . ' ' . t('(Download all the approved and unapproved examples of the entire book)')); + /*$commands[] = ajax_command_html('#ajax_selected_book_pdf', l('Download PDF', 'textbook_companion/generate_book/' . $book_default_value . '/1') . ' ' . t('(Download PDF of all the approved and unapproved examples of the entire book)')); + $commands[] = ajax_command_html('#ajax_selected_book_regenerate_pdf', l('Regenerate PDF', 'textbook_companion/delete_book/' . $book_default_value) . ' ' . t('(Manually Regenerate PDF of the entire book)'));*/ + /*$commands[] = ajax_command_html('#ajax_selected_book_notes', l('Notes for Reviewers', 'code_approval/notes/' . $book_default_value));*/ + $form['book_actions']['#options'] = _bulk_list_book_actions(); + $commands[] = ajax_command_replace('#ajax_selected_book_action', drupal_render($form['book_actions'])); + $form['chapter']['#options'] = _ajax_bulk_get_chapter_list($book_default_value); + $commands[] = ajax_command_replace('#ajax_select_chapter_list', drupal_render($form['chapter'])); + $commands[] = ajax_command_html('#ajax_download_chapter', ''); + $form['chapter_actions']['#options'] = _bulk_list_book_actions(); + $commands[] = ajax_command_replace('#ajax_selected_chapter_action', drupal_render($form['chapter_actions'])); + $commands[] = ajax_command_html('#ajax_selected_chapter_action', ''); + $commands[] = ajax_command_html('#ajax_selected_example', ''); + $form['example_actions']['#options'] = _bulk_list_example_actions(); + $commands[] = ajax_command_replace('#ajax_selected_example_action', drupal_render($form['example_actions'])); + $commands[] = ajax_command_html('#ajax_selected_example_action', ''); + $commands[] = ajax_command_html('#ajax_download_selected_example', ''); + $commands[] = ajax_command_html('#ajax_edit_selected_example', ''); + $form['example_files']['#title'] = ''; + $form['example_files']['#markup'] = ''; + $commands[] = ajax_command_replace('#ajax_example_files_list', drupal_render($form['example_files'])); + } else { + $commands[] = ajax_command_html('#ajax_selected_book', ''); + $commands[] = ajax_command_html('#ajax_selected_book_pdf', ''); + $commands[] = ajax_command_html('#ajax_selected_book_regenerate_pdf', ''); + $commands[] = ajax_command_html('#ajax_selected_book_notes', ''); + $form['chapter']['#options'] = _ajax_bulk_get_chapter_list(); + $commands[] = ajax_command_replace('#ajax_select_chapter_list', drupal_render($form['chapter'])); + $commands[] = ajax_command_html('#ajax_select_chapter_list', ''); + $form['book_actions']['#options'] = _bulk_list_book_actions(); + $commands[] = ajax_command_replace('#ajax_selected_book_action', drupal_render($form['book_actions'])); + $commands[] = ajax_command_html('#ajax_selected_book_action', ''); + $form['chapter_actions']['#options'] = _bulk_list_chapter_actions(); + $commands[] = ajax_command_replace('#ajax_selected_chapter_action', drupal_render($form['chapter_actions'])); + $commands[] = ajax_command_html('#ajax_selected_chapter_action', ''); + $commands[] = ajax_command_html('#ajax_download_chapter', ''); + $commands[] = ajax_command_html('#ajax_selected_example', ''); + $form['example_actions']['#options'] = _bulk_list_example_actions(); + $commands[] = ajax_command_replace('#ajax_selected_example_action', drupal_render($form['example_actions'])); + $commands[] = ajax_command_html('#ajax_selected_example_action', ''); + $commands[] = ajax_command_html('#ajax_download_selected_example', ''); + $commands[] = ajax_command_html('#ajax_edit_selected_example', ''); + $form['example_files']['#title'] = ''; + $form['example_files']['#markup'] = ''; + $commands[] = ajax_command_replace('#ajax_example_files_list', drupal_render($form['example_files'])); + } + return array( + '#type' => 'ajax', + '#commands' => $commands + ); +} +function ajax_bulk_example_list_callback($form, $form_state) +{ + $commands = array(); + $chapter_default_value = $form_state['values']['chapter']; + if ($chapter_default_value > 0) { + $commands[] = ajax_command_html('#ajax_download_chapter', l('Download', 'textbook-companion/full-download/chapter/' . $chapter_default_value) . ' ' . t('(Download all the approved and unapproved examples of the entire chapter)')); + $form['chapter_actions']['#options'] = _bulk_list_chapter_actions(); + $commands[] = ajax_command_replace('#ajax_selected_chapter_action', drupal_render($form['chapter_actions'])); + $form['example']['#options'] = _ajax_bulk_get_examples($chapter_default_value); + $commands[] = ajax_command_replace('#ajax_selected_example', drupal_render($form['example'])); + $commands[] = ajax_command_html('#ajax_download_selected_example', ''); + $commands[] = ajax_command_html('#ajax_edit_selected_example', ''); + $form['example_actions']['#options'] = _bulk_list_example_actions(); + $commands[] = ajax_command_replace('#ajax_selected_example_action', drupal_render($form['example_actions'])); + $commands[] = ajax_command_html('#ajax_selected_example_action', ''); + $form['example_files']['#title'] = ''; + $form['example_files']['#markup'] = ''; + $commands[] = ajax_command_replace('#ajax_example_files_list', drupal_render($form['example_files'])); + } else { + $commands[] = ajax_command_html('#ajax_download_chapter', ''); + $form['chapter_actions']['#options'] = _bulk_list_chapter_actions(); + $commands[] = ajax_command_replace('#ajax_selected_chapter_action', drupal_render($form['chapter_actions'])); + $commands[] = ajax_command_html('#ajax_selected_chapter_action', ''); + $form['example']['#options'] = _ajax_bulk_get_examples(); + $commands[] = ajax_command_replace('#ajax_selected_example', drupal_render($form['example'])); + $commands[] = ajax_command_html('#ajax_selected_example', ''); + $commands[] = ajax_command_html('#ajax_download_selected_example', ''); + $commands[] = ajax_command_html('#ajax_edit_selected_example', ''); + $form['example_files']['#title'] = ''; + $form['example_files']['#markup'] = ''; + $commands[] = ajax_command_replace('#ajax_example_files_list', drupal_render($form['example_files'])); + $form['example_actions']['#options'] = _bulk_list_example_actions(); + $commands[] = ajax_command_replace('#ajax_selected_example_action', drupal_render($form['example_actions'])); + $commands[] = ajax_command_html('#ajax_selected_example_action', ''); + } + return array( + '#type' => 'ajax', + '#commands' => $commands + ); +} +function ajax_bulk_example_files_callback($form, $form_state) +{ + $commands = array(); + $example_list_default_value = $form_state['values']['example']; + //var_dump($example_list_default_value); + if ($example_list_default_value > 0) { + /*************************************************************************************/ + /*$example_list_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE example_id = %d", $form_state['values']['example']);*/ + $query = db_select('textbook_companion_example_files'); + $query->fields('textbook_companion_example_files'); + $query->condition('example_id', $example_list_default_value); + $example_list_q = $query->execute(); + if ($example_list_q) { + $example_files_rows = array(); + while ($example_list_data = $example_list_q->fetchObject()) { + $example_file_type = ''; + switch ($example_list_data->filetype) { + case 'S': + $example_file_type = 'Source or Main file'; + break; + case 'R': + $example_file_type = 'Result file'; + break; + case 'X': + $example_file_type = 'xcos file'; + break; + default: + $example_file_type = 'Unknown'; + break; + } + $example_files_rows[] = array( + l($example_list_data->filename, 'textbook-companion/download/file/' . $example_list_data->id), + $example_file_type + ); + } + /* dependency files */ + /*$dependency_list_q = db_query("SELECT dependency.id as dependency_id, dependency.filename as dependency_filename, dependency.caption as dependency_caption + FROM {textbook_companion_example_dependency} example_dependency LEFT JOIN {textbook_companion_dependency_files} dependency + ON example_dependency.dependency_id = dependency.id + WHERE example_dependency.example_id = %d", $form_state['values']['example']);*/ + /* + $query = db_select('textbook_companion_example_dependency', 'example_dependency'); + $query->fields('dependency', array('id', 'filename', 'caption')); + $query->addField('dependency','id','dependency_id'); + $query->addField('dependency','filename','dependency_filename'); + $query->addField('dependency','caption','dependency_caption'); + $query->leftJoin('textbook_companion_dependency_files', 'dependency', 'example_dependency.dependency_id = dependency.id'); + $query->condition('example_dependency.example_id', $form_state['values']['example']); + $dependency_list_q = $query->execute(); + + while ($dependency_list_data = $dependency_list_q->fetchObject()) + { $example_file_type = 'Dependency file'; $temp_caption = ''; if ($dependency_list_data->dependency_caption) - $temp_caption = ' (' . $dependency_list_data->dependency_caption . ')'; + $temp_caption = ' (' . $dependency_list_data->dependency_caption . ')'; $example_files_rows[] = array(l($dependency_list_data->dependency_filename, 'download/dependency/' . $dependency_list_data->dependency_id) . $temp_caption, $example_file_type); - } - - /* creating list of files table */ - $example_files_header = array('Filename', 'Type'); - $example_files = theme_table($example_files_header, $example_files_rows); - } - $form['run']['download_example'] = array( - '#type' => 'item', - '#value' => l('Download Example', 'download/example/' . $example_default_value), - ); - $form['run']['edit_example'] = array( - '#type' => 'item', - '#value' => l('Edit Example', 'code_approval/editcode/' . $example_default_value), - ); - - $form['run']['example_files'] = array( - '#type' => 'item', - '#title' => 'List of example files', - '#value' => $example_files, - ); - - $form['run']['approve_example'] = array( - '#type' => 'checkbox', - '#title' => t('Approve Example'), - ); - $form['run']['unapprove_example'] = array( - '#type' => 'checkbox', - '#title' => t('Pending Review Example'), - ); - $form['run']['disapprove_example'] = array( - '#type' => 'checkbox', - '#title' => t('Dis-approve Example (This will delete the example)'), - '#prefix' => '<div style="color:red;"><strong>', - '#suffix' => '</strong></div>', - ); + } + */ + /* creating list of files table */ + $example_files_header = array( + 'Filename', + 'Type' + ); + $example_files = theme('table', array( + 'header' => $example_files_header, + 'rows' => $example_files_rows + )); + $form['example_files']['#title'] = 'List of example files'; + $form['example_files']['#markup'] = $example_files; + $commands[] = ajax_command_replace('#ajax_example_files_list', drupal_render($form['example_files'])); + $commands[] = ajax_command_html('#ajax_download_selected_example', l('Download Example', 'textbook-companion/download/example/' . $example_list_default_value)); + $commands[] = ajax_command_html('#ajax_edit_selected_example', l('Edit Example', 'code_approval/editcode/' . $example_list_default_value)); + $form['example_actions']['#options'] = _bulk_list_example_actions(); + $commands[] = ajax_command_replace('#ajax_selected_example_action', drupal_render($form['example_actions'])); + //$commands[] = ajax_command_html('#ajax_selected_example_action', '' ); + } + } else { + $commands[] = ajax_command_html('#ajax_download_selected_example', ''); + $commands[] = ajax_command_html('#ajax_edit_selected_example', ''); + $form['example_files']['#title'] = ''; + $form['example_files']['#markup'] = ''; + $commands[] = ajax_command_replace('#ajax_example_files_list', drupal_render($form['example_files'])); + $form['example_actions']['#options'] = _bulk_list_example_actions(); + $commands[] = ajax_command_replace('#ajax_selected_example_action', drupal_render($form['example_actions'])); + $commands[] = ajax_command_html('#ajax_selected_example_action', ''); } - } - /************ END OF $_POST **************/ - - // if ($book_default_value > 0) - // { - $form['run']['message'] = array( - '#type' => 'textarea', - '#title' => t('If Dis-Approved please specify reason for Dis-Approval'), + return array( + '#type' => 'ajax', + '#commands' => $commands ); - - $form['run']['submit'] = array( - '#type' => 'submit', - '#name' => 'Bulk_approval', - '#value' => t('Submit') +} +function ajax_bulk_chapter_actions_callback() +{ + //if($form_state['values']['chapter_actions'] > 0){ + // $form['book_actions']['#options'] = _bulk_list_book_actions(); + //$commands[] = ajax_command_replace('#ajax_selected_book_action',drupal_render($form['book_actions'])); + // } + return array( + '#type' => 'ajax', + '#commands' => $commands ); - // } - - return $form; } - - -function bulk_approval_form_submit($form, &$form_state) +function edit_code_submission() { - global $user; - $root_path = textbook_companion_path(); - - if ($form_state['clicked_button']['#value'] == 'Submit') - { - if ($form_state['values']['run']['book']) - del_book_pdf($form_state['values']['run']['book']); - - if (user_access('bulk manage code')) - { - if ($form_state['values']['run']['approve_book'] == "1") - { - /* approving entire book */ - $chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE preference_id = %d", $form_state['values']['run']['book']); - while ($chapter_data = db_fetch_object($chapter_q)) - { - db_query("UPDATE {textbook_companion_example} SET approval_status = 1, approver_uid = %d WHERE chapter_id = %d AND approval_status = 0", $user->uid, $chapter_data->id); - } - drupal_set_message(t('Approved Entire Book.'), 'status'); - - /* email */ - $email_subject = t('Your uploaded examples have been approved'); - $email_body = t('Your all the uploaded examples for the book have been approved.'); - - } else if ($form_state['values']['run']['unapprove_book'] == "1") { - - /* approving entire book */ - $chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE preference_id = %d", $form_state['values']['run']['book']); - while ($chapter_data = db_fetch_object($chapter_q)) - { - db_query("UPDATE {textbook_companion_example} SET approval_status = 0 WHERE chapter_id = %d", $chapter_data->id); - } - drupal_set_message(t('Pending Review Entire Book.'), 'status'); - - /* email */ - $email_subject = t('Your uploaded examples have been marked as pending'); - $email_body = t('Your all the uploaded examples for the book have been marked as pending to be review. You will be able to see the exmaples after they have been approved by one of our reviewers.'); - - } else if ($form_state['values']['run']['disapprove_book'] == "1") { - - if (!user_access('bulk delete code')) - { - drupal_set_message(t('You do not have permission to Bulk Dis-Approved and Deleted Entire Book.'), 'error'); - return; - } - - if (delete_book($form_state['values']['run']['book'])) - { - drupal_set_message(t('Dis-Approved and Deleted Entire Book.'), 'status'); - } else { - drupal_set_message(t('Error Dis-Approving and Deleting Entire Book.'), 'error'); - } - - /* email */ - $email_subject = t('Your uploaded examples have been marked as dis-approved'); - $email_body = t('Your all the uploaded examples for the whole book have been marked as dis-approved. - -Reason for dis-approval: - -' . $form_state['values']['run']['message']); - - } else if ($form_state['values']['run']['delete_book_including_proposal'] == "1") { - - if (!user_access('bulk delete code')) - { - drupal_set_message(t('You do not have permission to Bulk Delete Entire Book Including Proposal.'), 'error'); - return; - } - - /* check if dependency files are present */ - $dep_q = db_query("SELECT * FROM {textbook_companion_dependency_files} WHERE preference_id = %d", $form_state['values']['run']['book']); - if ($dep_data = db_fetch_object($dep_q)) - { - drupal_set_message(t("Cannot delete book since it has dependency files that can be used by others. First delete the dependency files before deleing the Book."), 'error'); - return; - } - - if (delete_book($form_state['values']['run']['book'])) - { - drupal_set_message(t('Dis-Approved and Deleted Entire Book examples.'), 'status'); - - $dir_path = $root_path . $form_state['values']['run']['book']; - if (is_dir($dir_path)) - { - $res = rmdir($dir_path); - if (!$res) - { - drupal_set_message(t("Cannot delete Book directory : " . $dir_path . ". Please contact administrator."), 'error'); - return; - } - } else { - drupal_set_message(t("Book directory not present : " . $dir_path . ". Skipping deleting book directory."), 'status'); - } - - /* deleting preference and proposal */ - $preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d", $form_state['values']['run']['book']); - $preference_data = db_fetch_object($preference_q); - $proposal_id = $preference_data->proposal_id; - db_query("DELETE FROM {textbook_companion_preference} WHERE proposal_id = %d", $proposal_id); - db_query("DELETE FROM {textbook_companion_proposal} WHERE id = %d", $proposal_id); - - drupal_set_message(t('Deleted Book Proposal.'), 'status'); - - /* email */ - $email_subject = t('Your uploaded examples including the book proposal have been deleted'); - $email_body = t('Your all the uploaded examples including the book have been deleted permanently. - -Reason for deletion: - -' . $form_state['values']['run']['message']); - - } else { - drupal_set_message(t('Error Dis-Approving and Deleting Entire Book.'), 'error'); - } - - } else if ($form_state['values']['run']['approve_chapter'] == "1") { - - db_query("UPDATE {textbook_companion_example} SET approval_status = 1, approver_uid = %d WHERE chapter_id = %d AND approval_status = 0", $user->uid, $form_state['values']['run']['chapter']); - drupal_set_message(t('Approved Entire Chapter.'), 'status'); - - /* email */ - $email_subject = t('Your uploaded examples have been approved'); - $email_body = t('Your all the uploaded examples for the chapter have been approved.'); - - } else if ($form_state['values']['run']['unapprove_chapter'] == "1") { - - db_query("UPDATE {textbook_companion_example} SET approval_status = 0 WHERE chapter_id = %d", $form_state['values']['run']['chapter']); - drupal_set_message(t('Entire Chapter marked as Pending Review.'), 'status'); - - /* email */ - $email_subject = t('Your uploaded examples have been marked as pending'); - $email_body = t('Your all the uploaded examples for the chapter have been marked as pending to be review.'); - - } else if ($form_state['values']['run']['disapprove_chapter'] == "1") { - - if (!user_access('bulk delete code')) - { - drupal_set_message(t('You do not have permission to Bulk Dis-Approved and Deleted Entire Chapter.'), 'error'); - return; - } - - if (delete_chapter($form_state['values']['run']['chapter'])) - { - drupal_set_message(t('Dis-Approved and Deleted Entire Chapter.'), 'status'); - } else { - drupal_set_message(t('Error Dis-Approving and Deleting Entire Chapter.'), 'error'); - } - - /* email */ - $email_subject = t('Your uploaded example have been marked as dis-approved'); - $email_body = t('Your uploaded example for the entire chapter have been marked as dis-approved. - -Reason for dis-approval: - -' . $form_state['values']['run']['message']); - - } else if ($form_state['values']['run']['approve_example'] == "1") { - - db_query("UPDATE {textbook_companion_example} SET approval_status = 1, approver_uid = %d WHERE id = %d", $user->uid, $form_state['values']['run']['example']); - drupal_set_message(t('Example approved.'), 'status'); - - /* email */ - $email_subject = t('Your uploaded example has been approved'); - $email_body = t('Your uploaded example has been approved.'); - - } else if ($form_state['values']['run']['unapprove_example'] == "1") { - - db_query("UPDATE {textbook_companion_example} SET approval_status = 0 WHERE id = %d", $form_state['values']['run']['example']); - drupal_set_message(t('Example marked as Pending Review.'), 'status'); - - /* email */ - $email_subject = t('Your uploaded example has been marked as pending'); - $email_body = t('Your uploaded example has been marked as pending to be review.'); - - } else if ($form_state['values']['run']['disapprove_example'] == "1") { - - if (delete_example($form_state['values']['run']['example'])) - { - drupal_set_message(t('Example Dis-Approved and Deleted.'), 'status'); - } else { - drupal_set_message(t('Error Dis-Approving and Deleting Example.'), 'error'); - } - - /* email */ - $email_subject = t('Your uploaded example has been marked as dis-approved'); - $email_body = t('Your uploaded example has been marked as dis-approved. - -Reason for dis-approval: - -' . $form_state['values']['run']['message']); - - } - - /****** sending email when everything done ******/ - if ($email_subject) - { - $email_to = $user->mail; - $param['standard']['subject'] = $email_subject; - $param['standard']['body'] = $email_body; - if (!drupal_mail('textbook_companion', 'standard', $email_to, language_default(), $param, variable_get('textbook_companion_from_email', NULL), TRUE)) - drupal_set_message('Error sending email message.', 'error'); - } - + /* get pending proposals to be approved */ + $proposal_rows = array(); + /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} ORDER BY id DESC");*/ + $query = db_select('textbook_companion_proposal'); + $query->fields('textbook_companion_proposal'); + $query->condition('proposal_status', 1); + $query->orderBy('id', 'DESC'); + $proposal_q = $query->execute(); + while ($proposal_data = $proposal_q->fetchObject()) { + /* get preference */ + /*$preference_q = db_query("SELECT * FROM textbook_companion_preference WHERE proposal_id = %d AND approval_status = 1 LIMIT 1", $proposal_data->id); + $preference_data = db_fetch_object($preference_q);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('proposal_id', $proposal_data->id); + $query->condition('approval_status', 1); + $query->condition('submited_all_examples_code', 1); + $query->range(0, 1); + $preference_q = $query->execute(); + $preference_data = $preference_q->fetchObject(); + if (!$preference_data) { + /* $preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND pref_number = 1 LIMIT 1", $proposal_data->id); + $preference_data = db_fetch_object($preference_q);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('proposal_id', $proposal_data->id); + $query->condition('pref_number', 1); + //$query->condition('approval_status', 0); + $query->range(0, 1); + $preference_q = $query->execute(); + $preference_data = $preference_q->fetchObject(); + } + $proposal_status = ''; + switch ($preference_data->submited_all_examples_code) { + case 0: + $proposal_status = 'Code Submission Pending'; + break; + case 1: + $proposal_status = 'Submitted code for all exmample for book'; + break; + } + $proposal_rows[] = array( + "{$preference_data->book} <br> +<em>by {$preference_data->author}</em>", + l($proposal_data->full_name, 'user/' . $proposal_data->uid), + $proposal_status, + l('Edit', 'textbook-companion/code-approval/edit-code-submission/edit/' . $preference_data->id) + ); + } + /* check if there are any pending proposals */ + if (!$proposal_rows) { + drupal_set_message(t('There are no proposals.'), 'status'); + return ''; + } + $proposal_header = array( + 'Title of the Book', + 'Contributor Name', + 'Status', + 'Action' + ); + $output = theme('table', array( + 'header' => $proposal_header, + 'rows' => $proposal_rows + )); + return $output; +} +function get_edit_code_submission($id = NULL) +{ + if ($id) { + return drupal_get_form('edit_code_submission_form', $id); } else { - drupal_set_message(t('You do not have permission to bulk manage code.'), 'error'); + return 'Access denied'; } - } } - -function _list_of_books() +function edit_code_submission_form($form, $form_state, $preference_id) { - $book_titles = array('0' => 'Please select...'); - $book_titles_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE approval_status = 1 OR approval_status = 3 ORDER BY book ASC"); - while ($book_titles_data = db_fetch_object($book_titles_q)) - { - $book_titles[$book_titles_data->id] = $book_titles_data->book . ' (Written by ' . $book_titles_data->author . ')'; - } - return $book_titles; + /* get current proposal */ + $preference_id = arg(4); + /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d", $preference_id); + $preference_data = db_fetch_object($preference_q);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('id', $preference_id); + $preference_data = $query->execute()->fetchObject(); + if (!$preference_data) { + drupal_set_message(t('Invalid book selected. Please try again.'), 'error'); + drupal_goto('textbook-companion/code-approval/edit-code-submission'); + return; + } + $form = array(); + $form['book'] = array( + '#type' => 'item', + '#title' => t('Title of the book'), + '#markup' => $preference_data->book + ); + $form['author'] = array( + '#type' => 'item', + '#title' => t('Author Name'), + '#markup' => $preference_data->author + ); + $form['isbn'] = array( + '#type' => 'item', + '#title' => t('ISBN No'), + '#markup' => $preference_data->isbn + ); + $form['publisher'] = array( + '#type' => 'item', + '#title' => t('Publisher & Place'), + '#markup' => $preference_data->publisher + ); + $form['edition'] = array( + '#type' => 'item', + '#title' => t('Edition'), + '#markup' => $preference_data->edition + ); + $form['year'] = array( + '#type' => 'item', + '#title' => t('Year of pulication'), + '#markup' => $preference_data->year + ); + $form['all_example_submitted'] = array( + '#type' => 'checkbox', + '#title' => t('Enable code submission interface for user'), + '#description' => 'Once you have submited this option user can upload more examples.', + '#required' => TRUE + ); + $form['hidden_preference_id'] = array( + '#type' => 'hidden', + '#value' => $preference_id + ); + $form['submit'] = array( + '#type' => 'submit', + '#value' => t('Submit') + ); + $form['cancle'] = array( + '#type' => 'item', + '#markup' => l('Cancle', 'textbook-companion/code-approval/edit-code-submission') + ); + return $form; } - -function _list_of_chapters($preference_id = 0) +function edit_code_submission_form_validate($form, $form_state) { - $book_chapters = array('0' => 'Please select...'); - $book_chapters_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE preference_id = %d ORDER BY number ASC", $preference_id); - while ($book_chapters_data = db_fetch_object($book_chapters_q)) - { - $book_chapters[$book_chapters_data->id] = $book_chapters_data->number . '. ' . $book_chapters_data->name; - } - return $book_chapters; + if ($form_state['values']['all_example_submitted'] != 1) { + form_set_error('all_example_submitted', t('Please check the field if you are intrested to submit the all uploaded examples for review!')); + } + return; } - -function _list_of_examples($chapter_id = 0) +function edit_code_submission_form_submit($form, $form_state) { - $book_examples = array('0' => 'Please select...'); - $book_examples_q = db_query("SELECT * FROM {textbook_companion_example} WHERE chapter_id = %d ORDER BY - CAST(SUBSTRING_INDEX(number, '.', 1) AS BINARY) ASC, - CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(number , '.', 2), '.', -1) AS UNSIGNED) ASC, - CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(number , '.', -1), '.', 1) AS UNSIGNED) ASC", $chapter_id); - while ($book_examples_data = db_fetch_object($book_examples_q)) - { - $book_examples[$book_examples_data->id] = $book_examples_data->number . ' (' . $book_examples_data->caption . ')'; - } - return $book_examples; + global $user; + if ($form_state['values']['all_example_submitted'] == 1) { + if (db_query('UPDATE textbook_companion_preference SET submited_all_examples_code = 0 WHERE id = :preference_id', array( + ':preference_id' => $form_state['values']['hidden_preference_id'] + ))) { + $query = ("SELECT proposal_id FROM textbook_companion_preference WHERE id= :preference_id"); + $args = array( + ":preference_id" => $form_state['values']['hidden_preference_id'] + ); + $proposal_data = db_query($query, $args); + $proposal_data_result = $proposal_data->fetchObject(); + $proposal_query = db_select('textbook_companion_proposal'); + $proposal_query->fields('textbook_companion_proposal'); + $proposal_query->condition('proposal_status', 1); + $proposal_query->condition('id', $proposal_data_result->proposal_id); + $proposal_data_query = $proposal_query->execute()->fetchObject(); + /* sending email */ + $book_user = user_load($proposal_data_query->uid); + $email_to = $book_user->mail; + $from = variable_get('textbook_companion_from_email', ''); + $bcc = variable_get('textbook_companion_emails', ''); + $cc = variable_get('textbook_companion_cc_emails', ''); + $param['all_code_submitted_status_changed']['proposal_id'] = $proposal_data_result->proposal_id; + $param['all_code_submitted_status_changed']['user_id'] = $user->uid; + $param['all_code_submitted_status_changed']['headers'] = array( + 'From' => $from, + 'MIME-Version' => '1.0', + 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes', + 'Content-Transfer-Encoding' => '8Bit', + 'X-Mailer' => 'Drupal', + 'Cc' => $cc, + 'Bcc' => $bcc + ); + if (!drupal_mail('textbook_companion', 'all_code_submitted_status_changed', $email_to, language_default(), $param, $from, TRUE)) + drupal_set_message('Error sending email message.', 'error'); + drupal_set_message('Enabled code submission interface for user'); + drupal_goto('textbook-companion/code-approval/edit-code-submission'); + } + } } - diff --git a/css/jquery-ui.css b/css/jquery-ui.css deleted file mode 100755 index 1e400aa..0000000 --- a/css/jquery-ui.css +++ /dev/null @@ -1,1178 +0,0 @@ -/*! jQuery UI - v1.10.3 - 2013-05-03 -* http://jqueryui.com -* Includes: jquery.ui.core.css, jquery.ui.accordion.css, jquery.ui.autocomplete.css, jquery.ui.button.css, jquery.ui.datepicker.css, jquery.ui.dialog.css, jquery.ui.menu.css, jquery.ui.progressbar.css, jquery.ui.resizable.css, jquery.ui.selectable.css, jquery.ui.slider.css, jquery.ui.spinner.css, jquery.ui.tabs.css, jquery.ui.tooltip.css -* To view and modify this theme, visit http://jqueryui.com/themeroller/?ffDefault=Verdana%2CArial%2Csans-serif&fwDefault=normal&fsDefault=1.1em&cornerRadius=4px&bgColorHeader=cccccc&bgTextureHeader=highlight_soft&bgImgOpacityHeader=75&borderColorHeader=aaaaaa&fcHeader=222222&iconColorHeader=222222&bgColorContent=ffffff&bgTextureContent=flat&bgImgOpacityContent=75&borderColorContent=aaaaaa&fcContent=222222&iconColorContent=222222&bgColorDefault=e6e6e6&bgTextureDefault=glass&bgImgOpacityDefault=75&borderColorDefault=d3d3d3&fcDefault=555555&iconColorDefault=888888&bgColorHover=dadada&bgTextureHover=glass&bgImgOpacityHover=75&borderColorHover=999999&fcHover=212121&iconColorHover=454545&bgColorActive=ffffff&bgTextureActive=glass&bgImgOpacityActive=65&borderColorActive=aaaaaa&fcActive=212121&iconColorActive=454545&bgColorHighlight=fbf9ee&bgTextureHighlight=glass&bgImgOpacityHighlight=55&borderColorHighlight=fcefa1&fcHighlight=363636&iconColorHighlight=2e83ff&bgColorError=fef1ec&bgTextureError=glass&bgImgOpacityError=95&borderColorError=cd0a0a&fcError=cd0a0a&iconColorError=cd0a0a&bgColorOverlay=aaaaaa&bgTextureOverlay=flat&bgImgOpacityOverlay=0&opacityOverlay=30&bgColorShadow=aaaaaa&bgTextureShadow=flat&bgImgOpacityShadow=0&opacityShadow=30&thicknessShadow=8px&offsetTopShadow=-8px&offsetLeftShadow=-8px&cornerRadiusShadow=8px -* Copyright 2013 jQuery Foundation and other contributors Licensed MIT */ - -/* Layout helpers -----------------------------------*/ -.ui-helper-hidden { - display: none; -} -.ui-helper-hidden-accessible { - border: 0; - clip: rect(0 0 0 0); - height: 1px; - margin: -1px; - overflow: hidden; - padding: 0; - position: absolute; - width: 1px; -} -.ui-helper-reset { - margin: 0; - padding: 0; - border: 0; - outline: 0; - line-height: 1.3; - text-decoration: none; - font-size: 100%; - list-style: none; -} -.ui-helper-clearfix:before, -.ui-helper-clearfix:after { - content: ""; - display: table; - border-collapse: collapse; -} -.ui-helper-clearfix:after { - clear: both; -} -.ui-helper-clearfix { - min-height: 0; /* support: IE7 */ -} -.ui-helper-zfix { - width: 100%; - height: 100%; - top: 0; - left: 0; - position: absolute; - opacity: 0; - filter:Alpha(Opacity=0); -} - -.ui-front { - z-index: 100; -} - - -/* Interaction Cues -----------------------------------*/ -.ui-state-disabled { - cursor: default !important; -} - - -/* Icons -----------------------------------*/ - -/* states and images */ -.ui-icon { - display: block; - text-indent: -99999px; - overflow: hidden; - background-repeat: no-repeat; -} - - -/* Misc visuals -----------------------------------*/ - -/* Overlays */ -.ui-widget-overlay { - position: fixed; - top: 0; - left: 0; - width: 100%; - height: 100%; -} -.ui-accordion .ui-accordion-header { - display: block; - cursor: pointer; - position: relative; - margin-top: 2px; - padding: .5em .5em .5em .7em; - min-height: 0; /* support: IE7 */ -} -.ui-accordion .ui-accordion-icons { - padding-left: 2.2em; -} -.ui-accordion .ui-accordion-noicons { - padding-left: .7em; -} -.ui-accordion .ui-accordion-icons .ui-accordion-icons { - padding-left: 2.2em; -} -.ui-accordion .ui-accordion-header .ui-accordion-header-icon { - position: absolute; - left: .5em; - top: 50%; - margin-top: -8px; -} -.ui-accordion .ui-accordion-content { - padding: 1em 2.2em; - border-top: 0; - overflow: auto; -} -.ui-autocomplete { - position: absolute; - top: 0; - left: 0; - cursor: default; -} -.ui-button { - display: inline-block; - position: relative; - padding: 0; - line-height: normal; - margin-right: .1em; - cursor: pointer; - vertical-align: middle; - text-align: center; - overflow: visible; /* removes extra width in IE */ -} -.ui-button, -.ui-button:link, -.ui-button:visited, -.ui-button:hover, -.ui-button:active { - text-decoration: none; -} -/* to make room for the icon, a width needs to be set here */ -.ui-button-icon-only { - width: 2.2em; -} -/* button elements seem to need a little more width */ -button.ui-button-icon-only { - width: 2.4em; -} -.ui-button-icons-only { - width: 3.4em; -} -button.ui-button-icons-only { - width: 3.7em; -} - -/* button text element */ -.ui-button .ui-button-text { - display: block; - line-height: normal; -} -.ui-button-text-only .ui-button-text { - padding: .4em 1em; -} -.ui-button-icon-only .ui-button-text, -.ui-button-icons-only .ui-button-text { - padding: .4em; - text-indent: -9999999px; -} -.ui-button-text-icon-primary .ui-button-text, -.ui-button-text-icons .ui-button-text { - padding: .4em 1em .4em 2.1em; -} -.ui-button-text-icon-secondary .ui-button-text, -.ui-button-text-icons .ui-button-text { - padding: .4em 2.1em .4em 1em; -} -.ui-button-text-icons .ui-button-text { - padding-left: 2.1em; - padding-right: 2.1em; -} -/* no icon support for input elements, provide padding by default */ -input.ui-button { - padding: .4em 1em; -} - -/* button icon element(s) */ -.ui-button-icon-only .ui-icon, -.ui-button-text-icon-primary .ui-icon, -.ui-button-text-icon-secondary .ui-icon, -.ui-button-text-icons .ui-icon, -.ui-button-icons-only .ui-icon { - position: absolute; - top: 50%; - margin-top: -8px; -} -.ui-button-icon-only .ui-icon { - left: 50%; - margin-left: -8px; -} -.ui-button-text-icon-primary .ui-button-icon-primary, -.ui-button-text-icons .ui-button-icon-primary, -.ui-button-icons-only .ui-button-icon-primary { - left: .5em; -} -.ui-button-text-icon-secondary .ui-button-icon-secondary, -.ui-button-text-icons .ui-button-icon-secondary, -.ui-button-icons-only .ui-button-icon-secondary { - right: .5em; -} - -/* button sets */ -.ui-buttonset { - margin-right: 7px; -} -.ui-buttonset .ui-button { - margin-left: 0; - margin-right: -.3em; -} - -/* workarounds */ -/* reset extra padding in Firefox, see h5bp.com/l */ -input.ui-button::-moz-focus-inner, -button.ui-button::-moz-focus-inner { - border: 0; - padding: 0; -} -.ui-datepicker { - width: 17em; - padding: .2em .2em 0; - display: none; -} -.ui-datepicker .ui-datepicker-header { - position: relative; - padding: .2em 0; -} -.ui-datepicker .ui-datepicker-prev, -.ui-datepicker .ui-datepicker-next { - position: absolute; - top: 2px; - width: 1.8em; - height: 1.8em; -} -.ui-datepicker .ui-datepicker-prev-hover, -.ui-datepicker .ui-datepicker-next-hover { - top: 1px; -} -.ui-datepicker .ui-datepicker-prev { - left: 2px; -} -.ui-datepicker .ui-datepicker-next { - right: 2px; -} -.ui-datepicker .ui-datepicker-prev-hover { - left: 1px; -} -.ui-datepicker .ui-datepicker-next-hover { - right: 1px; -} -.ui-datepicker .ui-datepicker-prev span, -.ui-datepicker .ui-datepicker-next span { - display: block; - position: absolute; - left: 50%; - margin-left: -8px; - top: 50%; - margin-top: -8px; -} -.ui-datepicker .ui-datepicker-title { - margin: 0 2.3em; - line-height: 1.8em; - text-align: center; -} -.ui-datepicker .ui-datepicker-title select { - font-size: 1em; - margin: 1px 0; -} -.ui-datepicker select.ui-datepicker-month-year { - width: 100%; -} -.ui-datepicker select.ui-datepicker-month, -.ui-datepicker select.ui-datepicker-year { - width: 49%; -} -.ui-datepicker table { - width: 100%; - font-size: .9em; - border-collapse: collapse; - margin: 0 0 .4em; -} -.ui-datepicker th { - padding: .7em .3em; - text-align: center; - font-weight: bold; - border: 0; -} -.ui-datepicker td { - border: 0; - padding: 1px; -} -.ui-datepicker td span, -.ui-datepicker td a { - display: block; - padding: .2em; - text-align: right; - text-decoration: none; -} -.ui-datepicker .ui-datepicker-buttonpane { - background-image: none; - margin: .7em 0 0 0; - padding: 0 .2em; - border-left: 0; - border-right: 0; - border-bottom: 0; -} -.ui-datepicker .ui-datepicker-buttonpane button { - float: right; - margin: .5em .2em .4em; - cursor: pointer; - padding: .2em .6em .3em .6em; - width: auto; - overflow: visible; -} -.ui-datepicker .ui-datepicker-buttonpane button.ui-datepicker-current { - float: left; -} - -/* with multiple calendars */ -.ui-datepicker.ui-datepicker-multi { - width: auto; -} -.ui-datepicker-multi .ui-datepicker-group { - float: left; -} -.ui-datepicker-multi .ui-datepicker-group table { - width: 95%; - margin: 0 auto .4em; -} -.ui-datepicker-multi-2 .ui-datepicker-group { - width: 50%; -} -.ui-datepicker-multi-3 .ui-datepicker-group { - width: 33.3%; -} -.ui-datepicker-multi-4 .ui-datepicker-group { - width: 25%; -} -.ui-datepicker-multi .ui-datepicker-group-last .ui-datepicker-header, -.ui-datepicker-multi .ui-datepicker-group-middle .ui-datepicker-header { - border-left-width: 0; -} -.ui-datepicker-multi .ui-datepicker-buttonpane { - clear: left; -} -.ui-datepicker-row-break { - clear: both; - width: 100%; - font-size: 0; -} - -/* RTL support */ -.ui-datepicker-rtl { - direction: rtl; -} -.ui-datepicker-rtl .ui-datepicker-prev { - right: 2px; - left: auto; -} -.ui-datepicker-rtl .ui-datepicker-next { - left: 2px; - right: auto; -} -.ui-datepicker-rtl .ui-datepicker-prev:hover { - right: 1px; - left: auto; -} -.ui-datepicker-rtl .ui-datepicker-next:hover { - left: 1px; - right: auto; -} -.ui-datepicker-rtl .ui-datepicker-buttonpane { - clear: right; -} -.ui-datepicker-rtl .ui-datepicker-buttonpane button { - float: left; -} -.ui-datepicker-rtl .ui-datepicker-buttonpane button.ui-datepicker-current, -.ui-datepicker-rtl .ui-datepicker-group { - float: right; -} -.ui-datepicker-rtl .ui-datepicker-group-last .ui-datepicker-header, -.ui-datepicker-rtl .ui-datepicker-group-middle .ui-datepicker-header { - border-right-width: 0; - border-left-width: 1px; -} -.ui-dialog { - position: absolute; - top: 0; - left: 0; - padding: .2em; - outline: 0; -} -.ui-dialog .ui-dialog-titlebar { - padding: .4em 1em; - position: relative; -} -.ui-dialog .ui-dialog-title { - float: left; - margin: .1em 0; - white-space: nowrap; - width: 90%; - overflow: hidden; - text-overflow: ellipsis; -} -.ui-dialog .ui-dialog-titlebar-close { - position: absolute; - right: .3em; - top: 50%; - width: 21px; - margin: -10px 0 0 0; - padding: 1px; - height: 20px; -} -.ui-dialog .ui-dialog-content { - position: relative; - border: 0; - padding: .5em 1em; - background: none; - overflow: auto; -} -.ui-dialog .ui-dialog-buttonpane { - text-align: left; - border-width: 1px 0 0 0; - background-image: none; - margin-top: .5em; - padding: .3em 1em .5em .4em; -} -.ui-dialog .ui-dialog-buttonpane .ui-dialog-buttonset { - float: right; -} -.ui-dialog .ui-dialog-buttonpane button { - margin: .5em .4em .5em 0; - cursor: pointer; -} -.ui-dialog .ui-resizable-se { - width: 12px; - height: 12px; - right: -5px; - bottom: -5px; - background-position: 16px 16px; -} -.ui-draggable .ui-dialog-titlebar { - cursor: move; -} -.ui-menu { - list-style: none; - padding: 2px; - margin: 0; - display: block; - outline: none; -} -.ui-menu .ui-menu { - margin-top: -3px; - position: absolute; -} -.ui-menu .ui-menu-item { - margin: 0; - padding: 0; - width: 100%; - /* support: IE10, see #8844 */ - list-style-image: url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7); -} -.ui-menu .ui-menu-divider { - margin: 5px -2px 5px -2px; - height: 0; - font-size: 0; - line-height: 0; - border-width: 1px 0 0 0; -} -.ui-menu .ui-menu-item a { - text-decoration: none; - display: block; - padding: 2px .4em; - line-height: 1.5; - min-height: 0; /* support: IE7 */ - font-weight: normal; -} -.ui-menu .ui-menu-item a.ui-state-focus, -.ui-menu .ui-menu-item a.ui-state-active { - font-weight: normal; - margin: -1px; -} - -.ui-menu .ui-state-disabled { - font-weight: normal; - margin: .4em 0 .2em; - line-height: 1.5; -} -.ui-menu .ui-state-disabled a { - cursor: default; -} - -/* icon support */ -.ui-menu-icons { - position: relative; -} -.ui-menu-icons .ui-menu-item a { - position: relative; - padding-left: 2em; -} - -/* left-aligned */ -.ui-menu .ui-icon { - position: absolute; - top: .2em; - left: .2em; -} - -/* right-aligned */ -.ui-menu .ui-menu-icon { - position: static; - float: right; -} -.ui-progressbar { - height: 2em; - text-align: left; - overflow: hidden; -} -.ui-progressbar .ui-progressbar-value { - margin: -1px; - height: 100%; -} -.ui-progressbar .ui-progressbar-overlay { - background: url("images/animated-overlay.gif"); - height: 100%; - filter: alpha(opacity=25); - opacity: 0.25; -} -.ui-progressbar-indeterminate .ui-progressbar-value { - background-image: none; -} -.ui-resizable { - position: relative; -} -.ui-resizable-handle { - position: absolute; - font-size: 0.1px; - display: block; -} -.ui-resizable-disabled .ui-resizable-handle, -.ui-resizable-autohide .ui-resizable-handle { - display: none; -} -.ui-resizable-n { - cursor: n-resize; - height: 7px; - width: 100%; - top: -5px; - left: 0; -} -.ui-resizable-s { - cursor: s-resize; - height: 7px; - width: 100%; - bottom: -5px; - left: 0; -} -.ui-resizable-e { - cursor: e-resize; - width: 7px; - right: -5px; - top: 0; - height: 100%; -} -.ui-resizable-w { - cursor: w-resize; - width: 7px; - left: -5px; - top: 0; - height: 100%; -} -.ui-resizable-se { - cursor: se-resize; - width: 12px; - height: 12px; - right: 1px; - bottom: 1px; -} -.ui-resizable-sw { - cursor: sw-resize; - width: 9px; - height: 9px; - left: -5px; - bottom: -5px; -} -.ui-resizable-nw { - cursor: nw-resize; - width: 9px; - height: 9px; - left: -5px; - top: -5px; -} -.ui-resizable-ne { - cursor: ne-resize; - width: 9px; - height: 9px; - right: -5px; - top: -5px; -} -.ui-selectable-helper { - position: absolute; - z-index: 100; - border: 1px dotted black; -} -.ui-slider { - position: relative; - text-align: left; -} -.ui-slider .ui-slider-handle { - position: absolute; - z-index: 2; - width: 1.2em; - height: 1.2em; - cursor: default; -} -.ui-slider .ui-slider-range { - position: absolute; - z-index: 1; - font-size: .7em; - display: block; - border: 0; - background-position: 0 0; -} - -/* For IE8 - See #6727 */ -.ui-slider.ui-state-disabled .ui-slider-handle, -.ui-slider.ui-state-disabled .ui-slider-range { - filter: inherit; -} - -.ui-slider-horizontal { - height: .8em; -} -.ui-slider-horizontal .ui-slider-handle { - top: -.3em; - margin-left: -.6em; -} -.ui-slider-horizontal .ui-slider-range { - top: 0; - height: 100%; -} -.ui-slider-horizontal .ui-slider-range-min { - left: 0; -} -.ui-slider-horizontal .ui-slider-range-max { - right: 0; -} - -.ui-slider-vertical { - width: .8em; - height: 100px; -} -.ui-slider-vertical .ui-slider-handle { - left: -.3em; - margin-left: 0; - margin-bottom: -.6em; -} -.ui-slider-vertical .ui-slider-range { - left: 0; - width: 100%; -} -.ui-slider-vertical .ui-slider-range-min { - bottom: 0; -} -.ui-slider-vertical .ui-slider-range-max { - top: 0; -} -.ui-spinner { - position: relative; - display: inline-block; - overflow: hidden; - padding: 0; - vertical-align: middle; -} -.ui-spinner-input { - border: none; - background: none; - color: inherit; - padding: 0; - margin: .2em 0; - vertical-align: middle; - margin-left: .4em; - margin-right: 22px; -} -.ui-spinner-button { - width: 16px; - height: 50%; - font-size: .5em; - padding: 0; - margin: 0; - text-align: center; - position: absolute; - cursor: default; - display: block; - overflow: hidden; - right: 0; -} -/* more specificity required here to overide default borders */ -.ui-spinner a.ui-spinner-button { - border-top: none; - border-bottom: none; - border-right: none; -} -/* vertical centre icon */ -.ui-spinner .ui-icon { - position: absolute; - margin-top: -8px; - top: 50%; - left: 0; -} -.ui-spinner-up { - top: 0; -} -.ui-spinner-down { - bottom: 0; -} - -/* TR overrides */ -.ui-spinner .ui-icon-triangle-1-s { - /* need to fix icons sprite */ - background-position: -65px -16px; -} -.ui-tabs { - position: relative;/* position: relative prevents IE scroll bug (element with position: relative inside container with overflow: auto appear as "fixed") */ - padding: .2em; -} -.ui-tabs .ui-tabs-nav { - margin: 0; - padding: .2em .2em 0; -} -.ui-tabs .ui-tabs-nav li { - list-style: none; - float: left; - position: relative; - top: 0; - margin: 1px .2em 0 0; - border-bottom-width: 0; - padding: 0; - white-space: nowrap; -} -.ui-tabs .ui-tabs-nav li a { - float: left; - padding: .5em 1em; - text-decoration: none; -} -.ui-tabs .ui-tabs-nav li.ui-tabs-active { - margin-bottom: -1px; - padding-bottom: 1px; -} -.ui-tabs .ui-tabs-nav li.ui-tabs-active a, -.ui-tabs .ui-tabs-nav li.ui-state-disabled a, -.ui-tabs .ui-tabs-nav li.ui-tabs-loading a { - cursor: text; -} -.ui-tabs .ui-tabs-nav li a, /* first selector in group seems obsolete, but required to overcome bug in Opera applying cursor: text overall if defined elsewhere... */ -.ui-tabs-collapsible .ui-tabs-nav li.ui-tabs-active a { - cursor: pointer; -} -.ui-tabs .ui-tabs-panel { - display: block; - border-width: 0; - padding: 1em 1.4em; - background: none; -} -.ui-tooltip { - padding: 8px; - position: absolute; - z-index: 9999; - max-width: 300px; - -webkit-box-shadow: 0 0 5px #aaa; - box-shadow: 0 0 5px #aaa; -} -body .ui-tooltip { - border-width: 2px; -} - -/* Component containers -----------------------------------*/ -.ui-widget { - font-family: Verdana,Arial,sans-serif; - font-size: 1.1em; -} -.ui-widget .ui-widget { - font-size: 1em; -} -.ui-widget input, -.ui-widget select, -.ui-widget textarea, -.ui-widget button { - font-family: Verdana,Arial,sans-serif; - font-size: 1em; -} -.ui-widget-content { - border: 1px solid #aaaaaa; - background: #ffffff url(images/ui-bg_flat_75_ffffff_40x100.png) 50% 50% repeat-x; - color: #222222; -} -.ui-widget-content a { - color: #222222; -} -.ui-widget-header { - border: 1px solid #aaaaaa; - background: #cccccc url(images/ui-bg_highlight-soft_75_cccccc_1x100.png) 50% 50% repeat-x; - color: #222222; - font-weight: bold; -} -.ui-widget-header a { - color: #222222; -} - -/* Interaction states -----------------------------------*/ -.ui-state-default, -.ui-widget-content .ui-state-default, -.ui-widget-header .ui-state-default { - border: 1px solid #d3d3d3; - background: #e6e6e6 url(images/ui-bg_glass_75_e6e6e6_1x400.png) 50% 50% repeat-x; - font-weight: normal; - color: #555555; -} -.ui-state-default a, -.ui-state-default a:link, -.ui-state-default a:visited { - color: #555555; - text-decoration: none; -} -.ui-state-hover, -.ui-widget-content .ui-state-hover, -.ui-widget-header .ui-state-hover, -.ui-state-focus, -.ui-widget-content .ui-state-focus, -.ui-widget-header .ui-state-focus { - border: 1px solid #999999; - background: #dadada url(images/ui-bg_glass_75_dadada_1x400.png) 50% 50% repeat-x; - font-weight: normal; - color: #212121; -} -.ui-state-hover a, -.ui-state-hover a:hover, -.ui-state-hover a:link, -.ui-state-hover a:visited { - color: #212121; - text-decoration: none; -} -.ui-state-active, -.ui-widget-content .ui-state-active, -.ui-widget-header .ui-state-active { - border: 1px solid #aaaaaa; - background: #ffffff url(images/ui-bg_glass_65_ffffff_1x400.png) 50% 50% repeat-x; - font-weight: normal; - color: #212121; -} -.ui-state-active a, -.ui-state-active a:link, -.ui-state-active a:visited { - color: #212121; - text-decoration: none; -} - -/* Interaction Cues -----------------------------------*/ -.ui-state-highlight, -.ui-widget-content .ui-state-highlight, -.ui-widget-header .ui-state-highlight { - border: 1px solid #fcefa1; - background: #fbf9ee url(images/ui-bg_glass_55_fbf9ee_1x400.png) 50% 50% repeat-x; - color: #363636; -} -.ui-state-highlight a, -.ui-widget-content .ui-state-highlight a, -.ui-widget-header .ui-state-highlight a { - color: #363636; -} -.ui-state-error, -.ui-widget-content .ui-state-error, -.ui-widget-header .ui-state-error { - border: 1px solid #cd0a0a; - background: #fef1ec url(images/ui-bg_glass_95_fef1ec_1x400.png) 50% 50% repeat-x; - color: #cd0a0a; -} -.ui-state-error a, -.ui-widget-content .ui-state-error a, -.ui-widget-header .ui-state-error a { - color: #cd0a0a; -} -.ui-state-error-text, -.ui-widget-content .ui-state-error-text, -.ui-widget-header .ui-state-error-text { - color: #cd0a0a; -} -.ui-priority-primary, -.ui-widget-content .ui-priority-primary, -.ui-widget-header .ui-priority-primary { - font-weight: bold; -} -.ui-priority-secondary, -.ui-widget-content .ui-priority-secondary, -.ui-widget-header .ui-priority-secondary { - opacity: .7; - filter:Alpha(Opacity=70); - font-weight: normal; -} -.ui-state-disabled, -.ui-widget-content .ui-state-disabled, -.ui-widget-header .ui-state-disabled { - opacity: .35; - filter:Alpha(Opacity=35); - background-image: none; -} -.ui-state-disabled .ui-icon { - filter:Alpha(Opacity=35); /* For IE8 - See #6059 */ -} - -/* Icons -----------------------------------*/ - -/* states and images */ -.ui-icon { - width: 16px; - height: 16px; -} -.ui-icon, -.ui-widget-content .ui-icon { - background-image: url(images/ui-icons_222222_256x240.png); -} -.ui-widget-header .ui-icon { - background-image: url(images/ui-icons_222222_256x240.png); -} -.ui-state-default .ui-icon { - background-image: url(images/ui-icons_888888_256x240.png); -} -.ui-state-hover .ui-icon, -.ui-state-focus .ui-icon { - background-image: url(images/ui-icons_454545_256x240.png); -} -.ui-state-active .ui-icon { - background-image: url(images/ui-icons_454545_256x240.png); -} -.ui-state-highlight .ui-icon { - background-image: url(images/ui-icons_2e83ff_256x240.png); -} -.ui-state-error .ui-icon, -.ui-state-error-text .ui-icon { - background-image: url(images/ui-icons_cd0a0a_256x240.png); -} - -/* positioning */ -.ui-icon-blank { background-position: 16px 16px; } -.ui-icon-carat-1-n { background-position: 0 0; } -.ui-icon-carat-1-ne { background-position: -16px 0; } -.ui-icon-carat-1-e { background-position: -32px 0; } -.ui-icon-carat-1-se { background-position: -48px 0; } -.ui-icon-carat-1-s { background-position: -64px 0; } -.ui-icon-carat-1-sw { background-position: -80px 0; } -.ui-icon-carat-1-w { background-position: -96px 0; } -.ui-icon-carat-1-nw { background-position: -112px 0; } -.ui-icon-carat-2-n-s { background-position: -128px 0; } -.ui-icon-carat-2-e-w { background-position: -144px 0; } -.ui-icon-triangle-1-n { background-position: 0 -16px; } -.ui-icon-triangle-1-ne { background-position: -16px -16px; } -.ui-icon-triangle-1-e { background-position: -32px -16px; } -.ui-icon-triangle-1-se { background-position: -48px -16px; } -.ui-icon-triangle-1-s { background-position: -64px -16px; } -.ui-icon-triangle-1-sw { background-position: -80px -16px; } -.ui-icon-triangle-1-w { background-position: -96px -16px; } -.ui-icon-triangle-1-nw { background-position: -112px -16px; } -.ui-icon-triangle-2-n-s { background-position: -128px -16px; } -.ui-icon-triangle-2-e-w { background-position: -144px -16px; } -.ui-icon-arrow-1-n { background-position: 0 -32px; } -.ui-icon-arrow-1-ne { background-position: -16px -32px; } -.ui-icon-arrow-1-e { background-position: -32px -32px; } -.ui-icon-arrow-1-se { background-position: -48px -32px; } -.ui-icon-arrow-1-s { background-position: -64px -32px; } -.ui-icon-arrow-1-sw { background-position: -80px -32px; } -.ui-icon-arrow-1-w { background-position: -96px -32px; } -.ui-icon-arrow-1-nw { background-position: -112px -32px; } -.ui-icon-arrow-2-n-s { background-position: -128px -32px; } -.ui-icon-arrow-2-ne-sw { background-position: -144px -32px; } -.ui-icon-arrow-2-e-w { background-position: -160px -32px; } -.ui-icon-arrow-2-se-nw { background-position: -176px -32px; } -.ui-icon-arrowstop-1-n { background-position: -192px -32px; } -.ui-icon-arrowstop-1-e { background-position: -208px -32px; } -.ui-icon-arrowstop-1-s { background-position: -224px -32px; } -.ui-icon-arrowstop-1-w { background-position: -240px -32px; } -.ui-icon-arrowthick-1-n { background-position: 0 -48px; } -.ui-icon-arrowthick-1-ne { background-position: -16px -48px; } -.ui-icon-arrowthick-1-e { background-position: -32px -48px; } -.ui-icon-arrowthick-1-se { background-position: -48px -48px; } -.ui-icon-arrowthick-1-s { background-position: -64px -48px; } -.ui-icon-arrowthick-1-sw { background-position: -80px -48px; } -.ui-icon-arrowthick-1-w { background-position: -96px -48px; } -.ui-icon-arrowthick-1-nw { background-position: -112px -48px; } -.ui-icon-arrowthick-2-n-s { background-position: -128px -48px; } -.ui-icon-arrowthick-2-ne-sw { background-position: -144px -48px; } -.ui-icon-arrowthick-2-e-w { background-position: -160px -48px; } -.ui-icon-arrowthick-2-se-nw { background-position: -176px -48px; } -.ui-icon-arrowthickstop-1-n { background-position: -192px -48px; } -.ui-icon-arrowthickstop-1-e { background-position: -208px -48px; } -.ui-icon-arrowthickstop-1-s { background-position: -224px -48px; } -.ui-icon-arrowthickstop-1-w { background-position: -240px -48px; } -.ui-icon-arrowreturnthick-1-w { background-position: 0 -64px; } -.ui-icon-arrowreturnthick-1-n { background-position: -16px -64px; } -.ui-icon-arrowreturnthick-1-e { background-position: -32px -64px; } -.ui-icon-arrowreturnthick-1-s { background-position: -48px -64px; } -.ui-icon-arrowreturn-1-w { background-position: -64px -64px; } -.ui-icon-arrowreturn-1-n { background-position: -80px -64px; } -.ui-icon-arrowreturn-1-e { background-position: -96px -64px; } -.ui-icon-arrowreturn-1-s { background-position: -112px -64px; } -.ui-icon-arrowrefresh-1-w { background-position: -128px -64px; } -.ui-icon-arrowrefresh-1-n { background-position: -144px -64px; } -.ui-icon-arrowrefresh-1-e { background-position: -160px -64px; } -.ui-icon-arrowrefresh-1-s { background-position: -176px -64px; } -.ui-icon-arrow-4 { background-position: 0 -80px; } -.ui-icon-arrow-4-diag { background-position: -16px -80px; } -.ui-icon-extlink { background-position: -32px -80px; } -.ui-icon-newwin { background-position: -48px -80px; } -.ui-icon-refresh { background-position: -64px -80px; } -.ui-icon-shuffle { background-position: -80px -80px; } -.ui-icon-transfer-e-w { background-position: -96px -80px; } -.ui-icon-transferthick-e-w { background-position: -112px -80px; } -.ui-icon-folder-collapsed { background-position: 0 -96px; } -.ui-icon-folder-open { background-position: -16px -96px; } -.ui-icon-document { background-position: -32px -96px; } -.ui-icon-document-b { background-position: -48px -96px; } -.ui-icon-note { background-position: -64px -96px; } -.ui-icon-mail-closed { background-position: -80px -96px; } -.ui-icon-mail-open { background-position: -96px -96px; } -.ui-icon-suitcase { background-position: -112px -96px; } -.ui-icon-comment { background-position: -128px -96px; } -.ui-icon-person { background-position: -144px -96px; } -.ui-icon-print { background-position: -160px -96px; } -.ui-icon-trash { background-position: -176px -96px; } -.ui-icon-locked { background-position: -192px -96px; } -.ui-icon-unlocked { background-position: -208px -96px; } -.ui-icon-bookmark { background-position: -224px -96px; } -.ui-icon-tag { background-position: -240px -96px; } -.ui-icon-home { background-position: 0 -112px; } -.ui-icon-flag { background-position: -16px -112px; } -.ui-icon-calendar { background-position: -32px -112px; } -.ui-icon-cart { background-position: -48px -112px; } -.ui-icon-pencil { background-position: -64px -112px; } -.ui-icon-clock { background-position: -80px -112px; } -.ui-icon-disk { background-position: -96px -112px; } -.ui-icon-calculator { background-position: -112px -112px; } -.ui-icon-zoomin { background-position: -128px -112px; } -.ui-icon-zoomout { background-position: -144px -112px; } -.ui-icon-search { background-position: -160px -112px; } -.ui-icon-wrench { background-position: -176px -112px; } -.ui-icon-gear { background-position: -192px -112px; } -.ui-icon-heart { background-position: -208px -112px; } -.ui-icon-star { background-position: -224px -112px; } -.ui-icon-link { background-position: -240px -112px; } -.ui-icon-cancel { background-position: 0 -128px; } -.ui-icon-plus { background-position: -16px -128px; } -.ui-icon-plusthick { background-position: -32px -128px; } -.ui-icon-minus { background-position: -48px -128px; } -.ui-icon-minusthick { background-position: -64px -128px; } -.ui-icon-close { background-position: -80px -128px; } -.ui-icon-closethick { background-position: -96px -128px; } -.ui-icon-key { background-position: -112px -128px; } -.ui-icon-lightbulb { background-position: -128px -128px; } -.ui-icon-scissors { background-position: -144px -128px; } -.ui-icon-clipboard { background-position: -160px -128px; } -.ui-icon-copy { background-position: -176px -128px; } -.ui-icon-contact { background-position: -192px -128px; } -.ui-icon-image { background-position: -208px -128px; } -.ui-icon-video { background-position: -224px -128px; } -.ui-icon-script { background-position: -240px -128px; } -.ui-icon-alert { background-position: 0 -144px; } -.ui-icon-info { background-position: -16px -144px; } -.ui-icon-notice { background-position: -32px -144px; } -.ui-icon-help { background-position: -48px -144px; } -.ui-icon-check { background-position: -64px -144px; } -.ui-icon-bullet { background-position: -80px -144px; } -.ui-icon-radio-on { background-position: -96px -144px; } -.ui-icon-radio-off { background-position: -112px -144px; } -.ui-icon-pin-w { background-position: -128px -144px; } -.ui-icon-pin-s { background-position: -144px -144px; } -.ui-icon-play { background-position: 0 -160px; } -.ui-icon-pause { background-position: -16px -160px; } -.ui-icon-seek-next { background-position: -32px -160px; } -.ui-icon-seek-prev { background-position: -48px -160px; } -.ui-icon-seek-end { background-position: -64px -160px; } -.ui-icon-seek-start { background-position: -80px -160px; } -/* ui-icon-seek-first is deprecated, use ui-icon-seek-start instead */ -.ui-icon-seek-first { background-position: -80px -160px; } -.ui-icon-stop { background-position: -96px -160px; } -.ui-icon-eject { background-position: -112px -160px; } -.ui-icon-volume-off { background-position: -128px -160px; } -.ui-icon-volume-on { background-position: -144px -160px; } -.ui-icon-power { background-position: 0 -176px; } -.ui-icon-signal-diag { background-position: -16px -176px; } -.ui-icon-signal { background-position: -32px -176px; } -.ui-icon-battery-0 { background-position: -48px -176px; } -.ui-icon-battery-1 { background-position: -64px -176px; } -.ui-icon-battery-2 { background-position: -80px -176px; } -.ui-icon-battery-3 { background-position: -96px -176px; } -.ui-icon-circle-plus { background-position: 0 -192px; } -.ui-icon-circle-minus { background-position: -16px -192px; } -.ui-icon-circle-close { background-position: -32px -192px; } -.ui-icon-circle-triangle-e { background-position: -48px -192px; } -.ui-icon-circle-triangle-s { background-position: -64px -192px; } -.ui-icon-circle-triangle-w { background-position: -80px -192px; } -.ui-icon-circle-triangle-n { background-position: -96px -192px; } -.ui-icon-circle-arrow-e { background-position: -112px -192px; } -.ui-icon-circle-arrow-s { background-position: -128px -192px; } -.ui-icon-circle-arrow-w { background-position: -144px -192px; } -.ui-icon-circle-arrow-n { background-position: -160px -192px; } -.ui-icon-circle-zoomin { background-position: -176px -192px; } -.ui-icon-circle-zoomout { background-position: -192px -192px; } -.ui-icon-circle-check { background-position: -208px -192px; } -.ui-icon-circlesmall-plus { background-position: 0 -208px; } -.ui-icon-circlesmall-minus { background-position: -16px -208px; } -.ui-icon-circlesmall-close { background-position: -32px -208px; } -.ui-icon-squaresmall-plus { background-position: -48px -208px; } -.ui-icon-squaresmall-minus { background-position: -64px -208px; } -.ui-icon-squaresmall-close { background-position: -80px -208px; } -.ui-icon-grip-dotted-vertical { background-position: 0 -224px; } -.ui-icon-grip-dotted-horizontal { background-position: -16px -224px; } -.ui-icon-grip-solid-vertical { background-position: -32px -224px; } -.ui-icon-grip-solid-horizontal { background-position: -48px -224px; } -.ui-icon-gripsmall-diagonal-se { background-position: -64px -224px; } -.ui-icon-grip-diagonal-se { background-position: -80px -224px; } - - -/* Misc visuals -----------------------------------*/ - -/* Corner radius */ -.ui-corner-all, -.ui-corner-top, -.ui-corner-left, -.ui-corner-tl { - border-top-left-radius: 4px; -} -.ui-corner-all, -.ui-corner-top, -.ui-corner-right, -.ui-corner-tr { - border-top-right-radius: 4px; -} -.ui-corner-all, -.ui-corner-bottom, -.ui-corner-left, -.ui-corner-bl { - border-bottom-left-radius: 4px; -} -.ui-corner-all, -.ui-corner-bottom, -.ui-corner-right, -.ui-corner-br { - border-bottom-right-radius: 4px; -} - -/* Overlays */ -.ui-widget-overlay { - background: #aaaaaa url(images/ui-bg_flat_0_aaaaaa_40x100.png) 50% 50% repeat-x; - opacity: .3; - filter: Alpha(Opacity=30); -} -.ui-widget-shadow { - margin: -8px 0 0 -8px; - padding: 8px; - background: #aaaaaa url(images/ui-bg_flat_0_aaaaaa_40x100.png) 50% 50% repeat-x; - opacity: .3; - filter: Alpha(Opacity=30); - border-radius: 8px; -} - diff --git a/css/textbook_companion.css b/css/textbook_companion.css deleted file mode 100755 index ae35e79..0000000 --- a/css/textbook_companion.css +++ /dev/null @@ -1,120 +0,0 @@ -.page-mycontact .resizable-textarea -{ - width:30%; -} -.resizable-textarea .form-textarea.resizable.textarea-processed#edit-chq-address -{ - height:117px; - width:296px; -} -.resizable-textarea .form-textarea.resizable.textarea-processed#edit-temp-chq-address -{ - height:117px; - width:296px; -} - -.collapsible#perm_cheque_address -{ - width:47%; - float:left; -} -.collapsible#temp_cheque_address -{ - width: 47%; - float: right; -} - -#cheque_delivery -{ - width:40%; - float:left; -} -#edit-submit2 -{ - float:right; -} -#commentf -{ - width:54%; -/* margin-left:45%; - margin-top:3.35%;*/ - float:right; -} -#edit-comment-cheque -{ - height:117px; - width:296px; -} - -#stu_cheque_details -{ - float:left; - width:48%; -} -#tea_cheque_details -{ - width: 46%; - float: right; -} -fieldset input[type="text"] -{ - width:290px; -} -#app_status -{ - width: 40%; - height: 270px; -} -#comment_cheque -{ - -} -#candidate_detail -{ - width:50%; - float:left; - margin:-0.4px 15px 15px; - margin-top -} -.page-certificate .sticky-enabled th{ - padding: 0px 65px 3px 0px; -} -#aicte-list-wrapper { - max-height: 500px; - height: 500px; - overflow-y: auto; - margin-top: 10px; - margin-bottom: 20px; - border: 1px solid #cccccc; -} -#aicte-list-wrapper .title { - border-bottom: 1px solid #cccccc; - padding: 7px 0 7px 4px; -} -#aicte-list-wrapper .title:hover { - background: #f5f5f5; -} -#aicte-form-wrapper { - max-height: 500px; - height: 500px; - overflow-y: auto; - margin-top: 10px; - margin-bottom: 20px; - border: 1px solid #cccccc; -} -#aicte-form-wrapper fieldset { - border: none; -} -#aicte-form-wrapper .form-item { - padding-bottom: 5px; - border-bottom: 1px solid #cccccc; -} -#textbook-companion-aicte-report-form { - display: none; - padding: 15px; - background: #ffffff; - -webkit-border-radius: 5px; - -moz-border-radius: 5px; - -o-border-radius: 5px; - border-radius: 5px; -} diff --git a/dependency.inc b/dependency.inc index a76d428..c99da1d 100755 --- a/dependency.inc +++ b/dependency.inc @@ -1,688 +1,810 @@ <?php // $Id$ - function upload_dependency_form($form_state) -{ - global $user; - - /************************ start approve book details ************************/ - $proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid = %d ORDER BY id DESC LIMIT 1", $user->uid); - $proposal_data = db_fetch_object($proposal_q); - if (!$proposal_data) { - drupal_set_message("Please submit a " . l('proposal', 'proposal') . ".", 'error'); - drupal_goto(''); - } - if ($proposal_data->proposal_status != 1 && $proposal_data->proposal_status != 4) - { - switch ($proposal_data->proposal_status ) - { - case 0: - drupal_set_message(t('We have already received your proposal. We will get back to you soon.'), 'status'); - drupal_goto(''); - return; - break; - case 2: - drupal_set_message(t('Your proposal has been dis-approved. Please create another proposal ' . l('here', 'proposal') . '.'), 'error'); - drupal_goto(''); - return; - break; - case 3: - drupal_set_message(t('Congratulations! You have completed your last book proposal. You have to create another proposal ' . l('here', 'proposal') . '.'), 'status'); - drupal_goto(''); - return; - break; - default: - drupal_set_message(t('Invalid proposal state. Please contact site administrator for further information.'), 'error'); - drupal_goto(''); - return; - break; - } - } - - $preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND approval_status = 1 LIMIT 1", $proposal_data->id); - $preference_data = db_fetch_object($preference_q); - if (!$preference_data) - { - drupal_set_message(t('Invalid Book Preference status. Please contact site administrator for further information.'), 'error'); - drupal_goto(''); - return; + global $user; + /************************ start approve book details ************************/ + /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid = %d ORDER BY id DESC LIMIT 1", $user->uid); + $proposal_data = db_fetch_object($proposal_q);*/ + $query = db_select('textbook_companion_proposal'); + $query->fields('textbook_companion_proposal'); + $query->condition('uid', $user->uid); + $query->orderBy('id', 'DESC'); + $query->range(0, 1); + $result = $query->execute(); + $proposal_data = $result->fetchObject(); + if (!$proposal_data) + { + drupal_set_message("Please submit a " . l('proposal', 'proposal') . ".", 'error'); + drupal_goto(''); + } + if ($proposal_data->proposal_status != 1 && $proposal_data->proposal_status != 4) + { + switch ($proposal_data->proposal_status) + { + case 0: + drupal_set_message(t('We have already received your proposal. We will get back to you soon.'), 'status'); + drupal_goto(''); + return; + break; + case 2: + drupal_set_message(t('Your proposal has been dis-approved. Please create another proposal ' . l('here', 'proposal') . '.'), 'error'); + drupal_goto(''); + return; + break; + case 3: + drupal_set_message(t('Congratulations! You have completed your last book proposal. You have to create another proposal ' . l('here', 'proposal') . '.'), 'status'); + drupal_goto(''); + return; + break; + default: + drupal_set_message(t('Invalid proposal state. Please contact site administrator for further information.'), 'error'); + drupal_goto(''); + return; + break; + } + } + /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND approval_status = 1 LIMIT 1", $proposal_data->id); + $preference_data = db_fetch_object($preference_q);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('proposal_id', $proposal_data->id); + $query->condition('approval_status', 1); + $query->range(0, 1); + $result = $query->execute(); + $preference_data = $result->fetchObject(); + if (!$preference_data) + { + drupal_set_message(t('Invalid Book Preference status. Please contact site administrator for further information.'), 'error'); + drupal_goto(''); + return; + } + /************************ end approve book details **************************/ + $form['#attributes'] = array( + 'enctype' => "multipart/form-data" + ); + $form['book_details']['book'] = array( + '#type' => 'item', + '#markup' => $preference_data->book, + '#title' => t('Title of the Book') + ); + $form['contributor_name'] = array( + '#type' => 'item', + '#markup' => $proposal_data->full_name, + '#title' => t('Contributor Name') + ); + $form['existing_depfile'] = array( + '#type' => 'item', + '#markup' => _list_existing_dependency($preference_data->id), + '#title' => t('List of existing dependency files for this book') + ); + $form['depfile'] = array( + '#type' => 'fieldset', + '#title' => t('Upload Dependency Files'), + '#collapsible' => FALSE, + '#collapsed' => FALSE + ); + $form['depfile']['depfile1'] = array( + '#type' => 'file', + '#title' => t('Upload dependency file'), + '#description' => t("Allowed file extensions : ") . variable_get('textbook_companion_dependency_extensions', '') + ); + $form['depfile']['depfile1_caption'] = array( + '#type' => 'textfield', + '#title' => t('Caption for dependency file'), + '#size' => 15, + '#maxlength' => 100, + '#required' => TRUE + ); + $form['depfile']['depfile1_description'] = array( + '#type' => 'textarea', + '#title' => t('Brief Description of the dependency file') + ); + $form['submit'] = array( + '#type' => 'submit', + '#value' => t('Submit') + ); + $form['cancel'] = array( + '#type' => 'item', + '#markup' => l(t('Back'), 'textbook_companion/code/upload') + ); + return $form; } - /************************ end approve book details **************************/ - - $form['#attributes'] = array('enctype' => "multipart/form-data"); - - $form['book_details']['book'] = array( - '#type' => 'item', - '#value' => $preference_data->book, - '#title' => t('Title of the Book'), - ); - $form['contributor_name'] = array( - '#type' => 'item', - '#value' => $proposal_data->full_name, - '#title' => t('Contributor Name'), - ); - - $form['existing_depfile'] = array( - '#type' => 'item', - '#value' => _list_existing_dependency($preference_data->id), - '#title' => t('List of existing dependency files for this book'), - ); - - $form['depfile'] = array( - '#type' => 'fieldset', - '#title' => t('Upload Dependency Files'), - '#collapsible' => FALSE, - '#collapsed' => FALSE, - ); - $form['depfile']['depfile1'] = array( - '#type' => 'file', - '#title' => t('Upload dependency file'), - '#description' => t("Allowed file extensions : ") . variable_get('textbook_companion_dependency_extensions', ''), - ); - $form['depfile']['depfile1_caption'] = array( - '#type' => 'textfield', - '#title' => t('Caption for dependency file'), - '#size' => 15, - '#maxlength' => 100, - '#required' => TRUE, - ); - $form['depfile']['depfile1_description'] = array( - '#type' => 'textarea', - '#title' => t('Brief Description of the dependency file'), - ); - - $form['submit'] = array( - '#type' => 'submit', - '#value' => t('Submit') - ); - - $form['cancel'] = array( - '#type' => 'markup', - '#value' => l(t('Back'), 'textbook_companion/code/upload'), - ); - return $form; -} - function upload_dependency_form_validate($form, &$form_state) -{ - global $user; - - /* get approved book details */ - $book_q = db_query("SELECT pro.id as pro_id, pre.id as pre_id, pre.book as pre_book, pro.full_name as pro_full_name FROM {textbook_companion_proposal} pro JOIN {textbook_companion_preference} pre ON pro.id = pre.proposal_id WHERE pro.proposal_status = 1 AND pre.approval_status = 1 AND pro.uid = %d", $user->uid); - $book_data = db_fetch_object($book_q); - - if (isset($_FILES['files'])) { - /* check for valid filename extensions */ - $allowed_extensions = explode(',' , variable_get('textbook_companion_dependency_extensions', '')); - foreach ($_FILES['files']['name'] as $file_form_name => $file_name) - { - if ($file_name) + global $user; + /* get approved book details */ + /*$book_q = db_query("SELECT pro.id as pro_id, pre.id as pre_id, pre.book as pre_book, pro.full_name as pro_full_name FROM {textbook_companion_proposal} pro JOIN {textbook_companion_preference} pre ON pro.id = pre.proposal_id WHERE pro.proposal_status = 1 AND pre.approval_status = 1 AND pro.uid = %d", $user->uid); + $book_data = db_fetch_object($book_q);*/ + $query = db_select('textbook_companion_proposal', 'pro'); + $query->fields('pro', array( + 'id', + 'full_name' + )); + $query->fields('pre', array( + 'id', + 'book' + )); + $query->innerJoin('textbook_companion_preference', 'pre', 'pro.id = pre.proposal_id'); + $query->condition('pro.proposal_status', 1); + $query->condition('pre.approval_status', 1); + $query->condition('pro.uid', $user->uid); + $result = $query->execute(); + $book_data = $result->fetchObject(); + if (isset($_FILES['files'])) { - $temp_extension = end(explode('.', strtolower($_FILES['files']['name'][$file_form_name]))); - if (!in_array($temp_extension, $allowed_extensions)) - form_set_error($file_form_name, t('Only ' . variable_get('textbook_companion_dependency_extensions', '') . ' extensions can be uploaded.')); - if ($_FILES['files']['size'][$file_form_name] <= 0) - form_set_error($file_form_name, t('File size cannot be zero.')); - - /* check if file already exists */ - $dep_exists_data = db_fetch_object(db_query("SELECT * FROM {textbook_companion_dependency_files} WHERE filename = '%s'", $_FILES['files']['name'][$file_form_name])); - if ($dep_exists_data) - form_set_error($file_form_name, t('Dependency file with the same name has already been uploaded in this or some other book. Please rename the file and try again.')); - - /* check if valid file name */ - if (!textbook_companion_check_valid_filename($_FILES['files']['name'][$file_form_name])) - form_set_error($file_form_name, t('Invalid file name specified. Only alphabets, numbers and underscore is allowed as a valid filename.')); + /* check for valid filename extensions */ + $allowed_extensions = explode(',', variable_get('textbook_companion_dependency_extensions', '')); + foreach ($_FILES['files']['name'] as $file_form_name => $file_name) + { + if ($file_name) + { + $temp_extension = end(explode('.', strtolower($_FILES['files']['name'][$file_form_name]))); + if (!in_array($temp_extension, $allowed_extensions)) + form_set_error($file_form_name, t('Only ' . variable_get('textbook_companion_dependency_extensions', '') . ' extensions can be uploaded.')); + if ($_FILES['files']['size'][$file_form_name] <= 0) + form_set_error($file_form_name, t('File size cannot be zero.')); + /* check if file already exists */ + /*$dep_exists_data = db_fetch_object(db_query("SELECT * FROM {textbook_companion_dependency_files} WHERE filename = '%s'", $_FILES['files']['name'][$file_form_name]));*/ + $query = db_select('textbook_companion_dependency_files'); + $query->fields('textbook_companion_dependency_files'); + $query->condition('filename', $_FILES['files']['name'][$file_form_name]); + $result = $query->execute(); + $dep_exists_data = $result->fetchObject(); + if ($dep_exists_data) + form_set_error($file_form_name, t('Dependency file with the same name has already been uploaded in this or some other book. Please rename the file and try again.')); + /* check if valid file name */ + if (!textbook_companion_check_valid_filename($_FILES['files']['name'][$file_form_name])) + form_set_error($file_form_name, t('Invalid file name specified. Only alphabets, numbers and underscore is allowed as a valid filename.')); + } + } } - } } -} - -function upload_dependency_form_submit($form, &$form_state) { - global $user; - - $root_path = textbook_companion_path(); - - /* get approved book details */ - $proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid = %d ORDER BY id DESC LIMIT 1", $user->uid); - $proposal_data = db_fetch_object($proposal_q); - if (!$proposal_data) +function upload_dependency_form_submit($form, &$form_state) { - drupal_set_message("Please submit a " . l('proposal', 'proposal') . ".", 'error'); - drupal_goto(''); - } - if ($proposal_data->proposal_status != 1 && $proposal_data->proposal_status != 4) - { - switch ($proposal_data->proposal_status ) - { - case 0: - drupal_set_message(t('We have already received your proposal. We will get back to you soon.'), 'status'); - drupal_goto(''); - return; - break; - case 2: - drupal_set_message(t('Your proposal has been dis-approved. Please create another proposal ' . l('here', 'proposal') . '.'), 'error'); - drupal_goto(''); - return; - break; - case 3: - drupal_set_message(t('Congratulations! You have completed your last book proposal. You have to create another proposal ' . l('here', 'proposal') . '.'), 'status'); - drupal_goto(''); - return; - break; - default: - drupal_set_message(t('Invalid proposal state. Please contact site administrator for further information.'), 'error'); - drupal_goto(''); - return; - break; - } - } - - $preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND approval_status = 1 LIMIT 1", $proposal_data->id); - $preference_data = db_fetch_object($preference_q); - if (!$preference_data) - { - drupal_set_message(t('Invalid Book Preference status. Please contact site administrator for further information.'), 'error'); - drupal_goto(''); - return; - } - - $preference_id = $preference_data->id; - - $dest_path = $preference_id . '/'; - if (!is_dir($root_path . $dest_path)) - mkdir($root_path . $dest_path); - - $dest_path .= 'DEPENDENCIES' . '/'; - if (!is_dir($root_path . $dest_path)) - mkdir($root_path . $dest_path); - - /* uploading dependencies */ - $file_upload_counter = 0; - $dependency_ids = array(); - $dependency_names = array(); - - foreach ($_FILES['files']['name'] as $file_form_name => $file_name) - { - if ($file_name) - { - /* uploading file */ - if (move_uploaded_file($_FILES['files']['tmp_name'][$file_form_name], $root_path . $dest_path . $_FILES['files']['name'][$file_form_name])) + global $user; + $root_path = textbook_companion_path(); + /* get approved book details */ + /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid = %d ORDER BY id DESC LIMIT 1", $user->uid); + $proposal_data = db_fetch_object($proposal_q);*/ + $query = db_select('textbook_companion_proposal'); + $query->fields('textbook_companion_proposal'); + $query->condition('uid', $user->uid); + $query->orderBy('id', 'DESC'); + $query->range(0, 1); + $result = $query->execute(); + $proposal_data = $result->fetchObject(); + if (!$proposal_data) { - /* for uploaded files making an entry in the database */ - db_query("INSERT INTO {textbook_companion_dependency_files} (preference_id, filename, filepath, filemime, filesize, caption, description, timestamp) - VALUES (%d, '%s', '%s', '%s', %d, '%s', '%s', %d)", - $preference_id, - $_FILES['files']['name'][$file_form_name], - $dest_path . $_FILES['files']['name'][$file_form_name], - $_FILES['files']['type'][$file_form_name], - $_FILES['files']['size'][$file_form_name], - $form_state['values'][$file_form_name . '_caption'], - $form_state['values'][$file_form_name . '_description'], - time() - ); - drupal_set_message($file_name . ' uploaded successfully.', 'status'); - $dependency_ids[] = db_last_insert_id('textbook_companion_dependency_files', 'id'); - $dependency_names[] = $_FILES['files']['name'][$file_form_name]; - $file_upload_counter++; - } else { - drupal_set_message('Error uploading dependency : ' . $dest_path . '/' . $_FILES['files']['name'][$file_form_name], 'error'); + drupal_set_message("Please submit a " . l('proposal', 'proposal') . ".", 'error'); + drupal_goto(''); } - } - } - - if ($file_upload_counter > 0) - { - drupal_set_message('Dependencies uploaded successfully.', 'status'); - - /* sending email */ - $param['dependency_uploaded']['user_id'] = $user->uid; - $param['dependency_uploaded']['dependency_names'] = $dependency_names; - - $email_to = $user->mail; - if (!drupal_mail('textbook_companion', 'dependency_uploaded', $email_to, language_default(), $param, variable_get('textbook_companion_from_email', NULL), TRUE)) - drupal_set_message('Error sending email message.', 'error'); + if ($proposal_data->proposal_status != 1 && $proposal_data->proposal_status != 4) + { + switch ($proposal_data->proposal_status) + { + case 0: + drupal_set_message(t('We have already received your proposal. We will get back to you soon.'), 'status'); + drupal_goto(''); + return; + break; + case 2: + drupal_set_message(t('Your proposal has been dis-approved. Please create another proposal ' . l('here', 'proposal') . '.'), 'error'); + drupal_goto(''); + return; + break; + case 3: + drupal_set_message(t('Congratulations! You have completed your last book proposal. You have to create another proposal ' . l('here', 'proposal') . '.'), 'status'); + drupal_goto(''); + return; + break; + default: + drupal_set_message(t('Invalid proposal state. Please contact site administrator for further information.'), 'error'); + drupal_goto(''); + return; + break; + } + } + /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND approval_status = 1 LIMIT 1", $proposal_data->id); + $preference_data = db_fetch_object($preference_q);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('proposal_id', $proposal_data->id); + $query->condition('approval_status', 1); + $query->range(0, 1); + $result = $query->execute(); + $preference_data = $result->fetchObject(); + if (!$preference_data) + { + drupal_set_message(t('Invalid Book Preference status. Please contact site administrator for further information.'), 'error'); + drupal_goto(''); + return; + } + $preference_id = $preference_data->id; + $dest_path = $preference_id . '/'; + if (!is_dir($root_path . $dest_path)) + mkdir($root_path . $dest_path); + $dest_path .= 'DEPENDENCIES' . '/'; + if (!is_dir($root_path . $dest_path)) + mkdir($root_path . $dest_path); + /* uploading dependencies */ + $file_upload_counter = 0; + $dependency_ids = array(); + $dependency_names = array(); + foreach ($_FILES['files']['name'] as $file_form_name => $file_name) + { + if ($file_name) + { + /* uploading file */ + if (move_uploaded_file($_FILES['files']['tmp_name'][$file_form_name], $root_path . $dest_path . $_FILES['files']['name'][$file_form_name])) + { + /* for uploaded files making an entry in the database */ + /* db_query("INSERT INTO {textbook_companion_dependency_files} (preference_id, filename, filepath, filemime, filesize, caption, description, timestamp) + VALUES (%d, '%s', '%s', '%s', %d, '%s', '%s', %d)", + $preference_id, + $_FILES['files']['name'][$file_form_name], + $dest_path . $_FILES['files']['name'][$file_form_name], + $_FILES['files']['type'][$file_form_name], + $_FILES['files']['size'][$file_form_name], + $form_state['values'][$file_form_name . '_caption'], + $form_state['values'][$file_form_name . '_description'], + time() + );*/ + $query = "INSERT INTO {textbook_companion_dependency_files} (preference_id, filename, filepath, filemime, filesize, caption, description, timestamp) + VALUES (:preference_id, :filename, :filepath, :filemime, :filesize, :caption, :description, :timestamp)"; + $args = array( + ":preference_id" => $preference_id, + ":filename" => $_FILES['files']['name'][$file_form_name], + ":filepath" => $dest_path . $_FILES['files']['name'][$file_form_name], + ":filemime" => $_FILES['files']['type'][$file_form_name], + ":filesize" => $_FILES['files']['size'][$file_form_name], + ":caption" => $form_state['values'][$file_form_name . '_caption'], + ":description" => $form_state['values'][$file_form_name . '_description'], + ":timestamp" => time() + ); + $result = db_query($query, $args, array( + 'return' => Database::RETURN_INSERT_ID + )); + drupal_set_message($file_name . ' uploaded successfully.', 'status'); + //$dependency_ids[] = db_last_insert_id('textbook_companion_dependency_files', 'id'); + $dependency_ids[] = $result; + $dependency_names[] = $_FILES['files']['name'][$file_form_name]; + $file_upload_counter++; + } + else + { + drupal_set_message('Error uploading dependency : ' . $dest_path . '/' . $_FILES['files']['name'][$file_form_name], 'error'); + } + } + } + if ($file_upload_counter > 0) + { + drupal_set_message('Dependencies uploaded successfully.', 'status'); + /* sending email */ + $param['dependency_uploaded']['user_id'] = $user->uid; + $param['dependency_uploaded']['dependency_names'] = $dependency_names; + $email_to = $user->mail; + if (!drupal_mail('textbook_companion', 'dependency_uploaded', $email_to, language_default(), $param, variable_get('textbook_companion_from_email', NULL), TRUE)) + drupal_set_message('Error sending email message.', 'error'); + } + drupal_goto('textbook_companion/code/upload_dep'); } - - drupal_goto('textbook_companion/code/upload_dep'); -} - function _list_existing_dependency($book_id) -{ - // $return_html = '<ul>'; - $return_html = ""; - $query = "SELECT * FROM textbook_companion_dependency_files WHERE preference_id = %d ORDER BY filename ASC"; - $result = db_query($query, $book_id); - - // $counter = 0; - // while ($row = db_fetch_object($query)) - // { - // $temp_caption = ''; - // if ($row->caption) - // $temp_caption = ' (' . $row->caption . ')'; - // $return_html .= '<li>' . l($row->filename . $temp_caption, 'download/dependency/' . $row->id) . '</li>'; - // $counter++; - // } - // if ($counter == 0) - // $return_html .= '<li>(None)</li>'; - // $return_html .= '</ul>'; - - $headers = array( - "File", "Action", - ); - $rows = array(); - while($row = db_fetch_object($result)) { - $item = array( - l($row->filename . $temp_caption, 'download/dependency/' . $row->id), - l("Edit", "textbook_companion/code/edit_dep/{$row->id}") - . " | " . l("Delete","textbook_companion/code/delete_dep/{$row->id}") + { + // $return_html = '<ul>'; + $return_html = ""; + /*$query = "SELECT * FROM textbook_companion_dependency_files WHERE preference_id = %d ORDER BY filename ASC"; + $result = db_query($query, $book_id);*/ + $query = db_select('textbook_companion_dependency_files'); + $query->fields('textbook_companion_dependency_files'); + $query->condition('preference_id', $book_id); + $query->orderBy('filename', 'ASC'); + $result = $query->execute(); + // $counter = 0; + // while ($row = db_fetch_object($query)) + // { + // $temp_caption = ''; + // if ($row->caption) + // $temp_caption = ' (' . $row->caption . ')'; + // $return_html .= '<li>' . l($row->filename . $temp_caption, 'download/dependency/' . $row->id) . '</li>'; + // $counter++; + // } + // if ($counter == 0) + // $return_html .= '<li>(None)</li>'; + // $return_html .= '</ul>'; + $headers = array( + "File", + "Action" ); - array_push($rows, $item); + $rows = array(); + while ($row = $result->fetchObject()) + { + $item = array( + l($row->filename . $temp_caption, 'download/dependency/' . $row->id), + l("Edit", "textbook_companion/code/edit_dep/{$row->id}") . " | " . l("Delete", "textbook_companion/code/delete_dep/{$row->id}") + ); + array_push($rows, $item); + } + $return_html .= theme("table", array( + "headers" => $headers, + "rows" => $rows + )); + return $return_html; } - $return_html .= theme("table", $headers, $rows); - return $return_html; -} - /******************** edit dependency section ********************/ - -function edit_dependency_form($form_state, $dependency_id=0) -{ - global $user; - - /************************ start approve book details ************************/ - $proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid = %d ORDER BY id DESC LIMIT 1", $user->uid); - $proposal_data = db_fetch_object($proposal_q); - if (!$proposal_data) +function edit_dependency_form($form_state, $dependency_id = 0) { - drupal_set_message("Please submit a " . l('proposal', 'proposal') . ".", 'error'); - drupal_goto(''); - } - if ($proposal_data->proposal_status != 1 && $proposal_data->proposal_status != 4) - { - switch ($proposal_data->proposal_status ) - { - case 0: - drupal_set_message(t('We have already received your proposal. We will get back to you soon.'), 'status'); - drupal_goto(''); - return; - break; - case 2: - drupal_set_message(t('Your proposal has been dis-approved. Please create another proposal ' . l('here', 'proposal') . '.'), 'error'); - drupal_goto(''); - return; - break; - case 3: - drupal_set_message(t('Congratulations! You have completed your last book proposal. You have to create another proposal ' . l('here', 'proposal') . '.'), 'status'); - drupal_goto(''); - return; - break; - default: - drupal_set_message(t('Invalid proposal state. Please contact site administrator for further information.'), 'error'); - drupal_goto(''); - return; - break; - } - } - - $preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND approval_status = 1 LIMIT 1", $proposal_data->id); - $preference_data = db_fetch_object($preference_q); - if (!$preference_data) - { - drupal_set_message(t('Invalid Book Preference status. Please contact site administrator for further information.'), 'error'); - drupal_goto(''); - return; - } - /************************ end approve book details **************************/ - /* fetching the default values */ - $query = " + global $user; + /************************ start approve book details ************************/ + /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid = %d ORDER BY id DESC LIMIT 1", $user->uid); + $proposal_data = db_fetch_object($proposal_q);*/ + $query = db_select('textbook_companion_proposal'); + $query->fields('textbook_companion_proposal'); + $query->condition('uid', $user->uid); + $query->orderBy('id', 'DESC'); + $query->range(0, 1); + $result = $query->execute(); + $proposal_data = $result->fetchObject(); + if (!$proposal_data) + { + drupal_set_message("Please submit a " . l('proposal', 'proposal') . ".", 'error'); + drupal_goto(''); + } + if ($proposal_data->proposal_status != 1 && $proposal_data->proposal_status != 4) + { + switch ($proposal_data->proposal_status) + { + case 0: + drupal_set_message(t('We have already received your proposal. We will get back to you soon.'), 'status'); + drupal_goto(''); + return; + break; + case 2: + drupal_set_message(t('Your proposal has been dis-approved. Please create another proposal ' . l('here', 'proposal') . '.'), 'error'); + drupal_goto(''); + return; + break; + case 3: + drupal_set_message(t('Congratulations! You have completed your last book proposal. You have to create another proposal ' . l('here', 'proposal') . '.'), 'status'); + drupal_goto(''); + return; + break; + default: + drupal_set_message(t('Invalid proposal state. Please contact site administrator for further information.'), 'error'); + drupal_goto(''); + return; + break; + } + } + /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND approval_status = 1 LIMIT 1", $proposal_data->id); + $preference_data = db_fetch_object($preference_q);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('proposal_id', $proposal_data->id); + $query->condition('approval_status', 1); + $query->range(0, 1); + $result = $query->execute(); + $preference_data = $result->fetchObject(); + if (!$preference_data) + { + drupal_set_message(t('Invalid Book Preference status. Please contact site administrator for further information.'), 'error'); + drupal_goto(''); + return; + } + /************************ end approve book details **************************/ + /* fetching the default values */ + /*$query = " SELECT * FROM {textbook_companion_dependency_files} WHERE id = {$dependency_id} - "; - $result = db_query($query); - $row = db_fetch_object($result); - - $form['#attributes'] = array('enctype' => "multipart/form-data"); - - $form['depfile'] = array( - '#type' => 'fieldset', - '#title' => t('Upload New Dependency File'), - '#collapsible' => FALSE, - '#collapsed' => FALSE, - ); - $form['depfile']['depfile1'] = array( - '#type' => 'file', - '#title' => t('Upload dependency file'), - '#description' => t("Allowed file extensions : ") . variable_get('textbook_companion_dependency_extensions', ''), - ); - $form['depfile']['depfile1_caption'] = array( - '#type' => 'textfield', - '#title' => t('Caption for dependency file'), - '#size' => 15, - '#maxlength' => 100, - '#required' => TRUE, - "#default_value" => $row->caption, - ); - $form['depfile']['depfile1_description'] = array( - '#type' => 'textarea', - '#title' => t('Brief Description of the dependency file'), - "#default_value" => $row->description, - ); - - $form["dependency_id"] = array( - "#type" => "hidden", - "#value" => $dependency_id - ); - - $form['submit'] = array( - '#type' => 'submit', - '#value' => t('Submit') - ); - - $form['cancel'] = array( - '#type' => 'markup', - '#value' => l(t('Back'), 'textbook_companion/code/upload_dep'), - ); - return $form; -} - + "; + $result = db_query($query); + $row = db_fetch_object($result);*/ + $query = db_select('textbook_companion_dependency_files'); + $query->fields('textbook_companion_dependency_files'); + $query->condition('id', $dependency_id); + $result = $query->execute(); + $row = $result->fetchObject(); + $form['#attributes'] = array( + 'enctype' => "multipart/form-data" + ); + $form['depfile'] = array( + '#type' => 'fieldset', + '#title' => t('Upload New Dependency File'), + '#collapsible' => FALSE, + '#collapsed' => FALSE + ); + $form['depfile']['depfile1'] = array( + '#type' => 'file', + '#title' => t('Upload dependency file'), + '#description' => t("Allowed file extensions : ") . variable_get('textbook_companion_dependency_extensions', '') + ); + $form['depfile']['depfile1_caption'] = array( + '#type' => 'textfield', + '#title' => t('Caption for dependency file'), + '#size' => 15, + '#maxlength' => 100, + '#required' => TRUE, + "#default_value" => $row->caption + ); + $form['depfile']['depfile1_description'] = array( + '#type' => 'textarea', + '#title' => t('Brief Description of the dependency file'), + "#default_value" => $row->description + ); + $form["dependency_id"] = array( + "#type" => "hidden", + "#value" => $dependency_id + ); + $form['submit'] = array( + '#type' => 'submit', + '#value' => t('Submit') + ); + $form['cancel'] = array( + '#type' => 'markup', + '#value' => l(t('Back'), 'textbook_companion/code/upload_dep') + ); + return $form; + } function edit_dependency_form_validate($form, &$form_state) -{ - global $user; - - if (isset($_FILES['files'])) { - /* check for valid filename extensions */ - $allowed_extensions = explode(',' , variable_get('textbook_companion_dependency_extensions', '')); - foreach ($_FILES['files']['name'] as $file_form_name => $file_name) - { - if ($file_name) + global $user; + if (isset($_FILES['files'])) { - $temp_extension = end(explode('.', strtolower($_FILES['files']['name'][$file_form_name]))); - if (!in_array($temp_extension, $allowed_extensions)) - form_set_error($file_form_name, t('Only ' . variable_get('textbook_companion_dependency_extensions', '') . ' extensions can be uploaded.')); - if ($_FILES['files']['size'][$file_form_name] <= 0) - form_set_error($file_form_name, t('File size cannot be zero.')); - - /* check if file already exists */ - $dep_exists_data = db_fetch_object( - db_query( - "SELECT * FROM {textbook_companion_dependency_files} WHERE filename = '%s' AND id != %d", - $_FILES['files']['name'][$file_form_name], - $form_state["values"]["dependency_id"] - ) - ); - - if ($dep_exists_data) - form_set_error($file_form_name, t('Dendency file with the same name has already been uploaded in this or some other book. Please rename the file and try again.')); - - /* check if valid file name */ - if (!textbook_companion_check_valid_filename($_FILES['files']['name'][$file_form_name])) - form_set_error($file_form_name, t('Invalid file name specified. Only alphabets, numbers and underscore is allowed as a valid filename.')); + /* check for valid filename extensions */ + $allowed_extensions = explode(',', variable_get('textbook_companion_dependency_extensions', '')); + foreach ($_FILES['files']['name'] as $file_form_name => $file_name) + { + if ($file_name) + { + $temp_extension = end(explode('.', strtolower($_FILES['files']['name'][$file_form_name]))); + if (!in_array($temp_extension, $allowed_extensions)) + form_set_error($file_form_name, t('Only ' . variable_get('textbook_companion_dependency_extensions', '') . ' extensions can be uploaded.')); + if ($_FILES['files']['size'][$file_form_name] <= 0) + form_set_error($file_form_name, t('File size cannot be zero.')); + /* check if file already exists */ + /*$dep_exists_data = db_fetch_object( + db_query( + "SELECT * FROM {textbook_companion_dependency_files} WHERE filename = '%s' AND id != %d", + $_FILES['files']['name'][$file_form_name], + $form_state["values"]["dependency_id"] + ) + );*/ + $query = db_select('textbook_companion_dependency_files'); + $query->fields('textbook_companion_dependency_files'); + $query->condition('filename', $_FILES['files']['name'][$file_form_name]); + $query->condition('id', $form_state["values"]["dependency_id"], '<>'); + $result = $query->execute(); + $dep_exists_data = $result->fetchObject(); + if ($dep_exists_data) + form_set_error($file_form_name, t('Dendency file with the same name has already been uploaded in this or some other book. Please rename the file and try again.')); + /* check if valid file name */ + if (!textbook_companion_check_valid_filename($_FILES['files']['name'][$file_form_name])) + form_set_error($file_form_name, t('Invalid file name specified. Only alphabets, numbers and underscore is allowed as a valid filename.')); + } + } } - } - } -} - -function edit_dependency_form_submit($form, &$form_state) { - global $user; - - $root_path = textbook_companion_path(); - - /* get approved book details */ - $proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid = %d ORDER BY id DESC LIMIT 1", $user->uid); - $proposal_data = db_fetch_object($proposal_q); - if (!$proposal_data) - { - drupal_set_message("Please submit a " . l('proposal', 'proposal') . ".", 'error'); - drupal_goto(''); } - if ($proposal_data->proposal_status != 1 && $proposal_data->proposal_status != 4) +function edit_dependency_form_submit($form, &$form_state) { - switch ($proposal_data->proposal_status ) - { - case 0: - drupal_set_message(t('We have already received your proposal. We will get back to you soon.'), 'status'); - drupal_goto(''); - return; - break; - case 2: - drupal_set_message(t('Your proposal has been dis-approved. Please create another proposal ' . l('here', 'proposal') . '.'), 'error'); - drupal_goto(''); - return; - break; - case 3: - drupal_set_message(t('Congratulations! You have completed your last book proposal. You have to create another proposal ' . l('here', 'proposal') . '.'), 'status'); - drupal_goto(''); - return; - break; - default: - drupal_set_message(t('Invalid proposal state. Please contact site administrator for further information.'), 'error'); - drupal_goto(''); - return; - break; - } - } - - $preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND approval_status = 1 LIMIT 1", $proposal_data->id); - $preference_data = db_fetch_object($preference_q); - if (!$preference_data) - { - drupal_set_message(t('Invalid Book Preference status. Please contact site administrator for further information.'), 'error'); - drupal_goto(''); - return; - } - - $preference_id = $preference_data->id; - - $dest_path = $preference_id . '/'; - if (!is_dir($root_path . $dest_path)) - mkdir($root_path . $dest_path); - - $dest_path .= 'DEPENDENCIES' . '/'; - if (!is_dir($root_path . $dest_path)) - mkdir($root_path . $dest_path); - - /* uploading dependencies */ - $file_upload_counter = 0; - $dependency_ids = array(); - $dependency_names = array(); - - /* deleting old dependency file if the filename changed */ - $query = " + global $user; + $root_path = textbook_companion_path(); + /* get approved book details */ + /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid = %d ORDER BY id DESC LIMIT 1", $user->uid); + $proposal_data = db_fetch_object($proposal_q);*/ + $query = db_select('textbook_companion_proposal'); + $query->fields('textbook_companion_proposal'); + $query->condition('uid', $user->uid); + $query->orderBy('id', 'DESC'); + $query->range(0, 1); + $result = $query->execute(); + $proposal_data = $result->fetchObject(); + if (!$proposal_data) + { + drupal_set_message("Please submit a " . l('proposal', 'proposal') . ".", 'error'); + drupal_goto(''); + } + if ($proposal_data->proposal_status != 1 && $proposal_data->proposal_status != 4) + { + switch ($proposal_data->proposal_status) + { + case 0: + drupal_set_message(t('We have already received your proposal. We will get back to you soon.'), 'status'); + drupal_goto(''); + return; + break; + case 2: + drupal_set_message(t('Your proposal has been dis-approved. Please create another proposal ' . l('here', 'proposal') . '.'), 'error'); + drupal_goto(''); + return; + break; + case 3: + drupal_set_message(t('Congratulations! You have completed your last book proposal. You have to create another proposal ' . l('here', 'proposal') . '.'), 'status'); + drupal_goto(''); + return; + break; + default: + drupal_set_message(t('Invalid proposal state. Please contact site administrator for further information.'), 'error'); + drupal_goto(''); + return; + break; + } + } + /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND approval_status = 1 LIMIT 1", $proposal_data->id); + $preference_data = db_fetch_object($preference_q);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('proposal_id', $proposal_data->id); + $query->condition('approval_status', 1); + $query->range(0, 1); + $result = $query->execute(); + $preference_data = $result->fetchObject(); + if (!$preference_data) + { + drupal_set_message(t('Invalid Book Preference status. Please contact site administrator for further information.'), 'error'); + drupal_goto(''); + return; + } + $preference_id = $preference_data->id; + $dest_path = $preference_id . '/'; + if (!is_dir($root_path . $dest_path)) + mkdir($root_path . $dest_path); + $dest_path .= 'DEPENDENCIES' . '/'; + if (!is_dir($root_path . $dest_path)) + mkdir($root_path . $dest_path); + /* uploading dependencies */ + $file_upload_counter = 0; + $dependency_ids = array(); + $dependency_names = array(); + /* deleting old dependency file if the filename changed */ + /*$query = " SELECT * FROM textbook_companion_dependency_files WHERE id = %d - "; - $result = db_query($query, $form_state["values"]["dependency_id"]); - $row = db_fetch_object($result); - if($row->filename != $_FILES["files"]["name"][$file_form_name] && $_FILES["files"]["name"][$file_form_name]) { - unlink($root_path . $dest_path . $row->filename); - } - - foreach ($_FILES['files']['name'] as $file_form_name => $file_name) - { - if ($file_name) - { - /* - * uploading file - * file will be overwritten if same name - */ - if (move_uploaded_file($_FILES['files']['tmp_name'][$file_form_name], $root_path . $dest_path . $_FILES['files']['name'][$file_form_name])) + "; + $result = db_query($query, $form_state["values"]["dependency_id"]); + $row = db_fetch_object($result);*/ + $query = db_select('textbook_companion_dependency_files'); + $query->fields('textbook_companion_dependency_files'); + $query->condition('id', $form_state["values"]["dependency_id"]); + $result = $query->execute(); + $row = $result->fetchObject(); + if ($row->filename != $_FILES["files"]["name"][$file_form_name] && $_FILES["files"]["name"][$file_form_name]) { - /* updating uploaded file entry in the database */ - db_query( - "UPDATE {textbook_companion_dependency_files} SET - filename = '%s', filepath = '%s', filemime = '%s', filesize = %d, - caption = '%s', description = '%s', timestamp = %s - WHERE id = %d", - $_FILES['files']['name'][$file_form_name], - $dest_path . $_FILES['files']['name'][$file_form_name], - $_FILES['files']['type'][$file_form_name], - $_FILES['files']['size'][$file_form_name], - $form_state['values'][$file_form_name . '_caption'], - $form_state['values'][$file_form_name . '_description'], - time(), - $form_state["values"]["dependency_id"] - ); - - drupal_set_message($file_name . ' uploaded successfully.', 'status'); - $dependency_ids[] = db_last_insert_id('textbook_companion_dependency_files', 'id'); - $dependency_names[] = $_FILES['files']['name'][$file_form_name]; - $file_upload_counter++; - } else { - drupal_set_message('Error uploading dependency : ' . $dest_path . '/' . $_FILES['files']['name'][$file_form_name], 'error'); + unlink($root_path . $dest_path . $row->filename); + } + foreach ($_FILES['files']['name'] as $file_form_name => $file_name) + { + if ($file_name) + { + /* + * uploading file + * file will be overwritten if same name + */ + if (move_uploaded_file($_FILES['files']['tmp_name'][$file_form_name], $root_path . $dest_path . $_FILES['files']['name'][$file_form_name])) + { + /* updating uploaded file entry in the database */ + /*db_query( + "UPDATE {textbook_companion_dependency_files} SET + filename = '%s', filepath = '%s', filemime = '%s', filesize = %d, + caption = '%s', description = '%s', timestamp = %s + WHERE id = %d", + $_FILES['files']['name'][$file_form_name], + $dest_path . $_FILES['files']['name'][$file_form_name], + $_FILES['files']['type'][$file_form_name], + $_FILES['files']['size'][$file_form_name], + $form_state['values'][$file_form_name . '_caption'], + $form_state['values'][$file_form_name . '_description'], + time(), + $form_state["values"]["dependency_id"] + );*/ + $query = db_update('textbook_companion_dependency_files'); + $query->fields(array( + 'filename' => $_FILES['files']['name'][$file_form_name], + 'filepath' => $dest_path . $_FILES['files']['name'][$file_form_name], + 'filemime' => $_FILES['files']['type'][$file_form_name], + 'filesize' => $_FILES['files']['size'][$file_form_name], + 'caption' => $form_state['values'][$file_form_name . '_caption'], + 'description' => $form_state['values'][$file_form_name . '_description'], + 'timestamp' => time() + )); + $query->condition('id', $form_state["values"]["dependency_id"]); + $num_updated = $query->execute(); + drupal_set_message($file_name . ' uploaded successfully.', 'status'); + $dependency_ids[] = db_last_insert_id('textbook_companion_dependency_files', 'id'); + $dependency_names[] = $_FILES['files']['name'][$file_form_name]; + $file_upload_counter++; + } + else + { + drupal_set_message('Error uploading dependency : ' . $dest_path . '/' . $_FILES['files']['name'][$file_form_name], 'error'); + } + } + } + if ($file_upload_counter > 0) + { + drupal_set_message('Dependencies uploaded successfully.', 'status'); + /* sending email */ + $param['dependency_uploaded']['user_id'] = $user->uid; + $param['dependency_uploaded']['dependency_names'] = $dependency_names; + $email_to = $user->mail; + if (!drupal_mail('textbook_companion', 'dependency_uploaded', $email_to, language_default(), $param, variable_get('textbook_companion_from_email', NULL), TRUE)) + drupal_set_message('Error sending email message.', 'error'); } - } + drupal_goto('textbook_companion/code/upload_dep'); } - - if ($file_upload_counter > 0) +function edit_dependency($dependency_id = 0) { - drupal_set_message('Dependencies uploaded successfully.', 'status'); - - /* sending email */ - $param['dependency_uploaded']['user_id'] = $user->uid; - $param['dependency_uploaded']['dependency_names'] = $dependency_names; - - $email_to = $user->mail; - if (!drupal_mail('textbook_companion', 'dependency_uploaded', $email_to, language_default(), $param, variable_get('textbook_companion_from_email', NULL), TRUE)) - drupal_set_message('Error sending email message.', 'error'); - } - - drupal_goto('textbook_companion/code/upload_dep'); -} - -function edit_dependency($dependency_id = 0) { - if($dependency_id){ - $page_content = ""; - $page_content .= drupal_get_form("edit_dependency_form", $dependency_id); - return $page_content; - } else { - drupal_goto("textbook_companion/code/upload_dep"); + if ($dependency_id) + { + $page_content = ""; + $page_content .= drupal_get_form("edit_dependency_form", $dependency_id); + return $page_content; + } + else + { + drupal_goto("textbook_companion/code/upload_dep"); + } } -} - /******************** delete dependency section ********************/ - -function delete_dependency($dependency_id = 0, $confirm = "") { - global $user; - - /************************ start approve book details ************************/ - $proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid = %d ORDER BY id DESC LIMIT 1", $user->uid); - $proposal_data = db_fetch_object($proposal_q); - if (!$proposal_data) - { - drupal_set_message("Please submit a " . l('proposal', 'proposal') . ".", 'error'); - drupal_goto(''); - } - if ($proposal_data->proposal_status != 1 && $proposal_data->proposal_status != 4) +function delete_dependency($dependency_id = 0, $confirm = "") { - switch ($proposal_data->proposal_status ) - { - case 0: - drupal_set_message(t('We have already received your proposal. We will get back to you soon.'), 'status'); - drupal_goto(''); - return; - break; - case 2: - drupal_set_message(t('Your proposal has been dis-approved. Please create another proposal ' . l('here', 'proposal') . '.'), 'error'); - drupal_goto(''); - return; - break; - case 3: - drupal_set_message(t('Congratulations! You have completed your last book proposal. You have to create another proposal ' . l('here', 'proposal') . '.'), 'status'); - drupal_goto(''); - return; - break; - default: - drupal_set_message(t('Invalid proposal state. Please contact site administrator for further information.'), 'error'); - drupal_goto(''); - return; - break; - } - } - - $preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND approval_status = 1 LIMIT 1", $proposal_data->id); - $preference_data = db_fetch_object($preference_q); - if (!$preference_data) - { - drupal_set_message(t('Invalid Book Preference status. Please contact site administrator for further information.'), 'error'); - drupal_goto(''); - return; - } - /************************ end approve book details **************************/ - $page_content = ""; - if($dependency_id && $confirm == "yes") { - /* removing the dependency file from filesystem */ - $query = " - SELECT * FROM {textbook_companion_dependency_files} - WHERE id = {$dependency_id} - "; - $result = db_query($query); - $row = db_fetch_object($result); - - if($preference_data->id == $row->preference_id) { - $root_path = textbook_companion_path(); - $dest_path = $row->preference_id . '/'; - $dest_path .= 'DEPENDENCIES' . '/'; - unlink($root_path . $dest_path . $row->filename); - - /* deleting entry in textbook_companion_dependency_files */ - $query = " - DELETE FROM {textbook_companion_dependency_files} + global $user; + /************************ start approve book details ************************/ + /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid = %d ORDER BY id DESC LIMIT 1", $user->uid); + $proposal_data = db_fetch_object($proposal_q);*/ + $query = db_select('textbook_companion_proposal'); + $query->fields('textbook_companion_proposal'); + $query->condition('uid', $user->uid); + $query->orderBy('id', 'DESC'); + $query->range(0, 1); + $result = $query->execute(); + $proposal_data = $result->fetchObject(); + if (!$proposal_data) + { + drupal_set_message("Please submit a " . l('proposal', 'proposal') . ".", 'error'); + drupal_goto(''); + } + if ($proposal_data->proposal_status != 1 && $proposal_data->proposal_status != 4) + { + switch ($proposal_data->proposal_status) + { + case 0: + drupal_set_message(t('We have already received your proposal. We will get back to you soon.'), 'status'); + drupal_goto(''); + return; + break; + case 2: + drupal_set_message(t('Your proposal has been dis-approved. Please create another proposal ' . l('here', 'proposal') . '.'), 'error'); + drupal_goto(''); + return; + break; + case 3: + drupal_set_message(t('Congratulations! You have completed your last book proposal. You have to create another proposal ' . l('here', 'proposal') . '.'), 'status'); + drupal_goto(''); + return; + break; + default: + drupal_set_message(t('Invalid proposal state. Please contact site administrator for further information.'), 'error'); + drupal_goto(''); + return; + break; + } + } + /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND approval_status = 1 LIMIT 1", $proposal_data->id); + $preference_data = db_fetch_object($preference_q);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('proposal_id', $proposal_data->id); + $query->condition('approval_status', 1); + $query->range(0, 1); + $result = $query->execute(); + $preference_data = $result->fetchObject(); + if (!$preference_data) + { + drupal_set_message(t('Invalid Book Preference status. Please contact site administrator for further information.'), 'error'); + drupal_goto(''); + return; + } + /************************ end approve book details **************************/ + $page_content = ""; + if ($dependency_id && $confirm == "yes") + { + /* removing the dependency file from filesystem */ + /*$query = " + SELECT * FROM {textbook_companion_dependency_files} WHERE id = {$dependency_id} "; - db_query($query); - - /* deleting entries from textbook_companion_example_dependency */ - $query = " - DELETE FROM {textbook_companion_example_dependency} - WHERE dependency_id = {$dependency_id} + $result = db_query($query); + $row = db_fetch_object($result);*/ + $query = db_select('textbook_companion_dependency_files'); + $query->fields('textbook_companion_dependency_files'); + $query->condition('id', $dependency_id); + $result = $query->execute(); + $row = $result->fetchObject(); + if ($preference_data->id == $row->preference_id) + { + $root_path = textbook_companion_path(); + $dest_path = $row->preference_id . '/'; + $dest_path .= 'DEPENDENCIES' . '/'; + unlink($root_path . $dest_path . $row->filename); + /* deleting entry in textbook_companion_dependency_files */ + /*$query = " + DELETE FROM {textbook_companion_dependency_files} + WHERE id = {$dependency_id} + "; + db_query($query);*/ + $query = db_delete('textbook_companion_dependency_files'); + $query->condition('id', $dependency_id); + $num_deleted = $query->execute(); + /* deleting entries from textbook_companion_example_dependency */ + /*$query = " + DELETE FROM {textbook_companion_example_dependency} + WHERE dependency_id = {$dependency_id} + "; + db_query($query);*/ + $query = db_delete('textbook_companion_example_dependency'); + $query->condition('dependency_id', $dependency_id); + $num_deleted = $query->execute(); + drupal_set_message("Dependency deleted successfully."); + drupal_goto("textbook_companion/code/upload_dep"); + } + else + { + drupal_set_message("Cannot delete other users dependency.", "error"); + drupal_goto("textbook_companion/code/upload_dep"); + } + } + else if ($dependency_id) + { + /*$query = " + SELECT * FROM {textbook_companion_dependency_files} + WHERE id = %d "; - db_query($query); - - drupal_set_message("Dependency deleted successfully."); - drupal_goto("textbook_companion/code/upload_dep"); - } else { - drupal_set_message("Cannot delete other users dependency.", "error"); - drupal_goto("textbook_companion/code/upload_dep"); - } - } else if($dependency_id) { - $query = " - SELECT * FROM {textbook_companion_dependency_files} - WHERE id = %d - "; - $result = db_query($query, $dependency_id); - $row = db_fetch_object($result); - - - if($preference_data->id == $row->preference_id) { - $page_content .= "Are you sure you want to delete this dependency?<br><br>"; - $page_content .= "Dependency filename: <b>{$row->filename}</b><br><br>"; - - /* fetching the examples linked to this dependency */ - $query = " - SELECT * FROM textbook_companion_example_dependency dep - LEFT JOIN textbook_companion_example exa ON exa.id = dep.example_id - WHERE dep.id = %d - "; - $result = db_query($query, $dependency_id); - $list = ""; - while($row = db_fetch_object($result)) { - $list .= "<li>Example {$row->number}</li>"; + $result = db_query($query, $dependency_id); + $row = db_fetch_object($result);*/ + $query = db_select('textbook_companion_dependency_files'); + $query->fields('textbook_companion_dependency_files'); + $query->condition('id', $dependency_id); + $result = $query->execute(); + $row = $result->fetchObject(); + if ($preference_data->id == $row->preference_id) + { + $page_content .= "Are you sure you want to delete this dependency?<br><br>"; + $page_content .= "Dependency filename: <b>{$row->filename}</b><br><br>"; + /* fetching the examples linked to this dependency */ + /*$query = " + SELECT * FROM textbook_companion_example_dependency dep + LEFT JOIN textbook_companion_example exa ON exa.id = dep.example_id + WHERE dep.id = %d + "; + $result = db_query($query, $dependency_id);*/ + $query = db_select('textbook_companion_example_dependency', 'dep'); + $query->fields('dep'); + $query->leftJoin('textbook_companion_example', 'exa', 'exa.id = dep.example_id'); + $query->condition('dep.id', $dependency_id); + $result = $query->execute(); + $list = ""; + while ($row = $result->fetchObject()) + { + $list .= "<li>Example {$row->number}</li>"; + } + if ($list) + { + $page_content .= "List of examples linking to this dependency are:"; + $page_content .= "<ul>{$list}</ul>"; + } + $page_content .= l("Delete dependency", "textbook_companion/code/delete_dep/{$dependency_id}/yes"); + $page_content .= " | "; + $page_content .= l("Cancel", "textbook_companion/code/upload_dep"); + } + else + { + drupal_set_message("Cannot delete other users dependency.", "error"); + drupal_goto("textbook_companion/code/upload_dep"); + } } - if($list) { - $page_content .= "List of examples linking to this dependency are:"; - $page_content .= "<ul>{$list}</ul>"; + else + { + drupal_goto("textbook_companion/code/upload_dep"); } - $page_content .= l("Delete dependency", "textbook_companion/code/delete_dep/{$dependency_id}/yes"); - $page_content .= " | "; - $page_content .= l("Cancel", "textbook_companion/code/upload_dep"); - } else { - drupal_set_message("Cannot delete other users dependency.", "error"); - drupal_goto("textbook_companion/code/upload_dep"); - } - } else { - drupal_goto("textbook_companion/code/upload_dep"); + return $page_content; } - return $page_content; -} diff --git a/dependency_approval.inc b/dependency_approval.inc index 4903141..81cf6f8 100755 --- a/dependency_approval.inc +++ b/dependency_approval.inc @@ -1,205 +1,240 @@ <?php - /******************************************************************************/ /**************************** DEPNDENCY APPROVAL ******************************/ /******************************************************************************/ - function textbook_companion_dependency_approval_form($form_state) -{ - // $form['#redirect'] = FALSE; - - // ahah_helper_register($form, $form_state); - - /* default value for ahah fields */ - // if (!isset($form_state['storage']['run']['dependency'])) - // { - // $dependency_default_value = 0; - // } else { - // $dependency_default_value = $form_state['storage']['run']['dependency']; - // } - - $form['run'] = array( - '#type' => 'fieldset', - '#title' => t('Manage Dependency'), - '#collapsible' => FALSE, - '#collapsed' => FALSE, - '#prefix' => '<div id="run-wrapper">', - '#suffix' => '</div>', - '#tree' => TRUE, - ); - - $form['run']['dependency'] = array( - '#type' => 'select', - '#title' => t('Dependency'), - '#options' => _textbook_companion_list_of_dependencies(), - '#default_value' => $dependency_default_value, - '#tree' => TRUE, - // '#ahah' => array( - // 'event' => 'change', - // 'effect' => 'none', - // 'path' => ahah_helper_path(array('run')), - // 'wrapper' => 'run-wrapper', - // 'progress' => array( - // 'type' => 'throbber', - // 'message' => t(''), - // ), - // ), - ); - - // $example_list = array(); - /************ START OF $_POST **************/ - /* - if ($_POST) { + // $form['#redirect'] = FALSE; + // ahah_helper_register($form, $form_state); + /* default value for ahah fields */ + // if (!isset($form_state['storage']['run']['dependency'])) + // { + // $dependency_default_value = 0; + // } else { + // $dependency_default_value = $form_state['storage']['run']['dependency']; + // } + $form['run'] = array( + '#type' => 'fieldset', + '#title' => t('Manage Dependency'), + '#collapsible' => FALSE, + '#collapsed' => FALSE, + '#prefix' => '<div id="run-wrapper">', + '#suffix' => '</div>', + '#tree' => TRUE + ); + $form['run']['dependency'] = array( + '#type' => 'select', + '#title' => t('Dependency'), + '#options' => _textbook_companion_list_of_dependencies(), + '#default_value' => $dependency_default_value, + '#tree' => TRUE + // '#ahah' => array( + // 'event' => 'change', + // 'effect' => 'none', + // 'path' => ahah_helper_path(array('run')), + // 'wrapper' => 'run-wrapper', + // 'progress' => array( + // 'type' => 'throbber', + // 'message' => t(''), + // ), + // ), + ); + // $example_list = array(); + /************ START OF $_POST **************/ + /* + if ($_POST) + { if ($dependency_default_value > 0) { - $example_id_q = db_query("SELECT * FROM {textbook_companion_example_dependency} WHERE dependency_id = %d", $dependency_default_value); - while ($example_id_data = db_fetch_object($example_id_q)) { - $example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE id = %d", $example_id_data->example_id); - $example_data = db_fetch_object($example_q); - $chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE id = %d", $example_data->chapter_id); - $chapter_data = db_fetch_object($chapter_q); - $preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d", $chapter_data->preference_id); - $preference_data = db_fetch_object($preference_q); - $example_list[] = array($example_data->number, $chapter_data->number . ' . ' . $chapter_data->name, $preference_data->book); - } - $example_list_header = array('Code', 'Chapter', 'Book'); - $example = theme_table($example_list_header, $example_list); - - if ($example_list) { - $form['run']['example_dependency'] = array( - '#type' => 'item', - '#value' => $example, - ); - $form['run']['example_dependency_message'] = array( - '#type' => 'item', - '#value' => 'Please unlink the dependency from the above example before deleting it', - ); - } + $example_id_q = db_query("SELECT * FROM {textbook_companion_example_dependency} WHERE dependency_id = %d", $dependency_default_value); + while ($example_id_data = db_fetch_object($example_id_q)) { + $example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE id = %d", $example_id_data->example_id); + $example_data = db_fetch_object($example_q); + $chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE id = %d", $example_data->chapter_id); + $chapter_data = db_fetch_object($chapter_q); + $preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d", $chapter_data->preference_id); + $preference_data = db_fetch_object($preference_q); + $example_list[] = array($example_data->number, $chapter_data->number . ' . ' . $chapter_data->name, $preference_data->book); + } + $example_list_header = array('Code', 'Chapter', 'Book'); + $example = theme_table($example_list_header, $example_list); + + if ($example_list) { + $form['run']['example_dependency'] = array( + '#type' => 'item', + '#value' => $example, + ); + $form['run']['example_dependency_message'] = array( + '#type' => 'item', + '#value' => 'Please unlink the dependency from the above example before deleting it', + ); + } + } } + */ + /* hidden form elements */ + // $form['run']['dependency_hidden'] = array( + // '#type' => 'hidden', + // '#value' => $form_state['values']['run']['dependency'], + // ); + // if (!$example_list && $dependency_default_value > 0) + // { + $form['run']['delete_dependency'] = array( + '#type' => 'checkbox', + '#title' => t('Delete Dependency') + ); + $form['run']['submit'] = array( + '#type' => 'submit', + '#value' => t('Submit') + ); + // } + return $form; } - */ - - /* hidden form elements */ - // $form['run']['dependency_hidden'] = array( - // '#type' => 'hidden', - // '#value' => $form_state['values']['run']['dependency'], - // ); - - // if (!$example_list && $dependency_default_value > 0) - // { - $form['run']['delete_dependency'] = array( - '#type' => 'checkbox', - '#title' => t('Delete Dependency'), - ); - $form['run']['submit'] = array( - '#type' => 'submit', - '#value' => t('Submit') - ); - // } - - return $form; -} - - function textbook_companion_dependency_approval_form_submit($form, &$form_state) -{ - global $user; - $root_path = textbook_companion_path(); - - if ($form_state['clicked_button']['#value'] == 'Submit') { - if (user_access('bulk manage code')) - { - if ($form_state['values']['run']['delete_dependency'] == "1") + global $user; + $root_path = textbook_companion_path(); + if ($form_state['clicked_button']['#value'] == 'Submit') { - $example_q = db_query("SELECT * FROM {textbook_companion_example_dependency} WHERE dependency_id = %d", $form_state['values']['run']['dependency']); - if ($example_data = db_fetch_object($example_q)) { - - $example_id_q = db_query("SELECT * FROM {textbook_companion_example_dependency} WHERE dependency_id = %d", $form_state['values']['run']['dependency']); - while ($example_id_data = db_fetch_object($example_id_q)) { - $example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE id = %d", $example_id_data->example_id); - $example_data = db_fetch_object($example_q); - $chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE id = %d", $example_data->chapter_id); - $chapter_data = db_fetch_object($chapter_q); - $preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d", $chapter_data->preference_id); - $preference_data = db_fetch_object($preference_q); - $example_list[] = array($preference_data->book, $chapter_data->number, $example_data->number); - } - $example_list_header = array('Book', 'Chapter', 'Code'); - $example = theme_table($example_list_header, $example_list); - - drupal_set_message('Cannot delete dependency since it is linked with following examples. Delete these examples first before deleting the dependency file :' . $example, 'error'); - - } else { - if (textbook_companion_delete_dependency($form_state['values']['run']['dependency'])) + if (user_access('bulk manage code')) { - drupal_set_message('Dependency deleted' , 'status'); - - /* email */ - $email_subject = t('Dependency deleted'); - $email_body = t('Dependency deleted : .') . $form_state['values']['run']['dependency']; - $email_to = $user->mail; - $param['standard']['subject'] = $email_subject; - $param['standard']['body'] = $email_body; - if (!drupal_mail('textbook_companion', 'standard', $email_to, language_default(), $param, variable_get('textbook_companion_from_email', NULL), TRUE)) - drupal_set_message('Error sending email message.', 'error'); + if ($form_state['values']['run']['delete_dependency'] == "1") + { + /*$example_q = db_query("SELECT * FROM {textbook_companion_example_dependency} WHERE dependency_id = %d", $form_state['values']['run']['dependency']);*/ + $query = db_select('textbook_companion_example_dependency'); + $query->fields('textbook_companion_example_dependency'); + $query->condition('dependency_id', $form_state['values']['run']['dependency']); + $example_q = $query->execute(); + if ($example_data = $example_q->fetchObject()) + { + /*$example_id_q = db_query("SELECT * FROM {textbook_companion_example_dependency} WHERE dependency_id = %d", $form_state['values']['run']['dependency']);*/ + $query = db_select('textbook_companion_example_dependency'); + $query->fields('textbook_companion_example_dependency'); + $query->condition('dependency_id', $form_state['values']['run']['dependency']); + $example_id_q = $query->execute(); + while ($example_id_data = $example_id_q->fetchObject()) + { + /*$example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE id = %d", $example_id_data->example_id); + $example_data = db_fetch_object($example_q);*/ + $query = db_select('textbook_companion_example'); + $query->fields('textbook_companion_example'); + $query->condition('id', $example_id_data->example_id); + $result = $query->execute(); + $example_data = $result->fetchObject(); + /*$chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE id = %d", $example_data->chapter_id); + $chapter_data = db_fetch_object($chapter_q);*/ + $query = db_select('textbook_companion_chapter'); + $query->fields('textbook_companion_chapter'); + $query->condition('id', $example_data->chapter_id); + $result = $query->execute(); + $chapter_data = $result->fetchObject(); + /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d", $chapter_data->preference_id); + $preference_data = db_fetch_object($preference_q);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('id', $chapter_data->preference_id); + $result = $query->execute(); + $preference_data = $result->fetchObject(); + $example_list[] = array( + $preference_data->book, + $chapter_data->number, + $example_data->number + ); + } + $example_list_header = array( + 'Book', + 'Chapter', + 'Code' + ); + $example = theme('table', array( + 'headers' => $example_list_header, + 'rows' => $example_list + )); + drupal_set_message('Cannot delete dependency since it is linked with following examples. Delete these examples first before deleting the dependency file :' . $example, 'error'); + } + else + { + if (textbook_companion_delete_dependency($form_state['values']['run']['dependency'])) + { + drupal_set_message('Dependency deleted', 'status'); + /* email */ + $email_subject = t('Dependency deleted'); + $email_body = t('Dependency deleted : .') . $form_state['values']['run']['dependency']; + $email_to = $user->mail; + $param['standard']['subject'] = $email_subject; + $param['standard']['body'] = $email_body; + if (!drupal_mail('textbook_companion', 'standard', $email_to, language_default(), $param, variable_get('textbook_companion_from_email', NULL), TRUE)) + drupal_set_message('Error sending email message.', 'error'); + } + } + } } - } } - } } -} - function _textbook_companion_list_of_dependencies() -{ - $dependencies = array('0' => 'Please select...'); - $dependency_q = db_query("SELECT * FROM {textbook_companion_dependency_files} ORDER BY filename ASC"); - while ($dependency_data = db_fetch_object($dependency_q)) { - $dependencies[$dependency_data->id] = $dependency_data->filename . ' (' . $dependency_data->filepath . ')'; + $dependencies = array( + '0' => 'Please select...' + ); + /*$dependency_q = db_query("SELECT * FROM {textbook_companion_dependency_files} ORDER BY filename ASC");*/ + $query = db_select('textbook_companion_dependency_files'); + $query->fields('textbook_companion_dependency_files'); + $query->orderBy('filename', 'ASC'); + $dependency_q = $query->execute(); + while ($dependency_data = $dependency_q->fetchObject()) + { + $dependencies[$dependency_data->id] = $dependency_data->filename . ' (' . $dependency_data->filepath . ')'; + } + return $dependencies; } - return $dependencies; -} - function textbook_companion_delete_dependency($dependency_id) -{ - global $user; - $root_path = textbook_companion_path(); - $status = TRUE; - - $dependency_files_q = db_query("SELECT * FROM {textbook_companion_dependency_files} WHERE id = %d", $dependency_id); - $dependency_files_data = db_fetch_object($dependency_files_q); - if (!$dependency_files_data) { - drupal_set_message(t('Invalid dependency.'), 'error'); - return FALSE; - } - - if (!file_exists($root_path . $dependency_files_data->filepath)) - { - drupal_set_message(t('Error deleting !file. File does not exists.', array('!file' => $dependency_files_data->filepath)), 'error'); - return FALSE; - } - - /* removing dependency file */ - if (!unlink($root_path . $dependency_files_data->filepath)) - { - $status = FALSE; - drupal_set_message(t('Error deleting !file', array('!file' => $dependency_files_data->filepath)), 'error'); - - /* sending email to admins */ - $email_to = variable_get('textbook_companion_emails', ''); - $param['standard']['subject'] = "[ERROR] Error deleting dependency file"; - $param['standard']['body'] = "Error deleting dependency files by " . $user->uid . " at " . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . " : + global $user; + $root_path = textbook_companion_path(); + $status = TRUE; + /*$dependency_files_q = db_query("SELECT * FROM {textbook_companion_dependency_files} WHERE id = %d", $dependency_id); + $dependency_files_data = db_fetch_object($dependency_files_q);*/ + $query = db_select('textbook_companion_dependency_files'); + $query->fields('textbook_companion_dependency_files'); + $query->condition('id', $dependency_id); + $result = $query->execute(); + $dependency_files_data = $result->fetchObject(); + if (!$dependency_files_data) + { + drupal_set_message(t('Invalid dependency.'), 'error'); + return FALSE; + } + if (!file_exists($root_path . $dependency_files_data->filepath)) + { + drupal_set_message(t('Error deleting !file. File does not exists.', array( + '!file' => $dependency_files_data->filepath + )), 'error'); + return FALSE; + } + /* removing dependency file */ + if (!unlink($root_path . $dependency_files_data->filepath)) + { + $status = FALSE; + drupal_set_message(t('Error deleting !file', array( + '!file' => $dependency_files_data->filepath + )), 'error'); + /* sending email to admins */ + $email_to = variable_get('textbook_companion_emails', ''); + $param['standard']['subject'] = "[ERROR] Error deleting dependency file"; + $param['standard']['body'] = "Error deleting dependency files by " . $user->uid . " at " . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . " : dependency id : " . $dependency_id . " - file id : " . $dependency_files_data->id . " + file id : " . $dependency_files_data->id . " file path : " . $dependency_files_data->filepath; - if (!drupal_mail('textbook_companion', 'standard', $email_to, language_default(), $param, variable_get('textbook_companion_from_email', NULL), TRUE)) - drupal_set_message('Error sending email message.', 'error'); - } else { - /* deleting dependency files database entries */ - db_query("DELETE FROM {textbook_companion_dependency_files} WHERE id = %d", $dependency_id); + if (!drupal_mail('textbook_companion', 'standard', $email_to, language_default(), $param, variable_get('textbook_companion_from_email', NULL), TRUE)) + drupal_set_message('Error sending email message.', 'error'); + } + else + { + /* deleting dependency files database entries */ + /*db_query("DELETE FROM {textbook_companion_dependency_files} WHERE id = %d", $dependency_id);*/ + $query = db_delete('textbook_companion_dependency_files'); + $query->condition('id', $dependency_id); + $num_deleted = $query->execute(); + } + return $status; } - return $status; -} diff --git a/download.inc b/download.inc index db9d5d8..be57897 100755 --- a/download.inc +++ b/download.inc @@ -1,204 +1,267 @@ <?php // $Id$ - function textbook_companion_download_example_file() -{ - $example_file_id = arg(2); - $root_path = textbook_companion_path(); - - $example_files_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE id = %d LIMIT 1", $example_file_id); - $example_file_data = db_fetch_object($example_files_q); - header('Content-Type: ' . $example_file_data->filemime); - header('Content-disposition: attachment; filename="' . $example_file_data->filename . '"'); - header('Content-Length: ' . filesize($root_path . $example_file_data->filepath)); - readfile($root_path . $example_file_data->filepath); -} - -function textbook_companion_download_dependency_file() -{ - $dependency_file_id = arg(2); - $root_path = textbook_companion_path(); - - $dependency_file_q = db_query("SELECT * FROM {textbook_companion_dependency_files} WHERE id = %d LIMIT 1", $dependency_file_id); - $dependency_file_data = db_fetch_object($dependency_file_q); - header('Content-Type: ' . $dependency_file_data->filemime); - header('Content-disposition: attachment; filename="' . $dependency_file_data->filename . '"'); - header('Content-Length: ' . filesize($root_path . $dependency_file_data->filepath)); - ob_clean(); - readfile($root_path . $dependency_file_data->filepath); - exit; -} - -function textbook_companion_download_example() -{ - $example_id = arg(2); - $root_path = textbook_companion_path(); - - /* get example data */ - $example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE id = %d", $example_id); - $example_data = db_fetch_object($example_q); - $chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE id = %d", $example_data->chapter_id); - $chapter_data = db_fetch_object($chapter_q); - $example_files_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE example_id = %d", $example_id); - $example_dependency_files_q = db_query("SELECT * FROM {textbook_companion_example_dependency} WHERE example_id = %d", $example_id); - - $EX_PATH = 'EX' . $example_data->number . '/'; - - /* zip filename */ - $zip_filename = $root_path . 'zip-' . time() . '-' . rand(0, 999999) . '.zip'; - - /* creating zip archive on the server */ - $zip = new ZipArchive; - $zip->open($zip_filename, ZipArchive::CREATE); - - while ($example_files_row = db_fetch_object($example_files_q)) { - $zip->addFile($root_path . $example_files_row->filepath, $EX_PATH . $example_files_row->filename); - } - /* dependency files */ - while ($example_dependency_files_row = db_fetch_object($example_dependency_files_q)) - { - $dependency_file_data = db_fetch_object(db_query("SELECT * FROM {textbook_companion_dependency_files} WHERE id = %d LIMIT 1", $example_dependency_files_row->dependency_id)); - if ($dependency_file_data) - $zip->addFile($root_path . $dependency_file_data->filepath, $EX_PATH . 'DEPENDENCIES/' . $dependency_file_data->filename); + $example_file_id = arg(3); + $root_path = textbook_companion_path(); + $root_temp_path = textbook_companion_temp_path(); + /*$example_files_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE id = %d LIMIT 1", $example_file_id); + $example_file_data = db_fetch_object($example_files_q);*/ + /*$query = db_select('textbook_companion_example_files'); + $query->fields('textbook_companion_example_files'); + $query->condition('id', $example_file_id); + $query->range(0, 1); + $result = $query->execute();*/ + $example_files_q = db_query("select * from textbook_companion_preference tcp join textbook_companion_chapter tcc on tcp.id=tcc.preference_id join textbook_companion_example tce ON tcc.id=tce.chapter_id join textbook_companion_example_files tcef on tce.id=tcef.example_id where tcef.id= :example_id LIMIT 1", array( + ':example_id' => $example_file_id + )); + $example_file_data = $example_files_q->fetchObject(); + header('Content-Type: ' . $example_file_data->filemime); + header('Content-disposition: attachment; filename="' . $example_file_data->filename . '"'); + header('Content-Length: ' . filesize($root_path . $example_file_data->directory_name . '/' . $example_file_data->filepath)); + ob_clean(); + readfile($root_path . $example_file_data->directory_name . '/' . $example_file_data->filepath); } - $zip_file_count = $zip->numFiles; - $zip->close(); - - if ($zip_file_count > 0) +function textbook_companion_download_sample_code() { - /* download zip file */ + $proposal_id = arg(3); + $root_path = textbook_companion_samplecode_path(); + $query = db_select('textbook_companion_proposal'); + $query->fields('textbook_companion_proposal'); + $query->condition('id', $proposal_id); + $query->range(0, 1); + $result = $query->execute(); + $example_file_data = $result->fetchObject(); + $samplecodename = substr($example_file_data->samplefilepath, strrpos($example_file_data->samplefilepath, '/') + 1); header('Content-Type: application/zip'); - header('Content-disposition: attachment; filename="EX' . $example_data->number . '.zip"'); - header('Content-Length: ' . filesize($zip_filename)); - readfile($zip_filename); - unlink($zip_filename); - } else { - drupal_set_message("There are no files in this examples to download", 'error'); - drupal_goto('textbook_runs'); - } -} - -function textbook_companion_download_chapter() -{ - $chapter_id = (int)arg(2); - $root_path = textbook_companion_path(); - - /* get example data */ - $chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE id = %d", $chapter_id); - $chapter_data = db_fetch_object($chapter_q); - $CH_PATH = 'CH' . $chapter_data->number . '/'; - - /* zip filename */ - $zip_filename = $root_path . 'zip-' . time() . '-' . rand(0, 999999) . '.zip'; - - /* creating zip archive on the server */ - $zip = new ZipArchive; - $zip->open($zip_filename, ZipArchive::CREATE); - - $example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE chapter_id = %d AND approval_status = 1", $chapter_id); - while ($example_row = db_fetch_object($example_q)) - { - $EX_PATH = 'EX' . $example_row->number . '/'; - $example_files_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE example_id = %d", $example_row->id); - while ($example_files_row = db_fetch_object($example_files_q)) - { - $zip->addFile($root_path . $example_files_row->filepath, $CH_PATH . $EX_PATH . $example_files_row->filename); - } + header('Content-disposition: attachment; filename="' . $samplecodename . '"'); + header('Content-Length: ' . filesize($root_path . $example_file_data->samplefilepath)); + ob_clean(); + readfile($root_path . $example_file_data->samplefilepath); } - $zip_file_count = $zip->numFiles; - $zip->close(); - - if ($zip_file_count > 0) +function textbook_companion_download_dependency_file() { - /* download zip file */ + $dependency_file_id = arg(3); + $root_path = textbook_companion_path(); + /*$dependency_file_q = db_query("SELECT * FROM {textbook_companion_dependency_files} WHERE id = %d LIMIT 1", $dependency_file_id); + $dependency_file_data = db_fetch_object($dependency_file_q);*/ + $query = db_select('textbook_companion_example_files'); + $query->fields('textbook_companion_example_files'); + $query->condition('id', $example_file_id); + $query->range(0, 1); + $result = $query->execute(); + $example_file_data = $result->fetchObject(); + header('Content-Type: ' . $dependency_file_data->filemime); + header('Content-disposition: attachment; filename="' . $dependency_file_data->filename . '"'); + header('Content-Length: ' . filesize($root_path . $dependency_file_data->filepath)); ob_clean(); - header('Content-Type: application/zip'); - header('Content-disposition: attachment; filename="CH' . $chapter_data->number . '.zip"'); - header('Content-Length: ' . filesize($zip_filename)); - readfile($zip_filename); - unlink($zip_filename); - } else { - drupal_set_message("There are no examples in this chapter to download", 'error'); - drupal_goto('textbook_run'); + readfile($root_path . $dependency_file_data->filepath); + exit; } -} - -function textbook_companion_download_book() -{ - $book_id = arg(2); - $root_path = textbook_companion_path(); - /* get example data */ - $book_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d", $book_id); - $book_data = db_fetch_object($book_q); - $zipname = str_replace(' ','_',($book_data->book)); - $BK_PATH = $zipname . '/'; - - /* zip filename */ - $zip_filename = $root_path . 'zip-' . time() . '-' . rand(0, 999999) . '.zip'; - - /* creating zip archive on the server */ - $zip = new ZipArchive; - $zip->open($zip_filename, ZipArchive::CREATE); - - $chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE preference_id = %d", $book_id); - while ($chapter_row = db_fetch_object($chapter_q)) +function textbook_companion_download_example() { - $CH_PATH = 'CH' . $chapter_row->number . '/'; - $example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE chapter_id = %d AND approval_status = 1", $chapter_row->id); - while ($example_row = db_fetch_object($example_q)) - { - $EX_PATH = 'EX' . $example_row->number . '/'; - $example_files_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE example_id = %d", $example_row->id); - $example_dependency_files_q = db_query("SELECT * FROM {textbook_companion_example_dependency} WHERE example_id = %d", $example_row->id); - while ($example_files_row = db_fetch_object($example_files_q)) + $example_id = arg(3); + $root_path = textbook_companion_path(); + $root_temp_path = textbook_companion_temp_path(); + /* get example data */ + /*$example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE id = %d", $example_id); + $example_data = db_fetch_object($example_q);*/ + $query = db_select('textbook_companion_example'); + $query->fields('textbook_companion_example'); + $query->condition('id', $example_id); + $result = $query->execute(); + $example_data = $result->fetchObject(); + /*$chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE id = %d", $example_data->chapter_id); + $chapter_data = db_fetch_object($chapter_q);*/ + $query = db_select('textbook_companion_chapter'); + $query->fields('textbook_companion_chapter'); + $query->condition('id', $example_data->chapter_id); + $result = $query->execute(); + $chapter_data = $result->fetchObject(); + /*$example_files_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE example_id = %d", $example_id);*/ + /* $query = db_select('textbook_companion_example_files'); + $query->fields('textbook_companion_example_files'); + $query->condition('example_id', $example_id); + $example_files_q = $query->execute();*/ + $example_files_q = db_query("select * from textbook_companion_preference tcp join textbook_companion_chapter tcc on tcp.id=tcc.preference_id join textbook_companion_example tce ON tcc.id=tce.chapter_id join textbook_companion_example_files tcef on tce.id=tcef.example_id where tcef.example_id= :example_id", array( + ':example_id' => $example_id + )); + $EX_PATH = 'EX' . $example_data->number . '/'; + /* zip filename */ + if (!is_dir($root_temp_path . 'tbc_download_temp')) + mkdir($root_temp_path . 'tbc_download_temp'); + $zip_filename = $root_temp_path .'tbc_download_temp/' . 'zip-' . time() . '-' . rand(0, 999999) . '.zip'; + /* creating zip archive on the server */ + $zip = new ZipArchive; + $zip->open($zip_filename, ZipArchive::CREATE); + while ($example_files_row = $example_files_q->fetchObject()) { - $zip->addFile($root_path . $example_files_row->filepath, $BK_PATH . $CH_PATH . $EX_PATH . $example_files_row->filename); + $zip->addFile($root_path . $example_files_row->directory_name . '/' . $example_files_row->filepath, $EX_PATH . $example_files_row->filename); } - /* dependency files */ - while ($example_dependency_files_row = db_fetch_object($example_dependency_files_q)) + $zip_file_count = $zip->numFiles; + $zip->close(); + if ($zip_file_count > 0) { - $dependency_file_data = db_fetch_object(db_query("SELECT * FROM {textbook_companion_dependency_files} WHERE id = %d LIMIT 1", $example_dependency_files_row->dependency_id)); - if ($dependency_file_data) - $zip->addFile($root_path . $dependency_file_data->filepath, $BK_PATH . $CH_PATH . $EX_PATH . 'DEPENDENCIES/' . $dependency_file_data->filename); + /* download zip file */ + header('Content-Type: application/octet-stream'); + header('Content-disposition: attachment; filename="EX' . $example_data->number . '.zip"'); + header('Content-Length: ' . filesize($zip_filename)); + ob_clean(); + readfile($zip_filename); + unlink($zip_filename); } - $query = "SELECT * FROM textbook_companion_dependency_files WHERE preference_id = %d"; - $result = db_query($query, $book_id); - while($row = db_fetch_object($result)) { - $zip->addFile($root_path . $row->filepath, $BK_PATH . 'DEPENDENCIES/' . $row->filename); + else + { + drupal_set_message("There are no files in this examples to download", 'error'); + drupal_goto('textbook-companion/textbook-run'); } - } } - $zip_file_count = $zip->numFiles; - $zip->close(); - - if ($zip_file_count > 0) +function textbook_companion_download_chapter() { - /* download zip file */ - global $user; - if($user->uid){ - header('Content-Type: application/zip'); - header('Content-disposition: attachment; filename="' . str_replace(' ','_',($book_data->book)) . '.zip"'); - header('Content-Length: ' . filesize($zip_filename)); - ob_clean(); - readfile($zip_filename); - unlink($zip_filename); - }else{ + $chapter_id = arg(3); + //var_dump($chapter_id);die; + $root_path = textbook_companion_path(); + /* get example data */ + /*$chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE id = %d", $chapter_id); + $chapter_data = db_fetch_object($chapter_q);*/ + $query = db_select('textbook_companion_chapter'); + $query->fields('textbook_companion_chapter'); + $query->condition('id', $chapter_id); + $result = $query->execute(); + $chapter_data = $result->fetchObject(); + $CH_PATH = 'CH' . $chapter_data->number . '/'; + /* zip filename */ +if (!is_dir($root_temp_path . 'tbc_download_temp')) + mkdir($root_temp_path . 'tbc_download_temp'); + $zip_filename = $root_temp_path .'tbc_download_temp/' . 'zip-' . time() . '-' . rand(0, 999999) . '.zip'; + + /* creating zip archive on the server */ + $zip = new ZipArchive; + $zip->open($zip_filename, ZipArchive::CREATE); + /*$example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE chapter_id = %d AND approval_status = 1", $chapter_id);*/ + $query = db_select('textbook_companion_example'); + $query->fields('textbook_companion_example'); + $query->condition('chapter_id', $chapter_id); + $query->condition('approval_status', 1); + $example_q = $query->execute(); + while ($example_row = $example_q->fetchObject()) + { + $EX_PATH = 'EX' . $example_row->number . '/'; + /*$example_files_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE example_id = %d", $example_row->id);*/ + /*$query = db_select('textbook_companion_example_files'); + $query->fields('textbook_companion_example_files'); + $query->condition('example_id', $example_row->id); + $example_files_q = $query->execute();*/ + $example_files_q = db_query("select * from textbook_companion_preference tcp join textbook_companion_chapter tcc on tcp.id=tcc.preference_id join textbook_companion_example tce ON tcc.id=tce.chapter_id join textbook_companion_example_files tcef on tce.id=tcef.example_id where tcef.example_id= :example_id", array( + ':example_id' => $example_row->id + )); + while ($example_files_row = $example_files_q->fetchObject()) + { + $zip->addFile($root_path . $example_files_row->directory_name . '/' . $example_files_row->filepath, $CH_PATH . $EX_PATH . $example_files_row->filename); + } + } + $zip_file_count = $zip->numFiles; + $zip->close(); + if ($zip_file_count > 0) + { + /* download zip file */ header('Content-Type: application/zip'); - header('Content-disposition: attachment; filename="' . str_replace(' ','_',($book_data->book)) . '.zip"'); + header('Content-disposition: attachment; filename="CH' . $chapter_data->number . '.zip"'); header('Content-Length: ' . filesize($zip_filename)); - header("Content-Transfer-Encoding: binary"); - header('Expires: 0'); - header('Pragma: no-cache'); - ob_end_flush(); ob_clean(); - flush(); readfile($zip_filename); unlink($zip_filename); - } - } else { - drupal_set_message("There are no examples in this book to download", 'error'); - drupal_goto('textbook_runs'); + } + else + { + drupal_set_message("There are no examples in this chapter to download", 'error'); + drupal_goto('textbook-companion/textbook-run'); + } + } +function textbook_companion_download_book() + { + $book_id = arg(3); + $root_path = textbook_companion_path(); + $root_temp_path = textbook_companion_temp_path(); + /* get example data */ + /*$book_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d", $book_id); + $book_data = db_fetch_object($book_q);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('id', $book_id); + $result = $query->execute(); + $book_data = $result->fetchObject(); + $zipname = str_replace(' ', '_', ($book_data->book)); + $directory_name = $book_data->directory_name; + $BK_PATH = $zipname . '/'; + /* zip filename */ + if (!is_dir($root_temp_path . 'tbc_download_temp')) + mkdir($root_temp_path . 'tbc_download_temp'); + $zip_filename = $root_temp_path .'tbc_download_temp/' . 'zip-' . time() . '-' . rand(0, 999999) . '.zip'; + /* creating zip archive on the server */ + $zip = new ZipArchive(); + $zip->open($zip_filename, ZipArchive::CREATE); + /*$chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE preference_id = %d", $book_id);*/ + $query = db_select('textbook_companion_chapter'); + $query->fields('textbook_companion_chapter'); + $query->condition('preference_id', $book_id); + $chapter_q = $query->execute(); + while ($chapter_row = $chapter_q->fetchObject()) + { + $CH_PATH = 'CH' . $chapter_row->number . '/'; + /*$example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE chapter_id = %d AND approval_status = 1", $chapter_row->id);*/ + $query = db_select('textbook_companion_example'); + $query->fields('textbook_companion_example'); + $query->condition('chapter_id', $chapter_row->id); + $query->condition('approval_status', 1); + $example_q = $query->execute(); + while ($example_row = $example_q->fetchObject()) + { + $EX_PATH = 'EX' . $example_row->number . '/'; + /*$example_files_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE example_id = %d", $example_row->id);*/ + $query = db_select('textbook_companion_example_files'); + $query->fields('textbook_companion_example_files'); + $query->condition('example_id', $example_row->id); + $example_files_q = $query->execute(); + while ($example_files_row = $example_files_q->fetchObject()) + { + $zip->addFile($root_path . $directory_name . '/' . $example_files_row->filepath, $BK_PATH . $CH_PATH . $EX_PATH . $example_files_row->filename); + } + } + } + $zip_file_count = $zip->numFiles; + $zip->close(); + if ($zip_file_count > 0) + { + /* download zip file */ + global $user; + if ($user->uid) + { + header('Content-Type: application/zip'); + header('Content-disposition: attachment; filename="' . str_replace(' ', '_', ($book_data->book)) . '.zip"'); + header('Content-Length: ' . filesize($zip_filename)); + ob_clean(); + readfile($zip_filename); + unlink($zip_filename); + } + else + { + header('Content-Type: application/zip'); + header('Content-disposition: attachment; filename="' . str_replace(' ', '_', ($book_data->book)) . '.zip"'); + header('Content-Length: ' . filesize($zip_filename)); + header("Content-Transfer-Encoding: binary"); + header('Expires: 0'); + header('Pragma: no-cache'); + ob_end_flush(); + ob_clean(); + flush(); + readfile($zip_filename); + unlink($zip_filename); + } + } + else + { + drupal_set_message("There are no examples in this book to download", 'error'); + drupal_goto('textbook-companion/textbook-run'); + } } -} - diff --git a/editcode.inc b/editcode.inc index 39d751e..972f487 100755 --- a/editcode.inc +++ b/editcode.inc @@ -1,1110 +1,716 @@ <?php // $Id$ - /******************************************************************************/ /***************************** EDIT EXAMPLE ***********************************/ /******************************************************************************/ - -function upload_examples_edit_form($form_state) -{ - global $user; - $example_id = arg(3); - - /* get example details */ - $example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE id = %d LIMIT 1", $example_id); - $example_data = db_fetch_object($example_q); - if (!$example_q) - { - drupal_set_message(t("Invalid example selected."), 'error'); - drupal_goto(''); - return; - } - if ($example_data->approval_status != 0) - { - drupal_set_message(t("You cannot edit an example after it has been approved or dis-approved. Please contact site administrator if you want to edit this example."), 'error'); - drupal_goto(''); - return; - } - - /* get examples files */ - $source_file = ""; $source_id = 0; - $result1_file = ""; $result1_id = 0; - $result2_file = ""; $result2_id = 0; - $xcos1_file = ""; $xcos1_id = 0; - $xcos2_file = ""; $xcos2_id = 0; - - $example_files_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE example_id = %d", $example_id); - while ($example_files_data = db_fetch_object($example_files_q)) - { - if ($example_files_data->filetype == "S") - { - $source_file = l($example_files_data->filename, 'download/file/' . $example_files_data->id); - $source_file_id = $example_files_data->id; - } - if ($example_files_data->filetype == "R") - { - if (strlen($result1_file) == 0) +function upload_examples_edit_form($form, $form_state) + { + global $user; + $example_id = arg(3); + /* get example details */ + /*$example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE id = %d LIMIT 1", $example_id); + $example_data = db_fetch_object($example_q);*/ + $query = db_select('textbook_companion_example'); + $query->fields('textbook_companion_example'); + $query->condition('id', $example_id); + $query->range(0, 1); + $example_q = $query->execute(); + $example_data = $example_q->fetchObject(); + if (!$example_q) { - $result1_file = l($example_files_data->filename, 'download/file/' . $example_files_data->id); - $result1_file_id = $example_files_data->id; - } else { - $result2_file = l($example_files_data->filename, 'download/file/' . $example_files_data->id); - $result2_file_id = $example_files_data->id; + drupal_set_message(t("Invalid example selected."), 'error'); + drupal_goto(''); + return; } - } - if ($example_files_data->filetype == "X") - { - if (strlen($xcos1_file) <= 0) + if ($example_data->approval_status != 0) { - $xcos1_file = l($example_files_data->filename, 'download/file/' . $example_files_data->id); - $xcos1_file_id = $example_files_data->id; - } else { - $xcos2_file = l($example_files_data->filename, 'download/file/' . $example_files_data->id); - $xcos2_file_id = $example_files_data->id; + drupal_set_message(t("You cannot edit an example after it has been approved or dis-approved. Please contact site administrator if you want to edit this example."), 'error'); + drupal_goto(''); + return; } - } - } - - /* get chapter details */ - $chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE id = %d", $example_data->chapter_id); - $chapter_data = db_fetch_object($chapter_q); - if (!$chapter_data) - { - drupal_set_message(t("Invalid chapter selected."), 'error'); - drupal_goto(''); - return; - } - - /* get preference details */ - $preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d", $chapter_data->preference_id); - $preference_data = db_fetch_object($preference_q); - if (!$preference_data) - { - drupal_set_message(t("Invalid book selected."), 'error'); - drupal_goto(''); - return; - } - if ($preference_data->approval_status != 1) - { - drupal_set_message(t("Cannot edit example. Either the book proposal has not been approved or it has been rejected."), 'error'); - drupal_goto(''); - return; - } - - /* get proposal details */ - $proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d", $preference_data->proposal_id); - $proposal_data = db_fetch_object($proposal_q); - if (!$proposal_data) - { - drupal_set_message(t("Invalid proposal selected."), 'error'); - drupal_goto(''); - return; - } - if ($proposal_data->uid != $user->uid) - { - drupal_set_message(t("You do not have permissions to edit this example."), 'error'); - drupal_goto(''); - return; - } - - $user_data = user_load($proposal_data->uid); - - /* add javascript for automatic book title, check if example uploaded, dependency selection effects */ - $chapter_name_js = " $(document).ready(function() { - $('#edit-existing-depfile-dep-book-title').change(function() { - var dep_selected = ''; - /* showing and hiding relevant files */ - $('.form-checkboxes .option').hide(); - $('.form-checkboxes .option').each(function(index) { - var activeClass = $('#edit-existing-depfile-dep-book-title').val(); - if ($(this).children().hasClass(activeClass)) { - $(this).show(); - } - if ($(this).children().attr('checked') == true) { - dep_selected += $(this).children().next().text() + '<br />'; - } - }); - /* showing list of already existing dependencies */ - $('#existing_depfile_selected').html(dep_selected); - }); - - $('.form-checkboxes .option').change(function() { - $('#edit-existing-depfile-dep-book-title').trigger('change'); - }); - $('#edit-existing-depfile-dep-book-title').trigger('change'); - });"; - drupal_add_js($chapter_name_js, 'inline', 'header'); - - $form['#redirect'] = 'textbook_companion/code'; - $form['#attributes'] = array('enctype' => "multipart/form-data"); - - $form['book_details']['book'] = array( - '#type' => 'item', - '#value' => $preference_data->book, - '#title' => t('Title of the Book'), - ); - $form['contributor_name'] = array( - '#type' => 'item', - '#value' => $proposal_data->full_name, - '#title' => t('Contributor Name'), - ); - $form['number'] = array( - '#type' => 'item', - '#title' => t('Chapter No'), - '#value' => $chapter_data->number, - ); - $form['name'] = array( - '#type' => 'item', - '#title' => t('Title of the Chapter'), - '#value' => $chapter_data->name, - ); - $form['example_number'] = array( - '#type' => 'item', - '#title' => t('Example No'), - '#value' => $example_data->number, - ); - $form['example_caption'] = array( - '#type' => 'textfield', - '#title' => t('Caption'), - '#size' => 40, - '#maxlength' => 255, - '#required' => TRUE, - '#default_value' => $example_data->caption, - ); - $form['example_warning'] = array( - '#type' => 'item', - '#title' => t('You should upload all the files (main or source files, result files, executable file if any)'), - '#prefix' => '<div style="color:red">', - '#suffix' => '</div>', - ); - - $form['sourcefile'] = array( - '#type' => 'fieldset', - '#title' => t('Main or Source Files'), - '#collapsible' => FALSE, - '#collapsed' => FALSE, - ); - if ($source_file) - { - $form['sourcefile']['cur_source'] = array( - '#type' => 'item', - '#title' => t('Existing Main or Source File'), - '#value' => $source_file, - ); - $form['sourcefile']['cur_source_checkbox'] = array( - '#type' => 'checkbox', - '#title' => t('Delete Existing Main or Source File'), - '#description' => 'Check to delete the existing Main or Source file.', - ); - $form['sourcefile']['sourcefile1'] = array( - '#type' => 'file', - '#title' => t('Upload New Main or Source File'), - '#size' => 48, - '#description' => t("Upload new Main or Source file above if you want to replace the existing file. Leave blank if you want to keep using the existing file. <br />") . - t('Allowed file extensions : ') . variable_get('textbook_companion_source_extensions', ''), - ); - $form['sourcefile']['cur_source_file_id'] = array( - '#type' => 'hidden', - '#value' => $source_file_id, - ); - } else { - $form['sourcefile']['sourcefile1'] = array( - '#type' => 'file', - '#title' => t('Upload New Main or Source File'), - '#size' => 48, - '#description' => t('Allowed file extensions : ') . variable_get('textbook_companion_source_extensions', ''), - ); - } - - $form['dep_files'] = array( - '#type' => 'item', - '#title' => t('Dependency Files'), - ); - - /************ START OF EXISTING DEPENDENCIES **************/ - - $dependency_files = array(); - $dependency_q = db_query("SELECT * FROM {textbook_companion_example_dependency} WHERE example_id = %d", $example_data->id); - while ($dependency_data = db_fetch_object($dependency_q)) - { - $dependency_files[] = $dependency_data->dependency_id; - } - - /* existing dependencies */ - $form['existing_depfile'] = array( - '#type' => 'fieldset', - '#title' => t('Use Already Existing Dependency Files'), - '#collapsible' => FALSE, - '#collapsed' => FALSE, - '#prefix' => '<div id="existing-depfile-wrapper">', - '#suffix' => '</div>', - '#tree' => TRUE, - ); - - /* existing dependencies */ - $form['existing_depfile']['selected'] = array( - '#type' => 'item', - '#title' => t('Existing Dependency Files Selected'), - '#value' => '<div id="existing_depfile_selected"></div>', - ); - - $form['existing_depfile']['dep_book_title'] = array( - '#type' => 'select', - '#title' => t('Title of the Book'), - '#options' => _list_of_book_titles(), - ); - - list($files_options, $files_options_class) = _list_of_book_dependency_files(); - $form['existing_depfile']['dep_chapter_example_files'] = array( - '#type' => 'checkboxes', - '#title' => t('Dependency Files'), - '#options' => $files_options, - '#options_class' => $files_options_class, - '#multiple' => TRUE, - '#default_value' => $dependency_files, - ); - - $form['existing_depfile']['dep_upload'] = array( - '#type' => 'item', - '#value' => l('Upload New Depedency Files', 'textbook_companion/code/upload_dep'), - ); - /************ END OF EXISTING DEPENDENCIES **************/ - - $form['result'] = array( - '#type' => 'fieldset', - '#title' => t('Result Files'), - '#collapsible' => FALSE, - '#collapsed' => FALSE, - ); - if ($result1_file) - { - $form['result']['cur_result1'] = array( - '#type' => 'item', - '#title' => t('Existing Result File 1'), - '#value' => $result1_file, - ); - $form['result']['cur_result1_checkbox'] = array( - '#type' => 'checkbox', - '#title' => t('Delete Existing Result File 1'), - '#description' => 'Check to delete the existing Result file.', - ); - $form['result']['result1'] = array( - '#type' => 'file', - '#title' => t('Upload New Result File 1'), - '#size' => 48, - '#description' => t("Upload new Result file above if you want to replace the existing file, leave blank if you want to keep using the existing file. <br />") . - t('Allowed file extensions : ') . variable_get('textbook_companion_result_extensions', ''), - ); - $form['result']['cur_result1_file_id'] = array( - '#type' => 'hidden', - '#value' => $result1_file_id, - ); - } else { - $form['result']['result1'] = array( - '#type' => 'file', - '#title' => t('Upload New Result File 1'), - '#size' => 48, - '#description' => t('Allowed file extensions : ') . variable_get('textbook_companion_result_extensions', ''), - ); - } - - $form['result']['br'] = array( - '#type' => 'item', - '#value' => "<br />", - ); - - if ($result2_file) - { - $form['result']['cur_result2'] = array( - '#type' => 'item', - '#title' => t('Existing Result File 2'), - '#value' => $result2_file, - ); - $form['result']['cur_result2_checkbox'] = array( - '#type' => 'checkbox', - '#title' => t('Delete Existing Result File 2'), - '#description' => 'Check to delete the existing Result file.', - ); - $form['result']['result2'] = array( - '#type' => 'file', - '#title' => t('Upload New Result file 2'), - '#size' => 48, - '#description' => t("Upload new Result file above if you want to replace the existing file. Leave blank if you want to keep using the existing file. <br />") . - t('Allowed file extensions : ') . variable_get('textbook_companion_result_extensions', ''), - ); - $form['result']['cur_result2_file_id'] = array( - '#type' => 'hidden', - '#value' => $result2_file_id, - ); - } else { - $form['result']['result2'] = array( - '#type' => 'file', - '#title' => t('Upload New Result file 2'), - '#size' => 48, - '#description' => t('Allowed file extensions : ') . variable_get('textbook_companion_result_extensions', ''), + /* get examples files */ + $source_file = ""; + $source_id = 0; + $result1_file = ""; + $result1_id = 0; + $result2_file = ""; + $result2_id = 0; + $xcos1_file = ""; + $xcos1_id = 0; + $xcos2_file = ""; + $xcos2_id = 0; + /*$example_files_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE example_id = %d", $example_id);*/ + $query = db_select('textbook_companion_example_files'); + $query->fields('textbook_companion_example_files'); + $query->condition('example_id', $example_id); + $example_files_q = $query->execute(); + while ($example_files_data = $example_files_q->fetchObject()) + { + if ($example_files_data->filetype == "S") + { + $source_file = l($example_files_data->filename, 'textbook-companion/download/file/' . $example_files_data->id); + $source_file_id = $example_files_data->id; + //var_dump($source_file);die; + } + } + /* get chapter details */ + /*$chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE id = %d", $example_data->chapter_id); + $chapter_data = db_fetch_object($chapter_q);*/ + $query = db_select('textbook_companion_chapter'); + $query->fields('textbook_companion_chapter'); + $query->condition('id', $example_data->chapter_id); + $result = $query->execute(); + $chapter_data = $result->fetchObject(); + if (!$chapter_data) + { + drupal_set_message(t("Invalid chapter selected."), 'error'); + drupal_goto(''); + return; + } + /* get preference details */ + /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d", $chapter_data->preference_id); + $preference_data = db_fetch_object($preference_q);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('id', $chapter_data->preference_id); + $result = $query->execute(); + $preference_data = $result->fetchObject(); + if (!$preference_data) + { + drupal_set_message(t("Invalid book selected."), 'error'); + drupal_goto(''); + return; + } + if ($preference_data->approval_status != 1) + { + drupal_set_message(t("Cannot edit example. Either the book proposal has not been approved or it has been rejected."), 'error'); + drupal_goto(''); + return; + } + /* get proposal details */ + /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d", $preference_data->proposal_id); + $proposal_data = db_fetch_object($proposal_q);*/ + $query = db_select('textbook_companion_proposal'); + $query->fields('textbook_companion_proposal'); + $query->condition('id', $preference_data->proposal_id); + $result = $query->execute(); + $proposal_data = $result->fetchObject(); + if (!$proposal_data) + { + drupal_set_message(t("Invalid proposal selected."), 'error'); + drupal_goto(''); + return; + } + if ($proposal_data->uid != $user->uid) + { + drupal_set_message(t("You do not have permissions to edit this example."), 'error'); + drupal_goto(''); + return; + } + $user_data = user_load($proposal_data->uid); + $form['#redirect'] = 'textbook-companion/code'; + $form['#attributes'] = array( + 'enctype' => "multipart/form-data" ); - } - $form['xcos'] = array( - '#type' => 'fieldset', - '#title' => t('XCOS Files'), - '#collapsible' => FALSE, - '#collapsed' => FALSE, - ); - if ($xcos1_file) - { - $form['xcos']['cur_xcos1'] = array( - '#type' => 'item', - '#title' => t('Existing xcos File 1'), - '#value' => $xcos1_file, + $form['book_details']['book'] = array( + '#type' => 'item', + '#markup' => $preference_data->book, + '#title' => t('Title of the Book') ); - $form['xcos']['cur_xcos1_checkbox'] = array( - '#type' => 'checkbox', - '#title' => t('Delete Existing xcos File 1'), - '#description' => 'Check to delete the existing xcos file.', + $form['contributor_name'] = array( + '#type' => 'item', + '#markup' => $proposal_data->full_name, + '#title' => t('Contributor Name') ); - $form['xcos']['xcos1'] = array( - '#type' => 'file', - '#title' => t('Upload New xcos file 1'), - '#size' => 48, - '#description' => t("Upload new xcos file above if you want to replace the existing file. Leave blank if you want to keep using the existing file. <br />") . - t('Allowed file extensions : ') . variable_get('textbook_companion_xcos_extensions', ''), + $form['number'] = array( + '#type' => 'item', + '#title' => t('Chapter No'), + '#markup' => $chapter_data->number ); - $form['sourcefile']['cur_xcos1_file_id'] = array( - '#type' => 'hidden', - '#value' => $xcos1_file_id, + $form['name'] = array( + '#type' => 'item', + '#title' => t('Title of the Chapter'), + '#markup' => $chapter_data->name ); - } else { - $form['xcos']['xcos1'] = array( - '#type' => 'file', - '#title' => t('Upload New xcos file 1'), - '#size' => 48, - '#description' => t('Allowed file extensions : ') . variable_get('textbook_companion_xcos_extensions', ''), + $form['example_number'] = array( + '#type' => 'item', + '#title' => t('Example No'), + '#markup' => $example_data->number ); - } - - $form['xcos']['br'] = array( - '#type' => 'item', - '#value' => "<br />", - ); - - if ($xcos2_file) - { - $form['xcos']['cur_xcos2'] = array( - '#type' => 'item', - '#title' => t('Existing xcos File 2'), - '#value' => $xcos2_file, + $form['example_caption'] = array( + '#type' => 'textfield', + '#title' => t('Caption'), + '#size' => 40, + '#maxlength' => 255, + '#required' => TRUE, + '#default_value' => $example_data->caption ); - $form['xcos']['cur_xcos2_checkbox'] = array( - '#type' => 'checkbox', - '#title' => t('Delete Existing xcos File 2'), - '#description' => 'Check to delete the existing xcos file.', + $form['example_warning'] = array( + '#type' => 'item', + '#title' => t('You should upload all the files (main or source files, result files, executable file if any)'), + '#prefix' => '<div style="color:red">', + '#suffix' => '</div>' ); - $form['xcos']['xcos2'] = array( - '#type' => 'file', - '#title' => t('Upload New xcos file 2'), - '#size' => 48, - '#description' => t("Upload new xcos file above if you want to replace the existing file. Leave blank if you want to keep using the existing file. <br />") . - t('Allowed file extensions : ') . variable_get('textbook_companion_xcos_extensions', ''), + $form['sourcefile'] = array( + '#type' => 'fieldset', + '#title' => t('Main or Source Files'), + '#collapsible' => FALSE, + '#collapsed' => FALSE ); - $form['xcos']['cur_xcos2_file_id'] = array( - '#type' => 'hidden', - '#value' => $xcos2_file_id, + if ($source_file) + { + $form['sourcefile']['cur_source'] = array( + '#type' => 'item', + '#title' => t('Existing Main or Source File'), + '#markup' => $source_file + ); + $form['sourcefile']['cur_source_checkbox'] = array( + '#type' => 'checkbox', + '#title' => t('Delete Existing Main or Source File'), + '#description' => 'Check to delete the existing Main or Source file.' + ); + $form['sourcefile']['sourcefile1'] = array( + '#type' => 'file', + '#title' => t('Upload New Main or Source File'), + '#size' => 48, + '#description' => t("Upload new Main or Source file above if you want to replace the existing file. Leave blank if you want to keep using the existing file. <br />") . t('Allowed file extensions : ') . variable_get('textbook_companion_source_extensions', '') + ); + $form['sourcefile']['cur_source_file_id'] = array( + '#type' => 'hidden', + '#value' => $source_file_id + ); + } + else + { + $form['sourcefile']['sourcefile1'] = array( + '#type' => 'file', + '#title' => t('Upload New Main or Source File'), + '#size' => 48, + '#description' => t('Allowed file extensions : ') . variable_get('textbook_companion_source_extensions', '') + ); + } + $form['submit'] = array( + '#type' => 'submit', + '#value' => t('Submit') ); - } else { - $form['xcos']['xcos2'] = array( - '#type' => 'file', - '#title' => t('Upload New xcos file 2'), - '#size' => 48, - '#description' => t('Allowed file extensions : ') . variable_get('textbook_companion_xcos_extensions', ''), + $form['cancel'] = array( + '#type' => 'item', + '#markup' => l(t('Cancel'), 'textbook-companion/code') ); + return $form; } - - $form['submit'] = array( - '#type' => 'submit', - '#value' => t('Submit') - ); - - $form['cancel'] = array( - '#type' => 'markup', - '#value' => l(t('Cancel'), 'textbook_companion/code'), - ); - return $form; -} - function upload_examples_edit_form_validate($form, &$form_state) -{ - if (!check_name($form_state['values']['example_caption'])) - form_set_error('example_caption', t('Example Caption can contain only alphabets, numbers and spaces.')); - - if (isset($_FILES['files'])) { - /* check for valid filename extensions */ - foreach ($_FILES['files']['name'] as $file_form_name => $file_name) - { - if ($file_name) + if (!check_name($form_state['values']['example_caption'])) + form_set_error('example_caption', t('Example Caption can contain only alphabets, numbers and spaces.')); + if (isset($_FILES['files'])) { - /* checking file type */ - if (strstr($file_form_name, 'source')) - $file_type = 'S'; - else if (strstr($file_form_name, 'result')) - $file_type = 'R'; - else if (strstr($file_form_name, 'xcos')) - $file_type = 'X'; - else - $file_type = 'U'; - - $allowed_extensions_str = ''; - switch ($file_type) - { - case 'S': - $allowed_extensions_str = variable_get('textbook_companion_source_extensions', ''); - break; - case 'R': - $allowed_extensions_str = variable_get('textbook_companion_result_extensions', ''); - break; - case 'X': - $allowed_extensions_str = variable_get('textbook_companion_xcos_extensions', ''); - break; - } - - $allowed_extensions = explode(',' , $allowed_extensions_str); - $temp_extension = end(explode('.', strtolower($_FILES['files']['name'][$file_form_name]))); - if (!in_array($temp_extension, $allowed_extensions)) - form_set_error($file_form_name, t('Only file with ' . $allowed_extensions_str . ' extensions can be uploaded.')); - if ($_FILES['files']['size'][$file_form_name] <= 0) - form_set_error($file_form_name, t('File size cannot be zero.')); - - /* check if valid file name */ - if (!textbook_companion_check_valid_filename($_FILES['files']['name'][$file_form_name])) - form_set_error($file_form_name, t('Invalid file name specified. Only alphabets, numbers and underscore is allowed as a valid filename.')); + /* check for valid filename extensions */ + foreach ($_FILES['files']['name'] as $file_form_name => $file_name) + { + if ($file_name) + { + /* checking file type */ + if (strstr($file_form_name, 'source')) + $file_type = 'S'; + else if (strstr($file_form_name, 'result')) + $file_type = 'R'; + else if (strstr($file_form_name, 'xcos')) + $file_type = 'X'; + else + $file_type = 'U'; + $allowed_extensions_str = ''; + switch ($file_type) + { + case 'S': + $allowed_extensions_str = variable_get('textbook_companion_source_extensions', ''); + break; + case 'R': + $allowed_extensions_str = variable_get('textbook_companion_result_extensions', ''); + break; + case 'X': + $allowed_extensions_str = variable_get('textbook_companion_xcos_extensions', ''); + break; + } + $allowed_extensions = explode(',', $allowed_extensions_str); + $temp_ext = explode('.', strtolower($_FILES['files']['name'][$file_form_name])); + $temp_extension = end($temp_ext); + if (!in_array($temp_extension, $allowed_extensions)) + form_set_error($file_form_name, t('Only file with ' . $allowed_extensions_str . ' extensions can be uploaded.')); + if ($_FILES['files']['size'][$file_form_name] <= 0) + form_set_error($file_form_name, t('File size cannot be zero.')); + /* check if valid file name */ + if (!textbook_companion_check_valid_filename($_FILES['files']['name'][$file_form_name])) + form_set_error($file_form_name, t('Invalid file name specified. Only alphabets, numbers and underscore is allowed as a valid filename.')); + } + } } - } - } - - /* add javascript again for automatic book title, check if example uploaded, dependency selection effects */ - $chapter_name_js = " $(document).ready(function() { + /* add javascript again for automatic book title, check if example uploaded, dependency selection effects */ + /*$chapter_name_js = " $(document).ready(function() { $('#edit-number').change(function() { - $.get('" . base_path() . "textbook_companion/ajax/chapter_title/' + $('#edit-number').val() + '/' + " . $row->pre_id . ", function(data) { - $('#edit-name').val(data); - }); + $.get('" . base_path() . "textbook-companion/ajax/chapter-title/' + $('#edit-number').val() + '/' + " . $row->pre_id . ", function(data) { + $('#edit-name').val(data); + }); }); $('#edit-example-number').change(function() { - $.get('" . base_path() . "textbook_companion/ajax/example_exists/' + $('#edit-number').val() + '/' + $('#edit-example-number').val(), function(data) { - if (data) { - alert(data); - } - }); + $.get('" . base_path() . "textbook-companion/ajax/example-exists/' + $('#edit-number').val() + '/' + $('#edit-example-number').val(), function(data) { + if (data) { + alert(data); + } + }); }); $('#edit-existing-depfile-dep-book-title').change(function() { - var dep_selected = ''; - /* showing and hiding relevant files */ - $('.form-checkboxes .option').hide(); - $('.form-checkboxes .option').each(function(index) { - var activeClass = $('#edit-existing-depfile-dep-book-title').val(); - if ($(this).children().hasClass(activeClass)) { - $(this).show(); - } - if ($(this).children().attr('checked') == true) { - dep_selected += $(this).children().next().text() + '<br />'; - } - }); - /* showing list of already existing dependencies */ - $('#existing_depfile_selected').html(dep_selected); + + var dep_selected = ''; + /* showing and hiding relevant files */ + /*$('.form-checkboxes .option').hide(); + $('.form-checkboxes .option').each(function(index) { + var activeClass = $('#edit-existing-depfile-dep-book-title').val(); + if ($(this).children().hasClass(activeClass)) { + $(this).show(); + } + if ($(this).children().attr('checked') == true) { + dep_selected += $(this).children().next().text() + '<br />'; + } + }); + /* showing list of already existing dependencies */ + /* $('#existing_depfile_selected').html(dep_selected); + }); - + $('.form-checkboxes .option').change(function() { - $('#edit-existing-depfile-dep-book-title').trigger('change'); + $('#edit-existing-depfile-dep-book-title').trigger('change'); }); $('#edit-existing-depfile-dep-book-title').trigger('change'); - });"; - drupal_add_js($chapter_name_js, 'inline', 'header'); -} - -function upload_examples_edit_form_submit($form, &$form_state) -{ - global $user; - $example_id = arg(3); - - /* get example details */ - $example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE id = %d LIMIT 1", $example_id); - $example_data = db_fetch_object($example_q); - if (!$example_q) - { - drupal_set_message(t("Invalid example selected."), 'error'); - drupal_goto(''); - return; - } - if ($example_data->approval_status != 0) - { - drupal_set_message(t("You cannot edit an example after it has been approved or dis-approved. Please contact site administrator if you want to edit this example."), 'error'); - drupal_goto(''); - return; - } - - /* get chapter details */ - $chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE id = %d", $example_data->chapter_id); - $chapter_data = db_fetch_object($chapter_q); - if (!$chapter_data) - { - drupal_set_message(t("Invalid chapter selected."), 'error'); - drupal_goto(''); - return; + });"; + drupal_add_js($chapter_name_js, 'inline', 'header');*/ } - - /* get preference details */ - $preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d", $chapter_data->preference_id); - $preference_data = db_fetch_object($preference_q); - if (!$preference_data) - { - drupal_set_message(t("Invalid book selected."), 'error'); - drupal_goto(''); - return; - } - if ($preference_data->approval_status != 1) - { - drupal_set_message(t("Cannot edit example. Either the book proposal has not been approved or it has been rejected."), 'error'); - drupal_goto(''); - return; - } - - /* get proposal details */ - $proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d", $preference_data->proposal_id); - $proposal_data = db_fetch_object($proposal_q); - if (!$proposal_data) - { - drupal_set_message(t("Invalid proposal selected."), 'error'); - drupal_goto(''); - return; - } - if ($proposal_data->uid != $user->uid) - { - drupal_set_message(t("You do not have permissions to edit this example."), 'error'); - drupal_goto(''); - return; - } - - /* creating directories */ - $root_path = textbook_companion_path(); - - $dest_path = $preference_data->id . '/'; - if (!is_dir($root_path . $dest_path)) - mkdir($root_path . $dest_path); - - $dest_path .= 'CH' . $chapter_data->number . '/'; - if (!is_dir($root_path . $dest_path)) - mkdir($root_path . $dest_path); - - $dest_path .= 'EX' . $example_data->number . '/'; - if (!is_dir($root_path . $dest_path)) - mkdir($root_path . $dest_path); - - /* updating example caption */ - db_query("UPDATE {textbook_companion_example} SET caption = '%s' WHERE id = %d", $form_state['values']['example_caption'], $example_id); - - /* handling dependencies */ - db_query("DELETE FROM {textbook_companion_example_dependency} WHERE example_id = %d", $example_data->id); - foreach ($form_state['values']['existing_depfile']['dep_chapter_example_files'] as $row) - { - if ($row > 0) - { - /* insterting into database */ - db_query("INSERT INTO {textbook_companion_example_dependency} (example_id, dependency_id, approval_status, timestamp) - VALUES (%d, %d, %d, %d)", - $example_data->id, - $row, - 0, - time() - ); - } - } - - /* handle source file */ - $cur_file_id = $form_state['values']['cur_source_file_id']; - if ($cur_file_id > 0) +function upload_examples_edit_form_submit($form, &$form_state) { - $file_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE id = %d AND example_id = %d", $cur_file_id, $example_data->id); - $file_data = db_fetch_object($file_q); - if (!$file_data) - { - drupal_set_message("Error deleting example source file. File not present in database.", 'error'); - return; - } - if (($form_state['values']['cur_source_checkbox'] == 1) && (!$_FILES['files']['name']['sourcefile1'])) - { - if (!delete_file($cur_file_id)) + global $user; + $example_id = arg(3); + /* get example details */ + /*$example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE id = %d LIMIT 1", $example_id); + $example_data = db_fetch_object($example_q);*/ + $query = db_select('textbook_companion_example'); + $query->fields('textbook_companion_example'); + $query->condition('id', $example_id); + $query->range(0, 1); + $example_q = $query->execute(); + $example_data = $example_q->fetchObject(); + if (!$example_q) { - drupal_set_message("Error deleting example source file.", 'error'); + drupal_set_message(t("Invalid example selected."), 'error'); + drupal_goto(''); return; } - } - } - if ($_FILES['files']['name']['sourcefile1']) - { - if ($cur_file_id > 0) - { - if (!delete_file($cur_file_id)) + if ($example_data->approval_status != 0) { - drupal_set_message("Error removing previous example source file.", 'error'); + drupal_set_message(t("You cannot edit an example after it has been approved or dis-approved. Please contact site administrator if you want to edit this example."), 'error'); + drupal_goto(''); return; } - } - if (file_exists($root_path . $dest_path . $_FILES['files']['name']['sourcefile1'])) - { - drupal_set_message(t("Error uploading source file. File !filename already exists.", array('!filename' => $_FILES['files']['name']['sourcefile1'])), 'error'); - return; - } - /* uploading file */ - if (move_uploaded_file($_FILES['files']['tmp_name']['sourcefile1'], $root_path . $dest_path . $_FILES['files']['name']['sourcefile1'])) - { - /* for uploaded files making an entry in the database */ - db_query("INSERT INTO {textbook_companion_example_files} (example_id, filename, filepath, filemime, filesize, filetype, timestamp) - VALUES (%d, '%s', '%s', '%s', %d, '%s', %d)", - $example_data->id, - $_FILES['files']['name']['sourcefile1'], - $dest_path . $_FILES['files']['name']['sourcefile1'], - $_FILES['files']['type']['sourcefile1'], - $_FILES['files']['size']['sourcefile1'], - 'S', - time() - ); - drupal_set_message($_FILES['files']['name']['sourcefile1'] . ' uploaded successfully.', 'status'); - } else { - drupal_set_message('Error uploading file : ' . $dest_path . '/' . $_FILES['files']['name']['sourcefile1'], 'error'); - } - } - - /* handle result1 file */ - $cur_file_id = $form_state['values']['cur_result1_file_id']; - if ($cur_file_id > 0) - { - $file_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE id = %d AND example_id = %d", $cur_file_id, $example_data->id); - $file_data = db_fetch_object($file_q); - if (!$file_data) - { - drupal_set_message("Error deleting example result 1 file. File not present in database.", 'error'); - return; - } - if (($form_state['values']['cur_result1_checkbox'] == 1) && (!$_FILES['files']['name']['result1'])) - { - if (!delete_file($cur_file_id)) + /* get chapter details */ + /*$chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE id = %d", $example_data->chapter_id); + $chapter_data = db_fetch_object($chapter_q);*/ + $query = db_select('textbook_companion_chapter'); + $query->fields('textbook_companion_chapter'); + $query->condition('id', $example_data->chapter_id); + $result = $query->execute(); + $chapter_data = $result->fetchObject(); + if (!$chapter_data) { - drupal_set_message("Error deleting example result 1 file.", 'error'); + drupal_set_message(t("Invalid chapter selected."), 'error'); + drupal_goto(''); return; } - } - } - if ($_FILES['files']['name']['result1']) - { - if ($cur_file_id > 0) - { - if (!delete_file($cur_file_id)) + /* get preference details */ + /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d", $chapter_data->preference_id); + $preference_data = db_fetch_object($preference_q);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('id', $chapter_data->preference_id); + $result = $query->execute(); + $preference_data = $result->fetchObject(); + if (!$preference_data) { - drupal_set_message("Error removing previous example result 1 file.", 'error'); + drupal_set_message(t("Invalid book selected."), 'error'); + drupal_goto(''); return; } - } - if (file_exists($root_path . $dest_path . $_FILES['files']['name']['result1'])) - { - drupal_set_message(t("Error uploading result 1 file. File !filename already exists.", array('!filename' => $_FILES['files']['name']['result1'])), 'error'); - return; - } - /* uploading file */ - if (move_uploaded_file($_FILES['files']['tmp_name']['result1'], $root_path . $dest_path . $_FILES['files']['name']['result1'])) - { - /* for uploaded files making an entry in the database */ - db_query("INSERT INTO {textbook_companion_example_files} (example_id, filename, filepath, filemime, filesize, filetype, timestamp) - VALUES (%d, '%s', '%s', '%s', %d, '%s', %d)", - $example_data->id, - $_FILES['files']['name']['result1'], - $dest_path . $_FILES['files']['name']['result1'], - $_FILES['files']['type']['result1'], - $_FILES['files']['size']['result1'], - 'R', - time() - ); - drupal_set_message($_FILES['files']['name']['result1'] . ' uploaded successfully.', 'status'); - } else { - drupal_set_message('Error uploading file : ' . $dest_path . '/' . $_FILES['files']['name']['result1'], 'error'); - } - } - - /* handle result2 file */ - $cur_file_id = $form_state['values']['cur_result2_file_id']; - if ($cur_file_id > 0) - { - $file_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE id = %d AND example_id = %d", $cur_file_id, $example_data->id); - $file_data = db_fetch_object($file_q); - if (!$file_data) - { - drupal_set_message("Error deleting example result 2 file. File not present in database.", 'error'); - return; - } - if (($form_state['values']['cur_result2_checkbox'] == 1) && (!$_FILES['files']['name']['result2'])) - { - if (!delete_file($cur_file_id)) + if ($preference_data->approval_status != 1) { - drupal_set_message("Error deleting example result 2 file.", 'error'); + drupal_set_message(t("Cannot edit example. Either the book proposal has not been approved or it has been rejected."), 'error'); + drupal_goto(''); return; } - } - } - if ($_FILES['files']['name']['result2']) - { - if ($cur_file_id > 0) - { - if (!delete_file($cur_file_id)) + /* get proposal details */ + /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d", $preference_data->proposal_id); + $proposal_data = db_fetch_object($proposal_q);*/ + $query = db_select('textbook_companion_proposal'); + $query->fields('textbook_companion_proposal'); + $query->condition('id', $preference_data->proposal_id); + $result = $query->execute(); + $proposal_data = $result->fetchObject(); + if (!$proposal_data) { - drupal_set_message("Error removing previous example result 2 file.", 'error'); + drupal_set_message(t("Invalid proposal selected."), 'error'); + drupal_goto(''); return; } - } - if (file_exists($root_path . $dest_path . $_FILES['files']['name']['result2'])) - { - drupal_set_message(t("Error uploading result 2 file. File !filename already exists.", array('!filename' => $_FILES['files']['name']['result2'])), 'error'); - return; - } - /* uploading file */ - if (move_uploaded_file($_FILES['files']['tmp_name']['result2'], $root_path . $dest_path . $_FILES['files']['name']['result2'])) - { - /* for uploaded files making an entry in the database */ - db_query("INSERT INTO {textbook_companion_example_files} (example_id, filename, filepath, filemime, filesize, filetype, timestamp) - VALUES (%d, '%s', '%s', '%s', %d, '%s', %d)", - $example_data->id, - $_FILES['files']['name']['result2'], - $dest_path . $_FILES['files']['name']['result2'], - $_FILES['files']['type']['result2'], - $_FILES['files']['size']['result2'], - 'R', - time() - ); - drupal_set_message($_FILES['files']['name']['result2'] . ' uploaded successfully.', 'status'); - } else { - drupal_set_message('Error uploading file : ' . $dest_path . '/' . $_FILES['files']['name']['result2'], 'error'); - } - } - - /* handle xcos1 file */ - $cur_file_id = $form_state['values']['cur_xcos1_file_id']; - if ($cur_file_id > 0) - { - $file_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE id = %d AND example_id = %d", $cur_file_id, $example_data->id); - $file_data = db_fetch_object($file_q); - if (!$file_data) - { - drupal_set_message("Error deleting example xcos 1 file. File not present in database.", 'error'); - return; - } - if (($form_state['values']['cur_xcos1_checkbox'] == 1) && (!$_FILES['files']['name']['xcos1'])) - { - if (!delete_file($cur_file_id)) + if ($proposal_data->uid != $user->uid) { - drupal_set_message("Error deleting example xcos 1 file.", 'error'); + drupal_set_message(t("You do not have permissions to edit this example."), 'error'); + drupal_goto(''); return; } - } - } - if ($_FILES['files']['name']['xcos1']) - { - if ($cur_file_id > 0) - { - if (!delete_file($cur_file_id)) + /* creating directories */ + $root_path = textbook_companion_path(); + $dest_path = $preference_data->directory_name . '/'; + if (!is_dir($root_path . $dest_path)) + mkdir($root_path . $dest_path); + $dest_path .= 'CH' . $chapter_data->number . '/'; + if (!is_dir($root_path . $dest_path)) + mkdir($root_path . $dest_path); + $dest_path .= 'EX' . $example_data->number . '/'; + if (!is_dir($root_path . $dest_path)) + mkdir($root_path . $dest_path); + $filepath = 'CH' . $chapter_data->number . '/' . 'EX' . $example_data->number . '/'; + /* updating example caption */ + /*db_query("UPDATE {textbook_companion_example} SET caption = '%s' WHERE id = %d", $form_state['values']['example_caption'], $example_id);*/ + $query = db_update('textbook_companion_example'); + $query->fields(array( + 'caption' => $form_state['values']['example_caption'] + )); + $query->condition('id', $example_id); + $num_updated = $query->execute(); + /* handle source file */ + if (isset($form_state['values']['cur_source_file_id'])) { - drupal_set_message("Error removing previous example xcos 1 file.", 'error'); - return; + $cur_file_id = $form_state['values']['cur_source_file_id']; } - } - if (file_exists($root_path . $dest_path . $_FILES['files']['name']['xcos1'])) - { - drupal_set_message(t("Error uploading xcos 1 file. File !filename already exists.", array('!filename' => $_FILES['files']['name']['xcos1'])), 'error'); - return; - } - /* uploading file */ - if (move_uploaded_file($_FILES['files']['tmp_name']['xcos1'], $root_path . $dest_path . $_FILES['files']['name']['xcos1'])) - { - /* for uploaded files making an entry in the database */ - db_query("INSERT INTO {textbook_companion_example_files} (example_id, filename, filepath, filemime, filesize, filetype, timestamp) - VALUES (%d, '%s', '%s', '%s', %d, '%s', %d)", - $example_data->id, - $_FILES['files']['name']['xcos1'], - $dest_path . $_FILES['files']['name']['xcos1'], - $_FILES['files']['type']['xcos1'], - $_FILES['files']['size']['xcos1'], - 'X', - time() - ); - drupal_set_message($_FILES['files']['name']['xcos1'] . ' uploaded successfully.', 'status'); - } else { - drupal_set_message('Error uploading file : ' . $dest_path . '/' . $_FILES['files']['name']['xcos1'], 'error'); - } - } - - /* handle xcos2 file */ - $cur_file_id = $form_state['values']['cur_xcos2_file_id']; - if ($cur_file_id > 0) - { - $file_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE id = %d AND example_id = %d", $cur_file_id, $example_data->id); - $file_data = db_fetch_object($file_q); - if (!$file_data) - { - drupal_set_message("Error deleting example xcos 2 file. File not present in database.", 'error'); - return; - } - if (($form_state['values']['cur_xcos2_checkbox'] == 1) && (!$_FILES['files']['name']['xcos2'])) - { - if (!delete_file($cur_file_id)) + else { - drupal_set_message("Error deleting example xcos 2 file.", 'error'); - return; + $cur_file_id = isset($form_state['values']['cur_source_file_id']); } - } - } - if ($_FILES['files']['name']['xcos2']) - { + //var_dump($cur_file_id);die; if ($cur_file_id > 0) - { - if (!delete_file($cur_file_id)) { - drupal_set_message("Error removing previous example xcos 2 file.", 'error'); - return; + /*$file_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE id = %d AND example_id = %d", $cur_file_id, $example_data->id); + $file_data = db_fetch_object($file_q);*/ + //var_dump($cur_file_id. $example_data->id);die; + $query = db_select('textbook_companion_example_files'); + $query->fields('textbook_companion_example_files'); + $query->condition('id', $cur_file_id); + $query->condition('example_id', $example_data->id); + $result = $query->execute(); + $file_data = $result->fetchObject(); + if (!$file_data) + { + drupal_set_message("Error deleting example source file. File not present in database.", 'error'); + return; + } + if (($form_state['values']['cur_source_checkbox'] == 1) && (!$_FILES['files']['name']['sourcefile1'])) + { + if (!delete_file($cur_file_id)) + { + drupal_set_message("Error deleting example source file.", 'error'); + return; + } + } } - } - if (file_exists($root_path . $dest_path . $_FILES['files']['name']['xcos2'])) - { - drupal_set_message(t("Error uploading xcos 2 file. File !filename already exists.", array('!filename' => $_FILES['files']['name']['xcos2'])), 'error'); - return; - } - /* uploading file */ - if (move_uploaded_file($_FILES['files']['tmp_name']['xcos2'], $root_path . $dest_path . $_FILES['files']['name']['xcos2'])) - { - /* for uploaded files making an entry in the database */ - db_query("INSERT INTO {textbook_companion_example_files} (example_id, filename, filepath, filemime, filesize, filetype, timestamp) - VALUES (%d, '%s', '%s', '%s', %d, '%s', %d)", - $example_data->id, - $_FILES['files']['name']['xcos2'], - $dest_path . $_FILES['files']['name']['xcos2'], - $_FILES['files']['type']['xcos2'], - $_FILES['files']['size']['xcos2'], - 'X', - time() - ); - drupal_set_message($_FILES['files']['name']['xcos2'] . ' uploaded successfully.', 'status'); - } else { - drupal_set_message('Error uploading file : ' . $dest_path . '/' . $_FILES['files']['name']['xcos2'], 'error'); - } + if ($_FILES['files']['name']['sourcefile1']) + { + if ($cur_file_id > 0) + { + if (!delete_file($cur_file_id)) + { + drupal_set_message("Error removing previous example source file.", 'error'); + return; + } + } + if (file_exists($root_path . $dest_path . $_FILES['files']['name']['sourcefile1'])) + { + drupal_set_message(t("Error uploading source file. File !filename already exists.", array( + '!filename' => $_FILES['files']['name']['sourcefile1'] + )), 'error'); + return; + } + /* uploading file */ + if (move_uploaded_file($_FILES['files']['tmp_name']['sourcefile1'], $root_path . $dest_path . $_FILES['files']['name']['sourcefile1'])) + { + /* for uploaded files making an entry in the database */ + /*db_query("INSERT INTO {textbook_companion_example_files} (example_id, filename, filepath, filemime, filesize, filetype, timestamp) + VALUES (%d, '%s', '%s', '%s', %d, '%s', %d)", + $example_data->id, + $_FILES['files']['name']['sourcefile1'], + $dest_path . $_FILES['files']['name']['sourcefile1'], + $_FILES['files']['type']['sourcefile1'], + $_FILES['files']['size']['sourcefile1'], + 'S', + time() + );*/ + $query = "INSERT INTO {textbook_companion_example_files} (example_id, filename, filepath, filemime, filesize, filetype, timestamp) VALUES (:example_id, :filename, :filepath, :filemime, :filesize, :filetype,:timestamp)"; + $args = array( + ":example_id" => $example_data->id, + ":filename" => $_FILES['files']['name']['sourcefile1'], + ":filepath" => $filepath . $_FILES['files']['name']['sourcefile1'], + ":filemime" => 'application/dwxml', + ":filesize" => $_FILES['files']['size']['sourcefile1'], + ":filetype" => 'S', + ":timestamp" => time() + ); + $result = db_query($query, $args, array( + 'return' => Database::RETURN_INSERT_ID + )); + drupal_set_message($_FILES['files']['name']['sourcefile1'] . ' uploaded successfully.', 'status'); + } + else + { + drupal_set_message('Error uploading file : ' . $dest_path . '/' . $_FILES['files']['name']['sourcefile1'], 'error'); + } + } + /* sending email */ + $email_to = $user->mail; + $from = variable_get('textbook_companion_from_email', ''); + $bcc = variable_get('textbook_companion_emails', ''); + $cc = variable_get('textbook_companion_cc_emails', ''); + $param['example_updated']['example_id'] = $example_id; + $param['example_updated']['user_id'] = $user->uid; + $param['example_updated']['headers'] = array( + 'From' => $from, + 'MIME-Version' => '1.0', + 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes', + 'Content-Transfer-Encoding' => '8Bit', + 'X-Mailer' => 'Drupal', + 'Cc' => $cc, + 'Bcc' => $bcc + ); + if (!drupal_mail('textbook_companion', 'example_updated', $email_to, language_default(), $param, $from, TRUE)) + drupal_set_message('Error sending email message.', 'error'); + drupal_set_message(t("Example successfully udpated."), 'status'); } - - /* sending email */ - $email_to = $user->mail; - $param['example_updated']['example_id'] = $example_id; - $param['example_updated']['user_id'] = $user->uid; - if (!drupal_mail('textbook_companion', 'example_updated', $email_to, language_default(), $param, variable_get('textbook_companion_from_email', NULL), TRUE)) - drupal_set_message('Error sending email message.', 'error'); - - drupal_set_message(t("Example successfully udpated."), 'status'); -} - - /******************************************************************************/ /**************************** EDIT CHAPTER TITLE ******************************/ /******************************************************************************/ - -function edit_chapter_title_form($form_state) -{ - global $user; - - /************************ start approve book details ************************/ - $proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid = %d ORDER BY id DESC LIMIT 1", $user->uid); - $proposal_data = db_fetch_object($proposal_q); - if (!$proposal_data) - { - drupal_set_message("Please submit a " . l('proposal', 'proposal') . ".", 'error'); - drupal_goto('textbook_companion/code'); - } - if ($proposal_data->proposal_status != 1 && $proposal_data->proposal_status != 4) - { - switch ($proposal_data->proposal_status ) - { - case 0: - drupal_set_message(t('We have already received your proposal. We will get back to you soon.'), 'status'); - drupal_goto('textbook_companion/code'); - return; - break; - case 2: - drupal_set_message(t('Your proposal has been dis-approved. Please create another proposal ' . l('here', 'proposal') . '.'), 'error'); - drupal_goto('textbook_companion/code'); - return; - break; - case 3: - drupal_set_message(t('Congratulations! You have completed your last book proposal. You have to create another proposal ' . l('here', 'proposal') . '.'), 'status'); - drupal_goto('textbook_companion/code'); - return; - break; - default: - drupal_set_message(t('Invalid proposal state. Please contact site administrator for further information.'), 'error'); - drupal_goto('textbook_companion/code'); - return; - break; - } - } - - $preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND approval_status = 1 LIMIT 1", $proposal_data->id); - $preference_data = db_fetch_object($preference_q); - if (!$preference_data) - { - drupal_set_message(t('Invalid Book Preference status. Please contact site administrator for further information.'), 'error'); - drupal_goto('textbook_companion/code'); - return; - } - /************************ end approve book details **************************/ - - $chapter_id = arg(4); - - $chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE id = %d AND preference_id = %d", $chapter_id, $preference_data->id); - $chapter_data = db_fetch_object($chapter_q); - if (!$chapter_data) - { - drupal_set_message(t('Invalid chapter.'), 'error'); - drupal_goto('textbook_companion/code'); - return; +function edit_chapter_title_form($form, $form_state) + { + global $user; + /************************ start approve book details ************************/ + /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid = %d ORDER BY id DESC LIMIT 1", $user->uid); + $proposal_data = db_fetch_object($proposal_q);*/ + $query = db_select('textbook_companion_proposal'); + $query->fields('textbook_companion_proposal'); + $query->condition('uid', $user->uid); + $query->orderBy('id', 'DESC'); + $query->range(0, 1); + $result = $query->execute(); + $proposal_data = $result->fetchObject(); + if (!$proposal_data) + { + drupal_set_message("Please submit a " . l('proposal', 'textbook-companion/proposal') . ".", 'error'); + drupal_goto('textbook-companion/code'); + } + if ($proposal_data->proposal_status != 1 && $proposal_data->proposal_status != 4) + { + switch ($proposal_data->proposal_status) + { + case 0: + drupal_set_message(t('We have already received your proposal. We will get back to you soon.'), 'status'); + drupal_goto('textbook-companion/code'); + return; + break; + case 2: + drupal_set_message(t('Your proposal has been dis-approved. Please create another proposal ' . l('here', 'proposal') . '.'), 'error'); + drupal_goto('textbook-companion/code'); + return; + break; + case 3: + drupal_set_message(t('Congratulations! You have completed your last book proposal. You have to create another proposal ' . l('here', 'textbook-companion/proposal') . '.'), 'status'); + drupal_goto('textbook-companion/code'); + return; + break; + default: + drupal_set_message(t('Invalid proposal state. Please contact site administrator for further information.'), 'error'); + drupal_goto('textbook-companion/code'); + return; + break; + } + } + /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND approval_status = 1 LIMIT 1", $proposal_data->id); + $preference_data = db_fetch_object($preference_q);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('proposal_id', $proposal_data->id); + $query->condition('approval_status', 1); + $query->range(0, 1); + $result = $query->execute(); + $preference_data = $result->fetchObject(); + if (!$preference_data) + { + drupal_set_message(t('Invalid Book Preference status. Please contact site administrator for further information.'), 'error'); + drupal_goto('textbook-companion/code'); + return; + } + /************************ end approve book details **************************/ + $chapter_id = arg(4); + /*$chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE id = %d AND preference_id = %d", $chapter_id, $preference_data->id); + $chapter_data = db_fetch_object($chapter_q);*/ + $query = db_select('textbook_companion_chapter'); + $query->fields('textbook_companion_chapter'); + $query->condition('id', $chapter_id); + $query->condition('preference_id', $preference_data->id); + $result = $query->execute(); + $chapter_data = $result->fetchObject(); + if (!$chapter_data) + { + drupal_set_message(t('Invalid chapter.'), 'error'); + drupal_goto('textbook-companion/code'); + return; + } + $form['#redirect'] = 'textbook-companion/code'; + $form['book_details']['book'] = array( + '#type' => 'item', + '#markup' => $preference_data->book, + '#title' => t('Title of the Book') + ); + $form['contributor_name'] = array( + '#type' => 'item', + '#markup' => $proposal_data->full_name, + '#title' => t('Contributor Name') + ); + $form['number'] = array( + '#type' => 'item', + '#title' => t('Chapter No'), + '#markup' => $chapter_data->number + ); + $form['chapter_title'] = array( + '#type' => 'textfield', + '#title' => t('Title of the Chapter'), + '#size' => 40, + '#maxlength' => 255, + '#required' => TRUE, + '#default_value' => $chapter_data->name + ); + $form['submit'] = array( + '#type' => 'submit', + '#value' => t('Submit') + ); + $form['cancel'] = array( + '#type' => 'markup', + '#value' => l(t('Cancel'), 'textbook_companion/code') + ); + return $form; } - - $form['#redirect'] = 'textbook_companion/code'; - - $form['book_details']['book'] = array( - '#type' => 'item', - '#value' => $preference_data->book, - '#title' => t('Title of the Book'), - ); - $form['contributor_name'] = array( - '#type' => 'item', - '#value' => $proposal_data->full_name, - '#title' => t('Contributor Name'), - ); - $form['number'] = array( - '#type' => 'item', - '#title' => t('Chapter No'), - '#value' => $chapter_data->number, - ); - - $form['chapter_title'] = array( - '#type' => 'textfield', - '#title' => t('Title of the Chapter'), - '#size' => 40, - '#maxlength' => 255, - '#required' => TRUE, - '#default_value' => $chapter_data->name, - ); - - $form['submit'] = array( - '#type' => 'submit', - '#value' => t('Submit') - ); - $form['cancel'] = array( - '#type' => 'markup', - '#value' => l(t('Cancel'), 'textbook_companion/code'), - ); - return $form; -} - function edit_chapter_title_form_validate($form, &$form_state) -{ - if (!check_name($form_state['values']['chapter_title'])) - form_set_error('chapter_title', t('Title of the Chapter can contain only alphabets, numbers and spaces.')); -} - -function edit_chapter_title_form_submit($form, &$form_state) -{ - global $user; - - /************************ start approve book details ************************/ - $proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid = %d ORDER BY id DESC LIMIT 1", $user->uid); - $proposal_data = db_fetch_object($proposal_q); - if (!$proposal_data) - { - drupal_set_message("Please submit a " . l('proposal', 'proposal') . ".", 'error'); - drupal_goto('textbook_companion/code'); - } - if ($proposal_data->proposal_status != 1 && $proposal_data->proposal_status != 4) { - switch ($proposal_data->proposal_status ) - { - case 0: - drupal_set_message(t('We have already received your proposal. We will get back to you soon.'), 'status'); - drupal_goto('textbook_companion/code'); - return; - break; - case 2: - drupal_set_message(t('Your proposal has been dis-approved. Please create another proposal ' . l('here', 'proposal') . '.'), 'error'); - drupal_goto('textbook_companion/code'); - return; - break; - case 3: - drupal_set_message(t('Congratulations! You have completed your last book proposal. You have to create another proposal ' . l('here', 'proposal') . '.'), 'status'); - drupal_goto('textbook_companion/code'); - return; - break; - default: - drupal_set_message(t('Invalid proposal state. Please contact site administrator for further information.'), 'error'); - drupal_goto('textbook_companion/code'); - return; - break; - } - } - - $preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND approval_status = 1 LIMIT 1", $proposal_data->id); - $preference_data = db_fetch_object($preference_q); - if (!$preference_data) - { - drupal_set_message(t('Invalid Book Preference status. Please contact site administrator for further information.'), 'error'); - drupal_goto('textbook_companion/code'); - return; + if (!check_name($form_state['values']['chapter_title'])) + form_set_error('chapter_title', t('Title of the Chapter can contain only alphabets, numbers and spaces.')); } - /************************ end approve book details **************************/ - - $chapter_id = arg(4); - - $chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE id = %d AND preference_id = %d", $chapter_id, $preference_data->id); - $chapter_data = db_fetch_object($chapter_q); - if (!$chapter_data) +function edit_chapter_title_form_submit($form, &$form_state) { - drupal_set_message(t('Invalid chapter.'), 'error'); - drupal_goto('textbook_companion/code'); - return; + global $user; + /************************ start approve book details ************************/ + /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid = %d ORDER BY id DESC LIMIT 1", $user->uid); + $proposal_data = db_fetch_object($proposal_q);*/ + $query = db_select('textbook_companion_proposal'); + $query->fields('textbook_companion_proposal'); + $query->condition('uid', $user->uid); + $query->orderBy('id', 'DESC'); + $query->range(0, 1); + $result = $query->execute(); + $proposal_data = $result->fetchObject(); + if (!$proposal_data) + { + drupal_set_message("Please submit a " . l('proposal', 'textbook-companion/proposal') . ".", 'error'); + drupal_goto('textbook-companion/code'); + } + if ($proposal_data->proposal_status != 1 && $proposal_data->proposal_status != 4) + { + switch ($proposal_data->proposal_status) + { + case 0: + drupal_set_message(t('We have already received your proposal. We will get back to you soon.'), 'status'); + drupal_goto('textbook-companion/code'); + return; + break; + case 2: + drupal_set_message(t('Your proposal has been dis-approved. Please create another proposal ' . l('here', 'proposal') . '.'), 'error'); + drupal_goto('textbook-companion/code'); + return; + break; + case 3: + drupal_set_message(t('Congratulations! You have completed your last book proposal. You have to create another proposal ' . l('here', 'textbook-companion/proposal') . '.'), 'status'); + drupal_goto('textbook-companion/code'); + return; + break; + default: + drupal_set_message(t('Invalid proposal state. Please contact site administrator for further information.'), 'error'); + drupal_goto('textbook-companion/code'); + return; + break; + } + } + /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND approval_status = 1 LIMIT 1", $proposal_data->id); + $preference_data = db_fetch_object($preference_q);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('proposal_id', $proposal_data->id); + $query->condition('approval_status', 1); + $query->range(0, 1); + $result = $query->execute(); + $preference_data = $result->fetchObject(); + if (!$preference_data) + { + drupal_set_message(t('Invalid Book Preference status. Please contact site administrator for further information.'), 'error'); + drupal_goto('textbook-companion/code'); + return; + } + /************************ end approve book details **************************/ + $chapter_id = arg(4); + /*$chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE id = %d AND preference_id = %d", $chapter_id, $preference_data->id); + $chapter_data = db_fetch_object($chapter_q);*/ + $query = db_select('textbook_companion_chapter'); + $query->fields('textbook_companion_chapter'); + $query->condition('id', $chapter_id); + $query->condition('preference_id', $preference_data->id); + $result = $query->execute(); + $chapter_data = $result->fetchObject(); + if (!$chapter_data) + { + drupal_set_message(t('Invalid chapter.'), 'error'); + drupal_goto('textbookcompanion/code'); + return; + } + /*db_query("UPDATE {textbook_companion_chapter} SET name = '%s' WHERE id = %d", $form_state['values']['chapter_title'], $chapter_id);*/ + $query = db_update('textbook_companion_chapter'); + $query->fields(array( + 'name' => $form_state['values']['chapter_title'] + )); + $query->condition('id', $chapter_id); + $num_updated = $query->execute(); + drupal_set_message(t('Title of the Chapter updated.'), 'status'); } - db_query("UPDATE {textbook_companion_chapter} SET name = '%s' WHERE id = %d", $form_state['values']['chapter_title'], $chapter_id); - drupal_set_message(t('Title of the Chapter updated.'), 'status'); -} - - /******************************************************************************/ /************************** GENERAL FUNCTIONS *********************************/ /******************************************************************************/ - function _list_of_book_titles() -{ - $book_titles = array('0' => 'Please select...'); - $book_titles_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE approval_status = 1 OR approval_status = 3 ORDER BY book ASC"); - while ($book_titles_data = db_fetch_object($book_titles_q)) - { - $book_titles[$book_titles_data->id] = $book_titles_data->book . ' (Written by ' . $book_titles_data->author . ')'; - } - return $book_titles; -} - -function _list_of_book_dependency_files() -{ - $book_dependency_files = array(); - $book_dependency_files_class = array(); - $book_dependency_files_q = db_query("SELECT * FROM {textbook_companion_dependency_files} ORDER BY filename ASC"); - - while ($book_dependency_files_data = db_fetch_object($book_dependency_files_q)) { - $temp_caption = ''; - if ($book_dependency_files_data->caption) - $temp_caption .= ' (' . $book_dependency_files_data->caption . ')'; - $book_dependency_files[$book_dependency_files_data->id] = l($book_dependency_files_data->filename . $temp_caption, 'download/dependency/' . $book_dependency_files_data->id, array('attributes' => array('class' => $book_dependency_files_data->preference_id))); - $book_dependency_files_class[$book_dependency_files_data->id] = $book_dependency_files_data->preference_id; + $book_titles = array( + '0' => 'Please select...' + ); + /*$book_titles_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE approval_status = 1 OR approval_status = 3 ORDER BY book ASC");*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $or = db_or(); + $or->condition('approval_status', 1); + $or->condition('approval_status', 3); + $query->condition($or); + $query->orderBy('book', 'ASC'); + $book_titles_q = $query->execute(); + while ($book_titles_data = $book_titles_q->fetchObject()) + { + $book_titles[$book_titles_data->id] = $book_titles_data->book . ' (Written by ' . $book_titles_data->author . ')'; + } + return $book_titles; } - return array($book_dependency_files, $book_dependency_files_class); -} - diff --git a/editcodeadmin.inc b/editcodeadmin.inc index 41f0e83..32e3481 100755 --- a/editcodeadmin.inc +++ b/editcodeadmin.inc @@ -1,902 +1,472 @@ <?php // $Id$ - /******************************************************************************/ /***************************** EDIT EXAMPLE ***********************************/ /******************************************************************************/ - -function upload_examples_admin_edit_form($form_state) -{ - global $user; - $example_id = arg(2); - - /* get example details */ - $example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE id = %d LIMIT 1", $example_id); - $example_data = db_fetch_object($example_q); - if (!$example_q) +function upload_examples_admin_edit_form($form, &$form_state) { - drupal_set_message(t("Invalid example selected."), 'error'); - drupal_goto(''); - return; - } - - /* get examples files */ - $source_file = ""; $source_id = 0; - $result1_file = ""; $result1_id = 0; - $result2_file = ""; $result2_id = 0; - $xcos1_file = ""; $xcos1_id = 0; - $xcos2_file = ""; $xcos2_id = 0; - - $example_files_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE example_id = %d", $example_id); - while ($example_files_data = db_fetch_object($example_files_q)) - { - if ($example_files_data->filetype == "S") - { - $source_file = l($example_files_data->filename, 'download/file/' . $example_files_data->id); - $source_file_id = $example_files_data->id; - } - if ($example_files_data->filetype == "R") - { - if (strlen($result1_file) == 0) + global $user; + $example_id = arg(3); + /* get example details */ + /*$example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE id = %d LIMIT 1", $example_id); + $example_data = db_fetch_object($example_q);*/ + $query = db_select('textbook_companion_example'); + $query->fields('textbook_companion_example'); + $query->condition('id', $example_id); + $query->range(0, 1); + $example_q = $query->execute(); + $example_data = $example_q->fetchObject(); + if (!$example_q) { - $result1_file = l($example_files_data->filename, 'download/file/' . $example_files_data->id); - $result1_file_id = $example_files_data->id; - } else { - $result2_file = l($example_files_data->filename, 'download/file/' . $example_files_data->id); - $result2_file_id = $example_files_data->id; + drupal_set_message(t("Invalid example selected."), 'error'); + drupal_goto(''); + return; } - } - if ($example_files_data->filetype == "X") - { - if (strlen($xcos1_file) <= 0) + /* get examples files */ + $source_file = ""; + $source_id = 0; + $result1_file = ""; + $result1_id = 0; + $result2_file = ""; + $result2_id = 0; + $xcos1_file = ""; + $xcos1_id = 0; + $xcos2_file = ""; + $xcos2_id = 0; + /*$example_files_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE example_id = %d", $example_id);*/ + $query = db_select('textbook_companion_example_files'); + $query->fields('textbook_companion_example_files'); + $query->condition('example_id', $example_id); + $example_files_q = $query->execute(); + while ($example_files_data = $example_files_q->fetchObject()) { - $xcos1_file = l($example_files_data->filename, 'download/file/' . $example_files_data->id); - $xcos1_file_id = $example_files_data->id; - } else { - $xcos2_file = l($example_files_data->filename, 'download/file/' . $example_files_data->id); - $xcos2_file_id = $example_files_data->id; + if ($example_files_data->filetype == "S") + { + $source_file = l($example_files_data->filename, 'textbook-companion/download/file/' . $example_files_data->id); + $source_file_id = $example_files_data->id; + } + if ($example_files_data->filetype == "R") + { + if (strlen($result1_file) == 0) + { + $result1_file = l($example_files_data->filename, 'textbook-companion/download/file/' . $example_files_data->id); + $result1_file_id = $example_files_data->id; + } + else + { + $result2_file = l($example_files_data->filename, 'textbook-companion/download/file/' . $example_files_data->id); + $result2_file_id = $example_files_data->id; + } + } + if ($example_files_data->filetype == "X") + { + if (strlen($xcos1_file) <= 0) + { + $xcos1_file = l($example_files_data->filename, 'textbook-companion/download/file/' . $example_files_data->id); + $xcos1_file_id = $example_files_data->id; + } + else + { + $xcos2_file = l($example_files_data->filename, 'textbook-companion/download/file/' . $example_files_data->id); + $xcos2_file_id = $example_files_data->id; + } + } } - } - } - - /* get chapter details */ - $chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE id = %d", $example_data->chapter_id); - $chapter_data = db_fetch_object($chapter_q); - if (!$chapter_data) - { - drupal_set_message(t("Invalid chapter selected."), 'error'); - drupal_goto(''); - return; - } - - /* get preference details */ - $preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d", $chapter_data->preference_id); - $preference_data = db_fetch_object($preference_q); - if (!$preference_data) - { - drupal_set_message(t("Invalid book selected."), 'error'); - drupal_goto(''); - return; - } - - /* get proposal details */ - $proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d", $preference_data->proposal_id); - $proposal_data = db_fetch_object($proposal_q); - if (!$proposal_data) - { - drupal_set_message(t("Invalid proposal selected."), 'error'); - drupal_goto(''); - return; - } - - $user_data = user_load($proposal_data->uid); - - /* add javascript for automatic book title, check if example uploaded, dependency selection effects */ - $chapter_name_js = " $(document).ready(function() { - $('#edit-existing-depfile-dep-book-title').change(function() { - var dep_selected = ''; - /* showing and hiding relevant files */ - $('.form-checkboxes .option').hide(); - $('.form-checkboxes .option').each(function(index) { - var activeClass = $('#edit-existing-depfile-dep-book-title').val(); - if ($(this).children().hasClass(activeClass)) { - $(this).show(); - } - if ($(this).children().attr('checked') == true) { - dep_selected += $(this).children().next().text() + '<br />'; - } - }); - /* showing list of already existing dependencies */ - $('#existing_depfile_selected').html(dep_selected); - }); - - $('.form-checkboxes .option').change(function() { - $('#edit-existing-depfile-dep-book-title').trigger('change'); - }); - $('#edit-existing-depfile-dep-book-title').trigger('change'); - });"; - drupal_add_js($chapter_name_js, 'inline', 'header'); - - $form['#redirect'] = 'code_approval/bulk'; - $form['#attributes'] = array('enctype' => "multipart/form-data"); - - $form['book_details']['book'] = array( - '#type' => 'item', - '#value' => $preference_data->book, - '#title' => t('Title of the Book'), - ); - $form['contributor_name'] = array( - '#type' => 'item', - '#value' => $proposal_data->full_name, - '#title' => t('Contributor Name'), - ); - $form['number'] = array( - '#type' => 'item', - '#title' => t('Chapter No'), - '#value' => $chapter_data->number, - ); - $form['name'] = array( - '#type' => 'item', - '#title' => t('Title of the Chapter'), - '#value' => $chapter_data->name, - ); - $form['example_number'] = array( - '#type' => 'item', - '#title' => t('Example No'), - '#value' => $example_data->number, - ); - $form['example_caption'] = array( - '#type' => 'textfield', - '#title' => t('Caption'), - '#size' => 40, - '#maxlength' => 255, - '#required' => TRUE, - '#default_value' => $example_data->caption, - ); - $form['example_warning'] = array( - '#type' => 'item', - '#title' => t('You should upload all the files (main or source files, result files, executable file if any)'), - '#prefix' => '<div style="color:red">', - '#suffix' => '</div>', - ); - - $form['sourcefile'] = array( - '#type' => 'fieldset', - '#title' => t('Main or Source Files'), - '#collapsible' => FALSE, - '#collapsed' => FALSE, - ); - if ($source_file) - { - $form['sourcefile']['cur_source'] = array( - '#type' => 'item', - '#title' => t('Existing Main or Source File'), - '#value' => $source_file, - ); - $form['sourcefile']['cur_source_checkbox'] = array( - '#type' => 'checkbox', - '#title' => t('Delete Existing Main or Source File'), - '#description' => 'Check to delete the existing Main or Source file.', - ); - $form['sourcefile']['sourcefile1'] = array( - '#type' => 'file', - '#title' => t('Upload New Main or Source File'), - '#size' => 48, - '#description' => t("Upload new Main or Source file above if you want to replace the existing file. Leave blank if you want to keep using the existing file. <br />") . - t('Allowed file extensions : ') . variable_get('textbook_companion_source_extensions', ''), - ); - $form['sourcefile']['cur_source_file_id'] = array( - '#type' => 'hidden', - '#value' => $source_file_id, - ); - } else { - $form['sourcefile']['sourcefile1'] = array( - '#type' => 'file', - '#title' => t('Upload New Main or Source File'), - '#size' => 48, - '#description' => t('Allowed file extensions : ') . variable_get('textbook_companion_source_extensions', ''), - ); - } - - $form['dep_files'] = array( - '#type' => 'item', - '#title' => t('Dependency Files'), - ); - - /************ START OF EXISTING DEPENDENCIES **************/ - - $dependency_files = array(); - $dependency_q = db_query("SELECT * FROM {textbook_companion_example_dependency} WHERE example_id = %d", $example_data->id); - while ($dependency_data = db_fetch_object($dependency_q)) - { - $dependency_files[] = $dependency_data->dependency_id; - } - - /* existing dependencies */ - $form['existing_depfile'] = array( - '#type' => 'fieldset', - '#title' => t('Use Already Existing Dependency Files'), - '#collapsible' => FALSE, - '#collapsed' => FALSE, - '#prefix' => '<div id="existing-depfile-wrapper">', - '#suffix' => '</div>', - '#tree' => TRUE, - ); - - /* existing dependencies */ - $form['existing_depfile']['selected'] = array( - '#type' => 'item', - '#title' => t('Existing Dependency Files Selected'), - '#value' => '<div id="existing_depfile_selected"></div>', - ); - - $form['existing_depfile']['dep_book_title'] = array( - '#type' => 'select', - '#title' => t('Title of the Book'), - '#options' => _list_of_book_titles(), - ); - - list($files_options, $files_options_class) = _list_of_book_dependency_files(); - $form['existing_depfile']['dep_chapter_example_files'] = array( - '#type' => 'checkboxes', - '#title' => t('Dependency Files'), - '#options' => $files_options, - '#options_class' => $files_options_class, - '#multiple' => TRUE, - '#default_value' => $dependency_files, - ); - - $form['existing_depfile']['dep_upload'] = array( - '#type' => 'item', - '#value' => l('Upload New Depedency Files', 'textbook_companion/code/upload_dep'), - ); - /************ END OF EXISTING DEPENDENCIES **************/ - - $form['result'] = array( - '#type' => 'fieldset', - '#title' => t('Result Files'), - '#collapsible' => FALSE, - '#collapsed' => FALSE, - ); - if ($result1_file) - { - $form['result']['cur_result1'] = array( - '#type' => 'item', - '#title' => t('Existing Result File 1'), - '#value' => $result1_file, - ); - $form['result']['cur_result1_checkbox'] = array( - '#type' => 'checkbox', - '#title' => t('Delete Existing Result File 1'), - '#description' => 'Check to delete the existing Result file.', - ); - $form['result']['result1'] = array( - '#type' => 'file', - '#title' => t('Upload New Result File 1'), - '#size' => 48, - '#description' => t("Upload new Result file above if you want to replace the existing file, leave blank if you want to keep using the existing file. <br />") . - t('Allowed file extensions : ') . variable_get('textbook_companion_result_extensions', ''), - ); - $form['result']['cur_result1_file_id'] = array( - '#type' => 'hidden', - '#value' => $result1_file_id, - ); - } else { - $form['result']['result1'] = array( - '#type' => 'file', - '#title' => t('Upload New Result File 1'), - '#size' => 48, - '#description' => t('Allowed file extensions : ') . variable_get('textbook_companion_result_extensions', ''), - ); - } - - $form['result']['br'] = array( - '#type' => 'item', - '#value' => "<br />", - ); - - if ($result2_file) - { - $form['result']['cur_result2'] = array( - '#type' => 'item', - '#title' => t('Existing Result File 2'), - '#value' => $result2_file, - ); - $form['result']['cur_result2_checkbox'] = array( - '#type' => 'checkbox', - '#title' => t('Delete Existing Result File 2'), - '#description' => 'Check to delete the existing Result file.', - ); - $form['result']['result2'] = array( - '#type' => 'file', - '#title' => t('Upload New Result file 2'), - '#size' => 48, - '#description' => t("Upload new Result file above if you want to replace the existing file. Leave blank if you want to keep using the existing file. <br />") . - t('Allowed file extensions : ') . variable_get('textbook_companion_result_extensions', ''), - ); - $form['result']['cur_result2_file_id'] = array( - '#type' => 'hidden', - '#value' => $result2_file_id, - ); - } else { - $form['result']['result2'] = array( - '#type' => 'file', - '#title' => t('Upload New Result file 2'), - '#size' => 48, - '#description' => t('Allowed file extensions : ') . variable_get('textbook_companion_result_extensions', ''), - ); - } - $form['xcos'] = array( - '#type' => 'fieldset', - '#title' => t('XCOS Files'), - '#collapsible' => FALSE, - '#collapsed' => FALSE, - ); - if ($xcos1_file) - { - $form['xcos']['cur_xcos1'] = array( - '#type' => 'item', - '#title' => t('Existing xcos File 1'), - '#value' => $xcos1_file, - ); - $form['xcos']['cur_xcos1_checkbox'] = array( - '#type' => 'checkbox', - '#title' => t('Delete Existing xcos File 1'), - '#description' => 'Check to delete the existing xcos file.', + /* get chapter details */ + /*$chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE id = %d", $example_data->chapter_id); + $chapter_data = db_fetch_object($chapter_q);*/ + $query = db_select('textbook_companion_chapter'); + $query->fields('textbook_companion_chapter'); + $query->condition('id', $example_data->chapter_id); + $result = $query->execute(); + $chapter_data = $result->fetchObject(); + if (!$chapter_data) + { + drupal_set_message(t("Invalid chapter selected."), 'error'); + drupal_goto(''); + return; + } + /* get preference details */ + /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d", $chapter_data->preference_id); + $preference_data = db_fetch_object($preference_q);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('id', $chapter_data->preference_id); + $result = $query->execute(); + $preference_data = $result->fetchObject(); + if (!$preference_data) + { + drupal_set_message(t("Invalid book selected."), 'error'); + drupal_goto(''); + return; + } + /* get proposal details */ + /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d", $preference_data->proposal_id); + $proposal_data = db_fetch_object($proposal_q);*/ + $query = db_select('textbook_companion_proposal'); + $query->fields('textbook_companion_proposal'); + $query->condition('id', $preference_data->proposal_id); + $result = $query->execute(); + $proposal_data = $result->fetchObject(); + if (!$proposal_data) + { + drupal_set_message(t("Invalid proposal selected."), 'error'); + drupal_goto(''); + return; + } + $user_data = user_load($proposal_data->uid); + $form['#redirect'] = 'code_approval/bulk'; + $form['#attributes'] = array( + 'enctype' => "multipart/form-data" ); - $form['xcos']['xcos1'] = array( - '#type' => 'file', - '#title' => t('Upload New xcos file 1'), - '#size' => 48, - '#description' => t("Upload new xcos file above if you want to replace the existing file. Leave blank if you want to keep using the existing file. <br />") . - t('Allowed file extensions : ') . variable_get('textbook_companion_xcos_extensions', ''), + $form['book_details']['book'] = array( + '#type' => 'item', + '#markup' => $preference_data->book, + '#title' => t('Title of the Book') ); - $form['sourcefile']['cur_xcos1_file_id'] = array( - '#type' => 'hidden', - '#value' => $xcos1_file_id, + $form['contributor_name'] = array( + '#type' => 'item', + '#markup' => $proposal_data->full_name, + '#title' => t('Contributor Name') ); - } else { - $form['xcos']['xcos1'] = array( - '#type' => 'file', - '#title' => t('Upload New xcos file 1'), - '#size' => 48, - '#description' => t('Allowed file extensions : ') . variable_get('textbook_companion_xcos_extensions', ''), + $form['number'] = array( + '#type' => 'item', + '#title' => t('Chapter No'), + '#markup' => $chapter_data->number ); - } - - $form['xcos']['br'] = array( - '#type' => 'item', - '#value' => "<br />", - ); - - if ($xcos2_file) - { - $form['xcos']['cur_xcos2'] = array( - '#type' => 'item', - '#title' => t('Existing xcos File 2'), - '#value' => $xcos2_file, + $form['name'] = array( + '#type' => 'item', + '#title' => t('Title of the Chapter'), + '#markup' => $chapter_data->name ); - $form['xcos']['cur_xcos2_checkbox'] = array( - '#type' => 'checkbox', - '#title' => t('Delete Existing xcos File 2'), - '#description' => 'Check to delete the existing xcos file.', + $form['example_number'] = array( + '#type' => 'item', + '#title' => t('Example No'), + '#markup' => $example_data->number ); - $form['xcos']['xcos2'] = array( - '#type' => 'file', - '#title' => t('Upload New xcos file 2'), - '#size' => 48, - '#description' => t("Upload new xcos file above if you want to replace the existing file. Leave blank if you want to keep using the existing file. <br />") . - t('Allowed file extensions : ') . variable_get('textbook_companion_xcos_extensions', ''), + $form['example_caption'] = array( + '#type' => 'textfield', + '#title' => t('Caption'), + '#size' => 40, + '#maxlength' => 255, + '#required' => TRUE, + '#default_value' => $example_data->caption ); - $form['xcos']['cur_xcos2_file_id'] = array( - '#type' => 'hidden', - '#value' => $xcos2_file_id, + $form['example_warning'] = array( + '#type' => 'item', + '#title' => t('You should upload all the files (main or source files, result files, executable file if any)'), + '#prefix' => '<div style="color:red">', + '#suffix' => '</div>' ); - } else { - $form['xcos']['xcos2'] = array( - '#type' => 'file', - '#title' => t('Upload New xcos file 2'), - '#size' => 48, - '#description' => t('Allowed file extensions : ') . variable_get('textbook_companion_xcos_extensions', ''), + $form['sourcefile'] = array( + '#type' => 'fieldset', + '#title' => t('Main or Source Files'), + '#collapsible' => FALSE, + '#collapsed' => FALSE ); - } - - $form['submit'] = array( - '#type' => 'submit', - '#value' => t('Submit') - ); - - $form['cancel'] = array( - '#type' => 'markup', - '#value' => l(t('Cancel'), 'textbook_companion/code'), - ); - return $form; -} - -function upload_examples_admin_edit_form_validate($form, &$form_state) -{ - if (!check_name($form_state['values']['example_caption'])) - form_set_error('example_caption', t('Example Caption can contain only alphabets, numbers and spaces.')); - - if (isset($_FILES['files'])) - { - /* check for valid filename extensions */ - foreach ($_FILES['files']['name'] as $file_form_name => $file_name) - { - if ($file_name) + if ($source_file) { - /* checking file type */ - if (strstr($file_form_name, 'source')) - $file_type = 'S'; - else if (strstr($file_form_name, 'result')) - $file_type = 'R'; - else if (strstr($file_form_name, 'xcos')) - $file_type = 'X'; - else - $file_type = 'U'; - - $allowed_extensions_str = ''; - switch ($file_type) - { - case 'S': - $allowed_extensions_str = variable_get('textbook_companion_source_extensions', ''); - break; - case 'R': - $allowed_extensions_str = variable_get('textbook_companion_result_extensions', ''); - break; - case 'X': - $allowed_extensions_str = variable_get('textbook_companion_xcos_extensions', ''); - break; - } - - $allowed_extensions = explode(',' , $allowed_extensions_str); - $temp_extension = end(explode('.', strtolower($_FILES['files']['name'][$file_form_name]))); - if (!in_array($temp_extension, $allowed_extensions)) - form_set_error($file_form_name, t('Only file with ' . $allowed_extensions_str . ' extensions can be uploaded.')); - if ($_FILES['files']['size'][$file_form_name] <= 0) - form_set_error($file_form_name, t('File size cannot be zero.')); - - /* check if valid file name */ - if (!textbook_companion_check_valid_filename($_FILES['files']['name'][$file_form_name])) - form_set_error($file_form_name, t('Invalid file name specified. Only alphabets, numbers and underscore is allowed as a valid filename.')); + $form['sourcefile']['cur_source'] = array( + '#type' => 'item', + '#title' => t('Existing Main or Source File'), + '#markup' => $source_file + ); + $form['sourcefile']['cur_source_checkbox'] = array( + '#type' => 'checkbox', + '#title' => t('Delete Existing Main or Source File'), + '#description' => 'Check to delete the existing Main or Source file.' + ); + $form['sourcefile']['sourcefile1'] = array( + '#type' => 'file', + '#title' => t('Upload New Main or Source File'), + '#size' => 48, + '#description' => t("Upload new Main or Source file above if you want to replace the existing file. Leave blank if you want to keep using the existing file. <br />") . t('Allowed file extensions : ') . variable_get('textbook_companion_source_extensions', '') + ); + $form['sourcefile']['cur_source_file_id'] = array( + '#type' => 'hidden', + '#default_value' => $source_file_id + ); } - } - } - - /* add javascript again for automatic book title, check if example uploaded, dependency selection effects */ - $chapter_name_js = " $(document).ready(function() { - $('#edit-number').change(function() { - $.get('" . base_path() . "textbook_companion/ajax/chapter_title/' + $('#edit-number').val() + '/' + " . $row->pre_id . ", function(data) { - $('#edit-name').val(data); - }); - }); - $('#edit-example-number').change(function() { - $.get('" . base_path() . "textbook_companion/ajax/example_exists/' + $('#edit-number').val() + '/' + $('#edit-example-number').val(), function(data) { - if (data) { - alert(data); - } - }); - }); - $('#edit-existing-depfile-dep-book-title').change(function() { - var dep_selected = ''; - /* showing and hiding relevant files */ - $('.form-checkboxes .option').hide(); - $('.form-checkboxes .option').each(function(index) { - var activeClass = $('#edit-existing-depfile-dep-book-title').val(); - if ($(this).children().hasClass(activeClass)) { - $(this).show(); - } - if ($(this).children().attr('checked') == true) { - dep_selected += $(this).children().next().text() + '<br />'; - } - }); - /* showing list of already existing dependencies */ - $('#existing_depfile_selected').html(dep_selected); - }); - - $('.form-checkboxes .option').change(function() { - $('#edit-existing-depfile-dep-book-title').trigger('change'); - }); - $('#edit-existing-depfile-dep-book-title').trigger('change'); - });"; - drupal_add_js($chapter_name_js, 'inline', 'header'); -} - -function upload_examples_admin_edit_form_submit($form, &$form_state) -{ - global $user; - $example_id = arg(2); - - /* get example details */ - $example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE id = %d LIMIT 1", $example_id); - $example_data = db_fetch_object($example_q); - if (!$example_q) - { - drupal_set_message(t("Invalid example selected."), 'error'); - drupal_goto(''); - return; - } - - /* get chapter details */ - $chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE id = %d", $example_data->chapter_id); - $chapter_data = db_fetch_object($chapter_q); - if (!$chapter_data) - { - drupal_set_message(t("Invalid chapter selected."), 'error'); - drupal_goto(''); - return; - } - - /* get preference details */ - $preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d", $chapter_data->preference_id); - $preference_data = db_fetch_object($preference_q); - if (!$preference_data) - { - drupal_set_message(t("Invalid book selected."), 'error'); - drupal_goto(''); - return; - } - - /* get proposal details */ - $proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d", $preference_data->proposal_id); - $proposal_data = db_fetch_object($proposal_q); - if (!$proposal_data) - { - drupal_set_message(t("Invalid proposal selected."), 'error'); - drupal_goto(''); - return; - } - $user_data = user_load($proposal_data->uid); - - /* creating directories */ - $root_path = textbook_companion_path(); - - $dest_path = $preference_data->id . '/'; - if (!is_dir($root_path . $dest_path)) - mkdir($root_path . $dest_path); - - $dest_path .= 'CH' . $chapter_data->number . '/'; - if (!is_dir($root_path . $dest_path)) - mkdir($root_path . $dest_path); - - $dest_path .= 'EX' . $example_data->number . '/'; - if (!is_dir($root_path . $dest_path)) - mkdir($root_path . $dest_path); - - /* updating example caption */ - db_query("UPDATE {textbook_companion_example} SET caption = '%s' WHERE id = %d", $form_state['values']['example_caption'], $example_id); - - /* handling dependencies */ - db_query("DELETE FROM {textbook_companion_example_dependency} WHERE example_id = %d", $example_data->id); - foreach ($form_state['values']['existing_depfile']['dep_chapter_example_files'] as $row) - { - if ($row > 0) - { - /* insterting into database */ - db_query("INSERT INTO {textbook_companion_example_dependency} (example_id, dependency_id, approval_status, timestamp) - VALUES (%d, %d, %d, %d)", - $example_data->id, - $row, - 0, - time() - ); - } - } - - /* handle source file */ - $cur_file_id = $form_state['values']['cur_source_file_id']; - if ($cur_file_id > 0) - { - $file_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE id = %d AND example_id = %d", $cur_file_id, $example_data->id); - $file_data = db_fetch_object($file_q); - if (!$file_data) - { - drupal_set_message("Error deleting example source file. File not present in database.", 'error'); - return; - } - if (($form_state['values']['cur_source_checkbox'] == 1) && (!$_FILES['files']['name']['sourcefile1'])) - { - if (!delete_file($cur_file_id)) + else { - drupal_set_message("Error deleting example source file.", 'error'); - return; + $form['sourcefile']['sourcefile1'] = array( + '#type' => 'file', + '#title' => t('Upload New Main or Source File'), + '#size' => 48, + '#description' => t('Allowed file extensions : ') . variable_get('textbook_companion_source_extensions', '') + ); } - } + $form['submit'] = array( + '#type' => 'submit', + '#value' => t('Submit') + ); + $form['cancel'] = array( + '#type' => 'markup', + '#value' => l(t('Cancel'), 'textbook-companion/code') + ); + return $form; } - if ($_FILES['files']['name']['sourcefile1']) +function upload_examples_admin_edit_form_validate($form, &$form_state) { - if ($cur_file_id > 0) - { - if (!delete_file($cur_file_id)) + if (!check_name($form_state['values']['example_caption'])) + form_set_error('example_caption', t('Example Caption can contain only alphabets, numbers and spaces.')); + if (isset($_FILES['files'])) { - drupal_set_message("Error removing previous example source file.", 'error'); - return; + /* check for valid filename extensions */ + foreach ($_FILES['files']['name'] as $file_form_name => $file_name) + { + if ($file_name) + { + /* checking file type */ + if (strstr($file_form_name, 'source')) + $file_type = 'S'; + else if (strstr($file_form_name, 'result')) + $file_type = 'R'; + else if (strstr($file_form_name, 'xcos')) + $file_type = 'X'; + else + $file_type = 'U'; + $allowed_extensions_str = ''; + switch ($file_type) + { + case 'S': + $allowed_extensions_str = variable_get('textbook_companion_source_extensions', ''); + break; + case 'R': + $allowed_extensions_str = variable_get('textbook_companion_result_extensions', ''); + break; + case 'X': + $allowed_extensions_str = variable_get('textbook_companion_xcos_extensions', ''); + break; + } + $allowed_extensions = explode(',', $allowed_extensions_str); + $temp_ext = explode('.', strtolower($_FILES['files']['name'][$file_form_name])); + $temp_extension = end($temp_ext); + if (!in_array($temp_extension, $allowed_extensions)) + form_set_error($file_form_name, t('Only file with ' . $allowed_extensions_str . ' extensions can be uploaded.')); + if ($_FILES['files']['size'][$file_form_name] <= 0) + form_set_error($file_form_name, t('File size cannot be zero.')); + /* check if valid file name */ + if (!textbook_companion_check_valid_filename($_FILES['files']['name'][$file_form_name])) + form_set_error($file_form_name, t('Invalid file name specified. Only alphabets, numbers and underscore is allowed as a valid filename.')); + } + } } - } - if (file_exists($root_path . $dest_path . $_FILES['files']['name']['sourcefile1'])) - { - drupal_set_message(t("Error uploading source file. File !filename already exists.", array('!filename' => $_FILES['files']['name']['sourcefile1'])), 'error'); - return; - } - /* uploading file */ - if (move_uploaded_file($_FILES['files']['tmp_name']['sourcefile1'], $root_path . $dest_path . $_FILES['files']['name']['sourcefile1'])) - { - /* for uploaded files making an entry in the database */ - db_query("INSERT INTO {textbook_companion_example_files} (example_id, filename, filepath, filemime, filesize, filetype, timestamp) - VALUES (%d, '%s', '%s', '%s', %d, '%s', %d)", - $example_data->id, - $_FILES['files']['name']['sourcefile1'], - $dest_path . $_FILES['files']['name']['sourcefile1'], - $_FILES['files']['type']['sourcefile1'], - $_FILES['files']['size']['sourcefile1'], - 'S', - time() - ); - drupal_set_message($_FILES['files']['name']['sourcefile1'] . ' uploaded successfully.', 'status'); - } else { - drupal_set_message('Error uploading file : ' . $dest_path . '/' . $_FILES['files']['name']['sourcefile1'], 'error'); - } } - - /* handle result1 file */ - $cur_file_id = $form_state['values']['cur_result1_file_id']; - if ($cur_file_id > 0) +function upload_examples_admin_edit_form_submit($form, &$form_state) { - $file_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE id = %d AND example_id = %d", $cur_file_id, $example_data->id); - $file_data = db_fetch_object($file_q); - if (!$file_data) - { - drupal_set_message("Error deleting example result 1 file. File not present in database.", 'error'); - return; - } - if (($form_state['values']['cur_result1_checkbox'] == 1) && (!$_FILES['files']['name']['result1'])) - { - if (!delete_file($cur_file_id)) + global $user; + $example_id = arg(3); + /* get example details */ + /*$example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE id = %d LIMIT 1", $example_id); + $example_data = db_fetch_object($example_q);*/ + $query = db_select('textbook_companion_example'); + $query->fields('textbook_companion_example'); + $query->condition('id', $example_id); + $query->range(0, 1); + $example_q = $query->execute(); + $example_data = $example_q->fetchObject(); + if (!$example_q) { - drupal_set_message("Error deleting example result 1 file.", 'error'); + drupal_set_message(t("Invalid example selected."), 'error'); + drupal_goto(''); return; } - } - } - if ($_FILES['files']['name']['result1']) - { - if ($cur_file_id > 0) - { - if (!delete_file($cur_file_id)) + /* get chapter details */ + /*$chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE id = %d", $example_data->chapter_id); + $chapter_data = db_fetch_object($chapter_q);*/ + $query = db_select('textbook_companion_chapter'); + $query->fields('textbook_companion_chapter'); + $query->condition('id', $example_data->chapter_id); + $chapter_q = $query->execute(); + $chapter_data = $chapter_q->fetchObject(); + if (!$chapter_data) { - drupal_set_message("Error removing previous example result 1 file.", 'error'); + drupal_set_message(t("Invalid chapter selected."), 'error'); + drupal_goto(''); return; } - } - if (file_exists($root_path . $dest_path . $_FILES['files']['name']['result1'])) - { - drupal_set_message(t("Error uploading result 1 file. File !filename already exists.", array('!filename' => $_FILES['files']['name']['result1'])), 'error'); - return; - } - /* uploading file */ - if (move_uploaded_file($_FILES['files']['tmp_name']['result1'], $root_path . $dest_path . $_FILES['files']['name']['result1'])) - { - /* for uploaded files making an entry in the database */ - db_query("INSERT INTO {textbook_companion_example_files} (example_id, filename, filepath, filemime, filesize, filetype, timestamp) - VALUES (%d, '%s', '%s', '%s', %d, '%s', %d)", - $example_data->id, - $_FILES['files']['name']['result1'], - $dest_path . $_FILES['files']['name']['result1'], - $_FILES['files']['type']['result1'], - $_FILES['files']['size']['result1'], - 'R', - time() - ); - drupal_set_message($_FILES['files']['name']['result1'] . ' uploaded successfully.', 'status'); - } else { - drupal_set_message('Error uploading file : ' . $dest_path . '/' . $_FILES['files']['name']['result1'], 'error'); - } - } - - /* handle result2 file */ - $cur_file_id = $form_state['values']['cur_result2_file_id']; - if ($cur_file_id > 0) - { - $file_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE id = %d AND example_id = %d", $cur_file_id, $example_data->id); - $file_data = db_fetch_object($file_q); - if (!$file_data) - { - drupal_set_message("Error deleting example result 2 file. File not present in database.", 'error'); - return; - } - if (($form_state['values']['cur_result2_checkbox'] == 1) && (!$_FILES['files']['name']['result2'])) - { - if (!delete_file($cur_file_id)) + /* get preference details */ + /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d", $chapter_data->preference_id); + $preference_data = db_fetch_object($preference_q);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('id', $chapter_data->preference_id); + $result = $query->execute(); + $preference_data = $result->fetchObject(); + if (!$preference_data) { - drupal_set_message("Error deleting example result 2 file.", 'error'); + drupal_set_message(t("Invalid book selected."), 'error'); + drupal_goto(''); return; } - } - } - if ($_FILES['files']['name']['result2']) - { - if ($cur_file_id > 0) - { - if (!delete_file($cur_file_id)) + /* get proposal details */ + /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d", $preference_data->proposal_id); + $proposal_data = db_fetch_object($proposal_q);*/ + $query = db_select('textbook_companion_proposal'); + $query->fields('textbook_companion_proposal'); + $query->condition('id', $preference_data->proposal_id); + $result = $query->execute(); + $proposal_data = $result->fetchObject(); + if (!$proposal_data) { - drupal_set_message("Error removing previous example result 2 file.", 'error'); + drupal_set_message(t("Invalid proposal selected."), 'error'); + drupal_goto(''); return; } - } - if (file_exists($root_path . $dest_path . $_FILES['files']['name']['result2'])) - { - drupal_set_message(t("Error uploading result 2 file. File !filename already exists.", array('!filename' => $_FILES['files']['name']['result2'])), 'error'); - return; - } - /* uploading file */ - if (move_uploaded_file($_FILES['files']['tmp_name']['result2'], $root_path . $dest_path . $_FILES['files']['name']['result2'])) - { - /* for uploaded files making an entry in the database */ - db_query("INSERT INTO {textbook_companion_example_files} (example_id, filename, filepath, filemime, filesize, filetype, timestamp) - VALUES (%d, '%s', '%s', '%s', %d, '%s', %d)", - $example_data->id, - $_FILES['files']['name']['result2'], - $dest_path . $_FILES['files']['name']['result2'], - $_FILES['files']['type']['result2'], - $_FILES['files']['size']['result2'], - 'R', - time() - ); - drupal_set_message($_FILES['files']['name']['result2'] . ' uploaded successfully.', 'status'); - } else { - drupal_set_message('Error uploading file : ' . $dest_path . '/' . $_FILES['files']['name']['result2'], 'error'); - } - } - - /* handle xcos1 file */ - $cur_file_id = $form_state['values']['cur_xcos1_file_id']; - if ($cur_file_id > 0) - { - $file_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE id = %d AND example_id = %d", $cur_file_id, $example_data->id); - $file_data = db_fetch_object($file_q); - if (!$file_data) - { - drupal_set_message("Error deleting example xcos 1 file. File not present in database.", 'error'); - return; - } - if (($form_state['values']['cur_xcos1_checkbox'] == 1) && (!$_FILES['files']['name']['xcos1'])) - { - if (!delete_file($cur_file_id)) + $user_data = user_load($proposal_data->uid); + /* creating directories */ + $root_path = textbook_companion_path(); + $dest_path = $preference_data->directory_name . '/'; + if (!is_dir($root_path . $dest_path)) + mkdir($root_path . $dest_path); + $dest_path .= 'CH' . $chapter_data->number . '/'; + if (!is_dir($root_path . $dest_path)) + mkdir($root_path . $dest_path); + $dest_path .= 'EX' . $example_data->number . '/'; + if (!is_dir($root_path . $dest_path)) + mkdir($root_path . $dest_path); + $filepath = 'CH' . $chapter_data->number . '/' . 'EX' . $example_data->number . '/'; + /* updating example caption */ + /*db_query("UPDATE {textbook_companion_example} SET caption = '%s' WHERE id = %d", $form_state['values']['example_caption'], $example_id);*/ + $query = db_update('textbook_companion_example'); + $query->fields(array( + 'caption' => $form_state['values']['example_caption'] + )); + $query->condition('id', $example_id); + $num_updated = $query->execute(); + /* handle source file */ + if (empty($form_state['values']['cur_source_file_id'])) { - drupal_set_message("Error deleting example xcos 1 file.", 'error'); - return; + $form_state['values']['cur_source_file_id'] = 0; } - } - } - if ($_FILES['files']['name']['xcos1']) - { + $cur_file_id = $form_state['values']['cur_source_file_id']; if ($cur_file_id > 0) - { - if (!delete_file($cur_file_id)) - { - drupal_set_message("Error removing previous example xcos 1 file.", 'error'); - return; - } - } - if (file_exists($root_path . $dest_path . $_FILES['files']['name']['xcos1'])) - { - drupal_set_message(t("Error uploading xcos 1 file. File !filename already exists.", array('!filename' => $_FILES['files']['name']['xcos1'])), 'error'); - return; - } - /* uploading file */ - if (move_uploaded_file($_FILES['files']['tmp_name']['xcos1'], $root_path . $dest_path . $_FILES['files']['name']['xcos1'])) - { - /* for uploaded files making an entry in the database */ - db_query("INSERT INTO {textbook_companion_example_files} (example_id, filename, filepath, filemime, filesize, filetype, timestamp) - VALUES (%d, '%s', '%s', '%s', %d, '%s', %d)", - $example_data->id, - $_FILES['files']['name']['xcos1'], - $dest_path . $_FILES['files']['name']['xcos1'], - $_FILES['files']['type']['xcos1'], - $_FILES['files']['size']['xcos1'], - 'X', - time() - ); - drupal_set_message($_FILES['files']['name']['xcos1'] . ' uploaded successfully.', 'status'); - } else { - drupal_set_message('Error uploading file : ' . $dest_path . '/' . $_FILES['files']['name']['xcos1'], 'error'); - } - } - - /* handle xcos2 file */ - $cur_file_id = $form_state['values']['cur_xcos2_file_id']; - if ($cur_file_id > 0) - { - $file_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE id = %d AND example_id = %d", $cur_file_id, $example_data->id); - $file_data = db_fetch_object($file_q); - if (!$file_data) - { - drupal_set_message("Error deleting example xcos 2 file. File not present in database.", 'error'); - return; - } - if (($form_state['values']['cur_xcos2_checkbox'] == 1) && (!$_FILES['files']['name']['xcos2'])) - { - if (!delete_file($cur_file_id)) { - drupal_set_message("Error deleting example xcos 2 file.", 'error'); - return; + /*$file_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE id = %d AND example_id = %d", $cur_file_id, $example_data->id); + $file_data = db_fetch_object($file_q);*/ + $query = db_select('textbook_companion_example_files'); + $query->fields('textbook_companion_example_files'); + $query->condition('id', $cur_file_id); + $query->condition('example_id', $example_data->id); + $result = $query->execute(); + $file_data = $result->fetchObject(); + if (!$file_data) + { + drupal_set_message("Error deleting example source file. File not present in database.", 'error'); + return; + } + if (($form_state['values']['cur_source_checkbox'] == 1) && (!$_FILES['files']['name']['sourcefile1'])) + { + if (!delete_file($cur_file_id)) + { + drupal_set_message("Error deleting example source file.", 'error'); + return; + } + } } - } - } - if ($_FILES['files']['name']['xcos2']) - { - if ($cur_file_id > 0) - { - if (!delete_file($cur_file_id)) + if ($_FILES['files']['name']['sourcefile1']) { - drupal_set_message("Error removing previous example xcos 2 file.", 'error'); - return; + if ($cur_file_id > 0) + { + if (!delete_file($cur_file_id)) + { + drupal_set_message("Error removing previous example source file.", 'error'); + return; + } + } + if (file_exists($root_path . $dest_path . $_FILES['files']['name']['sourcefile1'])) + { + drupal_set_message(t("Error uploading source file. File !filename already exists.", array( + '!filename' => $_FILES['files']['name']['sourcefile1'] + )), 'error'); + return; + } + /* uploading file */ + if (move_uploaded_file($_FILES['files']['tmp_name']['sourcefile1'], $root_path . $dest_path . $_FILES['files']['name']['sourcefile1'])) + { + /* for uploaded files making an entry in the database */ + /*db_query("INSERT INTO {textbook_companion_example_files} (example_id, filename, filepath, filemime, filesize, filetype, timestamp) + VALUES (%d, '%s', '%s', '%s', %d, '%s', %d)", + $example_data->id, + $_FILES['files']['name']['sourcefile1'], + $dest_path . $_FILES['files']['name']['sourcefile1'], + $_FILES['files']['type']['sourcefile1'], + $_FILES['files']['size']['sourcefile1'], + 'S', + time() + );*/ + $query = "INSERT INTO {textbook_companion_example_files} (example_id, filename, filepath, filemime, filesize, filetype, timestamp) + VALUES (:example_id, :filename, :filepath, :filemime, :filesize, :filetype, :timestamp)"; + $args = array( + ":example_id" => $example_data->id, + ":filename" => $_FILES['files']['name']['sourcefile1'], + ":filepath" => $filepath . $_FILES['files']['name']['sourcefile1'], + ":filemime" => 'application/dwxml', + ":filesize" => $_FILES['files']['size']['sourcefile1'], + ":filetype" => 'S', + ":timestamp" => time() + ); + $result = db_query($query, $args, array( + 'return' => Database::RETURN_INSERT_ID + )); + drupal_set_message($_FILES['files']['name']['sourcefile1'] . ' uploaded successfully.', 'status'); + } + else + { + drupal_set_message('Error uploading file : ' . $dest_path . '/' . $_FILES['files']['name']['sourcefile1'], 'error'); + } } - } - if (file_exists($root_path . $dest_path . $_FILES['files']['name']['xcos2'])) - { - drupal_set_message(t("Error uploading xcos 2 file. File !filename already exists.", array('!filename' => $_FILES['files']['name']['xcos2'])), 'error'); - return; - } - /* uploading file */ - if (move_uploaded_file($_FILES['files']['tmp_name']['xcos2'], $root_path . $dest_path . $_FILES['files']['name']['xcos2'])) - { - /* for uploaded files making an entry in the database */ - db_query("INSERT INTO {textbook_companion_example_files} (example_id, filename, filepath, filemime, filesize, filetype, timestamp) - VALUES (%d, '%s', '%s', '%s', %d, '%s', %d)", - $example_data->id, - $_FILES['files']['name']['xcos2'], - $dest_path . $_FILES['files']['name']['xcos2'], - $_FILES['files']['type']['xcos2'], - $_FILES['files']['size']['xcos2'], - 'X', - time() - ); - drupal_set_message($_FILES['files']['name']['xcos2'] . ' uploaded successfully.', 'status'); - } else { - drupal_set_message('Error uploading file : ' . $dest_path . '/' . $_FILES['files']['name']['xcos2'], 'error'); - } + /* sending email */ + $email_to = $user_data->mail; + $param['example_updated_admin']['example_id'] = $example_id; + $param['example_updated_admin']['user_id'] = $proposal_data->uid; + if (!drupal_mail('textbook_companion', 'example_updated_admin', $email_to, language_default(), $param, variable_get('textbook_companion_from_email', NULL), TRUE)) + drupal_set_message('Error sending email message.', 'error'); + drupal_set_message(t("Example successfully udpated."), 'status'); } - - /* sending email */ - $email_to = $user_data->mail; - $param['example_updated_admin']['example_id'] = $example_id; - $param['example_updated_admin']['user_id'] = $proposal_data->uid; - if (!drupal_mail('textbook_companion', 'example_updated_admin', $email_to, language_default(), $param, variable_get('textbook_companion_from_email', NULL), TRUE)) - drupal_set_message('Error sending email message.', 'error'); - - drupal_set_message(t("Example successfully udpated."), 'status'); -} - /******************************************************************************/ /************************** GENERAL FUNCTIONS *********************************/ /******************************************************************************/ - function _list_of_book_titles() -{ - $book_titles = array('0' => 'Please select...'); - $book_titles_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE approval_status = 1 OR approval_status = 3 ORDER BY book ASC"); - while ($book_titles_data = db_fetch_object($book_titles_q)) { - $book_titles[$book_titles_data->id] = $book_titles_data->book . ' (Written by ' . $book_titles_data->author . ')'; + $book_titles = array( + '0' => 'Please select...' + ); + /*$book_titles_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE approval_status = 1 OR approval_status = 3 ORDER BY book ASC");*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $or = db_or(); + $or->condition('approval_status', 1); + $or->condition('approval_status', 3); + $query->condition($or); + $query->orderBy('book', 'ASC'); + $book_titles_q = $query->execute(); + while ($book_titles_data = $book_titles_q->fetchObject()) + { + $book_titles[$book_titles_data->id] = $book_titles_data->book . ' (Written by ' . $book_titles_data->author . ')'; + } + return $book_titles; } - return $book_titles; -} - function _list_of_book_dependency_files() -{ - $book_dependency_files = array(); - $book_dependency_files_class = array(); - $book_dependency_files_q = db_query("SELECT * FROM {textbook_companion_dependency_files} ORDER BY filename ASC"); - - while ($book_dependency_files_data = db_fetch_object($book_dependency_files_q)) { - $temp_caption = ''; - if ($book_dependency_files_data->caption) - $temp_caption .= ' (' . $book_dependency_files_data->caption . ')'; - $book_dependency_files[$book_dependency_files_data->id] = l($book_dependency_files_data->filename . $temp_caption, 'download/dependency/' . $book_dependency_files_data->id); - $book_dependency_files_class[$book_dependency_files_data->id] = $book_dependency_files_data->preference_id; + $book_dependency_files = array(); + $book_dependency_files_class = array(); + /*$book_dependency_files_q = db_query("SELECT * FROM {textbook_companion_dependency_files} ORDER BY filename ASC");*/ + $query = db_select('textbook_companion_dependency_files'); + $query->fields('textbook_companion_dependency_files'); + $query->orderBy('filename', 'ASC'); + $book_dependency_files_q = $query->execute(); + while ($book_dependency_files_data = $book_dependency_files_q->fetchObject()) + { + $temp_caption = ''; + if ($book_dependency_files_data->caption) + $temp_caption .= ' (' . $book_dependency_files_data->caption . ')'; + $book_dependency_files[$book_dependency_files_data->id] = l($book_dependency_files_data->filename . $temp_caption, '/textbook-companion/download/dependency/' . $book_dependency_files_data->id); + $book_dependency_files_class[$book_dependency_files_data->id] = $book_dependency_files_data->preference_id; + } + return array( + $book_dependency_files, + $book_dependency_files_class + ); } - return array($book_dependency_files, $book_dependency_files_class); -} - diff --git a/full_download.inc b/full_download.inc index a269bd8..e688ec4 100755 --- a/full_download.inc +++ b/full_download.inc @@ -1,172 +1,183 @@ <?php // $Id$ - function textbook_companion_download_full_chapter() -{ - $chapter_id = arg(2); - $root_path = textbook_companion_path(); - $APPROVE_PATH = 'APPROVED/'; - $PENDING_PATH = 'PENDING/'; - - /* get example data */ - $chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE id = %d", $chapter_id); - $chapter_data = db_fetch_object($chapter_q); - $CH_PATH = 'CH' . $chapter_data->number . '/'; - - /* zip filename */ - $zip_filename = $root_path . 'zip-' . time() . '-' . rand(0, 999999) . '.zip'; - - /* creating zip archive on the server */ - $zip = new ZipArchive; - $zip->open($zip_filename, ZipArchive::CREATE); - - /* approved examples */ - $example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE chapter_id = %d AND approval_status = 1", $chapter_id); - while ($example_row = db_fetch_object($example_q)) { - $EX_PATH = 'EX' . $example_row->number . '/'; - $example_files_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE example_id = %d", $example_row->id); - $example_dependency_files_q = db_query("SELECT * FROM {textbook_companion_example_dependency} WHERE example_id = %d", $example_row->id); - while ($example_files_row = db_fetch_object($example_files_q)) - { - $zip->addFile($root_path . $example_files_row->filepath, $APPROVE_PATH . $CH_PATH . $EX_PATH . $example_files_row->filename); - } - /* dependency files */ - while ($example_dependency_files_row = db_fetch_object($example_dependency_files_q)) - { - $dependency_file_data = db_fetch_object(db_query("SELECT * FROM {textbook_companion_dependency_files} WHERE id = %d LIMIT 1", $example_dependency_files_row->dependency_id)); - if ($dependency_file_data) - $zip->addFile($root_path . $dependency_file_data->filepath, $APPROVE_PATH . $CH_PATH . $EX_PATH . 'DEPENDENCIES/' . $dependency_file_data->filename); - } - } - - /* unapproved examples */ - $example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE chapter_id = %d AND approval_status = 0", $chapter_id); - while ($example_row = db_fetch_object($example_q)) - { - $EX_PATH = 'EX' . $example_row->number . '/'; - $example_files_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE example_id = %d", $example_row->id); - $example_dependency_files_q = db_query("SELECT * FROM {textbook_companion_example_dependency} WHERE example_id = %d", $example_row->id); - while ($example_files_row = db_fetch_object($example_files_q)) - { - $zip->addFile($root_path . $example_files_row->filepath, $PENDING_PATH . $CH_PATH . $EX_PATH . $example_files_row->filename); - } - /* dependency files */ - while ($example_dependency_files_row = db_fetch_object($example_dependency_files_q)) - { - $dependency_file_data = db_fetch_object(db_query("SELECT * FROM {textbook_companion_dependency_files} WHERE id = %d LIMIT 1", $example_dependency_files_row->dependency_id)); - if ($dependency_file_data) - $zip->addFile($root_path . $dependency_file_data->filepath, $PENDING_PATH . $CH_PATH . $EX_PATH . 'DEPENDENCIES/' . $dependency_file_data->filename); - } - } - - $zip_file_count = $zip->numFiles; - $zip->close(); - - if ($zip_file_count > 0) - { - /* download zip file */ - header('Content-Type: application/zip'); - header('Content-disposition: attachment; filename="CH' . $chapter_data->number . '.zip"'); - header('Content-Length: ' . filesize($zip_filename)); - header("Content-Transfer-Encoding: binary"); - header('Expires: 0'); - header('Pragma: no-cache'); - ob_end_flush(); - ob_clean(); - flush(); - - readfile($zip_filename); - unlink($zip_filename); - } else { - drupal_set_message("There are no examples in this chapter to download", 'error'); - drupal_goto('code_approval/bulk'); - } -} - -function textbook_companion_download_full_book() -{ - $book_id = arg(2); - $root_path = textbook_companion_path(); - $APPROVE_PATH = 'APPROVED/'; - $PENDING_PATH = 'PENDING/'; - /* get example data */ - $book_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d", $book_id); - $book_data = db_fetch_object($book_q); - $BK_PATH = $book_data->book . '/'; - - /* zip filename */ - $zip_filename = $root_path . 'zip-' . time() . '-' . rand(0, 999999) . '.zip'; - - /* creating zip archive on the server */ - $zip = new ZipArchive; - $zip->open($zip_filename, ZipArchive::CREATE); - - /* approved examples */ - $chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE preference_id = %d", $book_id); - while ($chapter_row = db_fetch_object($chapter_q)) - { - $CH_PATH = 'CH' . $chapter_row->number . '/'; - $example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE chapter_id = %d AND approval_status = 1", $chapter_row->id); - while ($example_row = db_fetch_object($example_q)) - { - $EX_PATH = 'EX' . $example_row->number . '/'; - $example_files_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE example_id = %d", $example_row->id); - $example_dependency_files_q = db_query("SELECT * FROM {textbook_companion_example_dependency} WHERE example_id = %d", $example_row->id); - while ($example_files_row = db_fetch_object($example_files_q)) + $chapter_id = arg(3); + $root_path = textbook_companion_path(); + $APPROVE_PATH = 'APPROVED/'; + $PENDING_PATH = 'PENDING/'; + /* get example data */ + /*$chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE id = %d", $chapter_id); + $chapter_data = db_fetch_object($chapter_q);*/ + $query = db_select('textbook_companion_chapter'); + $query->fields('textbook_companion_chapter'); + $query->condition('id', $chapter_id); + $chapter_q = $query->execute(); + $chapter_data = $chapter_q->fetchObject(); + $CH_PATH = 'CH' . $chapter_data->number . '/'; + /* zip filename */ + $zip_filename = $root_path . 'zip-' . time() . '-' . rand(0, 999999) . '.zip'; + /* creating zip archive on the server */ + $zip = new ZipArchive; + $zip->open($zip_filename, ZipArchive::CREATE); + /* approved examples */ + /*$example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE chapter_id = %d AND approval_status = 1", $chapter_id);*/ + $query = db_select('textbook_companion_example'); + $query->fields('textbook_companion_example'); + $query->condition('chapter_id', $chapter_id); + $query->condition('approval_status', 1); + $example_q = $query->execute(); + while ($example_row = $example_q->fetchObject()) { - $zip->addFile($root_path . $example_files_row->filepath, $BK_PATH . $APPROVE_PATH . $CH_PATH . $EX_PATH . $example_files_row->filename); + $EX_PATH = 'EX' . $example_row->number . '/'; + /*$example_files_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE example_id = %d", $example_row->id);*/ + $query = db_select('textbook_companion_example_files'); + $query->fields('textbook_companion_example_files'); + $query->condition('example_id', $example_row->id); + $example_files_q = $query->execute(); + while ($example_files_row = $example_files_q->fetchObject()) + { + $zip->addFile($root_path . $example_files_row->filepath, $APPROVE_PATH . $CH_PATH . $EX_PATH . $example_files_row->filename); + } } - /* dependency files */ - while ($example_dependency_files_row = db_fetch_object($example_dependency_files_q)) + /* unapproved examples */ + /*$example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE chapter_id = %d AND approval_status = 0", $chapter_id);*/ + $query = db_select('textbook_companion_example'); + $query->fields('textbook_companion_example'); + $query->condition('chapter_id', $chapter_id); + $query->condition('approval_status', 0); + $example_q = $query->execute(); + while ($example_row = $example_q->fetchObject()) { - $dependency_file_data = db_fetch_object(db_query("SELECT * FROM {textbook_companion_dependency_files} WHERE id = %d LIMIT 1", $example_dependency_files_row->dependency_id)); - if ($dependency_file_data) - $zip->addFile($root_path . $dependency_file_data->filepath, $BK_PATH . $APPROVE_PATH . $CH_PATH . $EX_PATH . 'DEPENDENCIES/' . $dependency_file_data->filename); + $EX_PATH = 'EX' . $example_row->number . '/'; + /*$example_files_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE example_id = %d", $example_row->id);*/ + $example_files_q = db_query("select * from textbook_companion_preference tcp join textbook_companion_chapter tcc on tcp.id=tcc.preference_id join textbook_companion_example tce ON tcc.id=tce.chapter_id join textbook_companion_example_files tcef on tce.id=tcef.example_id where tcef.example_id= :example_id", array( + ':example_id' => $example_row->id + )); + /*$query = db_select('textbook_companion_example_files'); + $query->fields('textbook_companion_example_files'); + $query->condition('example_id', $example_row->id); + $example_files_q = $query->execute();*/ + while ($example_files_row = $example_files_q->fetchObject()) + { + $zip->addFile($root_path . $example_files_row->directory_name . '/' . $example_files_row->filepath, $PENDING_PATH . $CH_PATH . $EX_PATH . $example_files_row->filename); + } } - } - - /* unapproved examples */ - $example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE chapter_id = %d AND approval_status = 0", $chapter_row->id); - while ($example_row = db_fetch_object($example_q)) - { - $EX_PATH = 'EX' . $example_row->number . '/'; - $example_files_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE example_id = %d", $example_row->id); - $example_dependency_files_q = db_query("SELECT * FROM {textbook_companion_example_dependency} WHERE example_id = %d", $example_row->id); - while ($example_files_row = db_fetch_object($example_files_q)) + $zip_file_count = $zip->numFiles; + $zip->close(); + if ($zip_file_count > 0) { - $zip->addFile($root_path . $example_files_row->filepath, $BK_PATH . $PENDING_PATH . $CH_PATH . $EX_PATH . $example_files_row->filename); + /* download zip file */ + header('Content-Type: application/zip'); + header('Content-disposition: attachment; filename="CH' . $chapter_data->number . '.zip"'); + header('Content-Length: ' . filesize($zip_filename)); + header("Content-Transfer-Encoding: binary"); + header('Expires: 0'); + header('Pragma: no-cache'); + ob_end_flush(); + ob_clean(); + flush(); + readfile($zip_filename); + unlink($zip_filename); } - /* dependency files */ - while ($example_dependency_files_row = db_fetch_object($example_dependency_files_q)) + else { - $dependency_file_data = db_fetch_object(db_query("SELECT * FROM {textbook_companion_dependency_files} WHERE id = %d LIMIT 1", $example_dependency_files_row->dependency_id)); - if ($dependency_file_data) - $zip->addFile($root_path . $dependency_file_data->filepath, $BK_PATH . $PENDING_PATH . $CH_PATH . $EX_PATH . 'DEPENDENCIES/' . $dependency_file_data->filename); + drupal_set_message("There are no examples in this chapter to download", 'error'); + drupal_goto('textbook-companion/code-approval/bulk'); } - } } - - $zip_file_count = $zip->numFiles; - $zip->close(); - - if ($zip_file_count > 0) +function textbook_companion_download_full_book() { - /* download zip file */ - header('Content-Type: application/zip'); - header('Content-disposition: attachment; filename="' . $book_data->book . '.zip"'); - header('Content-Length: ' . filesize($zip_filename)); - //header("Content-Transfer-Encoding: binary"); - //header('Expires: 0'); - //header('Pragma: no-cache'); - //ob_end_flush(); - ob_clean(); - //flush(); - readfile($zip_filename); - unlink($zip_filename); - } else { - drupal_set_message("There are no examples in this book to download", 'error'); - drupal_goto('code_approval/bulk'); + $book_id = arg(3); + $root_path = textbook_companion_path(); + $APPROVE_PATH = 'APPROVED/'; + $PENDING_PATH = 'PENDING/'; + /* get example data */ + /*$book_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d", $book_id); + $book_data = db_fetch_object($book_q);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('id', $book_id); + $book_q = $query->execute(); + $book_data = $book_q->fetchObject(); + //$zipname = str_replace(' ','_',($book_data->book)); + //$BK_PATH = $zipname . '/'; + $BK_PATH = $book_data->book . '/'; + /* zip filename */ + $zip_filename = $root_path . 'zip-' . time() . '-' . rand(0, 999999) . '.zip'; + /* creating zip archive on the server */ + $zip = new ZipArchive; + $zip->open($zip_filename, ZipArchive::CREATE); + /* approved examples */ + /*$chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE preference_id = %d", $book_id);*/ + $query = db_select('textbook_companion_chapter'); + $query->fields('textbook_companion_chapter'); + $query->condition('preference_id', $book_id); + $chapter_q = $query->execute(); + while ($chapter_row = $chapter_q->fetchObject()) + { + $CH_PATH = 'CH' . $chapter_row->number . '/'; + /*$example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE chapter_id = %d AND approval_status = 1", $chapter_row->id);*/ + $query = db_select('textbook_companion_example'); + $query->fields('textbook_companion_example'); + $query->condition('chapter_id', $chapter_row->id); + $query->condition('approval_status', 1); + $example_q = $query->execute(); + while ($example_row = $example_q->fetchObject()) + { + $EX_PATH = 'EX' . $example_row->number . '/'; + /*$example_files_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE example_id = %d", $example_row->id);*/ + $example_files_q = db_query("select * from textbook_companion_preference tcp join textbook_companion_chapter tcc on tcp.id=tcc.preference_id join textbook_companion_example tce ON tcc.id=tce.chapter_id join textbook_companion_example_files tcef on tce.id=tcef.example_id where tcef.example_id= :example_id", array( + ':example_id' => $example_row->id + )); + /*$query = db_select('textbook_companion_example_files'); + $query->fields('textbook_companion_example_files'); + $query->condition('example_id', $example_row->id); + $example_files_q = $query->execute();*/ + while ($example_files_row = $example_files_q->fetchObject()) + { + $zip->addFile($root_path . $example_files_row->directory_name . '/' . $example_files_row->filepath, $BK_PATH . $APPROVE_PATH . $CH_PATH . $EX_PATH . $example_files_row->filename); + } + } + /* unapproved examples */ + /* $example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE chapter_id = %d AND approval_status = 0", $chapter_row->id);*/ + $query = db_select('textbook_companion_example'); + $query->fields('textbook_companion_example'); + $query->condition('chapter_id', $chapter_row->id); + $query->condition('approval_status', 0); + $example_q = $query->execute(); + while ($example_row = $example_q->fetchObject()) + { + $EX_PATH = 'EX' . $example_row->number . '/'; + /*$example_files_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE example_id = %d", $example_row->id);*/ + $example_files_q = db_query("select * from textbook_companion_preference tcp join textbook_companion_chapter tcc on tcp.id=tcc.preference_id join textbook_companion_example tce ON tcc.id=tce.chapter_id join textbook_companion_example_files tcef on tce.id=tcef.example_id where tcef.example_id= :example_id", array( + ':example_id' => $example_row->id + )); + /*$query = db_select('textbook_companion_example_files'); + $query->fields('textbook_companion_example_files'); + $query->condition('example_id', $example_row->id); + $example_files_q = $query->execute();*/ + while ($example_files_row = $example_files_q->fetchObject()) + { + $zip->addFile($root_path . $example_files_row->directory_name . '/' . $example_files_row->filepath, $BK_PATH . $PENDING_PATH . $CH_PATH . $EX_PATH . $example_files_row->filename); + } + } + } + $zip_file_count = $zip->numFiles; + $zip->close(); + if ($zip_file_count > 0) + { + /* download zip file */ + header('Content-Type: application/zip'); + header('Content-disposition: attachment; filename="' . str_replace(' ', '_', ($book_data->book)) . '.zip"'); + header('Content-Length: ' . filesize($zip_filename)); + ob_clean(); + readfile($zip_filename); + unlink($zip_filename); + } + else + { + drupal_set_message("There are no examples in this book to download", 'error'); + drupal_goto('textbook-companion/code-approval/bulk'); + } } -} - diff --git a/general.inc b/general.inc index 2e36eae..5c79e92 100755 --- a/general.inc +++ b/general.inc @@ -1,192 +1,408 @@ <?php // $Id$ - function list_chapters() -{ - global $user; - - /************************ start approve book details ************************/ - $proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid = %d ORDER BY id DESC LIMIT 1", $user->uid); - $proposal_data = db_fetch_object($proposal_q); - if (!$proposal_data) { - drupal_set_message("Please submit a " . l('proposal', 'proposal') . ".", 'error'); - drupal_goto(''); - } - if ($proposal_data->proposal_status != 1) - { - switch ($proposal_data->proposal_status ) - { - case 0: - drupal_set_message(t('We have already received your proposal. We will get back to you soon.'), 'status'); - drupal_goto(''); - return; - break; - case 2: - drupal_set_message(t('Your proposal has been dis-approved. Please create another proposal ' . l('here', 'proposal') . '.'), 'error'); - drupal_goto(''); - return; - break; - case 3: - drupal_set_message(t('Congratulations! You have completed your last book proposal. You have to create another proposal ' . l('here', 'proposal') . '.'), 'status'); + global $user; + /************************ start approve book details ************************/ + /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid = %d ORDER BY id DESC LIMIT 1", $user->uid); + $proposal_data = db_fetch_object($proposal_q);*/ + $query = db_select('textbook_companion_proposal'); + $query->fields('textbook_companion_proposal'); + $query->condition('uid', $user->uid); + $query->orderBy('id', 'DESC'); + $query->range(0, 1); + $result = $query->execute(); + $proposal_data = $result->fetchObject(); + if (!$proposal_data) + { + drupal_set_message("Please submit a " . l('proposal', 'textbook-companion/proposal') . ".", 'error'); + drupal_goto(''); + } + if ($proposal_data->proposal_status != 1 && $proposal_data->proposal_status != 4) + { + switch ($proposal_data->proposal_status) + { + case 0: + drupal_set_message(t('We have already received your proposal. We will get back to you soon.'), 'status'); + drupal_goto(''); + return; + break; + case 2: + drupal_set_message(t('Your proposal has been dis-approved. Please create another proposal ' . l('here', 'textbook-companion/proposal') . '.'), 'error'); + drupal_goto(''); + return; + break; + case 3: + drupal_set_message(t('Congratulations! You have completed your last book proposal. You have to create another proposal ' . l('here', 'textbook-companion/proposal') . '.'), 'status'); + drupal_goto(''); + return; + break; +case 5: + drupal_set_message(t('You have submitted your all examples.'), 'status'); drupal_goto(''); return; - break; - default: - drupal_set_message(t('Invalid proposal state. Please contact site administrator for further information.'), 'error'); - drupal_goto(''); - return; - break; - } + default: + drupal_set_message(t('Invalid proposal state. Please contact site administrator for further information.'), 'error'); + drupal_goto(''); + return; + break; + } + } + + + /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND approval_status = 1 LIMIT 1", $proposal_data->id); + $preference_data = db_fetch_object($preference_q);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('proposal_id', $proposal_data->id); + $query->condition('approval_status', 1); + $query->range(0, 1); + $result = $query->execute(); + $preference_data = $result->fetchObject(); + if (!$preference_data) + { + drupal_set_message(t('Invalid Book Preference status. Please contact site administrator for further information.'), 'error'); + drupal_goto(''); + return; + } + /************************ end approve book details **************************/ + $return_html = '<br />'; + $return_html .= '<strong>Title of the Book:</strong><br />' . $preference_data->book . '<br /><br />'; + $return_html .= '<strong>Contributor Name:</strong><br />' . $proposal_data->full_name . '<br /><br />'; + $return_html .= l('Upload Example Code', 'textbook-companion/code/upload') . '<br />'; + /* get chapter list */ + $chapter_rows = array(); + /*$chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE preference_id = %d ORDER BY number ASC", $preference_data->id);*/ + $query = db_select('textbook_companion_chapter'); + $query->fields('textbook_companion_chapter'); + $query->condition('preference_id', $preference_data->id); + $query->orderBy('number', 'ASC'); + $chapter_q = $query->execute(); + while ($chapter_data = $chapter_q->fetchObject()) + { + /* get example list */ + /* $example_q = db_query("SELECT count(*) as example_count FROM {textbook_companion_example} WHERE chapter_id = %d", $chapter_data->id); + $example_data = db_fetch_object($example_q);*/ + $query = db_select('textbook_companion_example'); + $query->addExpression('count(*)', 'example_count'); + $query->condition('chapter_id', $chapter_data->id); + $result = $query->execute(); + $example_data = $result->fetchObject(); + $chapter_rows[] = array( + $chapter_data->number, + $chapter_data->name . ' (' . l('Edit', 'textbook-companion/code/chapter/edit/' . $chapter_data->id) . ')', + $example_data->example_count, + l('View', 'textbook-companion/code/list-examples/' . $chapter_data->id) + ); + } + /* check if there are any chapters */ + if (!$chapter_rows) + { + drupal_set_message(t('No uploads found.'), 'status'); + return $return_html; + } + $chapter_header = array( + 'Chapter No.', + 'Title of the Chapter', + 'Uploaded Examples', + 'Actions' + ); + $return_html .= theme('table', array( + 'header' => $chapter_header, + 'rows' => $chapter_rows + )); + $submit_all_code_form = drupal_get_form('submit_all_code_form',$proposal_data->id, $preference_data->id); + $return_html .= drupal_render($submit_all_code_form); + return $return_html; } - - $preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND approval_status = 1 LIMIT 1", $proposal_data->id); - $preference_data = db_fetch_object($preference_q); - if (!$preference_data) +function list_examples() { - drupal_set_message(t('Invalid Book Preference status. Please contact site administrator for further information.'), 'error'); - drupal_goto(''); - return; - } - /************************ end approve book details **************************/ - - $return_html = '<br />'; - $return_html .= '<strong>Title of the Book:</strong><br />' . $preference_data->book . '<br /><br />'; - $return_html .= '<strong>Contributor Name:</strong><br />' . $proposal_data->full_name . '<br /><br />'; - $return_html .= l('Upload Example Code', 'textbook_companion/code/upload') . '<br />'; + global $user; + /************************ start approve book details ************************/ + /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid = %d ORDER BY id DESC LIMIT 1", $user->uid); + $proposal_data = db_fetch_object($proposal_q);*/ + $query = db_select('textbook_companion_proposal'); + $query->fields('textbook_companion_proposal'); + $query->condition('uid', $user->uid); + $query->orderBy('id', 'DESC'); + $query->range(0, 1); + $result = $query->execute(); + $proposal_data = $result->fetchObject(); + if (!$proposal_data) + { + drupal_set_message("Please submit a " . l('proposal', 'textbook-companion/proposal') . ".", 'error'); + drupal_goto(''); + } + if ($proposal_data->proposal_status != 1 && $proposal_data->proposal_status != 4) + { + switch ($proposal_data->proposal_status) + { + case 0: + drupal_set_message(t('We have already received your proposal. We will get back to you soon.'), 'status'); + drupal_goto(''); + return; + break; + case 2: + drupal_set_message(t('Your proposal has been dis-approved. Please create another proposal ' . l('here', 'textbook-companion/proposal') . '.'), 'error'); + drupal_goto(''); + return; + break; + case 3: + drupal_set_message(t('Congratulations! You have completed your last book proposal. You have to create another proposal ' . l('here', 'textbook-companion/proposal') . '.'), 'status'); + drupal_goto(''); + return; + break; +case 5: + drupal_set_message(t('You have submitted your all codes.'), 'status'); + drupal_goto(''); + return; - /* get chapter list */ - $chapter_rows = array(); - $chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE preference_id = %d ORDER BY number ASC", $preference_data->id); - while ($chapter_data = db_fetch_object($chapter_q)) - { + default: + drupal_set_message(t('Invalid proposal state. Please contact site administrator for further information.'), 'error'); + drupal_goto(''); + return; + break; + } + } + /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND approval_status = 1 LIMIT 1", $proposal_data->id); + $preference_data = db_fetch_object($preference_q);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('proposal_id', $proposal_data->id); + $query->condition('approval_status', 1); + $query->range(0, 1); + $result = $query->execute(); + $preference_data = $result->fetchObject(); + if (!$preference_data) + { + drupal_set_message(t('Invalid Book Preference status. Please contact site administrator for further information.'), 'error'); + drupal_goto(''); + return; + } + /************************ end approve book details **************************/ + /* get chapter details */ + $chapter_id = arg(3); + /*$chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE id = %d AND preference_id = %d LIMIT 1", $chapter_id, $preference_data->id);*/ + $query = db_select('textbook_companion_chapter'); + $query->fields('textbook_companion_chapter'); + $query->condition('id', $chapter_id); + $query->condition('preference_id', $preference_data->id); + $query->range(0, 1); + $chapter_q = $query->execute(); + if ($chapter_data = $chapter_q->fetchObject()) + { + $return_html = '<br />'; + $return_html .= '<strong>Title of the Book:</strong><br />' . $preference_data->book . '<br /><br />'; + $return_html .= '<strong>Contributor Name:</strong><br />' . $proposal_data->full_name . '<br /><br />'; + $return_html .= '<strong>Chapter Number:</strong><br />' . $chapter_data->number . '<br /><br />'; + $return_html .= '<strong>Title of the Chapter:</strong><br />' . $chapter_data->name . '<br />'; + } + else + { + drupal_set_message(t('Invalid chapter.'), 'error'); + drupal_goto('textbook-companion/code'); + return; + } + $return_html .= '<br />' . l('Back to Chapter List', 'textbook-companion/code'); /* get example list */ - $example_q = db_query("SELECT count(*) as example_count FROM {textbook_companion_example} WHERE chapter_id = %d", $chapter_data->id); - $example_data = db_fetch_object($example_q); - $chapter_rows[] = array($chapter_data->number, $chapter_data->name . ' (' . l('Edit', 'textbook_companion/code/chapter/edit/' . $chapter_data->id) . ')', $example_data->example_count, l('View', 'textbook_companion/code/list_examples/' . $chapter_data->id)); - } - - /* check if there are any chapters */ - if (!$chapter_rows) - { - drupal_set_message(t('No uploads found.'), 'status'); + $example_rows = array(); + $query = db_select('textbook_companion_example'); + $query->fields('textbook_companion_example'); + $query->condition('chapter_id', $chapter_id); + $example_q = $query->execute(); + while ($example_data = $example_q->fetchObject()) + { + /* approval status */ + $approval_status = ''; + switch ($example_data->approval_status) + { + case 0: + $approval_status = 'Pending'; + break; + case 1: + $approval_status = 'Approved'; + break; + case 2: + $approval_status = 'Rejected'; + break; + } + /* example files */ + $example_files = ''; + /*$example_files_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE example_id = %d ORDER BY filetype", $example_data->id);*/ + $query = db_select('textbook_companion_example_files'); + $query->fields('textbook_companion_example_files'); + $query->condition('example_id', $example_data->id); + $query->orderBy('filetype', 'ASC'); + $example_files_q = $query->execute(); + while ($example_files_data = $example_files_q->fetchObject()) + { + $file_type = ''; + switch ($example_files_data->filetype) + { + case 'S': + $file_type = 'Main or Source'; + break; + case 'R': + $file_type = 'Result'; + break; + case 'X': + $file_type = 'xcos'; + break; + default: + } + $example_files .= l($example_files_data->filename, 'textbook-companion/download/file/' . $example_files_data->id) . ' (' . $file_type . ')<br />'; + } + if ($example_data->approval_status == 0) + { + $example_rows[] = array( + 'data' => array( + $example_data->number, + $example_data->caption, + $approval_status, + $example_files, + l('Edit', 'textbook-companion/code/edit/' . $example_data->id) . ' | ' . l('Delete', 'textbook-companion/code/delete/' . $example_data->id, array( + 'attributes' => array( + 'onClick' => 'return confirm("Are you sure you want to delete the example?")' + ) + )) + ), + 'valign' => 'top' + ); + } + else + { + $example_rows[] = array( + 'data' => array( + $example_data->number, + $example_data->caption, + $approval_status, + $example_files, + l('Download', 'textbook-companion/download/example/' . $example_data->id) + ), + 'valign' => 'top' + ); + } + } + $example_header = array( + 'Example No.', + 'Caption', + 'Status', + 'Files', + 'Action' + ); + $return_html .= theme('table', array( + 'header' => $example_header, + 'rows' => $example_rows + )); + return $return_html; } - - $chapter_header = array('Chapter No.', 'Title of the Chapter', 'Uploaded Examples', 'Actions'); - $return_html .= theme_table($chapter_header, $chapter_rows); - return $return_html; +/*function all_example_submitted_check_form($form,$form_state,$preference_id){ + $form = array(); + $form['all_example_submitted'] = array( + '#type' => 'checkbox', + '#title' => t('I have submitted codes for all the examples'), + '#description' => 'Once you have submited this option you are not able to upload more examples.', + '#required' => TRUE, + ); + $form['hidden_preference_id'] = array( + '#type' => 'hidden', + '#value' => $preference_id + ); + $form['submit'] = array( + '#type' => 'submit', + '#value' => t('Submit') + ); + return $form; } +*/ -function list_examples() -{ - global $user; - - /************************ start approve book details ************************/ - $proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid = %d ORDER BY id DESC LIMIT 1", $user->uid); - $proposal_data = db_fetch_object($proposal_q); - if (!$proposal_data) - { - drupal_set_message("Please submit a " . l('proposal', 'proposal') . ".", 'error'); - drupal_goto(''); - } - if ($proposal_data->proposal_status != 1) - { - switch ($proposal_data->proposal_status ) - { - case 0: - drupal_set_message(t('We have already received your proposal. We will get back to you soon.'), 'status'); - drupal_goto(''); - return; - break; - case 2: - drupal_set_message(t('Your proposal has been dis-approved. Please create another proposal ' . l('here', 'proposal') . '.'), 'error'); - drupal_goto(''); - return; - break; - case 3: - drupal_set_message(t('Congratulations! You have completed your last book proposal. You have to create another proposal ' . l('here', 'proposal') . '.'), 'status'); - drupal_goto(''); - return; - break; - default: - drupal_set_message(t('Invalid proposal state. Please contact site administrator for further information.'), 'error'); - drupal_goto(''); - return; - break; - } - } +function all_example_submitted_check_form_submit($form,$form_state){ +global $user; +if ($form_state['values']['all_example_submitted'] == 1) { +db_query('UPDATE textbook_companion_preference SET submited_all_examples_code = 1 WHERE id = :preference_id',array(':preference_id' => $form_state['values']['hidden_preference_id'])); + /* sending email */ + $query = ("SELECT proposal_id FROM textbook_companion_preference WHERE id= :preference_id"); + $args = array(":preference_id" => $form_state['values']['hidden_preference_id']); + $proposal_data = db_query($query,$args); + $proposal_data_result = $proposal_data->fetchObject(); - $preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND approval_status = 1 LIMIT 1", $proposal_data->id); - $preference_data = db_fetch_object($preference_q); - if (!$preference_data) - { - drupal_set_message(t('Invalid Book Preference status. Please contact site administrator for further information.'), 'error'); - drupal_goto(''); - return; - } - /************************ end approve book details **************************/ + $email_to = $user->mail; + $from = variable_get('textbook_companion_from_email', ''); + $bcc = variable_get('textbook_companion_emails', ''); + $cc = variable_get('textbook_companion_cc_emails', ''); + $param['all_code_submitted']['proposal_id'] = $proposal_data_result->proposal_id; + $param['all_code_submitted']['user_id'] = $user->uid; + $param['all_code_submitted']['headers'] = array( + 'From' => $from, + 'MIME-Version' => '1.0', + 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes', + 'Content-Transfer-Encoding' => '8Bit', + 'X-Mailer' => 'Drupal', + 'Cc' => $cc, + 'Bcc' => $bcc + ); + if (!drupal_mail('textbook_companion', 'all_code_submitted', $email_to, language_default(), $param, $from, TRUE)) + drupal_set_message('Error sending email message.', 'error'); +} +} - /* get chapter details */ - $chapter_id = arg(3); - $chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE id = %d AND preference_id = %d LIMIT 1", $chapter_id, $preference_data->id); - if ($chapter_data = db_fetch_object($chapter_q)) - { - $return_html = '<br />'; - $return_html .= '<strong>Title of the Book:</strong><br />' . $preference_data->book . '<br /><br />'; - $return_html .= '<strong>Contributor Name:</strong><br />' . $proposal_data->full_name . '<br /><br />'; - $return_html .= '<strong>Chapter Number:</strong><br />' . $chapter_data->number . '<br /><br />'; - $return_html .= '<strong>Title of the Chapter:</strong><br />' . $chapter_data->name . '<br />'; - } else { - drupal_set_message(t('Invalid chapter.'), 'error'); - drupal_goto('textbook_companion/code'); - return; - } +function submit_all_code_form($form,&$form_state,$proposal_id,$preference_id){ +$form = array(); +$form['submit_all_code'] = array( + '#type' => 'checkbox', + '#title' => t('I have uploaded all the codes'), + '#description' => 'Once you have submited this option you are not able to upload more examples.', + '#required' => TRUE, +); +$form['prop_id'] = array( + '#type' => 'hidden', + '#value' => $proposal_id +); +$form['pref_id'] = array( + '#type' => 'hidden', + '#value' => $preference_id +); - $return_html .= '<br />' . l('Back to Chapter List', 'textbook_companion/code'); +$form['submit'] = array( + '#type' => 'submit', + '#value' => t('Submit') + ); - /* get example list */ - $example_rows = array(); - $example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE chapter_id = %d ORDER BY - CAST(SUBSTRING_INDEX(number, '.', 1) AS BINARY) ASC, - CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(number , '.', 2), '.', -1) AS UNSIGNED) ASC, - CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(number , '.', -1), '.', 1) AS UNSIGNED) ASC", $chapter_id); - while ($example_data = db_fetch_object($example_q)) - { - /* approval status */ - $approval_status = ''; - switch ($example_data->approval_status) - { - case 0: $approval_status = 'Pending'; break; - case 1: $approval_status = 'Approved'; break; - case 2: $approval_status = 'Rejected'; break; - } + $form['cancel'] = array( + '#type' => 'markup', + '#value' => l(t('Cancel'), 'textbook-companion/code'), + ); + return $form; +} - /* example files */ - $example_files = ''; - $example_files_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE example_id = %d ORDER BY filetype", $example_data->id); - while ($example_files_data = db_fetch_object($example_files_q)) - { - $file_type = ''; - switch ($example_files_data->filetype) - { - case 'S': $file_type = 'Main or Source'; break; - case 'R': $file_type = 'Result'; break; - case 'X': $file_type = 'xcos'; break; - default: - } - $example_files .= l($example_files_data->filename, 'download/file/' . $example_files_data->id) . ' (' . $file_type . ')<br />'; - } +function submit_all_code_form_submit($form,&$form_state){ +global $user; +if($form_state['values']['submit_all_code']== 1){ +db_query('UPDATE textbook_companion_proposal SET proposal_status = 5 WHERE id = :id', array(":id" =>$form_state['values']['prop_id'])); +/* sending email */ + $query = ("SELECT proposal_id FROM textbook_companion_preference WHERE id= :preference_id"); + $args = array(":preference_id" => $form_state['values']['pref_id']); + $proposal_data = db_query($query,$args); + $proposal_data_result = $proposal_data->fetchObject(); - if ($example_data->approval_status == 0) - { - $example_rows[] = array('data' => array($example_data->number, $example_data->caption, $approval_status, $example_files, l('Edit', 'textbook_companion/code/edit/' . $example_data->id) . ' | ' . l('Delete', 'textbook_companion/code/delete/' . $example_data->id, array('attributes' => array('onClick' => 'return confirm("Are you sure you want to delete the example?")')))), 'valign' => 'top'); - } else { - $example_rows[] = array('data' => array($example_data->number, $example_data->caption, $approval_status, $example_files, l('Download', 'download/example/' . $example_data->id)), 'valign' => 'top'); - } - } + $email_to = $user->mail; + $from = variable_get('textbook_companion_from_email', ''); + $bcc = variable_get('textbook_companion_emails', ''); + $cc = variable_get('textbook_companion_cc_emails', ''); + $params['all_code_submitted']['proposal_id'] = $proposal_data_result->proposal_id; + $params['all_code_submitted']['user_id'] = $user->uid; + $params['all_code_submitted']['headers'] = array( + 'From' => $from, + 'MIME-Version' => '1.0', + 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes', + 'Content-Transfer-Encoding' => '8Bit', + 'X-Mailer' => 'Drupal', + 'Cc' => $cc, + 'Bcc' => $bcc + ); + if (!drupal_mail('textbook_companion', 'all_code_submitted', $email_to, language_default(), $params, $from, TRUE)) + drupal_set_message('Error sending email message.', 'error'); +} - $example_header = array('Example No.', 'Caption', 'Status', 'Files', 'Action'); - $return_html .= theme_table($example_header, $example_rows); - return $return_html; -} +} diff --git a/js/jquery-1.9.1.js b/js/jquery-1.9.1.js deleted file mode 100755 index 2d33ce3..0000000 --- a/js/jquery-1.9.1.js +++ /dev/null @@ -1,9598 +0,0 @@ -/*! - * jQuery JavaScript Library v1.9.1 - * http://jquery.com/ - * - * Includes Sizzle.js - * http://sizzlejs.com/ - * - * Copyright 2005, 2012 jQuery Foundation, Inc. and other contributors - * Released under the MIT license - * http://jquery.org/license - * - * Date: 2013-2-4 - */ -(function( window, undefined ) { - -// Can't do this because several apps including ASP.NET trace -// the stack via arguments.caller.callee and Firefox dies if -// you try to trace through "use strict" call chains. (#13335) -// Support: Firefox 18+ -//"use strict"; -var - // The deferred used on DOM ready - readyList, - - // A central reference to the root jQuery(document) - rootjQuery, - - // Support: IE<9 - // For `typeof node.method` instead of `node.method !== undefined` - core_strundefined = typeof undefined, - - // Use the correct document accordingly with window argument (sandbox) - document = window.document, - location = window.location, - - // Map over jQuery in case of overwrite - _jQuery = window.jQuery, - - // Map over the $ in case of overwrite - _$ = window.$, - - // [[Class]] -> type pairs - class2type = {}, - - // List of deleted data cache ids, so we can reuse them - core_deletedIds = [], - - core_version = "1.9.1", - - // Save a reference to some core methods - core_concat = core_deletedIds.concat, - core_push = core_deletedIds.push, - core_slice = core_deletedIds.slice, - core_indexOf = core_deletedIds.indexOf, - core_toString = class2type.toString, - core_hasOwn = class2type.hasOwnProperty, - core_trim = core_version.trim, - - // Define a local copy of jQuery - jQuery = function( selector, context ) { - // The jQuery object is actually just the init constructor 'enhanced' - return new jQuery.fn.init( selector, context, rootjQuery ); - }, - - // Used for matching numbers - core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, - - // Used for splitting on whitespace - core_rnotwhite = /\S+/g, - - // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) - rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, - - // A simple way to check for HTML strings - // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) - // Strict HTML recognition (#11290: must start with <) - rquickExpr = /^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/, - - // Match a standalone tag - rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, - - // JSON RegExp - rvalidchars = /^[\],:{}\s]*$/, - rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, - rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, - rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g, - - // Matches dashed string for camelizing - rmsPrefix = /^-ms-/, - rdashAlpha = /-([\da-z])/gi, - - // Used by jQuery.camelCase as callback to replace() - fcamelCase = function( all, letter ) { - return letter.toUpperCase(); - }, - - // The ready event handler - completed = function( event ) { - - // readyState === "complete" is good enough for us to call the dom ready in oldIE - if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) { - detach(); - jQuery.ready(); - } - }, - // Clean-up method for dom ready events - detach = function() { - if ( document.addEventListener ) { - document.removeEventListener( "DOMContentLoaded", completed, false ); - window.removeEventListener( "load", completed, false ); - - } else { - document.detachEvent( "onreadystatechange", completed ); - window.detachEvent( "onload", completed ); - } - }; - -jQuery.fn = jQuery.prototype = { - // The current version of jQuery being used - jquery: core_version, - - constructor: jQuery, - init: function( selector, context, rootjQuery ) { - var match, elem; - - // HANDLE: $(""), $(null), $(undefined), $(false) - if ( !selector ) { - return this; - } - - // Handle HTML strings - if ( typeof selector === "string" ) { - if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { - // Assume that strings that start and end with <> are HTML and skip the regex check - match = [ null, selector, null ]; - - } else { - match = rquickExpr.exec( selector ); - } - - // Match html or make sure no context is specified for #id - if ( match && (match[1] || !context) ) { - - // HANDLE: $(html) -> $(array) - if ( match[1] ) { - context = context instanceof jQuery ? context[0] : context; - - // scripts is true for back-compat - jQuery.merge( this, jQuery.parseHTML( - match[1], - context && context.nodeType ? context.ownerDocument || context : document, - true - ) ); - - // HANDLE: $(html, props) - if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { - for ( match in context ) { - // Properties of context are called as methods if possible - if ( jQuery.isFunction( this[ match ] ) ) { - this[ match ]( context[ match ] ); - - // ...and otherwise set as attributes - } else { - this.attr( match, context[ match ] ); - } - } - } - - return this; - - // HANDLE: $(#id) - } else { - elem = document.getElementById( match[2] ); - - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document #6963 - if ( elem && elem.parentNode ) { - // Handle the case where IE and Opera return items - // by name instead of ID - if ( elem.id !== match[2] ) { - return rootjQuery.find( selector ); - } - - // Otherwise, we inject the element directly into the jQuery object - this.length = 1; - this[0] = elem; - } - - this.context = document; - this.selector = selector; - return this; - } - - // HANDLE: $(expr, $(...)) - } else if ( !context || context.jquery ) { - return ( context || rootjQuery ).find( selector ); - - // HANDLE: $(expr, context) - // (which is just equivalent to: $(context).find(expr) - } else { - return this.constructor( context ).find( selector ); - } - - // HANDLE: $(DOMElement) - } else if ( selector.nodeType ) { - this.context = this[0] = selector; - this.length = 1; - return this; - - // HANDLE: $(function) - // Shortcut for document ready - } else if ( jQuery.isFunction( selector ) ) { - return rootjQuery.ready( selector ); - } - - if ( selector.selector !== undefined ) { - this.selector = selector.selector; - this.context = selector.context; - } - - return jQuery.makeArray( selector, this ); - }, - - // Start with an empty selector - selector: "", - - // The default length of a jQuery object is 0 - length: 0, - - // The number of elements contained in the matched element set - size: function() { - return this.length; - }, - - toArray: function() { - return core_slice.call( this ); - }, - - // Get the Nth element in the matched element set OR - // Get the whole matched element set as a clean array - get: function( num ) { - return num == null ? - - // Return a 'clean' array - this.toArray() : - - // Return just the object - ( num < 0 ? this[ this.length + num ] : this[ num ] ); - }, - - // Take an array of elements and push it onto the stack - // (returning the new matched element set) - pushStack: function( elems ) { - - // Build a new jQuery matched element set - var ret = jQuery.merge( this.constructor(), elems ); - - // Add the old object onto the stack (as a reference) - ret.prevObject = this; - ret.context = this.context; - - // Return the newly-formed element set - return ret; - }, - - // Execute a callback for every element in the matched set. - // (You can seed the arguments with an array of args, but this is - // only used internally.) - each: function( callback, args ) { - return jQuery.each( this, callback, args ); - }, - - ready: function( fn ) { - // Add the callback - jQuery.ready.promise().done( fn ); - - return this; - }, - - slice: function() { - return this.pushStack( core_slice.apply( this, arguments ) ); - }, - - first: function() { - return this.eq( 0 ); - }, - - last: function() { - return this.eq( -1 ); - }, - - eq: function( i ) { - var len = this.length, - j = +i + ( i < 0 ? len : 0 ); - return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); - }, - - map: function( callback ) { - return this.pushStack( jQuery.map(this, function( elem, i ) { - return callback.call( elem, i, elem ); - })); - }, - - end: function() { - return this.prevObject || this.constructor(null); - }, - - // For internal use only. - // Behaves like an Array's method, not like a jQuery method. - push: core_push, - sort: [].sort, - splice: [].splice -}; - -// Give the init function the jQuery prototype for later instantiation -jQuery.fn.init.prototype = jQuery.fn; - -jQuery.extend = jQuery.fn.extend = function() { - var src, copyIsArray, copy, name, options, clone, - target = arguments[0] || {}, - i = 1, - length = arguments.length, - deep = false; - - // Handle a deep copy situation - if ( typeof target === "boolean" ) { - deep = target; - target = arguments[1] || {}; - // skip the boolean and the target - i = 2; - } - - // Handle case when target is a string or something (possible in deep copy) - if ( typeof target !== "object" && !jQuery.isFunction(target) ) { - target = {}; - } - - // extend jQuery itself if only one argument is passed - if ( length === i ) { - target = this; - --i; - } - - for ( ; i < length; i++ ) { - // Only deal with non-null/undefined values - if ( (options = arguments[ i ]) != null ) { - // Extend the base object - for ( name in options ) { - src = target[ name ]; - copy = options[ name ]; - - // Prevent never-ending loop - if ( target === copy ) { - continue; - } - - // Recurse if we're merging plain objects or arrays - if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { - if ( copyIsArray ) { - copyIsArray = false; - clone = src && jQuery.isArray(src) ? src : []; - - } else { - clone = src && jQuery.isPlainObject(src) ? src : {}; - } - - // Never move original objects, clone them - target[ name ] = jQuery.extend( deep, clone, copy ); - - // Don't bring in undefined values - } else if ( copy !== undefined ) { - target[ name ] = copy; - } - } - } - } - - // Return the modified object - return target; -}; - -jQuery.extend({ - noConflict: function( deep ) { - if ( window.$ === jQuery ) { - window.$ = _$; - } - - if ( deep && window.jQuery === jQuery ) { - window.jQuery = _jQuery; - } - - return jQuery; - }, - - // Is the DOM ready to be used? Set to true once it occurs. - isReady: false, - - // A counter to track how many items to wait for before - // the ready event fires. See #6781 - readyWait: 1, - - // Hold (or release) the ready event - holdReady: function( hold ) { - if ( hold ) { - jQuery.readyWait++; - } else { - jQuery.ready( true ); - } - }, - - // Handle when the DOM is ready - ready: function( wait ) { - - // Abort if there are pending holds or we're already ready - if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { - return; - } - - // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). - if ( !document.body ) { - return setTimeout( jQuery.ready ); - } - - // Remember that the DOM is ready - jQuery.isReady = true; - - // If a normal DOM Ready event fired, decrement, and wait if need be - if ( wait !== true && --jQuery.readyWait > 0 ) { - return; - } - - // If there are functions bound, to execute - readyList.resolveWith( document, [ jQuery ] ); - - // Trigger any bound ready events - if ( jQuery.fn.trigger ) { - jQuery( document ).trigger("ready").off("ready"); - } - }, - - // See test/unit/core.js for details concerning isFunction. - // Since version 1.3, DOM methods and functions like alert - // aren't supported. They return false on IE (#2968). - isFunction: function( obj ) { - return jQuery.type(obj) === "function"; - }, - - isArray: Array.isArray || function( obj ) { - return jQuery.type(obj) === "array"; - }, - - isWindow: function( obj ) { - return obj != null && obj == obj.window; - }, - - isNumeric: function( obj ) { - return !isNaN( parseFloat(obj) ) && isFinite( obj ); - }, - - type: function( obj ) { - if ( obj == null ) { - return String( obj ); - } - return typeof obj === "object" || typeof obj === "function" ? - class2type[ core_toString.call(obj) ] || "object" : - typeof obj; - }, - - isPlainObject: function( obj ) { - // Must be an Object. - // Because of IE, we also have to check the presence of the constructor property. - // Make sure that DOM nodes and window objects don't pass through, as well - if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { - return false; - } - - try { - // Not own constructor property must be Object - if ( obj.constructor && - !core_hasOwn.call(obj, "constructor") && - !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { - return false; - } - } catch ( e ) { - // IE8,9 Will throw exceptions on certain host objects #9897 - return false; - } - - // Own properties are enumerated firstly, so to speed up, - // if last one is own, then all properties are own. - - var key; - for ( key in obj ) {} - - return key === undefined || core_hasOwn.call( obj, key ); - }, - - isEmptyObject: function( obj ) { - var name; - for ( name in obj ) { - return false; - } - return true; - }, - - error: function( msg ) { - throw new Error( msg ); - }, - - // data: string of html - // context (optional): If specified, the fragment will be created in this context, defaults to document - // keepScripts (optional): If true, will include scripts passed in the html string - parseHTML: function( data, context, keepScripts ) { - if ( !data || typeof data !== "string" ) { - return null; - } - if ( typeof context === "boolean" ) { - keepScripts = context; - context = false; - } - context = context || document; - - var parsed = rsingleTag.exec( data ), - scripts = !keepScripts && []; - - // Single tag - if ( parsed ) { - return [ context.createElement( parsed[1] ) ]; - } - - parsed = jQuery.buildFragment( [ data ], context, scripts ); - if ( scripts ) { - jQuery( scripts ).remove(); - } - return jQuery.merge( [], parsed.childNodes ); - }, - - parseJSON: function( data ) { - // Attempt to parse using the native JSON parser first - if ( window.JSON && window.JSON.parse ) { - return window.JSON.parse( data ); - } - - if ( data === null ) { - return data; - } - - if ( typeof data === "string" ) { - - // Make sure leading/trailing whitespace is removed (IE can't handle it) - data = jQuery.trim( data ); - - if ( data ) { - // Make sure the incoming data is actual JSON - // Logic borrowed from http://json.org/json2.js - if ( rvalidchars.test( data.replace( rvalidescape, "@" ) - .replace( rvalidtokens, "]" ) - .replace( rvalidbraces, "")) ) { - - return ( new Function( "return " + data ) )(); - } - } - } - - jQuery.error( "Invalid JSON: " + data ); - }, - - // Cross-browser xml parsing - parseXML: function( data ) { - var xml, tmp; - if ( !data || typeof data !== "string" ) { - return null; - } - try { - if ( window.DOMParser ) { // Standard - tmp = new DOMParser(); - xml = tmp.parseFromString( data , "text/xml" ); - } else { // IE - xml = new ActiveXObject( "Microsoft.XMLDOM" ); - xml.async = "false"; - xml.loadXML( data ); - } - } catch( e ) { - xml = undefined; - } - if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { - jQuery.error( "Invalid XML: " + data ); - } - return xml; - }, - - noop: function() {}, - - // Evaluates a script in a global context - // Workarounds based on findings by Jim Driscoll - // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context - globalEval: function( data ) { - if ( data && jQuery.trim( data ) ) { - // We use execScript on Internet Explorer - // We use an anonymous function so that context is window - // rather than jQuery in Firefox - ( window.execScript || function( data ) { - window[ "eval" ].call( window, data ); - } )( data ); - } - }, - - // Convert dashed to camelCase; used by the css and data modules - // Microsoft forgot to hump their vendor prefix (#9572) - camelCase: function( string ) { - return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); - }, - - nodeName: function( elem, name ) { - return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); - }, - - // args is for internal usage only - each: function( obj, callback, args ) { - var value, - i = 0, - length = obj.length, - isArray = isArraylike( obj ); - - if ( args ) { - if ( isArray ) { - for ( ; i < length; i++ ) { - value = callback.apply( obj[ i ], args ); - - if ( value === false ) { - break; - } - } - } else { - for ( i in obj ) { - value = callback.apply( obj[ i ], args ); - - if ( value === false ) { - break; - } - } - } - - // A special, fast, case for the most common use of each - } else { - if ( isArray ) { - for ( ; i < length; i++ ) { - value = callback.call( obj[ i ], i, obj[ i ] ); - - if ( value === false ) { - break; - } - } - } else { - for ( i in obj ) { - value = callback.call( obj[ i ], i, obj[ i ] ); - - if ( value === false ) { - break; - } - } - } - } - - return obj; - }, - - // Use native String.trim function wherever possible - trim: core_trim && !core_trim.call("\uFEFF\xA0") ? - function( text ) { - return text == null ? - "" : - core_trim.call( text ); - } : - - // Otherwise use our own trimming functionality - function( text ) { - return text == null ? - "" : - ( text + "" ).replace( rtrim, "" ); - }, - - // results is for internal usage only - makeArray: function( arr, results ) { - var ret = results || []; - - if ( arr != null ) { - if ( isArraylike( Object(arr) ) ) { - jQuery.merge( ret, - typeof arr === "string" ? - [ arr ] : arr - ); - } else { - core_push.call( ret, arr ); - } - } - - return ret; - }, - - inArray: function( elem, arr, i ) { - var len; - - if ( arr ) { - if ( core_indexOf ) { - return core_indexOf.call( arr, elem, i ); - } - - len = arr.length; - i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; - - for ( ; i < len; i++ ) { - // Skip accessing in sparse arrays - if ( i in arr && arr[ i ] === elem ) { - return i; - } - } - } - - return -1; - }, - - merge: function( first, second ) { - var l = second.length, - i = first.length, - j = 0; - - if ( typeof l === "number" ) { - for ( ; j < l; j++ ) { - first[ i++ ] = second[ j ]; - } - } else { - while ( second[j] !== undefined ) { - first[ i++ ] = second[ j++ ]; - } - } - - first.length = i; - - return first; - }, - - grep: function( elems, callback, inv ) { - var retVal, - ret = [], - i = 0, - length = elems.length; - inv = !!inv; - - // Go through the array, only saving the items - // that pass the validator function - for ( ; i < length; i++ ) { - retVal = !!callback( elems[ i ], i ); - if ( inv !== retVal ) { - ret.push( elems[ i ] ); - } - } - - return ret; - }, - - // arg is for internal usage only - map: function( elems, callback, arg ) { - var value, - i = 0, - length = elems.length, - isArray = isArraylike( elems ), - ret = []; - - // Go through the array, translating each of the items to their - if ( isArray ) { - for ( ; i < length; i++ ) { - value = callback( elems[ i ], i, arg ); - - if ( value != null ) { - ret[ ret.length ] = value; - } - } - - // Go through every key on the object, - } else { - for ( i in elems ) { - value = callback( elems[ i ], i, arg ); - - if ( value != null ) { - ret[ ret.length ] = value; - } - } - } - - // Flatten any nested arrays - return core_concat.apply( [], ret ); - }, - - // A global GUID counter for objects - guid: 1, - - // Bind a function to a context, optionally partially applying any - // arguments. - proxy: function( fn, context ) { - var args, proxy, tmp; - - if ( typeof context === "string" ) { - tmp = fn[ context ]; - context = fn; - fn = tmp; - } - - // Quick check to determine if target is callable, in the spec - // this throws a TypeError, but we will just return undefined. - if ( !jQuery.isFunction( fn ) ) { - return undefined; - } - - // Simulated bind - args = core_slice.call( arguments, 2 ); - proxy = function() { - return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) ); - }; - - // Set the guid of unique handler to the same of original handler, so it can be removed - proxy.guid = fn.guid = fn.guid || jQuery.guid++; - - return proxy; - }, - - // Multifunctional method to get and set values of a collection - // The value/s can optionally be executed if it's a function - access: function( elems, fn, key, value, chainable, emptyGet, raw ) { - var i = 0, - length = elems.length, - bulk = key == null; - - // Sets many values - if ( jQuery.type( key ) === "object" ) { - chainable = true; - for ( i in key ) { - jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); - } - - // Sets one value - } else if ( value !== undefined ) { - chainable = true; - - if ( !jQuery.isFunction( value ) ) { - raw = true; - } - - if ( bulk ) { - // Bulk operations run against the entire set - if ( raw ) { - fn.call( elems, value ); - fn = null; - - // ...except when executing function values - } else { - bulk = fn; - fn = function( elem, key, value ) { - return bulk.call( jQuery( elem ), value ); - }; - } - } - - if ( fn ) { - for ( ; i < length; i++ ) { - fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); - } - } - } - - return chainable ? - elems : - - // Gets - bulk ? - fn.call( elems ) : - length ? fn( elems[0], key ) : emptyGet; - }, - - now: function() { - return ( new Date() ).getTime(); - } -}); - -jQuery.ready.promise = function( obj ) { - if ( !readyList ) { - - readyList = jQuery.Deferred(); - - // Catch cases where $(document).ready() is called after the browser event has already occurred. - // we once tried to use readyState "interactive" here, but it caused issues like the one - // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 - if ( document.readyState === "complete" ) { - // Handle it asynchronously to allow scripts the opportunity to delay ready - setTimeout( jQuery.ready ); - - // Standards-based browsers support DOMContentLoaded - } else if ( document.addEventListener ) { - // Use the handy event callback - document.addEventListener( "DOMContentLoaded", completed, false ); - - // A fallback to window.onload, that will always work - window.addEventListener( "load", completed, false ); - - // If IE event model is used - } else { - // Ensure firing before onload, maybe late but safe also for iframes - document.attachEvent( "onreadystatechange", completed ); - - // A fallback to window.onload, that will always work - window.attachEvent( "onload", completed ); - - // If IE and not a frame - // continually check to see if the document is ready - var top = false; - - try { - top = window.frameElement == null && document.documentElement; - } catch(e) {} - - if ( top && top.doScroll ) { - (function doScrollCheck() { - if ( !jQuery.isReady ) { - - try { - // Use the trick by Diego Perini - // http://javascript.nwbox.com/IEContentLoaded/ - top.doScroll("left"); - } catch(e) { - return setTimeout( doScrollCheck, 50 ); - } - - // detach all dom ready events - detach(); - - // and execute any waiting functions - jQuery.ready(); - } - })(); - } - } - } - return readyList.promise( obj ); -}; - -// Populate the class2type map -jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { - class2type[ "[object " + name + "]" ] = name.toLowerCase(); -}); - -function isArraylike( obj ) { - var length = obj.length, - type = jQuery.type( obj ); - - if ( jQuery.isWindow( obj ) ) { - return false; - } - - if ( obj.nodeType === 1 && length ) { - return true; - } - - return type === "array" || type !== "function" && - ( length === 0 || - typeof length === "number" && length > 0 && ( length - 1 ) in obj ); -} - -// All jQuery objects should point back to these -rootjQuery = jQuery(document); -// String to Object options format cache -var optionsCache = {}; - -// Convert String-formatted options into Object-formatted ones and store in cache -function createOptions( options ) { - var object = optionsCache[ options ] = {}; - jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) { - object[ flag ] = true; - }); - return object; -} - -/* - * Create a callback list using the following parameters: - * - * options: an optional list of space-separated options that will change how - * the callback list behaves or a more traditional option object - * - * By default a callback list will act like an event callback list and can be - * "fired" multiple times. - * - * Possible options: - * - * once: will ensure the callback list can only be fired once (like a Deferred) - * - * memory: will keep track of previous values and will call any callback added - * after the list has been fired right away with the latest "memorized" - * values (like a Deferred) - * - * unique: will ensure a callback can only be added once (no duplicate in the list) - * - * stopOnFalse: interrupt callings when a callback returns false - * - */ -jQuery.Callbacks = function( options ) { - - // Convert options from String-formatted to Object-formatted if needed - // (we check in cache first) - options = typeof options === "string" ? - ( optionsCache[ options ] || createOptions( options ) ) : - jQuery.extend( {}, options ); - - var // Flag to know if list is currently firing - firing, - // Last fire value (for non-forgettable lists) - memory, - // Flag to know if list was already fired - fired, - // End of the loop when firing - firingLength, - // Index of currently firing callback (modified by remove if needed) - firingIndex, - // First callback to fire (used internally by add and fireWith) - firingStart, - // Actual callback list - list = [], - // Stack of fire calls for repeatable lists - stack = !options.once && [], - // Fire callbacks - fire = function( data ) { - memory = options.memory && data; - fired = true; - firingIndex = firingStart || 0; - firingStart = 0; - firingLength = list.length; - firing = true; - for ( ; list && firingIndex < firingLength; firingIndex++ ) { - if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { - memory = false; // To prevent further calls using add - break; - } - } - firing = false; - if ( list ) { - if ( stack ) { - if ( stack.length ) { - fire( stack.shift() ); - } - } else if ( memory ) { - list = []; - } else { - self.disable(); - } - } - }, - // Actual Callbacks object - self = { - // Add a callback or a collection of callbacks to the list - add: function() { - if ( list ) { - // First, we save the current length - var start = list.length; - (function add( args ) { - jQuery.each( args, function( _, arg ) { - var type = jQuery.type( arg ); - if ( type === "function" ) { - if ( !options.unique || !self.has( arg ) ) { - list.push( arg ); - } - } else if ( arg && arg.length && type !== "string" ) { - // Inspect recursively - add( arg ); - } - }); - })( arguments ); - // Do we need to add the callbacks to the - // current firing batch? - if ( firing ) { - firingLength = list.length; - // With memory, if we're not firing then - // we should call right away - } else if ( memory ) { - firingStart = start; - fire( memory ); - } - } - return this; - }, - // Remove a callback from the list - remove: function() { - if ( list ) { - jQuery.each( arguments, function( _, arg ) { - var index; - while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { - list.splice( index, 1 ); - // Handle firing indexes - if ( firing ) { - if ( index <= firingLength ) { - firingLength--; - } - if ( index <= firingIndex ) { - firingIndex--; - } - } - } - }); - } - return this; - }, - // Check if a given callback is in the list. - // If no argument is given, return whether or not list has callbacks attached. - has: function( fn ) { - return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); - }, - // Remove all callbacks from the list - empty: function() { - list = []; - return this; - }, - // Have the list do nothing anymore - disable: function() { - list = stack = memory = undefined; - return this; - }, - // Is it disabled? - disabled: function() { - return !list; - }, - // Lock the list in its current state - lock: function() { - stack = undefined; - if ( !memory ) { - self.disable(); - } - return this; - }, - // Is it locked? - locked: function() { - return !stack; - }, - // Call all callbacks with the given context and arguments - fireWith: function( context, args ) { - args = args || []; - args = [ context, args.slice ? args.slice() : args ]; - if ( list && ( !fired || stack ) ) { - if ( firing ) { - stack.push( args ); - } else { - fire( args ); - } - } - return this; - }, - // Call all the callbacks with the given arguments - fire: function() { - self.fireWith( this, arguments ); - return this; - }, - // To know if the callbacks have already been called at least once - fired: function() { - return !!fired; - } - }; - - return self; -}; -jQuery.extend({ - - Deferred: function( func ) { - var tuples = [ - // action, add listener, listener list, final state - [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], - [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], - [ "notify", "progress", jQuery.Callbacks("memory") ] - ], - state = "pending", - promise = { - state: function() { - return state; - }, - always: function() { - deferred.done( arguments ).fail( arguments ); - return this; - }, - then: function( /* fnDone, fnFail, fnProgress */ ) { - var fns = arguments; - return jQuery.Deferred(function( newDefer ) { - jQuery.each( tuples, function( i, tuple ) { - var action = tuple[ 0 ], - fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; - // deferred[ done | fail | progress ] for forwarding actions to newDefer - deferred[ tuple[1] ](function() { - var returned = fn && fn.apply( this, arguments ); - if ( returned && jQuery.isFunction( returned.promise ) ) { - returned.promise() - .done( newDefer.resolve ) - .fail( newDefer.reject ) - .progress( newDefer.notify ); - } else { - newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); - } - }); - }); - fns = null; - }).promise(); - }, - // Get a promise for this deferred - // If obj is provided, the promise aspect is added to the object - promise: function( obj ) { - return obj != null ? jQuery.extend( obj, promise ) : promise; - } - }, - deferred = {}; - - // Keep pipe for back-compat - promise.pipe = promise.then; - - // Add list-specific methods - jQuery.each( tuples, function( i, tuple ) { - var list = tuple[ 2 ], - stateString = tuple[ 3 ]; - - // promise[ done | fail | progress ] = list.add - promise[ tuple[1] ] = list.add; - - // Handle state - if ( stateString ) { - list.add(function() { - // state = [ resolved | rejected ] - state = stateString; - - // [ reject_list | resolve_list ].disable; progress_list.lock - }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); - } - - // deferred[ resolve | reject | notify ] - deferred[ tuple[0] ] = function() { - deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); - return this; - }; - deferred[ tuple[0] + "With" ] = list.fireWith; - }); - - // Make the deferred a promise - promise.promise( deferred ); - - // Call given func if any - if ( func ) { - func.call( deferred, deferred ); - } - - // All done! - return deferred; - }, - - // Deferred helper - when: function( subordinate /* , ..., subordinateN */ ) { - var i = 0, - resolveValues = core_slice.call( arguments ), - length = resolveValues.length, - - // the count of uncompleted subordinates - remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, - - // the master Deferred. If resolveValues consist of only a single Deferred, just use that. - deferred = remaining === 1 ? subordinate : jQuery.Deferred(), - - // Update function for both resolve and progress values - updateFunc = function( i, contexts, values ) { - return function( value ) { - contexts[ i ] = this; - values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; - if( values === progressValues ) { - deferred.notifyWith( contexts, values ); - } else if ( !( --remaining ) ) { - deferred.resolveWith( contexts, values ); - } - }; - }, - - progressValues, progressContexts, resolveContexts; - - // add listeners to Deferred subordinates; treat others as resolved - if ( length > 1 ) { - progressValues = new Array( length ); - progressContexts = new Array( length ); - resolveContexts = new Array( length ); - for ( ; i < length; i++ ) { - if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { - resolveValues[ i ].promise() - .done( updateFunc( i, resolveContexts, resolveValues ) ) - .fail( deferred.reject ) - .progress( updateFunc( i, progressContexts, progressValues ) ); - } else { - --remaining; - } - } - } - - // if we're not waiting on anything, resolve the master - if ( !remaining ) { - deferred.resolveWith( resolveContexts, resolveValues ); - } - - return deferred.promise(); - } -}); -jQuery.support = (function() { - - var support, all, a, - input, select, fragment, - opt, eventName, isSupported, i, - div = document.createElement("div"); - - // Setup - div.setAttribute( "className", "t" ); - div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; - - // Support tests won't run in some limited or non-browser environments - all = div.getElementsByTagName("*"); - a = div.getElementsByTagName("a")[ 0 ]; - if ( !all || !a || !all.length ) { - return {}; - } - - // First batch of tests - select = document.createElement("select"); - opt = select.appendChild( document.createElement("option") ); - input = div.getElementsByTagName("input")[ 0 ]; - - a.style.cssText = "top:1px;float:left;opacity:.5"; - support = { - // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) - getSetAttribute: div.className !== "t", - - // IE strips leading whitespace when .innerHTML is used - leadingWhitespace: div.firstChild.nodeType === 3, - - // Make sure that tbody elements aren't automatically inserted - // IE will insert them into empty tables - tbody: !div.getElementsByTagName("tbody").length, - - // Make sure that link elements get serialized correctly by innerHTML - // This requires a wrapper element in IE - htmlSerialize: !!div.getElementsByTagName("link").length, - - // Get the style information from getAttribute - // (IE uses .cssText instead) - style: /top/.test( a.getAttribute("style") ), - - // Make sure that URLs aren't manipulated - // (IE normalizes it by default) - hrefNormalized: a.getAttribute("href") === "/a", - - // Make sure that element opacity exists - // (IE uses filter instead) - // Use a regex to work around a WebKit issue. See #5145 - opacity: /^0.5/.test( a.style.opacity ), - - // Verify style float existence - // (IE uses styleFloat instead of cssFloat) - cssFloat: !!a.style.cssFloat, - - // Check the default checkbox/radio value ("" on WebKit; "on" elsewhere) - checkOn: !!input.value, - - // Make sure that a selected-by-default option has a working selected property. - // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) - optSelected: opt.selected, - - // Tests for enctype support on a form (#6743) - enctype: !!document.createElement("form").enctype, - - // Makes sure cloning an html5 element does not cause problems - // Where outerHTML is undefined, this still works - html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>", - - // jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode - boxModel: document.compatMode === "CSS1Compat", - - // Will be defined later - deleteExpando: true, - noCloneEvent: true, - inlineBlockNeedsLayout: false, - shrinkWrapBlocks: false, - reliableMarginRight: true, - boxSizingReliable: true, - pixelPosition: false - }; - - // Make sure checked status is properly cloned - input.checked = true; - support.noCloneChecked = input.cloneNode( true ).checked; - - // Make sure that the options inside disabled selects aren't marked as disabled - // (WebKit marks them as disabled) - select.disabled = true; - support.optDisabled = !opt.disabled; - - // Support: IE<9 - try { - delete div.test; - } catch( e ) { - support.deleteExpando = false; - } - - // Check if we can trust getAttribute("value") - input = document.createElement("input"); - input.setAttribute( "value", "" ); - support.input = input.getAttribute( "value" ) === ""; - - // Check if an input maintains its value after becoming a radio - input.value = "t"; - input.setAttribute( "type", "radio" ); - support.radioValue = input.value === "t"; - - // #11217 - WebKit loses check when the name is after the checked attribute - input.setAttribute( "checked", "t" ); - input.setAttribute( "name", "t" ); - - fragment = document.createDocumentFragment(); - fragment.appendChild( input ); - - // Check if a disconnected checkbox will retain its checked - // value of true after appended to the DOM (IE6/7) - support.appendChecked = input.checked; - - // WebKit doesn't clone checked state correctly in fragments - support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; - - // Support: IE<9 - // Opera does not clone events (and typeof div.attachEvent === undefined). - // IE9-10 clones events bound via attachEvent, but they don't trigger with .click() - if ( div.attachEvent ) { - div.attachEvent( "onclick", function() { - support.noCloneEvent = false; - }); - - div.cloneNode( true ).click(); - } - - // Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event) - // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP), test/csp.php - for ( i in { submit: true, change: true, focusin: true }) { - div.setAttribute( eventName = "on" + i, "t" ); - - support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false; - } - - div.style.backgroundClip = "content-box"; - div.cloneNode( true ).style.backgroundClip = ""; - support.clearCloneStyle = div.style.backgroundClip === "content-box"; - - // Run tests that need a body at doc ready - jQuery(function() { - var container, marginDiv, tds, - divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;", - body = document.getElementsByTagName("body")[0]; - - if ( !body ) { - // Return for frameset docs that don't have a body - return; - } - - container = document.createElement("div"); - container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; - - body.appendChild( container ).appendChild( div ); - - // Support: IE8 - // Check if table cells still have offsetWidth/Height when they are set - // to display:none and there are still other visible table cells in a - // table row; if so, offsetWidth/Height are not reliable for use when - // determining if an element has been hidden directly using - // display:none (it is still safe to use offsets if a parent element is - // hidden; don safety goggles and see bug #4512 for more information). - div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>"; - tds = div.getElementsByTagName("td"); - tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none"; - isSupported = ( tds[ 0 ].offsetHeight === 0 ); - - tds[ 0 ].style.display = ""; - tds[ 1 ].style.display = "none"; - - // Support: IE8 - // Check if empty table cells still have offsetWidth/Height - support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); - - // Check box-sizing and margin behavior - div.innerHTML = ""; - div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;"; - support.boxSizing = ( div.offsetWidth === 4 ); - support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 ); - - // Use window.getComputedStyle because jsdom on node.js will break without it. - if ( window.getComputedStyle ) { - support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; - support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; - - // Check if div with explicit width and no margin-right incorrectly - // gets computed margin-right based on width of container. (#3333) - // Fails in WebKit before Feb 2011 nightlies - // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right - marginDiv = div.appendChild( document.createElement("div") ); - marginDiv.style.cssText = div.style.cssText = divReset; - marginDiv.style.marginRight = marginDiv.style.width = "0"; - div.style.width = "1px"; - - support.reliableMarginRight = - !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); - } - - if ( typeof div.style.zoom !== core_strundefined ) { - // Support: IE<8 - // Check if natively block-level elements act like inline-block - // elements when setting their display to 'inline' and giving - // them layout - div.innerHTML = ""; - div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; - support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); - - // Support: IE6 - // Check if elements with layout shrink-wrap their children - div.style.display = "block"; - div.innerHTML = "<div></div>"; - div.firstChild.style.width = "5px"; - support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); - - if ( support.inlineBlockNeedsLayout ) { - // Prevent IE 6 from affecting layout for positioned elements #11048 - // Prevent IE from shrinking the body in IE 7 mode #12869 - // Support: IE<8 - body.style.zoom = 1; - } - } - - body.removeChild( container ); - - // Null elements to avoid leaks in IE - container = div = tds = marginDiv = null; - }); - - // Null elements to avoid leaks in IE - all = select = fragment = opt = a = input = null; - - return support; -})(); - -var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, - rmultiDash = /([A-Z])/g; - -function internalData( elem, name, data, pvt /* Internal Use Only */ ){ - if ( !jQuery.acceptData( elem ) ) { - return; - } - - var thisCache, ret, - internalKey = jQuery.expando, - getByName = typeof name === "string", - - // We have to handle DOM nodes and JS objects differently because IE6-7 - // can't GC object references properly across the DOM-JS boundary - isNode = elem.nodeType, - - // Only DOM nodes need the global jQuery cache; JS object data is - // attached directly to the object so GC can occur automatically - cache = isNode ? jQuery.cache : elem, - - // Only defining an ID for JS objects if its cache already exists allows - // the code to shortcut on the same path as a DOM node with no cache - id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; - - // Avoid doing any more work than we need to when trying to get data on an - // object that has no data at all - if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) { - return; - } - - if ( !id ) { - // Only DOM nodes need a new unique ID for each element since their data - // ends up in the global cache - if ( isNode ) { - elem[ internalKey ] = id = core_deletedIds.pop() || jQuery.guid++; - } else { - id = internalKey; - } - } - - if ( !cache[ id ] ) { - cache[ id ] = {}; - - // Avoids exposing jQuery metadata on plain JS objects when the object - // is serialized using JSON.stringify - if ( !isNode ) { - cache[ id ].toJSON = jQuery.noop; - } - } - - // An object can be passed to jQuery.data instead of a key/value pair; this gets - // shallow copied over onto the existing cache - if ( typeof name === "object" || typeof name === "function" ) { - if ( pvt ) { - cache[ id ] = jQuery.extend( cache[ id ], name ); - } else { - cache[ id ].data = jQuery.extend( cache[ id ].data, name ); - } - } - - thisCache = cache[ id ]; - - // jQuery data() is stored in a separate object inside the object's internal data - // cache in order to avoid key collisions between internal data and user-defined - // data. - if ( !pvt ) { - if ( !thisCache.data ) { - thisCache.data = {}; - } - - thisCache = thisCache.data; - } - - if ( data !== undefined ) { - thisCache[ jQuery.camelCase( name ) ] = data; - } - - // Check for both converted-to-camel and non-converted data property names - // If a data property was specified - if ( getByName ) { - - // First Try to find as-is property data - ret = thisCache[ name ]; - - // Test for null|undefined property data - if ( ret == null ) { - - // Try to find the camelCased property - ret = thisCache[ jQuery.camelCase( name ) ]; - } - } else { - ret = thisCache; - } - - return ret; -} - -function internalRemoveData( elem, name, pvt ) { - if ( !jQuery.acceptData( elem ) ) { - return; - } - - var i, l, thisCache, - isNode = elem.nodeType, - - // See jQuery.data for more information - cache = isNode ? jQuery.cache : elem, - id = isNode ? elem[ jQuery.expando ] : jQuery.expando; - - // If there is already no cache entry for this object, there is no - // purpose in continuing - if ( !cache[ id ] ) { - return; - } - - if ( name ) { - - thisCache = pvt ? cache[ id ] : cache[ id ].data; - - if ( thisCache ) { - - // Support array or space separated string names for data keys - if ( !jQuery.isArray( name ) ) { - - // try the string as a key before any manipulation - if ( name in thisCache ) { - name = [ name ]; - } else { - - // split the camel cased version by spaces unless a key with the spaces exists - name = jQuery.camelCase( name ); - if ( name in thisCache ) { - name = [ name ]; - } else { - name = name.split(" "); - } - } - } else { - // If "name" is an array of keys... - // When data is initially created, via ("key", "val") signature, - // keys will be converted to camelCase. - // Since there is no way to tell _how_ a key was added, remove - // both plain key and camelCase key. #12786 - // This will only penalize the array argument path. - name = name.concat( jQuery.map( name, jQuery.camelCase ) ); - } - - for ( i = 0, l = name.length; i < l; i++ ) { - delete thisCache[ name[i] ]; - } - - // If there is no data left in the cache, we want to continue - // and let the cache object itself get destroyed - if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) { - return; - } - } - } - - // See jQuery.data for more information - if ( !pvt ) { - delete cache[ id ].data; - - // Don't destroy the parent cache unless the internal data object - // had been the only thing left in it - if ( !isEmptyDataObject( cache[ id ] ) ) { - return; - } - } - - // Destroy the cache - if ( isNode ) { - jQuery.cleanData( [ elem ], true ); - - // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) - } else if ( jQuery.support.deleteExpando || cache != cache.window ) { - delete cache[ id ]; - - // When all else fails, null - } else { - cache[ id ] = null; - } -} - -jQuery.extend({ - cache: {}, - - // Unique for each copy of jQuery on the page - // Non-digits removed to match rinlinejQuery - expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ), - - // The following elements throw uncatchable exceptions if you - // attempt to add expando properties to them. - noData: { - "embed": true, - // Ban all objects except for Flash (which handle expandos) - "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", - "applet": true - }, - - hasData: function( elem ) { - elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; - return !!elem && !isEmptyDataObject( elem ); - }, - - data: function( elem, name, data ) { - return internalData( elem, name, data ); - }, - - removeData: function( elem, name ) { - return internalRemoveData( elem, name ); - }, - - // For internal use only. - _data: function( elem, name, data ) { - return internalData( elem, name, data, true ); - }, - - _removeData: function( elem, name ) { - return internalRemoveData( elem, name, true ); - }, - - // A method for determining if a DOM node can handle the data expando - acceptData: function( elem ) { - // Do not set data on non-element because it will not be cleared (#8335). - if ( elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9 ) { - return false; - } - - var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ]; - - // nodes accept data unless otherwise specified; rejection can be conditional - return !noData || noData !== true && elem.getAttribute("classid") === noData; - } -}); - -jQuery.fn.extend({ - data: function( key, value ) { - var attrs, name, - elem = this[0], - i = 0, - data = null; - - // Gets all values - if ( key === undefined ) { - if ( this.length ) { - data = jQuery.data( elem ); - - if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { - attrs = elem.attributes; - for ( ; i < attrs.length; i++ ) { - name = attrs[i].name; - - if ( !name.indexOf( "data-" ) ) { - name = jQuery.camelCase( name.slice(5) ); - - dataAttr( elem, name, data[ name ] ); - } - } - jQuery._data( elem, "parsedAttrs", true ); - } - } - - return data; - } - - // Sets multiple values - if ( typeof key === "object" ) { - return this.each(function() { - jQuery.data( this, key ); - }); - } - - return jQuery.access( this, function( value ) { - - if ( value === undefined ) { - // Try to fetch any internally stored data first - return elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : null; - } - - this.each(function() { - jQuery.data( this, key, value ); - }); - }, null, value, arguments.length > 1, null, true ); - }, - - removeData: function( key ) { - return this.each(function() { - jQuery.removeData( this, key ); - }); - } -}); - -function dataAttr( elem, key, data ) { - // If nothing was found internally, try to fetch any - // data from the HTML5 data-* attribute - if ( data === undefined && elem.nodeType === 1 ) { - - var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); - - data = elem.getAttribute( name ); - - if ( typeof data === "string" ) { - try { - data = data === "true" ? true : - data === "false" ? false : - data === "null" ? null : - // Only convert to a number if it doesn't change the string - +data + "" === data ? +data : - rbrace.test( data ) ? jQuery.parseJSON( data ) : - data; - } catch( e ) {} - - // Make sure we set the data so it isn't changed later - jQuery.data( elem, key, data ); - - } else { - data = undefined; - } - } - - return data; -} - -// checks a cache object for emptiness -function isEmptyDataObject( obj ) { - var name; - for ( name in obj ) { - - // if the public data object is empty, the private is still empty - if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { - continue; - } - if ( name !== "toJSON" ) { - return false; - } - } - - return true; -} -jQuery.extend({ - queue: function( elem, type, data ) { - var queue; - - if ( elem ) { - type = ( type || "fx" ) + "queue"; - queue = jQuery._data( elem, type ); - - // Speed up dequeue by getting out quickly if this is just a lookup - if ( data ) { - if ( !queue || jQuery.isArray(data) ) { - queue = jQuery._data( elem, type, jQuery.makeArray(data) ); - } else { - queue.push( data ); - } - } - return queue || []; - } - }, - - dequeue: function( elem, type ) { - type = type || "fx"; - - var queue = jQuery.queue( elem, type ), - startLength = queue.length, - fn = queue.shift(), - hooks = jQuery._queueHooks( elem, type ), - next = function() { - jQuery.dequeue( elem, type ); - }; - - // If the fx queue is dequeued, always remove the progress sentinel - if ( fn === "inprogress" ) { - fn = queue.shift(); - startLength--; - } - - hooks.cur = fn; - if ( fn ) { - - // Add a progress sentinel to prevent the fx queue from being - // automatically dequeued - if ( type === "fx" ) { - queue.unshift( "inprogress" ); - } - - // clear up the last queue stop function - delete hooks.stop; - fn.call( elem, next, hooks ); - } - - if ( !startLength && hooks ) { - hooks.empty.fire(); - } - }, - - // not intended for public consumption - generates a queueHooks object, or returns the current one - _queueHooks: function( elem, type ) { - var key = type + "queueHooks"; - return jQuery._data( elem, key ) || jQuery._data( elem, key, { - empty: jQuery.Callbacks("once memory").add(function() { - jQuery._removeData( elem, type + "queue" ); - jQuery._removeData( elem, key ); - }) - }); - } -}); - -jQuery.fn.extend({ - queue: function( type, data ) { - var setter = 2; - - if ( typeof type !== "string" ) { - data = type; - type = "fx"; - setter--; - } - - if ( arguments.length < setter ) { - return jQuery.queue( this[0], type ); - } - - return data === undefined ? - this : - this.each(function() { - var queue = jQuery.queue( this, type, data ); - - // ensure a hooks for this queue - jQuery._queueHooks( this, type ); - - if ( type === "fx" && queue[0] !== "inprogress" ) { - jQuery.dequeue( this, type ); - } - }); - }, - dequeue: function( type ) { - return this.each(function() { - jQuery.dequeue( this, type ); - }); - }, - // Based off of the plugin by Clint Helfers, with permission. - // http://blindsignals.com/index.php/2009/07/jquery-delay/ - delay: function( time, type ) { - time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; - type = type || "fx"; - - return this.queue( type, function( next, hooks ) { - var timeout = setTimeout( next, time ); - hooks.stop = function() { - clearTimeout( timeout ); - }; - }); - }, - clearQueue: function( type ) { - return this.queue( type || "fx", [] ); - }, - // Get a promise resolved when queues of a certain type - // are emptied (fx is the type by default) - promise: function( type, obj ) { - var tmp, - count = 1, - defer = jQuery.Deferred(), - elements = this, - i = this.length, - resolve = function() { - if ( !( --count ) ) { - defer.resolveWith( elements, [ elements ] ); - } - }; - - if ( typeof type !== "string" ) { - obj = type; - type = undefined; - } - type = type || "fx"; - - while( i-- ) { - tmp = jQuery._data( elements[ i ], type + "queueHooks" ); - if ( tmp && tmp.empty ) { - count++; - tmp.empty.add( resolve ); - } - } - resolve(); - return defer.promise( obj ); - } -}); -var nodeHook, boolHook, - rclass = /[\t\r\n]/g, - rreturn = /\r/g, - rfocusable = /^(?:input|select|textarea|button|object)$/i, - rclickable = /^(?:a|area)$/i, - rboolean = /^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i, - ruseDefault = /^(?:checked|selected)$/i, - getSetAttribute = jQuery.support.getSetAttribute, - getSetInput = jQuery.support.input; - -jQuery.fn.extend({ - attr: function( name, value ) { - return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); - }, - - removeAttr: function( name ) { - return this.each(function() { - jQuery.removeAttr( this, name ); - }); - }, - - prop: function( name, value ) { - return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); - }, - - removeProp: function( name ) { - name = jQuery.propFix[ name ] || name; - return this.each(function() { - // try/catch handles cases where IE balks (such as removing a property on window) - try { - this[ name ] = undefined; - delete this[ name ]; - } catch( e ) {} - }); - }, - - addClass: function( value ) { - var classes, elem, cur, clazz, j, - i = 0, - len = this.length, - proceed = typeof value === "string" && value; - - if ( jQuery.isFunction( value ) ) { - return this.each(function( j ) { - jQuery( this ).addClass( value.call( this, j, this.className ) ); - }); - } - - if ( proceed ) { - // The disjunction here is for better compressibility (see removeClass) - classes = ( value || "" ).match( core_rnotwhite ) || []; - - for ( ; i < len; i++ ) { - elem = this[ i ]; - cur = elem.nodeType === 1 && ( elem.className ? - ( " " + elem.className + " " ).replace( rclass, " " ) : - " " - ); - - if ( cur ) { - j = 0; - while ( (clazz = classes[j++]) ) { - if ( cur.indexOf( " " + clazz + " " ) < 0 ) { - cur += clazz + " "; - } - } - elem.className = jQuery.trim( cur ); - - } - } - } - - return this; - }, - - removeClass: function( value ) { - var classes, elem, cur, clazz, j, - i = 0, - len = this.length, - proceed = arguments.length === 0 || typeof value === "string" && value; - - if ( jQuery.isFunction( value ) ) { - return this.each(function( j ) { - jQuery( this ).removeClass( value.call( this, j, this.className ) ); - }); - } - if ( proceed ) { - classes = ( value || "" ).match( core_rnotwhite ) || []; - - for ( ; i < len; i++ ) { - elem = this[ i ]; - // This expression is here for better compressibility (see addClass) - cur = elem.nodeType === 1 && ( elem.className ? - ( " " + elem.className + " " ).replace( rclass, " " ) : - "" - ); - - if ( cur ) { - j = 0; - while ( (clazz = classes[j++]) ) { - // Remove *all* instances - while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { - cur = cur.replace( " " + clazz + " ", " " ); - } - } - elem.className = value ? jQuery.trim( cur ) : ""; - } - } - } - - return this; - }, - - toggleClass: function( value, stateVal ) { - var type = typeof value, - isBool = typeof stateVal === "boolean"; - - if ( jQuery.isFunction( value ) ) { - return this.each(function( i ) { - jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); - }); - } - - return this.each(function() { - if ( type === "string" ) { - // toggle individual class names - var className, - i = 0, - self = jQuery( this ), - state = stateVal, - classNames = value.match( core_rnotwhite ) || []; - - while ( (className = classNames[ i++ ]) ) { - // check each className given, space separated list - state = isBool ? state : !self.hasClass( className ); - self[ state ? "addClass" : "removeClass" ]( className ); - } - - // Toggle whole class name - } else if ( type === core_strundefined || type === "boolean" ) { - if ( this.className ) { - // store className if set - jQuery._data( this, "__className__", this.className ); - } - - // If the element has a class name or if we're passed "false", - // then remove the whole classname (if there was one, the above saved it). - // Otherwise bring back whatever was previously saved (if anything), - // falling back to the empty string if nothing was stored. - this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; - } - }); - }, - - hasClass: function( selector ) { - var className = " " + selector + " ", - i = 0, - l = this.length; - for ( ; i < l; i++ ) { - if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { - return true; - } - } - - return false; - }, - - val: function( value ) { - var ret, hooks, isFunction, - elem = this[0]; - - if ( !arguments.length ) { - if ( elem ) { - hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; - - if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { - return ret; - } - - ret = elem.value; - - return typeof ret === "string" ? - // handle most common string cases - ret.replace(rreturn, "") : - // handle cases where value is null/undef or number - ret == null ? "" : ret; - } - - return; - } - - isFunction = jQuery.isFunction( value ); - - return this.each(function( i ) { - var val, - self = jQuery(this); - - if ( this.nodeType !== 1 ) { - return; - } - - if ( isFunction ) { - val = value.call( this, i, self.val() ); - } else { - val = value; - } - - // Treat null/undefined as ""; convert numbers to string - if ( val == null ) { - val = ""; - } else if ( typeof val === "number" ) { - val += ""; - } else if ( jQuery.isArray( val ) ) { - val = jQuery.map(val, function ( value ) { - return value == null ? "" : value + ""; - }); - } - - hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; - - // If set returns undefined, fall back to normal setting - if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { - this.value = val; - } - }); - } -}); - -jQuery.extend({ - valHooks: { - option: { - get: function( elem ) { - // attributes.value is undefined in Blackberry 4.7 but - // uses .value. See #6932 - var val = elem.attributes.value; - return !val || val.specified ? elem.value : elem.text; - } - }, - select: { - get: function( elem ) { - var value, option, - options = elem.options, - index = elem.selectedIndex, - one = elem.type === "select-one" || index < 0, - values = one ? null : [], - max = one ? index + 1 : options.length, - i = index < 0 ? - max : - one ? index : 0; - - // Loop through all the selected options - for ( ; i < max; i++ ) { - option = options[ i ]; - - // oldIE doesn't update selected after form reset (#2551) - if ( ( option.selected || i === index ) && - // Don't return options that are disabled or in a disabled optgroup - ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && - ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { - - // Get the specific value for the option - value = jQuery( option ).val(); - - // We don't need an array for one selects - if ( one ) { - return value; - } - - // Multi-Selects return an array - values.push( value ); - } - } - - return values; - }, - - set: function( elem, value ) { - var values = jQuery.makeArray( value ); - - jQuery(elem).find("option").each(function() { - this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; - }); - - if ( !values.length ) { - elem.selectedIndex = -1; - } - return values; - } - } - }, - - attr: function( elem, name, value ) { - var hooks, notxml, ret, - nType = elem.nodeType; - - // don't get/set attributes on text, comment and attribute nodes - if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { - return; - } - - // Fallback to prop when attributes are not supported - if ( typeof elem.getAttribute === core_strundefined ) { - return jQuery.prop( elem, name, value ); - } - - notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); - - // All attributes are lowercase - // Grab necessary hook if one is defined - if ( notxml ) { - name = name.toLowerCase(); - hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); - } - - if ( value !== undefined ) { - - if ( value === null ) { - jQuery.removeAttr( elem, name ); - - } else if ( hooks && notxml && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { - return ret; - - } else { - elem.setAttribute( name, value + "" ); - return value; - } - - } else if ( hooks && notxml && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { - return ret; - - } else { - - // In IE9+, Flash objects don't have .getAttribute (#12945) - // Support: IE9+ - if ( typeof elem.getAttribute !== core_strundefined ) { - ret = elem.getAttribute( name ); - } - - // Non-existent attributes return null, we normalize to undefined - return ret == null ? - undefined : - ret; - } - }, - - removeAttr: function( elem, value ) { - var name, propName, - i = 0, - attrNames = value && value.match( core_rnotwhite ); - - if ( attrNames && elem.nodeType === 1 ) { - while ( (name = attrNames[i++]) ) { - propName = jQuery.propFix[ name ] || name; - - // Boolean attributes get special treatment (#10870) - if ( rboolean.test( name ) ) { - // Set corresponding property to false for boolean attributes - // Also clear defaultChecked/defaultSelected (if appropriate) for IE<8 - if ( !getSetAttribute && ruseDefault.test( name ) ) { - elem[ jQuery.camelCase( "default-" + name ) ] = - elem[ propName ] = false; - } else { - elem[ propName ] = false; - } - - // See #9699 for explanation of this approach (setting first, then removal) - } else { - jQuery.attr( elem, name, "" ); - } - - elem.removeAttribute( getSetAttribute ? name : propName ); - } - } - }, - - attrHooks: { - type: { - set: function( elem, value ) { - if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { - // Setting the type on a radio button after the value resets the value in IE6-9 - // Reset value to default in case type is set after value during creation - var val = elem.value; - elem.setAttribute( "type", value ); - if ( val ) { - elem.value = val; - } - return value; - } - } - } - }, - - propFix: { - tabindex: "tabIndex", - readonly: "readOnly", - "for": "htmlFor", - "class": "className", - maxlength: "maxLength", - cellspacing: "cellSpacing", - cellpadding: "cellPadding", - rowspan: "rowSpan", - colspan: "colSpan", - usemap: "useMap", - frameborder: "frameBorder", - contenteditable: "contentEditable" - }, - - prop: function( elem, name, value ) { - var ret, hooks, notxml, - nType = elem.nodeType; - - // don't get/set properties on text, comment and attribute nodes - if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { - return; - } - - notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); - - if ( notxml ) { - // Fix name and attach hooks - name = jQuery.propFix[ name ] || name; - hooks = jQuery.propHooks[ name ]; - } - - if ( value !== undefined ) { - if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { - return ret; - - } else { - return ( elem[ name ] = value ); - } - - } else { - if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { - return ret; - - } else { - return elem[ name ]; - } - } - }, - - propHooks: { - tabIndex: { - get: function( elem ) { - // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set - // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ - var attributeNode = elem.getAttributeNode("tabindex"); - - return attributeNode && attributeNode.specified ? - parseInt( attributeNode.value, 10 ) : - rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? - 0 : - undefined; - } - } - } -}); - -// Hook for boolean attributes -boolHook = { - get: function( elem, name ) { - var - // Use .prop to determine if this attribute is understood as boolean - prop = jQuery.prop( elem, name ), - - // Fetch it accordingly - attr = typeof prop === "boolean" && elem.getAttribute( name ), - detail = typeof prop === "boolean" ? - - getSetInput && getSetAttribute ? - attr != null : - // oldIE fabricates an empty string for missing boolean attributes - // and conflates checked/selected into attroperties - ruseDefault.test( name ) ? - elem[ jQuery.camelCase( "default-" + name ) ] : - !!attr : - - // fetch an attribute node for properties not recognized as boolean - elem.getAttributeNode( name ); - - return detail && detail.value !== false ? - name.toLowerCase() : - undefined; - }, - set: function( elem, value, name ) { - if ( value === false ) { - // Remove boolean attributes when set to false - jQuery.removeAttr( elem, name ); - } else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { - // IE<8 needs the *property* name - elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name ); - - // Use defaultChecked and defaultSelected for oldIE - } else { - elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true; - } - - return name; - } -}; - -// fix oldIE value attroperty -if ( !getSetInput || !getSetAttribute ) { - jQuery.attrHooks.value = { - get: function( elem, name ) { - var ret = elem.getAttributeNode( name ); - return jQuery.nodeName( elem, "input" ) ? - - // Ignore the value *property* by using defaultValue - elem.defaultValue : - - ret && ret.specified ? ret.value : undefined; - }, - set: function( elem, value, name ) { - if ( jQuery.nodeName( elem, "input" ) ) { - // Does not return so that setAttribute is also used - elem.defaultValue = value; - } else { - // Use nodeHook if defined (#1954); otherwise setAttribute is fine - return nodeHook && nodeHook.set( elem, value, name ); - } - } - }; -} - -// IE6/7 do not support getting/setting some attributes with get/setAttribute -if ( !getSetAttribute ) { - - // Use this for any attribute in IE6/7 - // This fixes almost every IE6/7 issue - nodeHook = jQuery.valHooks.button = { - get: function( elem, name ) { - var ret = elem.getAttributeNode( name ); - return ret && ( name === "id" || name === "name" || name === "coords" ? ret.value !== "" : ret.specified ) ? - ret.value : - undefined; - }, - set: function( elem, value, name ) { - // Set the existing or create a new attribute node - var ret = elem.getAttributeNode( name ); - if ( !ret ) { - elem.setAttributeNode( - (ret = elem.ownerDocument.createAttribute( name )) - ); - } - - ret.value = value += ""; - - // Break association with cloned elements by also using setAttribute (#9646) - return name === "value" || value === elem.getAttribute( name ) ? - value : - undefined; - } - }; - - // Set contenteditable to false on removals(#10429) - // Setting to empty string throws an error as an invalid value - jQuery.attrHooks.contenteditable = { - get: nodeHook.get, - set: function( elem, value, name ) { - nodeHook.set( elem, value === "" ? false : value, name ); - } - }; - - // Set width and height to auto instead of 0 on empty string( Bug #8150 ) - // This is for removals - jQuery.each([ "width", "height" ], function( i, name ) { - jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { - set: function( elem, value ) { - if ( value === "" ) { - elem.setAttribute( name, "auto" ); - return value; - } - } - }); - }); -} - - -// Some attributes require a special call on IE -// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx -if ( !jQuery.support.hrefNormalized ) { - jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { - jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { - get: function( elem ) { - var ret = elem.getAttribute( name, 2 ); - return ret == null ? undefined : ret; - } - }); - }); - - // href/src property should get the full normalized URL (#10299/#12915) - jQuery.each([ "href", "src" ], function( i, name ) { - jQuery.propHooks[ name ] = { - get: function( elem ) { - return elem.getAttribute( name, 4 ); - } - }; - }); -} - -if ( !jQuery.support.style ) { - jQuery.attrHooks.style = { - get: function( elem ) { - // Return undefined in the case of empty string - // Note: IE uppercases css property names, but if we were to .toLowerCase() - // .cssText, that would destroy case senstitivity in URL's, like in "background" - return elem.style.cssText || undefined; - }, - set: function( elem, value ) { - return ( elem.style.cssText = value + "" ); - } - }; -} - -// Safari mis-reports the default selected property of an option -// Accessing the parent's selectedIndex property fixes it -if ( !jQuery.support.optSelected ) { - jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { - get: function( elem ) { - var parent = elem.parentNode; - - if ( parent ) { - parent.selectedIndex; - - // Make sure that it also works with optgroups, see #5701 - if ( parent.parentNode ) { - parent.parentNode.selectedIndex; - } - } - return null; - } - }); -} - -// IE6/7 call enctype encoding -if ( !jQuery.support.enctype ) { - jQuery.propFix.enctype = "encoding"; -} - -// Radios and checkboxes getter/setter -if ( !jQuery.support.checkOn ) { - jQuery.each([ "radio", "checkbox" ], function() { - jQuery.valHooks[ this ] = { - get: function( elem ) { - // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified - return elem.getAttribute("value") === null ? "on" : elem.value; - } - }; - }); -} -jQuery.each([ "radio", "checkbox" ], function() { - jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { - set: function( elem, value ) { - if ( jQuery.isArray( value ) ) { - return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); - } - } - }); -}); -var rformElems = /^(?:input|select|textarea)$/i, - rkeyEvent = /^key/, - rmouseEvent = /^(?:mouse|contextmenu)|click/, - rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, - rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; - -function returnTrue() { - return true; -} - -function returnFalse() { - return false; -} - -/* - * Helper functions for managing events -- not part of the public interface. - * Props to Dean Edwards' addEvent library for many of the ideas. - */ -jQuery.event = { - - global: {}, - - add: function( elem, types, handler, data, selector ) { - var tmp, events, t, handleObjIn, - special, eventHandle, handleObj, - handlers, type, namespaces, origType, - elemData = jQuery._data( elem ); - - // Don't attach events to noData or text/comment nodes (but allow plain objects) - if ( !elemData ) { - return; - } - - // Caller can pass in an object of custom data in lieu of the handler - if ( handler.handler ) { - handleObjIn = handler; - handler = handleObjIn.handler; - selector = handleObjIn.selector; - } - - // Make sure that the handler has a unique ID, used to find/remove it later - if ( !handler.guid ) { - handler.guid = jQuery.guid++; - } - - // Init the element's event structure and main handler, if this is the first - if ( !(events = elemData.events) ) { - events = elemData.events = {}; - } - if ( !(eventHandle = elemData.handle) ) { - eventHandle = elemData.handle = function( e ) { - // Discard the second event of a jQuery.event.trigger() and - // when an event is called after a page has unloaded - return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ? - jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : - undefined; - }; - // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events - eventHandle.elem = elem; - } - - // Handle multiple events separated by a space - // jQuery(...).bind("mouseover mouseout", fn); - types = ( types || "" ).match( core_rnotwhite ) || [""]; - t = types.length; - while ( t-- ) { - tmp = rtypenamespace.exec( types[t] ) || []; - type = origType = tmp[1]; - namespaces = ( tmp[2] || "" ).split( "." ).sort(); - - // If event changes its type, use the special event handlers for the changed type - special = jQuery.event.special[ type ] || {}; - - // If selector defined, determine special event api type, otherwise given type - type = ( selector ? special.delegateType : special.bindType ) || type; - - // Update special based on newly reset type - special = jQuery.event.special[ type ] || {}; - - // handleObj is passed to all event handlers - handleObj = jQuery.extend({ - type: type, - origType: origType, - data: data, - handler: handler, - guid: handler.guid, - selector: selector, - needsContext: selector && jQuery.expr.match.needsContext.test( selector ), - namespace: namespaces.join(".") - }, handleObjIn ); - - // Init the event handler queue if we're the first - if ( !(handlers = events[ type ]) ) { - handlers = events[ type ] = []; - handlers.delegateCount = 0; - - // Only use addEventListener/attachEvent if the special events handler returns false - if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { - // Bind the global event handler to the element - if ( elem.addEventListener ) { - elem.addEventListener( type, eventHandle, false ); - - } else if ( elem.attachEvent ) { - elem.attachEvent( "on" + type, eventHandle ); - } - } - } - - if ( special.add ) { - special.add.call( elem, handleObj ); - - if ( !handleObj.handler.guid ) { - handleObj.handler.guid = handler.guid; - } - } - - // Add to the element's handler list, delegates in front - if ( selector ) { - handlers.splice( handlers.delegateCount++, 0, handleObj ); - } else { - handlers.push( handleObj ); - } - - // Keep track of which events have ever been used, for event optimization - jQuery.event.global[ type ] = true; - } - - // Nullify elem to prevent memory leaks in IE - elem = null; - }, - - // Detach an event or set of events from an element - remove: function( elem, types, handler, selector, mappedTypes ) { - var j, handleObj, tmp, - origCount, t, events, - special, handlers, type, - namespaces, origType, - elemData = jQuery.hasData( elem ) && jQuery._data( elem ); - - if ( !elemData || !(events = elemData.events) ) { - return; - } - - // Once for each type.namespace in types; type may be omitted - types = ( types || "" ).match( core_rnotwhite ) || [""]; - t = types.length; - while ( t-- ) { - tmp = rtypenamespace.exec( types[t] ) || []; - type = origType = tmp[1]; - namespaces = ( tmp[2] || "" ).split( "." ).sort(); - - // Unbind all events (on this namespace, if provided) for the element - if ( !type ) { - for ( type in events ) { - jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); - } - continue; - } - - special = jQuery.event.special[ type ] || {}; - type = ( selector ? special.delegateType : special.bindType ) || type; - handlers = events[ type ] || []; - tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); - - // Remove matching events - origCount = j = handlers.length; - while ( j-- ) { - handleObj = handlers[ j ]; - - if ( ( mappedTypes || origType === handleObj.origType ) && - ( !handler || handler.guid === handleObj.guid ) && - ( !tmp || tmp.test( handleObj.namespace ) ) && - ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { - handlers.splice( j, 1 ); - - if ( handleObj.selector ) { - handlers.delegateCount--; - } - if ( special.remove ) { - special.remove.call( elem, handleObj ); - } - } - } - - // Remove generic event handler if we removed something and no more handlers exist - // (avoids potential for endless recursion during removal of special event handlers) - if ( origCount && !handlers.length ) { - if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { - jQuery.removeEvent( elem, type, elemData.handle ); - } - - delete events[ type ]; - } - } - - // Remove the expando if it's no longer used - if ( jQuery.isEmptyObject( events ) ) { - delete elemData.handle; - - // removeData also checks for emptiness and clears the expando if empty - // so use it instead of delete - jQuery._removeData( elem, "events" ); - } - }, - - trigger: function( event, data, elem, onlyHandlers ) { - var handle, ontype, cur, - bubbleType, special, tmp, i, - eventPath = [ elem || document ], - type = core_hasOwn.call( event, "type" ) ? event.type : event, - namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; - - cur = tmp = elem = elem || document; - - // Don't do events on text and comment nodes - if ( elem.nodeType === 3 || elem.nodeType === 8 ) { - return; - } - - // focus/blur morphs to focusin/out; ensure we're not firing them right now - if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { - return; - } - - if ( type.indexOf(".") >= 0 ) { - // Namespaced trigger; create a regexp to match event type in handle() - namespaces = type.split("."); - type = namespaces.shift(); - namespaces.sort(); - } - ontype = type.indexOf(":") < 0 && "on" + type; - - // Caller can pass in a jQuery.Event object, Object, or just an event type string - event = event[ jQuery.expando ] ? - event : - new jQuery.Event( type, typeof event === "object" && event ); - - event.isTrigger = true; - event.namespace = namespaces.join("."); - event.namespace_re = event.namespace ? - new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : - null; - - // Clean up the event in case it is being reused - event.result = undefined; - if ( !event.target ) { - event.target = elem; - } - - // Clone any incoming data and prepend the event, creating the handler arg list - data = data == null ? - [ event ] : - jQuery.makeArray( data, [ event ] ); - - // Allow special events to draw outside the lines - special = jQuery.event.special[ type ] || {}; - if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { - return; - } - - // Determine event propagation path in advance, per W3C events spec (#9951) - // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) - if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { - - bubbleType = special.delegateType || type; - if ( !rfocusMorph.test( bubbleType + type ) ) { - cur = cur.parentNode; - } - for ( ; cur; cur = cur.parentNode ) { - eventPath.push( cur ); - tmp = cur; - } - - // Only add window if we got to document (e.g., not plain obj or detached DOM) - if ( tmp === (elem.ownerDocument || document) ) { - eventPath.push( tmp.defaultView || tmp.parentWindow || window ); - } - } - - // Fire handlers on the event path - i = 0; - while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { - - event.type = i > 1 ? - bubbleType : - special.bindType || type; - - // jQuery handler - handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); - if ( handle ) { - handle.apply( cur, data ); - } - - // Native handler - handle = ontype && cur[ ontype ]; - if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { - event.preventDefault(); - } - } - event.type = type; - - // If nobody prevented the default action, do it now - if ( !onlyHandlers && !event.isDefaultPrevented() ) { - - if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) && - !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { - - // Call a native DOM method on the target with the same name name as the event. - // Can't use an .isFunction() check here because IE6/7 fails that test. - // Don't do default actions on window, that's where global variables be (#6170) - if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) { - - // Don't re-trigger an onFOO event when we call its FOO() method - tmp = elem[ ontype ]; - - if ( tmp ) { - elem[ ontype ] = null; - } - - // Prevent re-triggering of the same event, since we already bubbled it above - jQuery.event.triggered = type; - try { - elem[ type ](); - } catch ( e ) { - // IE<9 dies on focus/blur to hidden element (#1486,#12518) - // only reproducible on winXP IE8 native, not IE9 in IE8 mode - } - jQuery.event.triggered = undefined; - - if ( tmp ) { - elem[ ontype ] = tmp; - } - } - } - } - - return event.result; - }, - - dispatch: function( event ) { - - // Make a writable jQuery.Event from the native event object - event = jQuery.event.fix( event ); - - var i, ret, handleObj, matched, j, - handlerQueue = [], - args = core_slice.call( arguments ), - handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [], - special = jQuery.event.special[ event.type ] || {}; - - // Use the fix-ed jQuery.Event rather than the (read-only) native event - args[0] = event; - event.delegateTarget = this; - - // Call the preDispatch hook for the mapped type, and let it bail if desired - if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { - return; - } - - // Determine handlers - handlerQueue = jQuery.event.handlers.call( this, event, handlers ); - - // Run delegates first; they may want to stop propagation beneath us - i = 0; - while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { - event.currentTarget = matched.elem; - - j = 0; - while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { - - // Triggered event must either 1) have no namespace, or - // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). - if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { - - event.handleObj = handleObj; - event.data = handleObj.data; - - ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) - .apply( matched.elem, args ); - - if ( ret !== undefined ) { - if ( (event.result = ret) === false ) { - event.preventDefault(); - event.stopPropagation(); - } - } - } - } - } - - // Call the postDispatch hook for the mapped type - if ( special.postDispatch ) { - special.postDispatch.call( this, event ); - } - - return event.result; - }, - - handlers: function( event, handlers ) { - var sel, handleObj, matches, i, - handlerQueue = [], - delegateCount = handlers.delegateCount, - cur = event.target; - - // Find delegate handlers - // Black-hole SVG <use> instance trees (#13180) - // Avoid non-left-click bubbling in Firefox (#3861) - if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { - - for ( ; cur != this; cur = cur.parentNode || this ) { - - // Don't check non-elements (#13208) - // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) - if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) { - matches = []; - for ( i = 0; i < delegateCount; i++ ) { - handleObj = handlers[ i ]; - - // Don't conflict with Object.prototype properties (#13203) - sel = handleObj.selector + " "; - - if ( matches[ sel ] === undefined ) { - matches[ sel ] = handleObj.needsContext ? - jQuery( sel, this ).index( cur ) >= 0 : - jQuery.find( sel, this, null, [ cur ] ).length; - } - if ( matches[ sel ] ) { - matches.push( handleObj ); - } - } - if ( matches.length ) { - handlerQueue.push({ elem: cur, handlers: matches }); - } - } - } - } - - // Add the remaining (directly-bound) handlers - if ( delegateCount < handlers.length ) { - handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); - } - - return handlerQueue; - }, - - fix: function( event ) { - if ( event[ jQuery.expando ] ) { - return event; - } - - // Create a writable copy of the event object and normalize some properties - var i, prop, copy, - type = event.type, - originalEvent = event, - fixHook = this.fixHooks[ type ]; - - if ( !fixHook ) { - this.fixHooks[ type ] = fixHook = - rmouseEvent.test( type ) ? this.mouseHooks : - rkeyEvent.test( type ) ? this.keyHooks : - {}; - } - copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; - - event = new jQuery.Event( originalEvent ); - - i = copy.length; - while ( i-- ) { - prop = copy[ i ]; - event[ prop ] = originalEvent[ prop ]; - } - - // Support: IE<9 - // Fix target property (#1925) - if ( !event.target ) { - event.target = originalEvent.srcElement || document; - } - - // Support: Chrome 23+, Safari? - // Target should not be a text node (#504, #13143) - if ( event.target.nodeType === 3 ) { - event.target = event.target.parentNode; - } - - // Support: IE<9 - // For mouse/key events, metaKey==false if it's undefined (#3368, #11328) - event.metaKey = !!event.metaKey; - - return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; - }, - - // Includes some event props shared by KeyEvent and MouseEvent - props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), - - fixHooks: {}, - - keyHooks: { - props: "char charCode key keyCode".split(" "), - filter: function( event, original ) { - - // Add which for key events - if ( event.which == null ) { - event.which = original.charCode != null ? original.charCode : original.keyCode; - } - - return event; - } - }, - - mouseHooks: { - props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), - filter: function( event, original ) { - var body, eventDoc, doc, - button = original.button, - fromElement = original.fromElement; - - // Calculate pageX/Y if missing and clientX/Y available - if ( event.pageX == null && original.clientX != null ) { - eventDoc = event.target.ownerDocument || document; - doc = eventDoc.documentElement; - body = eventDoc.body; - - event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); - event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); - } - - // Add relatedTarget, if necessary - if ( !event.relatedTarget && fromElement ) { - event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; - } - - // Add which for click: 1 === left; 2 === middle; 3 === right - // Note: button is not normalized, so don't use it - if ( !event.which && button !== undefined ) { - event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); - } - - return event; - } - }, - - special: { - load: { - // Prevent triggered image.load events from bubbling to window.load - noBubble: true - }, - click: { - // For checkbox, fire native event so checked state will be right - trigger: function() { - if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) { - this.click(); - return false; - } - } - }, - focus: { - // Fire native event if possible so blur/focus sequence is correct - trigger: function() { - if ( this !== document.activeElement && this.focus ) { - try { - this.focus(); - return false; - } catch ( e ) { - // Support: IE<9 - // If we error on focus to hidden element (#1486, #12518), - // let .trigger() run the handlers - } - } - }, - delegateType: "focusin" - }, - blur: { - trigger: function() { - if ( this === document.activeElement && this.blur ) { - this.blur(); - return false; - } - }, - delegateType: "focusout" - }, - - beforeunload: { - postDispatch: function( event ) { - - // Even when returnValue equals to undefined Firefox will still show alert - if ( event.result !== undefined ) { - event.originalEvent.returnValue = event.result; - } - } - } - }, - - simulate: function( type, elem, event, bubble ) { - // Piggyback on a donor event to simulate a different one. - // Fake originalEvent to avoid donor's stopPropagation, but if the - // simulated event prevents default then we do the same on the donor. - var e = jQuery.extend( - new jQuery.Event(), - event, - { type: type, - isSimulated: true, - originalEvent: {} - } - ); - if ( bubble ) { - jQuery.event.trigger( e, null, elem ); - } else { - jQuery.event.dispatch.call( elem, e ); - } - if ( e.isDefaultPrevented() ) { - event.preventDefault(); - } - } -}; - -jQuery.removeEvent = document.removeEventListener ? - function( elem, type, handle ) { - if ( elem.removeEventListener ) { - elem.removeEventListener( type, handle, false ); - } - } : - function( elem, type, handle ) { - var name = "on" + type; - - if ( elem.detachEvent ) { - - // #8545, #7054, preventing memory leaks for custom events in IE6-8 - // detachEvent needed property on element, by name of that event, to properly expose it to GC - if ( typeof elem[ name ] === core_strundefined ) { - elem[ name ] = null; - } - - elem.detachEvent( name, handle ); - } - }; - -jQuery.Event = function( src, props ) { - // Allow instantiation without the 'new' keyword - if ( !(this instanceof jQuery.Event) ) { - return new jQuery.Event( src, props ); - } - - // Event object - if ( src && src.type ) { - this.originalEvent = src; - this.type = src.type; - - // Events bubbling up the document may have been marked as prevented - // by a handler lower down the tree; reflect the correct value. - this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || - src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; - - // Event type - } else { - this.type = src; - } - - // Put explicitly provided properties onto the event object - if ( props ) { - jQuery.extend( this, props ); - } - - // Create a timestamp if incoming event doesn't have one - this.timeStamp = src && src.timeStamp || jQuery.now(); - - // Mark it as fixed - this[ jQuery.expando ] = true; -}; - -// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding -// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html -jQuery.Event.prototype = { - isDefaultPrevented: returnFalse, - isPropagationStopped: returnFalse, - isImmediatePropagationStopped: returnFalse, - - preventDefault: function() { - var e = this.originalEvent; - - this.isDefaultPrevented = returnTrue; - if ( !e ) { - return; - } - - // If preventDefault exists, run it on the original event - if ( e.preventDefault ) { - e.preventDefault(); - - // Support: IE - // Otherwise set the returnValue property of the original event to false - } else { - e.returnValue = false; - } - }, - stopPropagation: function() { - var e = this.originalEvent; - - this.isPropagationStopped = returnTrue; - if ( !e ) { - return; - } - // If stopPropagation exists, run it on the original event - if ( e.stopPropagation ) { - e.stopPropagation(); - } - - // Support: IE - // Set the cancelBubble property of the original event to true - e.cancelBubble = true; - }, - stopImmediatePropagation: function() { - this.isImmediatePropagationStopped = returnTrue; - this.stopPropagation(); - } -}; - -// Create mouseenter/leave events using mouseover/out and event-time checks -jQuery.each({ - mouseenter: "mouseover", - mouseleave: "mouseout" -}, function( orig, fix ) { - jQuery.event.special[ orig ] = { - delegateType: fix, - bindType: fix, - - handle: function( event ) { - var ret, - target = this, - related = event.relatedTarget, - handleObj = event.handleObj; - - // For mousenter/leave call the handler if related is outside the target. - // NB: No relatedTarget if the mouse left/entered the browser window - if ( !related || (related !== target && !jQuery.contains( target, related )) ) { - event.type = handleObj.origType; - ret = handleObj.handler.apply( this, arguments ); - event.type = fix; - } - return ret; - } - }; -}); - -// IE submit delegation -if ( !jQuery.support.submitBubbles ) { - - jQuery.event.special.submit = { - setup: function() { - // Only need this for delegated form submit events - if ( jQuery.nodeName( this, "form" ) ) { - return false; - } - - // Lazy-add a submit handler when a descendant form may potentially be submitted - jQuery.event.add( this, "click._submit keypress._submit", function( e ) { - // Node name check avoids a VML-related crash in IE (#9807) - var elem = e.target, - form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; - if ( form && !jQuery._data( form, "submitBubbles" ) ) { - jQuery.event.add( form, "submit._submit", function( event ) { - event._submit_bubble = true; - }); - jQuery._data( form, "submitBubbles", true ); - } - }); - // return undefined since we don't need an event listener - }, - - postDispatch: function( event ) { - // If form was submitted by the user, bubble the event up the tree - if ( event._submit_bubble ) { - delete event._submit_bubble; - if ( this.parentNode && !event.isTrigger ) { - jQuery.event.simulate( "submit", this.parentNode, event, true ); - } - } - }, - - teardown: function() { - // Only need this for delegated form submit events - if ( jQuery.nodeName( this, "form" ) ) { - return false; - } - - // Remove delegated handlers; cleanData eventually reaps submit handlers attached above - jQuery.event.remove( this, "._submit" ); - } - }; -} - -// IE change delegation and checkbox/radio fix -if ( !jQuery.support.changeBubbles ) { - - jQuery.event.special.change = { - - setup: function() { - - if ( rformElems.test( this.nodeName ) ) { - // IE doesn't fire change on a check/radio until blur; trigger it on click - // after a propertychange. Eat the blur-change in special.change.handle. - // This still fires onchange a second time for check/radio after blur. - if ( this.type === "checkbox" || this.type === "radio" ) { - jQuery.event.add( this, "propertychange._change", function( event ) { - if ( event.originalEvent.propertyName === "checked" ) { - this._just_changed = true; - } - }); - jQuery.event.add( this, "click._change", function( event ) { - if ( this._just_changed && !event.isTrigger ) { - this._just_changed = false; - } - // Allow triggered, simulated change events (#11500) - jQuery.event.simulate( "change", this, event, true ); - }); - } - return false; - } - // Delegated event; lazy-add a change handler on descendant inputs - jQuery.event.add( this, "beforeactivate._change", function( e ) { - var elem = e.target; - - if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) { - jQuery.event.add( elem, "change._change", function( event ) { - if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { - jQuery.event.simulate( "change", this.parentNode, event, true ); - } - }); - jQuery._data( elem, "changeBubbles", true ); - } - }); - }, - - handle: function( event ) { - var elem = event.target; - - // Swallow native change events from checkbox/radio, we already triggered them above - if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { - return event.handleObj.handler.apply( this, arguments ); - } - }, - - teardown: function() { - jQuery.event.remove( this, "._change" ); - - return !rformElems.test( this.nodeName ); - } - }; -} - -// Create "bubbling" focus and blur events -if ( !jQuery.support.focusinBubbles ) { - jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { - - // Attach a single capturing handler while someone wants focusin/focusout - var attaches = 0, - handler = function( event ) { - jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); - }; - - jQuery.event.special[ fix ] = { - setup: function() { - if ( attaches++ === 0 ) { - document.addEventListener( orig, handler, true ); - } - }, - teardown: function() { - if ( --attaches === 0 ) { - document.removeEventListener( orig, handler, true ); - } - } - }; - }); -} - -jQuery.fn.extend({ - - on: function( types, selector, data, fn, /*INTERNAL*/ one ) { - var type, origFn; - - // Types can be a map of types/handlers - if ( typeof types === "object" ) { - // ( types-Object, selector, data ) - if ( typeof selector !== "string" ) { - // ( types-Object, data ) - data = data || selector; - selector = undefined; - } - for ( type in types ) { - this.on( type, selector, data, types[ type ], one ); - } - return this; - } - - if ( data == null && fn == null ) { - // ( types, fn ) - fn = selector; - data = selector = undefined; - } else if ( fn == null ) { - if ( typeof selector === "string" ) { - // ( types, selector, fn ) - fn = data; - data = undefined; - } else { - // ( types, data, fn ) - fn = data; - data = selector; - selector = undefined; - } - } - if ( fn === false ) { - fn = returnFalse; - } else if ( !fn ) { - return this; - } - - if ( one === 1 ) { - origFn = fn; - fn = function( event ) { - // Can use an empty set, since event contains the info - jQuery().off( event ); - return origFn.apply( this, arguments ); - }; - // Use same guid so caller can remove using origFn - fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); - } - return this.each( function() { - jQuery.event.add( this, types, fn, data, selector ); - }); - }, - one: function( types, selector, data, fn ) { - return this.on( types, selector, data, fn, 1 ); - }, - off: function( types, selector, fn ) { - var handleObj, type; - if ( types && types.preventDefault && types.handleObj ) { - // ( event ) dispatched jQuery.Event - handleObj = types.handleObj; - jQuery( types.delegateTarget ).off( - handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, - handleObj.selector, - handleObj.handler - ); - return this; - } - if ( typeof types === "object" ) { - // ( types-object [, selector] ) - for ( type in types ) { - this.off( type, selector, types[ type ] ); - } - return this; - } - if ( selector === false || typeof selector === "function" ) { - // ( types [, fn] ) - fn = selector; - selector = undefined; - } - if ( fn === false ) { - fn = returnFalse; - } - return this.each(function() { - jQuery.event.remove( this, types, fn, selector ); - }); - }, - - bind: function( types, data, fn ) { - return this.on( types, null, data, fn ); - }, - unbind: function( types, fn ) { - return this.off( types, null, fn ); - }, - - delegate: function( selector, types, data, fn ) { - return this.on( types, selector, data, fn ); - }, - undelegate: function( selector, types, fn ) { - // ( namespace ) or ( selector, types [, fn] ) - return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); - }, - - trigger: function( type, data ) { - return this.each(function() { - jQuery.event.trigger( type, data, this ); - }); - }, - triggerHandler: function( type, data ) { - var elem = this[0]; - if ( elem ) { - return jQuery.event.trigger( type, data, elem, true ); - } - } -}); -/*! - * Sizzle CSS Selector Engine - * Copyright 2012 jQuery Foundation and other contributors - * Released under the MIT license - * http://sizzlejs.com/ - */ -(function( window, undefined ) { - -var i, - cachedruns, - Expr, - getText, - isXML, - compile, - hasDuplicate, - outermostContext, - - // Local document vars - setDocument, - document, - docElem, - documentIsXML, - rbuggyQSA, - rbuggyMatches, - matches, - contains, - sortOrder, - - // Instance-specific data - expando = "sizzle" + -(new Date()), - preferredDoc = window.document, - support = {}, - dirruns = 0, - done = 0, - classCache = createCache(), - tokenCache = createCache(), - compilerCache = createCache(), - - // General-purpose constants - strundefined = typeof undefined, - MAX_NEGATIVE = 1 << 31, - - // Array methods - arr = [], - pop = arr.pop, - push = arr.push, - slice = arr.slice, - // Use a stripped-down indexOf if we can't use a native one - indexOf = arr.indexOf || function( elem ) { - var i = 0, - len = this.length; - for ( ; i < len; i++ ) { - if ( this[i] === elem ) { - return i; - } - } - return -1; - }, - - - // Regular expressions - - // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace - whitespace = "[\\x20\\t\\r\\n\\f]", - // http://www.w3.org/TR/css3-syntax/#characters - characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", - - // Loosely modeled on CSS identifier characters - // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors - // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier - identifier = characterEncoding.replace( "w", "w#" ), - - // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors - operators = "([*^$|!~]?=)", - attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + - "*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", - - // Prefer arguments quoted, - // then not containing pseudos/brackets, - // then attribute selectors/non-parenthetical expressions, - // then anything else - // These preferences are here to reduce the number of selectors - // needing tokenize in the PSEUDO preFilter - pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)", - - // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter - rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), - - rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), - rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ), - rpseudo = new RegExp( pseudos ), - ridentifier = new RegExp( "^" + identifier + "$" ), - - matchExpr = { - "ID": new RegExp( "^#(" + characterEncoding + ")" ), - "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), - "NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ), - "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), - "ATTR": new RegExp( "^" + attributes ), - "PSEUDO": new RegExp( "^" + pseudos ), - "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + - "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + - "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), - // For use in libraries implementing .is() - // We use this for POS matching in `select` - "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + - whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) - }, - - rsibling = /[\x20\t\r\n\f]*[+~]/, - - rnative = /^[^{]+\{\s*\[native code/, - - // Easily-parseable/retrievable ID or TAG or CLASS selectors - rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, - - rinputs = /^(?:input|select|textarea|button)$/i, - rheader = /^h\d$/i, - - rescape = /'|\\/g, - rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g, - - // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters - runescape = /\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g, - funescape = function( _, escaped ) { - var high = "0x" + escaped - 0x10000; - // NaN means non-codepoint - return high !== high ? - escaped : - // BMP codepoint - high < 0 ? - String.fromCharCode( high + 0x10000 ) : - // Supplemental Plane codepoint (surrogate pair) - String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); - }; - -// Use a stripped-down slice if we can't use a native one -try { - slice.call( preferredDoc.documentElement.childNodes, 0 )[0].nodeType; -} catch ( e ) { - slice = function( i ) { - var elem, - results = []; - while ( (elem = this[i++]) ) { - results.push( elem ); - } - return results; - }; -} - -/** - * For feature detection - * @param {Function} fn The function to test for native support - */ -function isNative( fn ) { - return rnative.test( fn + "" ); -} - -/** - * Create key-value caches of limited size - * @returns {Function(string, Object)} Returns the Object data after storing it on itself with - * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) - * deleting the oldest entry - */ -function createCache() { - var cache, - keys = []; - - return (cache = function( key, value ) { - // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) - if ( keys.push( key += " " ) > Expr.cacheLength ) { - // Only keep the most recent entries - delete cache[ keys.shift() ]; - } - return (cache[ key ] = value); - }); -} - -/** - * Mark a function for special use by Sizzle - * @param {Function} fn The function to mark - */ -function markFunction( fn ) { - fn[ expando ] = true; - return fn; -} - -/** - * Support testing using an element - * @param {Function} fn Passed the created div and expects a boolean result - */ -function assert( fn ) { - var div = document.createElement("div"); - - try { - return fn( div ); - } catch (e) { - return false; - } finally { - // release memory in IE - div = null; - } -} - -function Sizzle( selector, context, results, seed ) { - var match, elem, m, nodeType, - // QSA vars - i, groups, old, nid, newContext, newSelector; - - if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { - setDocument( context ); - } - - context = context || document; - results = results || []; - - if ( !selector || typeof selector !== "string" ) { - return results; - } - - if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { - return []; - } - - if ( !documentIsXML && !seed ) { - - // Shortcuts - if ( (match = rquickExpr.exec( selector )) ) { - // Speed-up: Sizzle("#ID") - if ( (m = match[1]) ) { - if ( nodeType === 9 ) { - elem = context.getElementById( m ); - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document #6963 - if ( elem && elem.parentNode ) { - // Handle the case where IE, Opera, and Webkit return items - // by name instead of ID - if ( elem.id === m ) { - results.push( elem ); - return results; - } - } else { - return results; - } - } else { - // Context is not a document - if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && - contains( context, elem ) && elem.id === m ) { - results.push( elem ); - return results; - } - } - - // Speed-up: Sizzle("TAG") - } else if ( match[2] ) { - push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) ); - return results; - - // Speed-up: Sizzle(".CLASS") - } else if ( (m = match[3]) && support.getByClassName && context.getElementsByClassName ) { - push.apply( results, slice.call(context.getElementsByClassName( m ), 0) ); - return results; - } - } - - // QSA path - if ( support.qsa && !rbuggyQSA.test(selector) ) { - old = true; - nid = expando; - newContext = context; - newSelector = nodeType === 9 && selector; - - // qSA works strangely on Element-rooted queries - // We can work around this by specifying an extra ID on the root - // and working up from there (Thanks to Andrew Dupont for the technique) - // IE 8 doesn't work on object elements - if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { - groups = tokenize( selector ); - - if ( (old = context.getAttribute("id")) ) { - nid = old.replace( rescape, "\\$&" ); - } else { - context.setAttribute( "id", nid ); - } - nid = "[id='" + nid + "'] "; - - i = groups.length; - while ( i-- ) { - groups[i] = nid + toSelector( groups[i] ); - } - newContext = rsibling.test( selector ) && context.parentNode || context; - newSelector = groups.join(","); - } - - if ( newSelector ) { - try { - push.apply( results, slice.call( newContext.querySelectorAll( - newSelector - ), 0 ) ); - return results; - } catch(qsaError) { - } finally { - if ( !old ) { - context.removeAttribute("id"); - } - } - } - } - } - - // All others - return select( selector.replace( rtrim, "$1" ), context, results, seed ); -} - -/** - * Detect xml - * @param {Element|Object} elem An element or a document - */ -isXML = Sizzle.isXML = function( elem ) { - // documentElement is verified for cases where it doesn't yet exist - // (such as loading iframes in IE - #4833) - var documentElement = elem && (elem.ownerDocument || elem).documentElement; - return documentElement ? documentElement.nodeName !== "HTML" : false; -}; - -/** - * Sets document-related variables once based on the current document - * @param {Element|Object} [doc] An element or document object to use to set the document - * @returns {Object} Returns the current document - */ -setDocument = Sizzle.setDocument = function( node ) { - var doc = node ? node.ownerDocument || node : preferredDoc; - - // If no document and documentElement is available, return - if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { - return document; - } - - // Set our document - document = doc; - docElem = doc.documentElement; - - // Support tests - documentIsXML = isXML( doc ); - - // Check if getElementsByTagName("*") returns only elements - support.tagNameNoComments = assert(function( div ) { - div.appendChild( doc.createComment("") ); - return !div.getElementsByTagName("*").length; - }); - - // Check if attributes should be retrieved by attribute nodes - support.attributes = assert(function( div ) { - div.innerHTML = "<select></select>"; - var type = typeof div.lastChild.getAttribute("multiple"); - // IE8 returns a string for some attributes even when not present - return type !== "boolean" && type !== "string"; - }); - - // Check if getElementsByClassName can be trusted - support.getByClassName = assert(function( div ) { - // Opera can't find a second classname (in 9.6) - div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>"; - if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) { - return false; - } - - // Safari 3.2 caches class attributes and doesn't catch changes - div.lastChild.className = "e"; - return div.getElementsByClassName("e").length === 2; - }); - - // Check if getElementById returns elements by name - // Check if getElementsByName privileges form controls or returns elements by ID - support.getByName = assert(function( div ) { - // Inject content - div.id = expando + 0; - div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>"; - docElem.insertBefore( div, docElem.firstChild ); - - // Test - var pass = doc.getElementsByName && - // buggy browsers will return fewer than the correct 2 - doc.getElementsByName( expando ).length === 2 + - // buggy browsers will return more than the correct 0 - doc.getElementsByName( expando + 0 ).length; - support.getIdNotName = !doc.getElementById( expando ); - - // Cleanup - docElem.removeChild( div ); - - return pass; - }); - - // IE6/7 return modified attributes - Expr.attrHandle = assert(function( div ) { - div.innerHTML = "<a href='#'></a>"; - return div.firstChild && typeof div.firstChild.getAttribute !== strundefined && - div.firstChild.getAttribute("href") === "#"; - }) ? - {} : - { - "href": function( elem ) { - return elem.getAttribute( "href", 2 ); - }, - "type": function( elem ) { - return elem.getAttribute("type"); - } - }; - - // ID find and filter - if ( support.getIdNotName ) { - Expr.find["ID"] = function( id, context ) { - if ( typeof context.getElementById !== strundefined && !documentIsXML ) { - var m = context.getElementById( id ); - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document #6963 - return m && m.parentNode ? [m] : []; - } - }; - Expr.filter["ID"] = function( id ) { - var attrId = id.replace( runescape, funescape ); - return function( elem ) { - return elem.getAttribute("id") === attrId; - }; - }; - } else { - Expr.find["ID"] = function( id, context ) { - if ( typeof context.getElementById !== strundefined && !documentIsXML ) { - var m = context.getElementById( id ); - - return m ? - m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ? - [m] : - undefined : - []; - } - }; - Expr.filter["ID"] = function( id ) { - var attrId = id.replace( runescape, funescape ); - return function( elem ) { - var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); - return node && node.value === attrId; - }; - }; - } - - // Tag - Expr.find["TAG"] = support.tagNameNoComments ? - function( tag, context ) { - if ( typeof context.getElementsByTagName !== strundefined ) { - return context.getElementsByTagName( tag ); - } - } : - function( tag, context ) { - var elem, - tmp = [], - i = 0, - results = context.getElementsByTagName( tag ); - - // Filter out possible comments - if ( tag === "*" ) { - while ( (elem = results[i++]) ) { - if ( elem.nodeType === 1 ) { - tmp.push( elem ); - } - } - - return tmp; - } - return results; - }; - - // Name - Expr.find["NAME"] = support.getByName && function( tag, context ) { - if ( typeof context.getElementsByName !== strundefined ) { - return context.getElementsByName( name ); - } - }; - - // Class - Expr.find["CLASS"] = support.getByClassName && function( className, context ) { - if ( typeof context.getElementsByClassName !== strundefined && !documentIsXML ) { - return context.getElementsByClassName( className ); - } - }; - - // QSA and matchesSelector support - - // matchesSelector(:active) reports false when true (IE9/Opera 11.5) - rbuggyMatches = []; - - // qSa(:focus) reports false when true (Chrome 21), - // no need to also add to buggyMatches since matches checks buggyQSA - // A support test would require too much code (would include document ready) - rbuggyQSA = [ ":focus" ]; - - if ( (support.qsa = isNative(doc.querySelectorAll)) ) { - // Build QSA regex - // Regex strategy adopted from Diego Perini - assert(function( div ) { - // Select is set to empty string on purpose - // This is to test IE's treatment of not explictly - // setting a boolean content attribute, - // since its presence should be enough - // http://bugs.jquery.com/ticket/12359 - div.innerHTML = "<select><option selected=''></option></select>"; - - // IE8 - Some boolean attributes are not treated correctly - if ( !div.querySelectorAll("[selected]").length ) { - rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" ); - } - - // Webkit/Opera - :checked should return selected option elements - // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked - // IE8 throws error here and will not see later tests - if ( !div.querySelectorAll(":checked").length ) { - rbuggyQSA.push(":checked"); - } - }); - - assert(function( div ) { - - // Opera 10-12/IE8 - ^= $= *= and empty values - // Should not select anything - div.innerHTML = "<input type='hidden' i=''/>"; - if ( div.querySelectorAll("[i^='']").length ) { - rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" ); - } - - // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) - // IE8 throws error here and will not see later tests - if ( !div.querySelectorAll(":enabled").length ) { - rbuggyQSA.push( ":enabled", ":disabled" ); - } - - // Opera 10-11 does not throw on post-comma invalid pseudos - div.querySelectorAll("*,:x"); - rbuggyQSA.push(",.*:"); - }); - } - - if ( (support.matchesSelector = isNative( (matches = docElem.matchesSelector || - docElem.mozMatchesSelector || - docElem.webkitMatchesSelector || - docElem.oMatchesSelector || - docElem.msMatchesSelector) )) ) { - - assert(function( div ) { - // Check to see if it's possible to do matchesSelector - // on a disconnected node (IE 9) - support.disconnectedMatch = matches.call( div, "div" ); - - // This should fail with an exception - // Gecko does not error, returns false instead - matches.call( div, "[s!='']:x" ); - rbuggyMatches.push( "!=", pseudos ); - }); - } - - rbuggyQSA = new RegExp( rbuggyQSA.join("|") ); - rbuggyMatches = new RegExp( rbuggyMatches.join("|") ); - - // Element contains another - // Purposefully does not implement inclusive descendent - // As in, an element does not contain itself - contains = isNative(docElem.contains) || docElem.compareDocumentPosition ? - function( a, b ) { - var adown = a.nodeType === 9 ? a.documentElement : a, - bup = b && b.parentNode; - return a === bup || !!( bup && bup.nodeType === 1 && ( - adown.contains ? - adown.contains( bup ) : - a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 - )); - } : - function( a, b ) { - if ( b ) { - while ( (b = b.parentNode) ) { - if ( b === a ) { - return true; - } - } - } - return false; - }; - - // Document order sorting - sortOrder = docElem.compareDocumentPosition ? - function( a, b ) { - var compare; - - if ( a === b ) { - hasDuplicate = true; - return 0; - } - - if ( (compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b )) ) { - if ( compare & 1 || a.parentNode && a.parentNode.nodeType === 11 ) { - if ( a === doc || contains( preferredDoc, a ) ) { - return -1; - } - if ( b === doc || contains( preferredDoc, b ) ) { - return 1; - } - return 0; - } - return compare & 4 ? -1 : 1; - } - - return a.compareDocumentPosition ? -1 : 1; - } : - function( a, b ) { - var cur, - i = 0, - aup = a.parentNode, - bup = b.parentNode, - ap = [ a ], - bp = [ b ]; - - // Exit early if the nodes are identical - if ( a === b ) { - hasDuplicate = true; - return 0; - - // Parentless nodes are either documents or disconnected - } else if ( !aup || !bup ) { - return a === doc ? -1 : - b === doc ? 1 : - aup ? -1 : - bup ? 1 : - 0; - - // If the nodes are siblings, we can do a quick check - } else if ( aup === bup ) { - return siblingCheck( a, b ); - } - - // Otherwise we need full lists of their ancestors for comparison - cur = a; - while ( (cur = cur.parentNode) ) { - ap.unshift( cur ); - } - cur = b; - while ( (cur = cur.parentNode) ) { - bp.unshift( cur ); - } - - // Walk down the tree looking for a discrepancy - while ( ap[i] === bp[i] ) { - i++; - } - - return i ? - // Do a sibling check if the nodes have a common ancestor - siblingCheck( ap[i], bp[i] ) : - - // Otherwise nodes in our document sort first - ap[i] === preferredDoc ? -1 : - bp[i] === preferredDoc ? 1 : - 0; - }; - - // Always assume the presence of duplicates if sort doesn't - // pass them to our comparison function (as in Google Chrome). - hasDuplicate = false; - [0, 0].sort( sortOrder ); - support.detectDuplicates = hasDuplicate; - - return document; -}; - -Sizzle.matches = function( expr, elements ) { - return Sizzle( expr, null, null, elements ); -}; - -Sizzle.matchesSelector = function( elem, expr ) { - // Set document vars if needed - if ( ( elem.ownerDocument || elem ) !== document ) { - setDocument( elem ); - } - - // Make sure that attribute selectors are quoted - expr = expr.replace( rattributeQuotes, "='$1']" ); - - // rbuggyQSA always contains :focus, so no need for an existence check - if ( support.matchesSelector && !documentIsXML && (!rbuggyMatches || !rbuggyMatches.test(expr)) && !rbuggyQSA.test(expr) ) { - try { - var ret = matches.call( elem, expr ); - - // IE 9's matchesSelector returns false on disconnected nodes - if ( ret || support.disconnectedMatch || - // As well, disconnected nodes are said to be in a document - // fragment in IE 9 - elem.document && elem.document.nodeType !== 11 ) { - return ret; - } - } catch(e) {} - } - - return Sizzle( expr, document, null, [elem] ).length > 0; -}; - -Sizzle.contains = function( context, elem ) { - // Set document vars if needed - if ( ( context.ownerDocument || context ) !== document ) { - setDocument( context ); - } - return contains( context, elem ); -}; - -Sizzle.attr = function( elem, name ) { - var val; - - // Set document vars if needed - if ( ( elem.ownerDocument || elem ) !== document ) { - setDocument( elem ); - } - - if ( !documentIsXML ) { - name = name.toLowerCase(); - } - if ( (val = Expr.attrHandle[ name ]) ) { - return val( elem ); - } - if ( documentIsXML || support.attributes ) { - return elem.getAttribute( name ); - } - return ( (val = elem.getAttributeNode( name )) || elem.getAttribute( name ) ) && elem[ name ] === true ? - name : - val && val.specified ? val.value : null; -}; - -Sizzle.error = function( msg ) { - throw new Error( "Syntax error, unrecognized expression: " + msg ); -}; - -// Document sorting and removing duplicates -Sizzle.uniqueSort = function( results ) { - var elem, - duplicates = [], - i = 1, - j = 0; - - // Unless we *know* we can detect duplicates, assume their presence - hasDuplicate = !support.detectDuplicates; - results.sort( sortOrder ); - - if ( hasDuplicate ) { - for ( ; (elem = results[i]); i++ ) { - if ( elem === results[ i - 1 ] ) { - j = duplicates.push( i ); - } - } - while ( j-- ) { - results.splice( duplicates[ j ], 1 ); - } - } - - return results; -}; - -function siblingCheck( a, b ) { - var cur = b && a, - diff = cur && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); - - // Use IE sourceIndex if available on both nodes - if ( diff ) { - return diff; - } - - // Check if b follows a - if ( cur ) { - while ( (cur = cur.nextSibling) ) { - if ( cur === b ) { - return -1; - } - } - } - - return a ? 1 : -1; -} - -// Returns a function to use in pseudos for input types -function createInputPseudo( type ) { - return function( elem ) { - var name = elem.nodeName.toLowerCase(); - return name === "input" && elem.type === type; - }; -} - -// Returns a function to use in pseudos for buttons -function createButtonPseudo( type ) { - return function( elem ) { - var name = elem.nodeName.toLowerCase(); - return (name === "input" || name === "button") && elem.type === type; - }; -} - -// Returns a function to use in pseudos for positionals -function createPositionalPseudo( fn ) { - return markFunction(function( argument ) { - argument = +argument; - return markFunction(function( seed, matches ) { - var j, - matchIndexes = fn( [], seed.length, argument ), - i = matchIndexes.length; - - // Match elements found at the specified indexes - while ( i-- ) { - if ( seed[ (j = matchIndexes[i]) ] ) { - seed[j] = !(matches[j] = seed[j]); - } - } - }); - }); -} - -/** - * Utility function for retrieving the text value of an array of DOM nodes - * @param {Array|Element} elem - */ -getText = Sizzle.getText = function( elem ) { - var node, - ret = "", - i = 0, - nodeType = elem.nodeType; - - if ( !nodeType ) { - // If no nodeType, this is expected to be an array - for ( ; (node = elem[i]); i++ ) { - // Do not traverse comment nodes - ret += getText( node ); - } - } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { - // Use textContent for elements - // innerText usage removed for consistency of new lines (see #11153) - if ( typeof elem.textContent === "string" ) { - return elem.textContent; - } else { - // Traverse its children - for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { - ret += getText( elem ); - } - } - } else if ( nodeType === 3 || nodeType === 4 ) { - return elem.nodeValue; - } - // Do not include comment or processing instruction nodes - - return ret; -}; - -Expr = Sizzle.selectors = { - - // Can be adjusted by the user - cacheLength: 50, - - createPseudo: markFunction, - - match: matchExpr, - - find: {}, - - relative: { - ">": { dir: "parentNode", first: true }, - " ": { dir: "parentNode" }, - "+": { dir: "previousSibling", first: true }, - "~": { dir: "previousSibling" } - }, - - preFilter: { - "ATTR": function( match ) { - match[1] = match[1].replace( runescape, funescape ); - - // Move the given value to match[3] whether quoted or unquoted - match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape ); - - if ( match[2] === "~=" ) { - match[3] = " " + match[3] + " "; - } - - return match.slice( 0, 4 ); - }, - - "CHILD": function( match ) { - /* matches from matchExpr["CHILD"] - 1 type (only|nth|...) - 2 what (child|of-type) - 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) - 4 xn-component of xn+y argument ([+-]?\d*n|) - 5 sign of xn-component - 6 x of xn-component - 7 sign of y-component - 8 y of y-component - */ - match[1] = match[1].toLowerCase(); - - if ( match[1].slice( 0, 3 ) === "nth" ) { - // nth-* requires argument - if ( !match[3] ) { - Sizzle.error( match[0] ); - } - - // numeric x and y parameters for Expr.filter.CHILD - // remember that false/true cast respectively to 0/1 - match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); - match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); - - // other types prohibit arguments - } else if ( match[3] ) { - Sizzle.error( match[0] ); - } - - return match; - }, - - "PSEUDO": function( match ) { - var excess, - unquoted = !match[5] && match[2]; - - if ( matchExpr["CHILD"].test( match[0] ) ) { - return null; - } - - // Accept quoted arguments as-is - if ( match[4] ) { - match[2] = match[4]; - - // Strip excess characters from unquoted arguments - } else if ( unquoted && rpseudo.test( unquoted ) && - // Get excess from tokenize (recursively) - (excess = tokenize( unquoted, true )) && - // advance to the next closing parenthesis - (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { - - // excess is a negative index - match[0] = match[0].slice( 0, excess ); - match[2] = unquoted.slice( 0, excess ); - } - - // Return only captures needed by the pseudo filter method (type and argument) - return match.slice( 0, 3 ); - } - }, - - filter: { - - "TAG": function( nodeName ) { - if ( nodeName === "*" ) { - return function() { return true; }; - } - - nodeName = nodeName.replace( runescape, funescape ).toLowerCase(); - return function( elem ) { - return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; - }; - }, - - "CLASS": function( className ) { - var pattern = classCache[ className + " " ]; - - return pattern || - (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && - classCache( className, function( elem ) { - return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" ); - }); - }, - - "ATTR": function( name, operator, check ) { - return function( elem ) { - var result = Sizzle.attr( elem, name ); - - if ( result == null ) { - return operator === "!="; - } - if ( !operator ) { - return true; - } - - result += ""; - - return operator === "=" ? result === check : - operator === "!=" ? result !== check : - operator === "^=" ? check && result.indexOf( check ) === 0 : - operator === "*=" ? check && result.indexOf( check ) > -1 : - operator === "$=" ? check && result.slice( -check.length ) === check : - operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : - operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : - false; - }; - }, - - "CHILD": function( type, what, argument, first, last ) { - var simple = type.slice( 0, 3 ) !== "nth", - forward = type.slice( -4 ) !== "last", - ofType = what === "of-type"; - - return first === 1 && last === 0 ? - - // Shortcut for :nth-*(n) - function( elem ) { - return !!elem.parentNode; - } : - - function( elem, context, xml ) { - var cache, outerCache, node, diff, nodeIndex, start, - dir = simple !== forward ? "nextSibling" : "previousSibling", - parent = elem.parentNode, - name = ofType && elem.nodeName.toLowerCase(), - useCache = !xml && !ofType; - - if ( parent ) { - - // :(first|last|only)-(child|of-type) - if ( simple ) { - while ( dir ) { - node = elem; - while ( (node = node[ dir ]) ) { - if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { - return false; - } - } - // Reverse direction for :only-* (if we haven't yet done so) - start = dir = type === "only" && !start && "nextSibling"; - } - return true; - } - - start = [ forward ? parent.firstChild : parent.lastChild ]; - - // non-xml :nth-child(...) stores cache data on `parent` - if ( forward && useCache ) { - // Seek `elem` from a previously-cached index - outerCache = parent[ expando ] || (parent[ expando ] = {}); - cache = outerCache[ type ] || []; - nodeIndex = cache[0] === dirruns && cache[1]; - diff = cache[0] === dirruns && cache[2]; - node = nodeIndex && parent.childNodes[ nodeIndex ]; - - while ( (node = ++nodeIndex && node && node[ dir ] || - - // Fallback to seeking `elem` from the start - (diff = nodeIndex = 0) || start.pop()) ) { - - // When found, cache indexes on `parent` and break - if ( node.nodeType === 1 && ++diff && node === elem ) { - outerCache[ type ] = [ dirruns, nodeIndex, diff ]; - break; - } - } - - // Use previously-cached element index if available - } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { - diff = cache[1]; - - // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) - } else { - // Use the same loop as above to seek `elem` from the start - while ( (node = ++nodeIndex && node && node[ dir ] || - (diff = nodeIndex = 0) || start.pop()) ) { - - if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { - // Cache the index of each encountered element - if ( useCache ) { - (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; - } - - if ( node === elem ) { - break; - } - } - } - } - - // Incorporate the offset, then check against cycle size - diff -= last; - return diff === first || ( diff % first === 0 && diff / first >= 0 ); - } - }; - }, - - "PSEUDO": function( pseudo, argument ) { - // pseudo-class names are case-insensitive - // http://www.w3.org/TR/selectors/#pseudo-classes - // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters - // Remember that setFilters inherits from pseudos - var args, - fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || - Sizzle.error( "unsupported pseudo: " + pseudo ); - - // The user may use createPseudo to indicate that - // arguments are needed to create the filter function - // just as Sizzle does - if ( fn[ expando ] ) { - return fn( argument ); - } - - // But maintain support for old signatures - if ( fn.length > 1 ) { - args = [ pseudo, pseudo, "", argument ]; - return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? - markFunction(function( seed, matches ) { - var idx, - matched = fn( seed, argument ), - i = matched.length; - while ( i-- ) { - idx = indexOf.call( seed, matched[i] ); - seed[ idx ] = !( matches[ idx ] = matched[i] ); - } - }) : - function( elem ) { - return fn( elem, 0, args ); - }; - } - - return fn; - } - }, - - pseudos: { - // Potentially complex pseudos - "not": markFunction(function( selector ) { - // Trim the selector passed to compile - // to avoid treating leading and trailing - // spaces as combinators - var input = [], - results = [], - matcher = compile( selector.replace( rtrim, "$1" ) ); - - return matcher[ expando ] ? - markFunction(function( seed, matches, context, xml ) { - var elem, - unmatched = matcher( seed, null, xml, [] ), - i = seed.length; - - // Match elements unmatched by `matcher` - while ( i-- ) { - if ( (elem = unmatched[i]) ) { - seed[i] = !(matches[i] = elem); - } - } - }) : - function( elem, context, xml ) { - input[0] = elem; - matcher( input, null, xml, results ); - return !results.pop(); - }; - }), - - "has": markFunction(function( selector ) { - return function( elem ) { - return Sizzle( selector, elem ).length > 0; - }; - }), - - "contains": markFunction(function( text ) { - return function( elem ) { - return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; - }; - }), - - // "Whether an element is represented by a :lang() selector - // is based solely on the element's language value - // being equal to the identifier C, - // or beginning with the identifier C immediately followed by "-". - // The matching of C against the element's language value is performed case-insensitively. - // The identifier C does not have to be a valid language name." - // http://www.w3.org/TR/selectors/#lang-pseudo - "lang": markFunction( function( lang ) { - // lang value must be a valid identifider - if ( !ridentifier.test(lang || "") ) { - Sizzle.error( "unsupported lang: " + lang ); - } - lang = lang.replace( runescape, funescape ).toLowerCase(); - return function( elem ) { - var elemLang; - do { - if ( (elemLang = documentIsXML ? - elem.getAttribute("xml:lang") || elem.getAttribute("lang") : - elem.lang) ) { - - elemLang = elemLang.toLowerCase(); - return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; - } - } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); - return false; - }; - }), - - // Miscellaneous - "target": function( elem ) { - var hash = window.location && window.location.hash; - return hash && hash.slice( 1 ) === elem.id; - }, - - "root": function( elem ) { - return elem === docElem; - }, - - "focus": function( elem ) { - return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); - }, - - // Boolean properties - "enabled": function( elem ) { - return elem.disabled === false; - }, - - "disabled": function( elem ) { - return elem.disabled === true; - }, - - "checked": function( elem ) { - // In CSS3, :checked should return both checked and selected elements - // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked - var nodeName = elem.nodeName.toLowerCase(); - return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); - }, - - "selected": function( elem ) { - // Accessing this property makes selected-by-default - // options in Safari work properly - if ( elem.parentNode ) { - elem.parentNode.selectedIndex; - } - - return elem.selected === true; - }, - - // Contents - "empty": function( elem ) { - // http://www.w3.org/TR/selectors/#empty-pseudo - // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), - // not comment, processing instructions, or others - // Thanks to Diego Perini for the nodeName shortcut - // Greater than "@" means alpha characters (specifically not starting with "#" or "?") - for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { - if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) { - return false; - } - } - return true; - }, - - "parent": function( elem ) { - return !Expr.pseudos["empty"]( elem ); - }, - - // Element/input types - "header": function( elem ) { - return rheader.test( elem.nodeName ); - }, - - "input": function( elem ) { - return rinputs.test( elem.nodeName ); - }, - - "button": function( elem ) { - var name = elem.nodeName.toLowerCase(); - return name === "input" && elem.type === "button" || name === "button"; - }, - - "text": function( elem ) { - var attr; - // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) - // use getAttribute instead to test this case - return elem.nodeName.toLowerCase() === "input" && - elem.type === "text" && - ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type ); - }, - - // Position-in-collection - "first": createPositionalPseudo(function() { - return [ 0 ]; - }), - - "last": createPositionalPseudo(function( matchIndexes, length ) { - return [ length - 1 ]; - }), - - "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { - return [ argument < 0 ? argument + length : argument ]; - }), - - "even": createPositionalPseudo(function( matchIndexes, length ) { - var i = 0; - for ( ; i < length; i += 2 ) { - matchIndexes.push( i ); - } - return matchIndexes; - }), - - "odd": createPositionalPseudo(function( matchIndexes, length ) { - var i = 1; - for ( ; i < length; i += 2 ) { - matchIndexes.push( i ); - } - return matchIndexes; - }), - - "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { - var i = argument < 0 ? argument + length : argument; - for ( ; --i >= 0; ) { - matchIndexes.push( i ); - } - return matchIndexes; - }), - - "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { - var i = argument < 0 ? argument + length : argument; - for ( ; ++i < length; ) { - matchIndexes.push( i ); - } - return matchIndexes; - }) - } -}; - -// Add button/input type pseudos -for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { - Expr.pseudos[ i ] = createInputPseudo( i ); -} -for ( i in { submit: true, reset: true } ) { - Expr.pseudos[ i ] = createButtonPseudo( i ); -} - -function tokenize( selector, parseOnly ) { - var matched, match, tokens, type, - soFar, groups, preFilters, - cached = tokenCache[ selector + " " ]; - - if ( cached ) { - return parseOnly ? 0 : cached.slice( 0 ); - } - - soFar = selector; - groups = []; - preFilters = Expr.preFilter; - - while ( soFar ) { - - // Comma and first run - if ( !matched || (match = rcomma.exec( soFar )) ) { - if ( match ) { - // Don't consume trailing commas as valid - soFar = soFar.slice( match[0].length ) || soFar; - } - groups.push( tokens = [] ); - } - - matched = false; - - // Combinators - if ( (match = rcombinators.exec( soFar )) ) { - matched = match.shift(); - tokens.push( { - value: matched, - // Cast descendant combinators to space - type: match[0].replace( rtrim, " " ) - } ); - soFar = soFar.slice( matched.length ); - } - - // Filters - for ( type in Expr.filter ) { - if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || - (match = preFilters[ type ]( match ))) ) { - matched = match.shift(); - tokens.push( { - value: matched, - type: type, - matches: match - } ); - soFar = soFar.slice( matched.length ); - } - } - - if ( !matched ) { - break; - } - } - - // Return the length of the invalid excess - // if we're just parsing - // Otherwise, throw an error or return tokens - return parseOnly ? - soFar.length : - soFar ? - Sizzle.error( selector ) : - // Cache the tokens - tokenCache( selector, groups ).slice( 0 ); -} - -function toSelector( tokens ) { - var i = 0, - len = tokens.length, - selector = ""; - for ( ; i < len; i++ ) { - selector += tokens[i].value; - } - return selector; -} - -function addCombinator( matcher, combinator, base ) { - var dir = combinator.dir, - checkNonElements = base && dir === "parentNode", - doneName = done++; - - return combinator.first ? - // Check against closest ancestor/preceding element - function( elem, context, xml ) { - while ( (elem = elem[ dir ]) ) { - if ( elem.nodeType === 1 || checkNonElements ) { - return matcher( elem, context, xml ); - } - } - } : - - // Check against all ancestor/preceding elements - function( elem, context, xml ) { - var data, cache, outerCache, - dirkey = dirruns + " " + doneName; - - // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching - if ( xml ) { - while ( (elem = elem[ dir ]) ) { - if ( elem.nodeType === 1 || checkNonElements ) { - if ( matcher( elem, context, xml ) ) { - return true; - } - } - } - } else { - while ( (elem = elem[ dir ]) ) { - if ( elem.nodeType === 1 || checkNonElements ) { - outerCache = elem[ expando ] || (elem[ expando ] = {}); - if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) { - if ( (data = cache[1]) === true || data === cachedruns ) { - return data === true; - } - } else { - cache = outerCache[ dir ] = [ dirkey ]; - cache[1] = matcher( elem, context, xml ) || cachedruns; - if ( cache[1] === true ) { - return true; - } - } - } - } - } - }; -} - -function elementMatcher( matchers ) { - return matchers.length > 1 ? - function( elem, context, xml ) { - var i = matchers.length; - while ( i-- ) { - if ( !matchers[i]( elem, context, xml ) ) { - return false; - } - } - return true; - } : - matchers[0]; -} - -function condense( unmatched, map, filter, context, xml ) { - var elem, - newUnmatched = [], - i = 0, - len = unmatched.length, - mapped = map != null; - - for ( ; i < len; i++ ) { - if ( (elem = unmatched[i]) ) { - if ( !filter || filter( elem, context, xml ) ) { - newUnmatched.push( elem ); - if ( mapped ) { - map.push( i ); - } - } - } - } - - return newUnmatched; -} - -function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { - if ( postFilter && !postFilter[ expando ] ) { - postFilter = setMatcher( postFilter ); - } - if ( postFinder && !postFinder[ expando ] ) { - postFinder = setMatcher( postFinder, postSelector ); - } - return markFunction(function( seed, results, context, xml ) { - var temp, i, elem, - preMap = [], - postMap = [], - preexisting = results.length, - - // Get initial elements from seed or context - elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), - - // Prefilter to get matcher input, preserving a map for seed-results synchronization - matcherIn = preFilter && ( seed || !selector ) ? - condense( elems, preMap, preFilter, context, xml ) : - elems, - - matcherOut = matcher ? - // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, - postFinder || ( seed ? preFilter : preexisting || postFilter ) ? - - // ...intermediate processing is necessary - [] : - - // ...otherwise use results directly - results : - matcherIn; - - // Find primary matches - if ( matcher ) { - matcher( matcherIn, matcherOut, context, xml ); - } - - // Apply postFilter - if ( postFilter ) { - temp = condense( matcherOut, postMap ); - postFilter( temp, [], context, xml ); - - // Un-match failing elements by moving them back to matcherIn - i = temp.length; - while ( i-- ) { - if ( (elem = temp[i]) ) { - matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); - } - } - } - - if ( seed ) { - if ( postFinder || preFilter ) { - if ( postFinder ) { - // Get the final matcherOut by condensing this intermediate into postFinder contexts - temp = []; - i = matcherOut.length; - while ( i-- ) { - if ( (elem = matcherOut[i]) ) { - // Restore matcherIn since elem is not yet a final match - temp.push( (matcherIn[i] = elem) ); - } - } - postFinder( null, (matcherOut = []), temp, xml ); - } - - // Move matched elements from seed to results to keep them synchronized - i = matcherOut.length; - while ( i-- ) { - if ( (elem = matcherOut[i]) && - (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { - - seed[temp] = !(results[temp] = elem); - } - } - } - - // Add elements to results, through postFinder if defined - } else { - matcherOut = condense( - matcherOut === results ? - matcherOut.splice( preexisting, matcherOut.length ) : - matcherOut - ); - if ( postFinder ) { - postFinder( null, results, matcherOut, xml ); - } else { - push.apply( results, matcherOut ); - } - } - }); -} - -function matcherFromTokens( tokens ) { - var checkContext, matcher, j, - len = tokens.length, - leadingRelative = Expr.relative[ tokens[0].type ], - implicitRelative = leadingRelative || Expr.relative[" "], - i = leadingRelative ? 1 : 0, - - // The foundational matcher ensures that elements are reachable from top-level context(s) - matchContext = addCombinator( function( elem ) { - return elem === checkContext; - }, implicitRelative, true ), - matchAnyContext = addCombinator( function( elem ) { - return indexOf.call( checkContext, elem ) > -1; - }, implicitRelative, true ), - matchers = [ function( elem, context, xml ) { - return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( - (checkContext = context).nodeType ? - matchContext( elem, context, xml ) : - matchAnyContext( elem, context, xml ) ); - } ]; - - for ( ; i < len; i++ ) { - if ( (matcher = Expr.relative[ tokens[i].type ]) ) { - matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; - } else { - matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); - - // Return special upon seeing a positional matcher - if ( matcher[ expando ] ) { - // Find the next relative operator (if any) for proper handling - j = ++i; - for ( ; j < len; j++ ) { - if ( Expr.relative[ tokens[j].type ] ) { - break; - } - } - return setMatcher( - i > 1 && elementMatcher( matchers ), - i > 1 && toSelector( tokens.slice( 0, i - 1 ) ).replace( rtrim, "$1" ), - matcher, - i < j && matcherFromTokens( tokens.slice( i, j ) ), - j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), - j < len && toSelector( tokens ) - ); - } - matchers.push( matcher ); - } - } - - return elementMatcher( matchers ); -} - -function matcherFromGroupMatchers( elementMatchers, setMatchers ) { - // A counter to specify which element is currently being matched - var matcherCachedRuns = 0, - bySet = setMatchers.length > 0, - byElement = elementMatchers.length > 0, - superMatcher = function( seed, context, xml, results, expandContext ) { - var elem, j, matcher, - setMatched = [], - matchedCount = 0, - i = "0", - unmatched = seed && [], - outermost = expandContext != null, - contextBackup = outermostContext, - // We must always have either seed elements or context - elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), - // Use integer dirruns iff this is the outermost matcher - dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1); - - if ( outermost ) { - outermostContext = context !== document && context; - cachedruns = matcherCachedRuns; - } - - // Add elements passing elementMatchers directly to results - // Keep `i` a string if there are no elements so `matchedCount` will be "00" below - for ( ; (elem = elems[i]) != null; i++ ) { - if ( byElement && elem ) { - j = 0; - while ( (matcher = elementMatchers[j++]) ) { - if ( matcher( elem, context, xml ) ) { - results.push( elem ); - break; - } - } - if ( outermost ) { - dirruns = dirrunsUnique; - cachedruns = ++matcherCachedRuns; - } - } - - // Track unmatched elements for set filters - if ( bySet ) { - // They will have gone through all possible matchers - if ( (elem = !matcher && elem) ) { - matchedCount--; - } - - // Lengthen the array for every element, matched or not - if ( seed ) { - unmatched.push( elem ); - } - } - } - - // Apply set filters to unmatched elements - matchedCount += i; - if ( bySet && i !== matchedCount ) { - j = 0; - while ( (matcher = setMatchers[j++]) ) { - matcher( unmatched, setMatched, context, xml ); - } - - if ( seed ) { - // Reintegrate element matches to eliminate the need for sorting - if ( matchedCount > 0 ) { - while ( i-- ) { - if ( !(unmatched[i] || setMatched[i]) ) { - setMatched[i] = pop.call( results ); - } - } - } - - // Discard index placeholder values to get only actual matches - setMatched = condense( setMatched ); - } - - // Add matches to results - push.apply( results, setMatched ); - - // Seedless set matches succeeding multiple successful matchers stipulate sorting - if ( outermost && !seed && setMatched.length > 0 && - ( matchedCount + setMatchers.length ) > 1 ) { - - Sizzle.uniqueSort( results ); - } - } - - // Override manipulation of globals by nested matchers - if ( outermost ) { - dirruns = dirrunsUnique; - outermostContext = contextBackup; - } - - return unmatched; - }; - - return bySet ? - markFunction( superMatcher ) : - superMatcher; -} - -compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { - var i, - setMatchers = [], - elementMatchers = [], - cached = compilerCache[ selector + " " ]; - - if ( !cached ) { - // Generate a function of recursive functions that can be used to check each element - if ( !group ) { - group = tokenize( selector ); - } - i = group.length; - while ( i-- ) { - cached = matcherFromTokens( group[i] ); - if ( cached[ expando ] ) { - setMatchers.push( cached ); - } else { - elementMatchers.push( cached ); - } - } - - // Cache the compiled function - cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); - } - return cached; -}; - -function multipleContexts( selector, contexts, results ) { - var i = 0, - len = contexts.length; - for ( ; i < len; i++ ) { - Sizzle( selector, contexts[i], results ); - } - return results; -} - -function select( selector, context, results, seed ) { - var i, tokens, token, type, find, - match = tokenize( selector ); - - if ( !seed ) { - // Try to minimize operations if there is only one group - if ( match.length === 1 ) { - - // Take a shortcut and set the context if the root selector is an ID - tokens = match[0] = match[0].slice( 0 ); - if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && - context.nodeType === 9 && !documentIsXML && - Expr.relative[ tokens[1].type ] ) { - - context = Expr.find["ID"]( token.matches[0].replace( runescape, funescape ), context )[0]; - if ( !context ) { - return results; - } - - selector = selector.slice( tokens.shift().value.length ); - } - - // Fetch a seed set for right-to-left matching - i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; - while ( i-- ) { - token = tokens[i]; - - // Abort if we hit a combinator - if ( Expr.relative[ (type = token.type) ] ) { - break; - } - if ( (find = Expr.find[ type ]) ) { - // Search, expanding context for leading sibling combinators - if ( (seed = find( - token.matches[0].replace( runescape, funescape ), - rsibling.test( tokens[0].type ) && context.parentNode || context - )) ) { - - // If seed is empty or no tokens remain, we can return early - tokens.splice( i, 1 ); - selector = seed.length && toSelector( tokens ); - if ( !selector ) { - push.apply( results, slice.call( seed, 0 ) ); - return results; - } - - break; - } - } - } - } - } - - // Compile and execute a filtering function - // Provide `match` to avoid retokenization if we modified the selector above - compile( selector, match )( - seed, - context, - documentIsXML, - results, - rsibling.test( selector ) - ); - return results; -} - -// Deprecated -Expr.pseudos["nth"] = Expr.pseudos["eq"]; - -// Easy API for creating new setFilters -function setFilters() {} -Expr.filters = setFilters.prototype = Expr.pseudos; -Expr.setFilters = new setFilters(); - -// Initialize with the default document -setDocument(); - -// Override sizzle attribute retrieval -Sizzle.attr = jQuery.attr; -jQuery.find = Sizzle; -jQuery.expr = Sizzle.selectors; -jQuery.expr[":"] = jQuery.expr.pseudos; -jQuery.unique = Sizzle.uniqueSort; -jQuery.text = Sizzle.getText; -jQuery.isXMLDoc = Sizzle.isXML; -jQuery.contains = Sizzle.contains; - - -})( window ); -var runtil = /Until$/, - rparentsprev = /^(?:parents|prev(?:Until|All))/, - isSimple = /^.[^:#\[\.,]*$/, - rneedsContext = jQuery.expr.match.needsContext, - // methods guaranteed to produce a unique set when starting from a unique set - guaranteedUnique = { - children: true, - contents: true, - next: true, - prev: true - }; - -jQuery.fn.extend({ - find: function( selector ) { - var i, ret, self, - len = this.length; - - if ( typeof selector !== "string" ) { - self = this; - return this.pushStack( jQuery( selector ).filter(function() { - for ( i = 0; i < len; i++ ) { - if ( jQuery.contains( self[ i ], this ) ) { - return true; - } - } - }) ); - } - - ret = []; - for ( i = 0; i < len; i++ ) { - jQuery.find( selector, this[ i ], ret ); - } - - // Needed because $( selector, context ) becomes $( context ).find( selector ) - ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); - ret.selector = ( this.selector ? this.selector + " " : "" ) + selector; - return ret; - }, - - has: function( target ) { - var i, - targets = jQuery( target, this ), - len = targets.length; - - return this.filter(function() { - for ( i = 0; i < len; i++ ) { - if ( jQuery.contains( this, targets[i] ) ) { - return true; - } - } - }); - }, - - not: function( selector ) { - return this.pushStack( winnow(this, selector, false) ); - }, - - filter: function( selector ) { - return this.pushStack( winnow(this, selector, true) ); - }, - - is: function( selector ) { - return !!selector && ( - typeof selector === "string" ? - // If this is a positional/relative selector, check membership in the returned set - // so $("p:first").is("p:last") won't return true for a doc with two "p". - rneedsContext.test( selector ) ? - jQuery( selector, this.context ).index( this[0] ) >= 0 : - jQuery.filter( selector, this ).length > 0 : - this.filter( selector ).length > 0 ); - }, - - closest: function( selectors, context ) { - var cur, - i = 0, - l = this.length, - ret = [], - pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? - jQuery( selectors, context || this.context ) : - 0; - - for ( ; i < l; i++ ) { - cur = this[i]; - - while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) { - if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { - ret.push( cur ); - break; - } - cur = cur.parentNode; - } - } - - return this.pushStack( ret.length > 1 ? jQuery.unique( ret ) : ret ); - }, - - // Determine the position of an element within - // the matched set of elements - index: function( elem ) { - - // No argument, return index in parent - if ( !elem ) { - return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1; - } - - // index in selector - if ( typeof elem === "string" ) { - return jQuery.inArray( this[0], jQuery( elem ) ); - } - - // Locate the position of the desired element - return jQuery.inArray( - // If it receives a jQuery object, the first element is used - elem.jquery ? elem[0] : elem, this ); - }, - - add: function( selector, context ) { - var set = typeof selector === "string" ? - jQuery( selector, context ) : - jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), - all = jQuery.merge( this.get(), set ); - - return this.pushStack( jQuery.unique(all) ); - }, - - addBack: function( selector ) { - return this.add( selector == null ? - this.prevObject : this.prevObject.filter(selector) - ); - } -}); - -jQuery.fn.andSelf = jQuery.fn.addBack; - -function sibling( cur, dir ) { - do { - cur = cur[ dir ]; - } while ( cur && cur.nodeType !== 1 ); - - return cur; -} - -jQuery.each({ - parent: function( elem ) { - var parent = elem.parentNode; - return parent && parent.nodeType !== 11 ? parent : null; - }, - parents: function( elem ) { - return jQuery.dir( elem, "parentNode" ); - }, - parentsUntil: function( elem, i, until ) { - return jQuery.dir( elem, "parentNode", until ); - }, - next: function( elem ) { - return sibling( elem, "nextSibling" ); - }, - prev: function( elem ) { - return sibling( elem, "previousSibling" ); - }, - nextAll: function( elem ) { - return jQuery.dir( elem, "nextSibling" ); - }, - prevAll: function( elem ) { - return jQuery.dir( elem, "previousSibling" ); - }, - nextUntil: function( elem, i, until ) { - return jQuery.dir( elem, "nextSibling", until ); - }, - prevUntil: function( elem, i, until ) { - return jQuery.dir( elem, "previousSibling", until ); - }, - siblings: function( elem ) { - return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); - }, - children: function( elem ) { - return jQuery.sibling( elem.firstChild ); - }, - contents: function( elem ) { - return jQuery.nodeName( elem, "iframe" ) ? - elem.contentDocument || elem.contentWindow.document : - jQuery.merge( [], elem.childNodes ); - } -}, function( name, fn ) { - jQuery.fn[ name ] = function( until, selector ) { - var ret = jQuery.map( this, fn, until ); - - if ( !runtil.test( name ) ) { - selector = until; - } - - if ( selector && typeof selector === "string" ) { - ret = jQuery.filter( selector, ret ); - } - - ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; - - if ( this.length > 1 && rparentsprev.test( name ) ) { - ret = ret.reverse(); - } - - return this.pushStack( ret ); - }; -}); - -jQuery.extend({ - filter: function( expr, elems, not ) { - if ( not ) { - expr = ":not(" + expr + ")"; - } - - return elems.length === 1 ? - jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : - jQuery.find.matches(expr, elems); - }, - - dir: function( elem, dir, until ) { - var matched = [], - cur = elem[ dir ]; - - while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { - if ( cur.nodeType === 1 ) { - matched.push( cur ); - } - cur = cur[dir]; - } - return matched; - }, - - sibling: function( n, elem ) { - var r = []; - - for ( ; n; n = n.nextSibling ) { - if ( n.nodeType === 1 && n !== elem ) { - r.push( n ); - } - } - - return r; - } -}); - -// Implement the identical functionality for filter and not -function winnow( elements, qualifier, keep ) { - - // Can't pass null or undefined to indexOf in Firefox 4 - // Set to 0 to skip string check - qualifier = qualifier || 0; - - if ( jQuery.isFunction( qualifier ) ) { - return jQuery.grep(elements, function( elem, i ) { - var retVal = !!qualifier.call( elem, i, elem ); - return retVal === keep; - }); - - } else if ( qualifier.nodeType ) { - return jQuery.grep(elements, function( elem ) { - return ( elem === qualifier ) === keep; - }); - - } else if ( typeof qualifier === "string" ) { - var filtered = jQuery.grep(elements, function( elem ) { - return elem.nodeType === 1; - }); - - if ( isSimple.test( qualifier ) ) { - return jQuery.filter(qualifier, filtered, !keep); - } else { - qualifier = jQuery.filter( qualifier, filtered ); - } - } - - return jQuery.grep(elements, function( elem ) { - return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; - }); -} -function createSafeFragment( document ) { - var list = nodeNames.split( "|" ), - safeFrag = document.createDocumentFragment(); - - if ( safeFrag.createElement ) { - while ( list.length ) { - safeFrag.createElement( - list.pop() - ); - } - } - return safeFrag; -} - -var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + - "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", - rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, - rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), - rleadingWhitespace = /^\s+/, - rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, - rtagName = /<([\w:]+)/, - rtbody = /<tbody/i, - rhtml = /<|&#?\w+;/, - rnoInnerhtml = /<(?:script|style|link)/i, - manipulation_rcheckableType = /^(?:checkbox|radio)$/i, - // checked="checked" or checked - rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, - rscriptType = /^$|\/(?:java|ecma)script/i, - rscriptTypeMasked = /^true\/(.*)/, - rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, - - // We have to close these tags to support XHTML (#13200) - wrapMap = { - option: [ 1, "<select multiple='multiple'>", "</select>" ], - legend: [ 1, "<fieldset>", "</fieldset>" ], - area: [ 1, "<map>", "</map>" ], - param: [ 1, "<object>", "</object>" ], - thead: [ 1, "<table>", "</table>" ], - tr: [ 2, "<table><tbody>", "</tbody></table>" ], - col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], - td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], - - // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, - // unless wrapped in a div with non-breaking characters in front of it. - _default: jQuery.support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ] - }, - safeFragment = createSafeFragment( document ), - fragmentDiv = safeFragment.appendChild( document.createElement("div") ); - -wrapMap.optgroup = wrapMap.option; -wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; -wrapMap.th = wrapMap.td; - -jQuery.fn.extend({ - text: function( value ) { - return jQuery.access( this, function( value ) { - return value === undefined ? - jQuery.text( this ) : - this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); - }, null, value, arguments.length ); - }, - - wrapAll: function( html ) { - if ( jQuery.isFunction( html ) ) { - return this.each(function(i) { - jQuery(this).wrapAll( html.call(this, i) ); - }); - } - - if ( this[0] ) { - // The elements to wrap the target around - var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); - - if ( this[0].parentNode ) { - wrap.insertBefore( this[0] ); - } - - wrap.map(function() { - var elem = this; - - while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { - elem = elem.firstChild; - } - - return elem; - }).append( this ); - } - - return this; - }, - - wrapInner: function( html ) { - if ( jQuery.isFunction( html ) ) { - return this.each(function(i) { - jQuery(this).wrapInner( html.call(this, i) ); - }); - } - - return this.each(function() { - var self = jQuery( this ), - contents = self.contents(); - - if ( contents.length ) { - contents.wrapAll( html ); - - } else { - self.append( html ); - } - }); - }, - - wrap: function( html ) { - var isFunction = jQuery.isFunction( html ); - - return this.each(function(i) { - jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); - }); - }, - - unwrap: function() { - return this.parent().each(function() { - if ( !jQuery.nodeName( this, "body" ) ) { - jQuery( this ).replaceWith( this.childNodes ); - } - }).end(); - }, - - append: function() { - return this.domManip(arguments, true, function( elem ) { - if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { - this.appendChild( elem ); - } - }); - }, - - prepend: function() { - return this.domManip(arguments, true, function( elem ) { - if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { - this.insertBefore( elem, this.firstChild ); - } - }); - }, - - before: function() { - return this.domManip( arguments, false, function( elem ) { - if ( this.parentNode ) { - this.parentNode.insertBefore( elem, this ); - } - }); - }, - - after: function() { - return this.domManip( arguments, false, function( elem ) { - if ( this.parentNode ) { - this.parentNode.insertBefore( elem, this.nextSibling ); - } - }); - }, - - // keepData is for internal use only--do not document - remove: function( selector, keepData ) { - var elem, - i = 0; - - for ( ; (elem = this[i]) != null; i++ ) { - if ( !selector || jQuery.filter( selector, [ elem ] ).length > 0 ) { - if ( !keepData && elem.nodeType === 1 ) { - jQuery.cleanData( getAll( elem ) ); - } - - if ( elem.parentNode ) { - if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { - setGlobalEval( getAll( elem, "script" ) ); - } - elem.parentNode.removeChild( elem ); - } - } - } - - return this; - }, - - empty: function() { - var elem, - i = 0; - - for ( ; (elem = this[i]) != null; i++ ) { - // Remove element nodes and prevent memory leaks - if ( elem.nodeType === 1 ) { - jQuery.cleanData( getAll( elem, false ) ); - } - - // Remove any remaining nodes - while ( elem.firstChild ) { - elem.removeChild( elem.firstChild ); - } - - // If this is a select, ensure that it displays empty (#12336) - // Support: IE<9 - if ( elem.options && jQuery.nodeName( elem, "select" ) ) { - elem.options.length = 0; - } - } - - return this; - }, - - clone: function( dataAndEvents, deepDataAndEvents ) { - dataAndEvents = dataAndEvents == null ? false : dataAndEvents; - deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; - - return this.map( function () { - return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); - }); - }, - - html: function( value ) { - return jQuery.access( this, function( value ) { - var elem = this[0] || {}, - i = 0, - l = this.length; - - if ( value === undefined ) { - return elem.nodeType === 1 ? - elem.innerHTML.replace( rinlinejQuery, "" ) : - undefined; - } - - // See if we can take a shortcut and just use innerHTML - if ( typeof value === "string" && !rnoInnerhtml.test( value ) && - ( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) && - ( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && - !wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) { - - value = value.replace( rxhtmlTag, "<$1></$2>" ); - - try { - for (; i < l; i++ ) { - // Remove element nodes and prevent memory leaks - elem = this[i] || {}; - if ( elem.nodeType === 1 ) { - jQuery.cleanData( getAll( elem, false ) ); - elem.innerHTML = value; - } - } - - elem = 0; - - // If using innerHTML throws an exception, use the fallback method - } catch(e) {} - } - - if ( elem ) { - this.empty().append( value ); - } - }, null, value, arguments.length ); - }, - - replaceWith: function( value ) { - var isFunc = jQuery.isFunction( value ); - - // Make sure that the elements are removed from the DOM before they are inserted - // this can help fix replacing a parent with child elements - if ( !isFunc && typeof value !== "string" ) { - value = jQuery( value ).not( this ).detach(); - } - - return this.domManip( [ value ], true, function( elem ) { - var next = this.nextSibling, - parent = this.parentNode; - - if ( parent ) { - jQuery( this ).remove(); - parent.insertBefore( elem, next ); - } - }); - }, - - detach: function( selector ) { - return this.remove( selector, true ); - }, - - domManip: function( args, table, callback ) { - - // Flatten any nested arrays - args = core_concat.apply( [], args ); - - var first, node, hasScripts, - scripts, doc, fragment, - i = 0, - l = this.length, - set = this, - iNoClone = l - 1, - value = args[0], - isFunction = jQuery.isFunction( value ); - - // We can't cloneNode fragments that contain checked, in WebKit - if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) { - return this.each(function( index ) { - var self = set.eq( index ); - if ( isFunction ) { - args[0] = value.call( this, index, table ? self.html() : undefined ); - } - self.domManip( args, table, callback ); - }); - } - - if ( l ) { - fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); - first = fragment.firstChild; - - if ( fragment.childNodes.length === 1 ) { - fragment = first; - } - - if ( first ) { - table = table && jQuery.nodeName( first, "tr" ); - scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); - hasScripts = scripts.length; - - // Use the original fragment for the last item instead of the first because it can end up - // being emptied incorrectly in certain situations (#8070). - for ( ; i < l; i++ ) { - node = fragment; - - if ( i !== iNoClone ) { - node = jQuery.clone( node, true, true ); - - // Keep references to cloned scripts for later restoration - if ( hasScripts ) { - jQuery.merge( scripts, getAll( node, "script" ) ); - } - } - - callback.call( - table && jQuery.nodeName( this[i], "table" ) ? - findOrAppend( this[i], "tbody" ) : - this[i], - node, - i - ); - } - - if ( hasScripts ) { - doc = scripts[ scripts.length - 1 ].ownerDocument; - - // Reenable scripts - jQuery.map( scripts, restoreScript ); - - // Evaluate executable scripts on first document insertion - for ( i = 0; i < hasScripts; i++ ) { - node = scripts[ i ]; - if ( rscriptType.test( node.type || "" ) && - !jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) { - - if ( node.src ) { - // Hope ajax is available... - jQuery.ajax({ - url: node.src, - type: "GET", - dataType: "script", - async: false, - global: false, - "throws": true - }); - } else { - jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) ); - } - } - } - } - - // Fix #11809: Avoid leaking memory - fragment = first = null; - } - } - - return this; - } -}); - -function findOrAppend( elem, tag ) { - return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) ); -} - -// Replace/restore the type attribute of script elements for safe DOM manipulation -function disableScript( elem ) { - var attr = elem.getAttributeNode("type"); - elem.type = ( attr && attr.specified ) + "/" + elem.type; - return elem; -} -function restoreScript( elem ) { - var match = rscriptTypeMasked.exec( elem.type ); - if ( match ) { - elem.type = match[1]; - } else { - elem.removeAttribute("type"); - } - return elem; -} - -// Mark scripts as having already been evaluated -function setGlobalEval( elems, refElements ) { - var elem, - i = 0; - for ( ; (elem = elems[i]) != null; i++ ) { - jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) ); - } -} - -function cloneCopyEvent( src, dest ) { - - if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { - return; - } - - var type, i, l, - oldData = jQuery._data( src ), - curData = jQuery._data( dest, oldData ), - events = oldData.events; - - if ( events ) { - delete curData.handle; - curData.events = {}; - - for ( type in events ) { - for ( i = 0, l = events[ type ].length; i < l; i++ ) { - jQuery.event.add( dest, type, events[ type ][ i ] ); - } - } - } - - // make the cloned public data object a copy from the original - if ( curData.data ) { - curData.data = jQuery.extend( {}, curData.data ); - } -} - -function fixCloneNodeIssues( src, dest ) { - var nodeName, e, data; - - // We do not need to do anything for non-Elements - if ( dest.nodeType !== 1 ) { - return; - } - - nodeName = dest.nodeName.toLowerCase(); - - // IE6-8 copies events bound via attachEvent when using cloneNode. - if ( !jQuery.support.noCloneEvent && dest[ jQuery.expando ] ) { - data = jQuery._data( dest ); - - for ( e in data.events ) { - jQuery.removeEvent( dest, e, data.handle ); - } - - // Event data gets referenced instead of copied if the expando gets copied too - dest.removeAttribute( jQuery.expando ); - } - - // IE blanks contents when cloning scripts, and tries to evaluate newly-set text - if ( nodeName === "script" && dest.text !== src.text ) { - disableScript( dest ).text = src.text; - restoreScript( dest ); - - // IE6-10 improperly clones children of object elements using classid. - // IE10 throws NoModificationAllowedError if parent is null, #12132. - } else if ( nodeName === "object" ) { - if ( dest.parentNode ) { - dest.outerHTML = src.outerHTML; - } - - // This path appears unavoidable for IE9. When cloning an object - // element in IE9, the outerHTML strategy above is not sufficient. - // If the src has innerHTML and the destination does not, - // copy the src.innerHTML into the dest.innerHTML. #10324 - if ( jQuery.support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { - dest.innerHTML = src.innerHTML; - } - - } else if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) { - // IE6-8 fails to persist the checked state of a cloned checkbox - // or radio button. Worse, IE6-7 fail to give the cloned element - // a checked appearance if the defaultChecked value isn't also set - - dest.defaultChecked = dest.checked = src.checked; - - // IE6-7 get confused and end up setting the value of a cloned - // checkbox/radio button to an empty string instead of "on" - if ( dest.value !== src.value ) { - dest.value = src.value; - } - - // IE6-8 fails to return the selected option to the default selected - // state when cloning options - } else if ( nodeName === "option" ) { - dest.defaultSelected = dest.selected = src.defaultSelected; - - // IE6-8 fails to set the defaultValue to the correct value when - // cloning other types of input fields - } else if ( nodeName === "input" || nodeName === "textarea" ) { - dest.defaultValue = src.defaultValue; - } -} - -jQuery.each({ - appendTo: "append", - prependTo: "prepend", - insertBefore: "before", - insertAfter: "after", - replaceAll: "replaceWith" -}, function( name, original ) { - jQuery.fn[ name ] = function( selector ) { - var elems, - i = 0, - ret = [], - insert = jQuery( selector ), - last = insert.length - 1; - - for ( ; i <= last; i++ ) { - elems = i === last ? this : this.clone(true); - jQuery( insert[i] )[ original ]( elems ); - - // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() - core_push.apply( ret, elems.get() ); - } - - return this.pushStack( ret ); - }; -}); - -function getAll( context, tag ) { - var elems, elem, - i = 0, - found = typeof context.getElementsByTagName !== core_strundefined ? context.getElementsByTagName( tag || "*" ) : - typeof context.querySelectorAll !== core_strundefined ? context.querySelectorAll( tag || "*" ) : - undefined; - - if ( !found ) { - for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) { - if ( !tag || jQuery.nodeName( elem, tag ) ) { - found.push( elem ); - } else { - jQuery.merge( found, getAll( elem, tag ) ); - } - } - } - - return tag === undefined || tag && jQuery.nodeName( context, tag ) ? - jQuery.merge( [ context ], found ) : - found; -} - -// Used in buildFragment, fixes the defaultChecked property -function fixDefaultChecked( elem ) { - if ( manipulation_rcheckableType.test( elem.type ) ) { - elem.defaultChecked = elem.checked; - } -} - -jQuery.extend({ - clone: function( elem, dataAndEvents, deepDataAndEvents ) { - var destElements, node, clone, i, srcElements, - inPage = jQuery.contains( elem.ownerDocument, elem ); - - if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { - clone = elem.cloneNode( true ); - - // IE<=8 does not properly clone detached, unknown element nodes - } else { - fragmentDiv.innerHTML = elem.outerHTML; - fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); - } - - if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && - (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { - - // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 - destElements = getAll( clone ); - srcElements = getAll( elem ); - - // Fix all IE cloning issues - for ( i = 0; (node = srcElements[i]) != null; ++i ) { - // Ensure that the destination node is not null; Fixes #9587 - if ( destElements[i] ) { - fixCloneNodeIssues( node, destElements[i] ); - } - } - } - - // Copy the events from the original to the clone - if ( dataAndEvents ) { - if ( deepDataAndEvents ) { - srcElements = srcElements || getAll( elem ); - destElements = destElements || getAll( clone ); - - for ( i = 0; (node = srcElements[i]) != null; i++ ) { - cloneCopyEvent( node, destElements[i] ); - } - } else { - cloneCopyEvent( elem, clone ); - } - } - - // Preserve script evaluation history - destElements = getAll( clone, "script" ); - if ( destElements.length > 0 ) { - setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); - } - - destElements = srcElements = node = null; - - // Return the cloned set - return clone; - }, - - buildFragment: function( elems, context, scripts, selection ) { - var j, elem, contains, - tmp, tag, tbody, wrap, - l = elems.length, - - // Ensure a safe fragment - safe = createSafeFragment( context ), - - nodes = [], - i = 0; - - for ( ; i < l; i++ ) { - elem = elems[ i ]; - - if ( elem || elem === 0 ) { - - // Add nodes directly - if ( jQuery.type( elem ) === "object" ) { - jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); - - // Convert non-html into a text node - } else if ( !rhtml.test( elem ) ) { - nodes.push( context.createTextNode( elem ) ); - - // Convert html into DOM nodes - } else { - tmp = tmp || safe.appendChild( context.createElement("div") ); - - // Deserialize a standard representation - tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(); - wrap = wrapMap[ tag ] || wrapMap._default; - - tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2]; - - // Descend through wrappers to the right content - j = wrap[0]; - while ( j-- ) { - tmp = tmp.lastChild; - } - - // Manually add leading whitespace removed by IE - if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { - nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); - } - - // Remove IE's autoinserted <tbody> from table fragments - if ( !jQuery.support.tbody ) { - - // String was a <table>, *may* have spurious <tbody> - elem = tag === "table" && !rtbody.test( elem ) ? - tmp.firstChild : - - // String was a bare <thead> or <tfoot> - wrap[1] === "<table>" && !rtbody.test( elem ) ? - tmp : - 0; - - j = elem && elem.childNodes.length; - while ( j-- ) { - if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) { - elem.removeChild( tbody ); - } - } - } - - jQuery.merge( nodes, tmp.childNodes ); - - // Fix #12392 for WebKit and IE > 9 - tmp.textContent = ""; - - // Fix #12392 for oldIE - while ( tmp.firstChild ) { - tmp.removeChild( tmp.firstChild ); - } - - // Remember the top-level container for proper cleanup - tmp = safe.lastChild; - } - } - } - - // Fix #11356: Clear elements from fragment - if ( tmp ) { - safe.removeChild( tmp ); - } - - // Reset defaultChecked for any radios and checkboxes - // about to be appended to the DOM in IE 6/7 (#8060) - if ( !jQuery.support.appendChecked ) { - jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked ); - } - - i = 0; - while ( (elem = nodes[ i++ ]) ) { - - // #4087 - If origin and destination elements are the same, and this is - // that element, do not do anything - if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { - continue; - } - - contains = jQuery.contains( elem.ownerDocument, elem ); - - // Append to fragment - tmp = getAll( safe.appendChild( elem ), "script" ); - - // Preserve script evaluation history - if ( contains ) { - setGlobalEval( tmp ); - } - - // Capture executables - if ( scripts ) { - j = 0; - while ( (elem = tmp[ j++ ]) ) { - if ( rscriptType.test( elem.type || "" ) ) { - scripts.push( elem ); - } - } - } - } - - tmp = null; - - return safe; - }, - - cleanData: function( elems, /* internal */ acceptData ) { - var elem, type, id, data, - i = 0, - internalKey = jQuery.expando, - cache = jQuery.cache, - deleteExpando = jQuery.support.deleteExpando, - special = jQuery.event.special; - - for ( ; (elem = elems[i]) != null; i++ ) { - - if ( acceptData || jQuery.acceptData( elem ) ) { - - id = elem[ internalKey ]; - data = id && cache[ id ]; - - if ( data ) { - if ( data.events ) { - for ( type in data.events ) { - if ( special[ type ] ) { - jQuery.event.remove( elem, type ); - - // This is a shortcut to avoid jQuery.event.remove's overhead - } else { - jQuery.removeEvent( elem, type, data.handle ); - } - } - } - - // Remove cache only if it was not already removed by jQuery.event.remove - if ( cache[ id ] ) { - - delete cache[ id ]; - - // IE does not allow us to delete expando properties from nodes, - // nor does it have a removeAttribute function on Document nodes; - // we must handle all of these cases - if ( deleteExpando ) { - delete elem[ internalKey ]; - - } else if ( typeof elem.removeAttribute !== core_strundefined ) { - elem.removeAttribute( internalKey ); - - } else { - elem[ internalKey ] = null; - } - - core_deletedIds.push( id ); - } - } - } - } - } -}); -var iframe, getStyles, curCSS, - ralpha = /alpha\([^)]*\)/i, - ropacity = /opacity\s*=\s*([^)]*)/, - rposition = /^(top|right|bottom|left)$/, - // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" - // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display - rdisplayswap = /^(none|table(?!-c[ea]).+)/, - rmargin = /^margin/, - rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), - rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), - rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ), - elemdisplay = { BODY: "block" }, - - cssShow = { position: "absolute", visibility: "hidden", display: "block" }, - cssNormalTransform = { - letterSpacing: 0, - fontWeight: 400 - }, - - cssExpand = [ "Top", "Right", "Bottom", "Left" ], - cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; - -// return a css property mapped to a potentially vendor prefixed property -function vendorPropName( style, name ) { - - // shortcut for names that are not vendor prefixed - if ( name in style ) { - return name; - } - - // check for vendor prefixed names - var capName = name.charAt(0).toUpperCase() + name.slice(1), - origName = name, - i = cssPrefixes.length; - - while ( i-- ) { - name = cssPrefixes[ i ] + capName; - if ( name in style ) { - return name; - } - } - - return origName; -} - -function isHidden( elem, el ) { - // isHidden might be called from jQuery#filter function; - // in that case, element will be second argument - elem = el || elem; - return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); -} - -function showHide( elements, show ) { - var display, elem, hidden, - values = [], - index = 0, - length = elements.length; - - for ( ; index < length; index++ ) { - elem = elements[ index ]; - if ( !elem.style ) { - continue; - } - - values[ index ] = jQuery._data( elem, "olddisplay" ); - display = elem.style.display; - if ( show ) { - // Reset the inline display of this element to learn if it is - // being hidden by cascaded rules or not - if ( !values[ index ] && display === "none" ) { - elem.style.display = ""; - } - - // Set elements which have been overridden with display: none - // in a stylesheet to whatever the default browser style is - // for such an element - if ( elem.style.display === "" && isHidden( elem ) ) { - values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) ); - } - } else { - - if ( !values[ index ] ) { - hidden = isHidden( elem ); - - if ( display && display !== "none" || !hidden ) { - jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) ); - } - } - } - } - - // Set the display of most of the elements in a second loop - // to avoid the constant reflow - for ( index = 0; index < length; index++ ) { - elem = elements[ index ]; - if ( !elem.style ) { - continue; - } - if ( !show || elem.style.display === "none" || elem.style.display === "" ) { - elem.style.display = show ? values[ index ] || "" : "none"; - } - } - - return elements; -} - -jQuery.fn.extend({ - css: function( name, value ) { - return jQuery.access( this, function( elem, name, value ) { - var len, styles, - map = {}, - i = 0; - - if ( jQuery.isArray( name ) ) { - styles = getStyles( elem ); - len = name.length; - - for ( ; i < len; i++ ) { - map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); - } - - return map; - } - - return value !== undefined ? - jQuery.style( elem, name, value ) : - jQuery.css( elem, name ); - }, name, value, arguments.length > 1 ); - }, - show: function() { - return showHide( this, true ); - }, - hide: function() { - return showHide( this ); - }, - toggle: function( state ) { - var bool = typeof state === "boolean"; - - return this.each(function() { - if ( bool ? state : isHidden( this ) ) { - jQuery( this ).show(); - } else { - jQuery( this ).hide(); - } - }); - } -}); - -jQuery.extend({ - // Add in style property hooks for overriding the default - // behavior of getting and setting a style property - cssHooks: { - opacity: { - get: function( elem, computed ) { - if ( computed ) { - // We should always get a number back from opacity - var ret = curCSS( elem, "opacity" ); - return ret === "" ? "1" : ret; - } - } - } - }, - - // Exclude the following css properties to add px - cssNumber: { - "columnCount": true, - "fillOpacity": true, - "fontWeight": true, - "lineHeight": true, - "opacity": true, - "orphans": true, - "widows": true, - "zIndex": true, - "zoom": true - }, - - // Add in properties whose names you wish to fix before - // setting or getting the value - cssProps: { - // normalize float css property - "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" - }, - - // Get and set the style property on a DOM Node - style: function( elem, name, value, extra ) { - // Don't set styles on text and comment nodes - if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { - return; - } - - // Make sure that we're working with the right name - var ret, type, hooks, - origName = jQuery.camelCase( name ), - style = elem.style; - - name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); - - // gets hook for the prefixed version - // followed by the unprefixed version - hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; - - // Check if we're setting a value - if ( value !== undefined ) { - type = typeof value; - - // convert relative number strings (+= or -=) to relative numbers. #7345 - if ( type === "string" && (ret = rrelNum.exec( value )) ) { - value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); - // Fixes bug #9237 - type = "number"; - } - - // Make sure that NaN and null values aren't set. See: #7116 - if ( value == null || type === "number" && isNaN( value ) ) { - return; - } - - // If a number was passed in, add 'px' to the (except for certain CSS properties) - if ( type === "number" && !jQuery.cssNumber[ origName ] ) { - value += "px"; - } - - // Fixes #8908, it can be done more correctly by specifing setters in cssHooks, - // but it would mean to define eight (for every problematic property) identical functions - if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) { - style[ name ] = "inherit"; - } - - // If a hook was provided, use that value, otherwise just set the specified value - if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { - - // Wrapped to prevent IE from throwing errors when 'invalid' values are provided - // Fixes bug #5509 - try { - style[ name ] = value; - } catch(e) {} - } - - } else { - // If a hook was provided get the non-computed value from there - if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { - return ret; - } - - // Otherwise just get the value from the style object - return style[ name ]; - } - }, - - css: function( elem, name, extra, styles ) { - var num, val, hooks, - origName = jQuery.camelCase( name ); - - // Make sure that we're working with the right name - name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); - - // gets hook for the prefixed version - // followed by the unprefixed version - hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; - - // If a hook was provided get the computed value from there - if ( hooks && "get" in hooks ) { - val = hooks.get( elem, true, extra ); - } - - // Otherwise, if a way to get the computed value exists, use that - if ( val === undefined ) { - val = curCSS( elem, name, styles ); - } - - //convert "normal" to computed value - if ( val === "normal" && name in cssNormalTransform ) { - val = cssNormalTransform[ name ]; - } - - // Return, converting to number if forced or a qualifier was provided and val looks numeric - if ( extra === "" || extra ) { - num = parseFloat( val ); - return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; - } - return val; - }, - - // A method for quickly swapping in/out CSS properties to get correct calculations - swap: function( elem, options, callback, args ) { - var ret, name, - old = {}; - - // Remember the old values, and insert the new ones - for ( name in options ) { - old[ name ] = elem.style[ name ]; - elem.style[ name ] = options[ name ]; - } - - ret = callback.apply( elem, args || [] ); - - // Revert the old values - for ( name in options ) { - elem.style[ name ] = old[ name ]; - } - - return ret; - } -}); - -// NOTE: we've included the "window" in window.getComputedStyle -// because jsdom on node.js will break without it. -if ( window.getComputedStyle ) { - getStyles = function( elem ) { - return window.getComputedStyle( elem, null ); - }; - - curCSS = function( elem, name, _computed ) { - var width, minWidth, maxWidth, - computed = _computed || getStyles( elem ), - - // getPropertyValue is only needed for .css('filter') in IE9, see #12537 - ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined, - style = elem.style; - - if ( computed ) { - - if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { - ret = jQuery.style( elem, name ); - } - - // A tribute to the "awesome hack by Dean Edwards" - // Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right - // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels - // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values - if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { - - // Remember the original values - width = style.width; - minWidth = style.minWidth; - maxWidth = style.maxWidth; - - // Put in the new values to get a computed value out - style.minWidth = style.maxWidth = style.width = ret; - ret = computed.width; - - // Revert the changed values - style.width = width; - style.minWidth = minWidth; - style.maxWidth = maxWidth; - } - } - - return ret; - }; -} else if ( document.documentElement.currentStyle ) { - getStyles = function( elem ) { - return elem.currentStyle; - }; - - curCSS = function( elem, name, _computed ) { - var left, rs, rsLeft, - computed = _computed || getStyles( elem ), - ret = computed ? computed[ name ] : undefined, - style = elem.style; - - // Avoid setting ret to empty string here - // so we don't default to auto - if ( ret == null && style && style[ name ] ) { - ret = style[ name ]; - } - - // From the awesome hack by Dean Edwards - // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 - - // If we're not dealing with a regular pixel number - // but a number that has a weird ending, we need to convert it to pixels - // but not position css attributes, as those are proportional to the parent element instead - // and we can't measure the parent instead because it might trigger a "stacking dolls" problem - if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) { - - // Remember the original values - left = style.left; - rs = elem.runtimeStyle; - rsLeft = rs && rs.left; - - // Put in the new values to get a computed value out - if ( rsLeft ) { - rs.left = elem.currentStyle.left; - } - style.left = name === "fontSize" ? "1em" : ret; - ret = style.pixelLeft + "px"; - - // Revert the changed values - style.left = left; - if ( rsLeft ) { - rs.left = rsLeft; - } - } - - return ret === "" ? "auto" : ret; - }; -} - -function setPositiveNumber( elem, value, subtract ) { - var matches = rnumsplit.exec( value ); - return matches ? - // Guard against undefined "subtract", e.g., when used as in cssHooks - Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : - value; -} - -function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { - var i = extra === ( isBorderBox ? "border" : "content" ) ? - // If we already have the right measurement, avoid augmentation - 4 : - // Otherwise initialize for horizontal or vertical properties - name === "width" ? 1 : 0, - - val = 0; - - for ( ; i < 4; i += 2 ) { - // both box models exclude margin, so add it if we want it - if ( extra === "margin" ) { - val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); - } - - if ( isBorderBox ) { - // border-box includes padding, so remove it if we want content - if ( extra === "content" ) { - val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); - } - - // at this point, extra isn't border nor margin, so remove border - if ( extra !== "margin" ) { - val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); - } - } else { - // at this point, extra isn't content, so add padding - val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); - - // at this point, extra isn't content nor padding, so add border - if ( extra !== "padding" ) { - val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); - } - } - } - - return val; -} - -function getWidthOrHeight( elem, name, extra ) { - - // Start with offset property, which is equivalent to the border-box value - var valueIsBorderBox = true, - val = name === "width" ? elem.offsetWidth : elem.offsetHeight, - styles = getStyles( elem ), - isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; - - // some non-html elements return undefined for offsetWidth, so check for null/undefined - // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 - // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 - if ( val <= 0 || val == null ) { - // Fall back to computed then uncomputed css if necessary - val = curCSS( elem, name, styles ); - if ( val < 0 || val == null ) { - val = elem.style[ name ]; - } - - // Computed unit is not pixels. Stop here and return. - if ( rnumnonpx.test(val) ) { - return val; - } - - // we need the check for style in case a browser which returns unreliable values - // for getComputedStyle silently falls back to the reliable elem.style - valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] ); - - // Normalize "", auto, and prepare for extra - val = parseFloat( val ) || 0; - } - - // use the active box-sizing model to add/subtract irrelevant styles - return ( val + - augmentWidthOrHeight( - elem, - name, - extra || ( isBorderBox ? "border" : "content" ), - valueIsBorderBox, - styles - ) - ) + "px"; -} - -// Try to determine the default display value of an element -function css_defaultDisplay( nodeName ) { - var doc = document, - display = elemdisplay[ nodeName ]; - - if ( !display ) { - display = actualDisplay( nodeName, doc ); - - // If the simple way fails, read from inside an iframe - if ( display === "none" || !display ) { - // Use the already-created iframe if possible - iframe = ( iframe || - jQuery("<iframe frameborder='0' width='0' height='0'/>") - .css( "cssText", "display:block !important" ) - ).appendTo( doc.documentElement ); - - // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse - doc = ( iframe[0].contentWindow || iframe[0].contentDocument ).document; - doc.write("<!doctype html><html><body>"); - doc.close(); - - display = actualDisplay( nodeName, doc ); - iframe.detach(); - } - - // Store the correct default display - elemdisplay[ nodeName ] = display; - } - - return display; -} - -// Called ONLY from within css_defaultDisplay -function actualDisplay( name, doc ) { - var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), - display = jQuery.css( elem[0], "display" ); - elem.remove(); - return display; -} - -jQuery.each([ "height", "width" ], function( i, name ) { - jQuery.cssHooks[ name ] = { - get: function( elem, computed, extra ) { - if ( computed ) { - // certain elements can have dimension info if we invisibly show them - // however, it must have a current display style that would benefit from this - return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ? - jQuery.swap( elem, cssShow, function() { - return getWidthOrHeight( elem, name, extra ); - }) : - getWidthOrHeight( elem, name, extra ); - } - }, - - set: function( elem, value, extra ) { - var styles = extra && getStyles( elem ); - return setPositiveNumber( elem, value, extra ? - augmentWidthOrHeight( - elem, - name, - extra, - jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box", - styles - ) : 0 - ); - } - }; -}); - -if ( !jQuery.support.opacity ) { - jQuery.cssHooks.opacity = { - get: function( elem, computed ) { - // IE uses filters for opacity - return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? - ( 0.01 * parseFloat( RegExp.$1 ) ) + "" : - computed ? "1" : ""; - }, - - set: function( elem, value ) { - var style = elem.style, - currentStyle = elem.currentStyle, - opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "", - filter = currentStyle && currentStyle.filter || style.filter || ""; - - // IE has trouble with opacity if it does not have layout - // Force it by setting the zoom level - style.zoom = 1; - - // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 - // if value === "", then remove inline opacity #12685 - if ( ( value >= 1 || value === "" ) && - jQuery.trim( filter.replace( ralpha, "" ) ) === "" && - style.removeAttribute ) { - - // Setting style.filter to null, "" & " " still leave "filter:" in the cssText - // if "filter:" is present at all, clearType is disabled, we want to avoid this - // style.removeAttribute is IE Only, but so apparently is this code path... - style.removeAttribute( "filter" ); - - // if there is no filter style applied in a css rule or unset inline opacity, we are done - if ( value === "" || currentStyle && !currentStyle.filter ) { - return; - } - } - - // otherwise, set new filter values - style.filter = ralpha.test( filter ) ? - filter.replace( ralpha, opacity ) : - filter + " " + opacity; - } - }; -} - -// These hooks cannot be added until DOM ready because the support test -// for it is not run until after DOM ready -jQuery(function() { - if ( !jQuery.support.reliableMarginRight ) { - jQuery.cssHooks.marginRight = { - get: function( elem, computed ) { - if ( computed ) { - // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right - // Work around by temporarily setting element display to inline-block - return jQuery.swap( elem, { "display": "inline-block" }, - curCSS, [ elem, "marginRight" ] ); - } - } - }; - } - - // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 - // getComputedStyle returns percent when specified for top/left/bottom/right - // rather than make the css module depend on the offset module, we just check for it here - if ( !jQuery.support.pixelPosition && jQuery.fn.position ) { - jQuery.each( [ "top", "left" ], function( i, prop ) { - jQuery.cssHooks[ prop ] = { - get: function( elem, computed ) { - if ( computed ) { - computed = curCSS( elem, prop ); - // if curCSS returns percentage, fallback to offset - return rnumnonpx.test( computed ) ? - jQuery( elem ).position()[ prop ] + "px" : - computed; - } - } - }; - }); - } - -}); - -if ( jQuery.expr && jQuery.expr.filters ) { - jQuery.expr.filters.hidden = function( elem ) { - // Support: Opera <= 12.12 - // Opera reports offsetWidths and offsetHeights less than zero on some elements - return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 || - (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none"); - }; - - jQuery.expr.filters.visible = function( elem ) { - return !jQuery.expr.filters.hidden( elem ); - }; -} - -// These hooks are used by animate to expand properties -jQuery.each({ - margin: "", - padding: "", - border: "Width" -}, function( prefix, suffix ) { - jQuery.cssHooks[ prefix + suffix ] = { - expand: function( value ) { - var i = 0, - expanded = {}, - - // assumes a single number if not a string - parts = typeof value === "string" ? value.split(" ") : [ value ]; - - for ( ; i < 4; i++ ) { - expanded[ prefix + cssExpand[ i ] + suffix ] = - parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; - } - - return expanded; - } - }; - - if ( !rmargin.test( prefix ) ) { - jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; - } -}); -var r20 = /%20/g, - rbracket = /\[\]$/, - rCRLF = /\r?\n/g, - rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, - rsubmittable = /^(?:input|select|textarea|keygen)/i; - -jQuery.fn.extend({ - serialize: function() { - return jQuery.param( this.serializeArray() ); - }, - serializeArray: function() { - return this.map(function(){ - // Can add propHook for "elements" to filter or add form elements - var elements = jQuery.prop( this, "elements" ); - return elements ? jQuery.makeArray( elements ) : this; - }) - .filter(function(){ - var type = this.type; - // Use .is(":disabled") so that fieldset[disabled] works - return this.name && !jQuery( this ).is( ":disabled" ) && - rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && - ( this.checked || !manipulation_rcheckableType.test( type ) ); - }) - .map(function( i, elem ){ - var val = jQuery( this ).val(); - - return val == null ? - null : - jQuery.isArray( val ) ? - jQuery.map( val, function( val ){ - return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; - }) : - { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; - }).get(); - } -}); - -//Serialize an array of form elements or a set of -//key/values into a query string -jQuery.param = function( a, traditional ) { - var prefix, - s = [], - add = function( key, value ) { - // If value is a function, invoke it and return its value - value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); - s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); - }; - - // Set traditional to true for jQuery <= 1.3.2 behavior. - if ( traditional === undefined ) { - traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; - } - - // If an array was passed in, assume that it is an array of form elements. - if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { - // Serialize the form elements - jQuery.each( a, function() { - add( this.name, this.value ); - }); - - } else { - // If traditional, encode the "old" way (the way 1.3.2 or older - // did it), otherwise encode params recursively. - for ( prefix in a ) { - buildParams( prefix, a[ prefix ], traditional, add ); - } - } - - // Return the resulting serialization - return s.join( "&" ).replace( r20, "+" ); -}; - -function buildParams( prefix, obj, traditional, add ) { - var name; - - if ( jQuery.isArray( obj ) ) { - // Serialize array item. - jQuery.each( obj, function( i, v ) { - if ( traditional || rbracket.test( prefix ) ) { - // Treat each array item as a scalar. - add( prefix, v ); - - } else { - // Item is non-scalar (array or object), encode its numeric index. - buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); - } - }); - - } else if ( !traditional && jQuery.type( obj ) === "object" ) { - // Serialize object item. - for ( name in obj ) { - buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); - } - - } else { - // Serialize scalar item. - add( prefix, obj ); - } -} -jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + - "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + - "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { - - // Handle event binding - jQuery.fn[ name ] = function( data, fn ) { - return arguments.length > 0 ? - this.on( name, null, data, fn ) : - this.trigger( name ); - }; -}); - -jQuery.fn.hover = function( fnOver, fnOut ) { - return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); -}; -var - // Document location - ajaxLocParts, - ajaxLocation, - ajax_nonce = jQuery.now(), - - ajax_rquery = /\?/, - rhash = /#.*$/, - rts = /([?&])_=[^&]*/, - rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL - // #7653, #8125, #8152: local protocol detection - rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, - rnoContent = /^(?:GET|HEAD)$/, - rprotocol = /^\/\//, - rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, - - // Keep a copy of the old load method - _load = jQuery.fn.load, - - /* Prefilters - * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) - * 2) These are called: - * - BEFORE asking for a transport - * - AFTER param serialization (s.data is a string if s.processData is true) - * 3) key is the dataType - * 4) the catchall symbol "*" can be used - * 5) execution will start with transport dataType and THEN continue down to "*" if needed - */ - prefilters = {}, - - /* Transports bindings - * 1) key is the dataType - * 2) the catchall symbol "*" can be used - * 3) selection will start with transport dataType and THEN go to "*" if needed - */ - transports = {}, - - // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression - allTypes = "*/".concat("*"); - -// #8138, IE may throw an exception when accessing -// a field from window.location if document.domain has been set -try { - ajaxLocation = location.href; -} catch( e ) { - // Use the href attribute of an A element - // since IE will modify it given document.location - ajaxLocation = document.createElement( "a" ); - ajaxLocation.href = ""; - ajaxLocation = ajaxLocation.href; -} - -// Segment location into parts -ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; - -// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport -function addToPrefiltersOrTransports( structure ) { - - // dataTypeExpression is optional and defaults to "*" - return function( dataTypeExpression, func ) { - - if ( typeof dataTypeExpression !== "string" ) { - func = dataTypeExpression; - dataTypeExpression = "*"; - } - - var dataType, - i = 0, - dataTypes = dataTypeExpression.toLowerCase().match( core_rnotwhite ) || []; - - if ( jQuery.isFunction( func ) ) { - // For each dataType in the dataTypeExpression - while ( (dataType = dataTypes[i++]) ) { - // Prepend if requested - if ( dataType[0] === "+" ) { - dataType = dataType.slice( 1 ) || "*"; - (structure[ dataType ] = structure[ dataType ] || []).unshift( func ); - - // Otherwise append - } else { - (structure[ dataType ] = structure[ dataType ] || []).push( func ); - } - } - } - }; -} - -// Base inspection function for prefilters and transports -function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { - - var inspected = {}, - seekingTransport = ( structure === transports ); - - function inspect( dataType ) { - var selected; - inspected[ dataType ] = true; - jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { - var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); - if( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { - options.dataTypes.unshift( dataTypeOrTransport ); - inspect( dataTypeOrTransport ); - return false; - } else if ( seekingTransport ) { - return !( selected = dataTypeOrTransport ); - } - }); - return selected; - } - - return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); -} - -// A special extend for ajax options -// that takes "flat" options (not to be deep extended) -// Fixes #9887 -function ajaxExtend( target, src ) { - var deep, key, - flatOptions = jQuery.ajaxSettings.flatOptions || {}; - - for ( key in src ) { - if ( src[ key ] !== undefined ) { - ( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ]; - } - } - if ( deep ) { - jQuery.extend( true, target, deep ); - } - - return target; -} - -jQuery.fn.load = function( url, params, callback ) { - if ( typeof url !== "string" && _load ) { - return _load.apply( this, arguments ); - } - - var selector, response, type, - self = this, - off = url.indexOf(" "); - - if ( off >= 0 ) { - selector = url.slice( off, url.length ); - url = url.slice( 0, off ); - } - - // If it's a function - if ( jQuery.isFunction( params ) ) { - - // We assume that it's the callback - callback = params; - params = undefined; - - // Otherwise, build a param string - } else if ( params && typeof params === "object" ) { - type = "POST"; - } - - // If we have elements to modify, make the request - if ( self.length > 0 ) { - jQuery.ajax({ - url: url, - - // if "type" variable is undefined, then "GET" method will be used - type: type, - dataType: "html", - data: params - }).done(function( responseText ) { - - // Save response for use in complete callback - response = arguments; - - self.html( selector ? - - // If a selector was specified, locate the right elements in a dummy div - // Exclude scripts to avoid IE 'Permission Denied' errors - jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) : - - // Otherwise use the full result - responseText ); - - }).complete( callback && function( jqXHR, status ) { - self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); - }); - } - - return this; -}; - -// Attach a bunch of functions for handling common AJAX events -jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ){ - jQuery.fn[ type ] = function( fn ){ - return this.on( type, fn ); - }; -}); - -jQuery.each( [ "get", "post" ], function( i, method ) { - jQuery[ method ] = function( url, data, callback, type ) { - // shift arguments if data argument was omitted - if ( jQuery.isFunction( data ) ) { - type = type || callback; - callback = data; - data = undefined; - } - - return jQuery.ajax({ - url: url, - type: method, - dataType: type, - data: data, - success: callback - }); - }; -}); - -jQuery.extend({ - - // Counter for holding the number of active queries - active: 0, - - // Last-Modified header cache for next request - lastModified: {}, - etag: {}, - - ajaxSettings: { - url: ajaxLocation, - type: "GET", - isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), - global: true, - processData: true, - async: true, - contentType: "application/x-www-form-urlencoded; charset=UTF-8", - /* - timeout: 0, - data: null, - dataType: null, - username: null, - password: null, - cache: null, - throws: false, - traditional: false, - headers: {}, - */ - - accepts: { - "*": allTypes, - text: "text/plain", - html: "text/html", - xml: "application/xml, text/xml", - json: "application/json, text/javascript" - }, - - contents: { - xml: /xml/, - html: /html/, - json: /json/ - }, - - responseFields: { - xml: "responseXML", - text: "responseText" - }, - - // Data converters - // Keys separate source (or catchall "*") and destination types with a single space - converters: { - - // Convert anything to text - "* text": window.String, - - // Text to html (true = no transformation) - "text html": true, - - // Evaluate text as a json expression - "text json": jQuery.parseJSON, - - // Parse text as xml - "text xml": jQuery.parseXML - }, - - // For options that shouldn't be deep extended: - // you can add your own custom options here if - // and when you create one that shouldn't be - // deep extended (see ajaxExtend) - flatOptions: { - url: true, - context: true - } - }, - - // Creates a full fledged settings object into target - // with both ajaxSettings and settings fields. - // If target is omitted, writes into ajaxSettings. - ajaxSetup: function( target, settings ) { - return settings ? - - // Building a settings object - ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : - - // Extending ajaxSettings - ajaxExtend( jQuery.ajaxSettings, target ); - }, - - ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), - ajaxTransport: addToPrefiltersOrTransports( transports ), - - // Main method - ajax: function( url, options ) { - - // If url is an object, simulate pre-1.5 signature - if ( typeof url === "object" ) { - options = url; - url = undefined; - } - - // Force options to be an object - options = options || {}; - - var // Cross-domain detection vars - parts, - // Loop variable - i, - // URL without anti-cache param - cacheURL, - // Response headers as string - responseHeadersString, - // timeout handle - timeoutTimer, - - // To know if global events are to be dispatched - fireGlobals, - - transport, - // Response headers - responseHeaders, - // Create the final options object - s = jQuery.ajaxSetup( {}, options ), - // Callbacks context - callbackContext = s.context || s, - // Context for global events is callbackContext if it is a DOM node or jQuery collection - globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? - jQuery( callbackContext ) : - jQuery.event, - // Deferreds - deferred = jQuery.Deferred(), - completeDeferred = jQuery.Callbacks("once memory"), - // Status-dependent callbacks - statusCode = s.statusCode || {}, - // Headers (they are sent all at once) - requestHeaders = {}, - requestHeadersNames = {}, - // The jqXHR state - state = 0, - // Default abort message - strAbort = "canceled", - // Fake xhr - jqXHR = { - readyState: 0, - - // Builds headers hashtable if needed - getResponseHeader: function( key ) { - var match; - if ( state === 2 ) { - if ( !responseHeaders ) { - responseHeaders = {}; - while ( (match = rheaders.exec( responseHeadersString )) ) { - responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; - } - } - match = responseHeaders[ key.toLowerCase() ]; - } - return match == null ? null : match; - }, - - // Raw string - getAllResponseHeaders: function() { - return state === 2 ? responseHeadersString : null; - }, - - // Caches the header - setRequestHeader: function( name, value ) { - var lname = name.toLowerCase(); - if ( !state ) { - name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; - requestHeaders[ name ] = value; - } - return this; - }, - - // Overrides response content-type header - overrideMimeType: function( type ) { - if ( !state ) { - s.mimeType = type; - } - return this; - }, - - // Status-dependent callbacks - statusCode: function( map ) { - var code; - if ( map ) { - if ( state < 2 ) { - for ( code in map ) { - // Lazy-add the new callback in a way that preserves old ones - statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; - } - } else { - // Execute the appropriate callbacks - jqXHR.always( map[ jqXHR.status ] ); - } - } - return this; - }, - - // Cancel the request - abort: function( statusText ) { - var finalText = statusText || strAbort; - if ( transport ) { - transport.abort( finalText ); - } - done( 0, finalText ); - return this; - } - }; - - // Attach deferreds - deferred.promise( jqXHR ).complete = completeDeferred.add; - jqXHR.success = jqXHR.done; - jqXHR.error = jqXHR.fail; - - // Remove hash character (#7531: and string promotion) - // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) - // Handle falsy url in the settings object (#10093: consistency with old signature) - // We also use the url parameter if available - s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); - - // Alias method option to type as per ticket #12004 - s.type = options.method || options.type || s.method || s.type; - - // Extract dataTypes list - s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( core_rnotwhite ) || [""]; - - // A cross-domain request is in order when we have a protocol:host:port mismatch - if ( s.crossDomain == null ) { - parts = rurl.exec( s.url.toLowerCase() ); - s.crossDomain = !!( parts && - ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || - ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) != - ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) ) - ); - } - - // Convert data if not already a string - if ( s.data && s.processData && typeof s.data !== "string" ) { - s.data = jQuery.param( s.data, s.traditional ); - } - - // Apply prefilters - inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); - - // If request was aborted inside a prefilter, stop there - if ( state === 2 ) { - return jqXHR; - } - - // We can fire global events as of now if asked to - fireGlobals = s.global; - - // Watch for a new set of requests - if ( fireGlobals && jQuery.active++ === 0 ) { - jQuery.event.trigger("ajaxStart"); - } - - // Uppercase the type - s.type = s.type.toUpperCase(); - - // Determine if request has content - s.hasContent = !rnoContent.test( s.type ); - - // Save the URL in case we're toying with the If-Modified-Since - // and/or If-None-Match header later on - cacheURL = s.url; - - // More options handling for requests with no content - if ( !s.hasContent ) { - - // If data is available, append data to url - if ( s.data ) { - cacheURL = ( s.url += ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + s.data ); - // #9682: remove data so that it's not used in an eventual retry - delete s.data; - } - - // Add anti-cache in url if needed - if ( s.cache === false ) { - s.url = rts.test( cacheURL ) ? - - // If there is already a '_' parameter, set its value - cacheURL.replace( rts, "$1_=" + ajax_nonce++ ) : - - // Otherwise add one to the end - cacheURL + ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ajax_nonce++; - } - } - - // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. - if ( s.ifModified ) { - if ( jQuery.lastModified[ cacheURL ] ) { - jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); - } - if ( jQuery.etag[ cacheURL ] ) { - jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); - } - } - - // Set the correct header, if data is being sent - if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { - jqXHR.setRequestHeader( "Content-Type", s.contentType ); - } - - // Set the Accepts header for the server, depending on the dataType - jqXHR.setRequestHeader( - "Accept", - s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? - s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : - s.accepts[ "*" ] - ); - - // Check for headers option - for ( i in s.headers ) { - jqXHR.setRequestHeader( i, s.headers[ i ] ); - } - - // Allow custom headers/mimetypes and early abort - if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { - // Abort if not done already and return - return jqXHR.abort(); - } - - // aborting is no longer a cancellation - strAbort = "abort"; - - // Install callbacks on deferreds - for ( i in { success: 1, error: 1, complete: 1 } ) { - jqXHR[ i ]( s[ i ] ); - } - - // Get transport - transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); - - // If no transport, we auto-abort - if ( !transport ) { - done( -1, "No Transport" ); - } else { - jqXHR.readyState = 1; - - // Send global event - if ( fireGlobals ) { - globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); - } - // Timeout - if ( s.async && s.timeout > 0 ) { - timeoutTimer = setTimeout(function() { - jqXHR.abort("timeout"); - }, s.timeout ); - } - - try { - state = 1; - transport.send( requestHeaders, done ); - } catch ( e ) { - // Propagate exception as error if not done - if ( state < 2 ) { - done( -1, e ); - // Simply rethrow otherwise - } else { - throw e; - } - } - } - - // Callback for when everything is done - function done( status, nativeStatusText, responses, headers ) { - var isSuccess, success, error, response, modified, - statusText = nativeStatusText; - - // Called once - if ( state === 2 ) { - return; - } - - // State is "done" now - state = 2; - - // Clear timeout if it exists - if ( timeoutTimer ) { - clearTimeout( timeoutTimer ); - } - - // Dereference transport for early garbage collection - // (no matter how long the jqXHR object will be used) - transport = undefined; - - // Cache response headers - responseHeadersString = headers || ""; - - // Set readyState - jqXHR.readyState = status > 0 ? 4 : 0; - - // Get response data - if ( responses ) { - response = ajaxHandleResponses( s, jqXHR, responses ); - } - - // If successful, handle type chaining - if ( status >= 200 && status < 300 || status === 304 ) { - - // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. - if ( s.ifModified ) { - modified = jqXHR.getResponseHeader("Last-Modified"); - if ( modified ) { - jQuery.lastModified[ cacheURL ] = modified; - } - modified = jqXHR.getResponseHeader("etag"); - if ( modified ) { - jQuery.etag[ cacheURL ] = modified; - } - } - - // if no content - if ( status === 204 ) { - isSuccess = true; - statusText = "nocontent"; - - // if not modified - } else if ( status === 304 ) { - isSuccess = true; - statusText = "notmodified"; - - // If we have data, let's convert it - } else { - isSuccess = ajaxConvert( s, response ); - statusText = isSuccess.state; - success = isSuccess.data; - error = isSuccess.error; - isSuccess = !error; - } - } else { - // We extract error from statusText - // then normalize statusText and status for non-aborts - error = statusText; - if ( status || !statusText ) { - statusText = "error"; - if ( status < 0 ) { - status = 0; - } - } - } - - // Set data for the fake xhr object - jqXHR.status = status; - jqXHR.statusText = ( nativeStatusText || statusText ) + ""; - - // Success/Error - if ( isSuccess ) { - deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); - } else { - deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); - } - - // Status-dependent callbacks - jqXHR.statusCode( statusCode ); - statusCode = undefined; - - if ( fireGlobals ) { - globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", - [ jqXHR, s, isSuccess ? success : error ] ); - } - - // Complete - completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); - - if ( fireGlobals ) { - globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); - // Handle the global AJAX counter - if ( !( --jQuery.active ) ) { - jQuery.event.trigger("ajaxStop"); - } - } - } - - return jqXHR; - }, - - getScript: function( url, callback ) { - return jQuery.get( url, undefined, callback, "script" ); - }, - - getJSON: function( url, data, callback ) { - return jQuery.get( url, data, callback, "json" ); - } -}); - -/* Handles responses to an ajax request: - * - sets all responseXXX fields accordingly - * - finds the right dataType (mediates between content-type and expected dataType) - * - returns the corresponding response - */ -function ajaxHandleResponses( s, jqXHR, responses ) { - var firstDataType, ct, finalDataType, type, - contents = s.contents, - dataTypes = s.dataTypes, - responseFields = s.responseFields; - - // Fill responseXXX fields - for ( type in responseFields ) { - if ( type in responses ) { - jqXHR[ responseFields[type] ] = responses[ type ]; - } - } - - // Remove auto dataType and get content-type in the process - while( dataTypes[ 0 ] === "*" ) { - dataTypes.shift(); - if ( ct === undefined ) { - ct = s.mimeType || jqXHR.getResponseHeader("Content-Type"); - } - } - - // Check if we're dealing with a known content-type - if ( ct ) { - for ( type in contents ) { - if ( contents[ type ] && contents[ type ].test( ct ) ) { - dataTypes.unshift( type ); - break; - } - } - } - - // Check to see if we have a response for the expected dataType - if ( dataTypes[ 0 ] in responses ) { - finalDataType = dataTypes[ 0 ]; - } else { - // Try convertible dataTypes - for ( type in responses ) { - if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { - finalDataType = type; - break; - } - if ( !firstDataType ) { - firstDataType = type; - } - } - // Or just use first one - finalDataType = finalDataType || firstDataType; - } - - // If we found a dataType - // We add the dataType to the list if needed - // and return the corresponding response - if ( finalDataType ) { - if ( finalDataType !== dataTypes[ 0 ] ) { - dataTypes.unshift( finalDataType ); - } - return responses[ finalDataType ]; - } -} - -// Chain conversions given the request and the original response -function ajaxConvert( s, response ) { - var conv2, current, conv, tmp, - converters = {}, - i = 0, - // Work with a copy of dataTypes in case we need to modify it for conversion - dataTypes = s.dataTypes.slice(), - prev = dataTypes[ 0 ]; - - // Apply the dataFilter if provided - if ( s.dataFilter ) { - response = s.dataFilter( response, s.dataType ); - } - - // Create converters map with lowercased keys - if ( dataTypes[ 1 ] ) { - for ( conv in s.converters ) { - converters[ conv.toLowerCase() ] = s.converters[ conv ]; - } - } - - // Convert to each sequential dataType, tolerating list modification - for ( ; (current = dataTypes[++i]); ) { - - // There's only work to do if current dataType is non-auto - if ( current !== "*" ) { - - // Convert response if prev dataType is non-auto and differs from current - if ( prev !== "*" && prev !== current ) { - - // Seek a direct converter - conv = converters[ prev + " " + current ] || converters[ "* " + current ]; - - // If none found, seek a pair - if ( !conv ) { - for ( conv2 in converters ) { - - // If conv2 outputs current - tmp = conv2.split(" "); - if ( tmp[ 1 ] === current ) { - - // If prev can be converted to accepted input - conv = converters[ prev + " " + tmp[ 0 ] ] || - converters[ "* " + tmp[ 0 ] ]; - if ( conv ) { - // Condense equivalence converters - if ( conv === true ) { - conv = converters[ conv2 ]; - - // Otherwise, insert the intermediate dataType - } else if ( converters[ conv2 ] !== true ) { - current = tmp[ 0 ]; - dataTypes.splice( i--, 0, current ); - } - - break; - } - } - } - } - - // Apply converter (if not an equivalence) - if ( conv !== true ) { - - // Unless errors are allowed to bubble, catch and return them - if ( conv && s["throws"] ) { - response = conv( response ); - } else { - try { - response = conv( response ); - } catch ( e ) { - return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; - } - } - } - } - - // Update prev for next iteration - prev = current; - } - } - - return { state: "success", data: response }; -} -// Install script dataType -jQuery.ajaxSetup({ - accepts: { - script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" - }, - contents: { - script: /(?:java|ecma)script/ - }, - converters: { - "text script": function( text ) { - jQuery.globalEval( text ); - return text; - } - } -}); - -// Handle cache's special case and global -jQuery.ajaxPrefilter( "script", function( s ) { - if ( s.cache === undefined ) { - s.cache = false; - } - if ( s.crossDomain ) { - s.type = "GET"; - s.global = false; - } -}); - -// Bind script tag hack transport -jQuery.ajaxTransport( "script", function(s) { - - // This transport only deals with cross domain requests - if ( s.crossDomain ) { - - var script, - head = document.head || jQuery("head")[0] || document.documentElement; - - return { - - send: function( _, callback ) { - - script = document.createElement("script"); - - script.async = true; - - if ( s.scriptCharset ) { - script.charset = s.scriptCharset; - } - - script.src = s.url; - - // Attach handlers for all browsers - script.onload = script.onreadystatechange = function( _, isAbort ) { - - if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { - - // Handle memory leak in IE - script.onload = script.onreadystatechange = null; - - // Remove the script - if ( script.parentNode ) { - script.parentNode.removeChild( script ); - } - - // Dereference the script - script = null; - - // Callback if not abort - if ( !isAbort ) { - callback( 200, "success" ); - } - } - }; - - // Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending - // Use native DOM manipulation to avoid our domManip AJAX trickery - head.insertBefore( script, head.firstChild ); - }, - - abort: function() { - if ( script ) { - script.onload( undefined, true ); - } - } - }; - } -}); -var oldCallbacks = [], - rjsonp = /(=)\?(?=&|$)|\?\?/; - -// Default jsonp settings -jQuery.ajaxSetup({ - jsonp: "callback", - jsonpCallback: function() { - var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( ajax_nonce++ ) ); - this[ callback ] = true; - return callback; - } -}); - -// Detect, normalize options and install callbacks for jsonp requests -jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { - - var callbackName, overwritten, responseContainer, - jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ? - "url" : - typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data" - ); - - // Handle iff the expected data type is "jsonp" or we have a parameter to set - if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) { - - // Get callback name, remembering preexisting value associated with it - callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? - s.jsonpCallback() : - s.jsonpCallback; - - // Insert callback into url or form data - if ( jsonProp ) { - s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName ); - } else if ( s.jsonp !== false ) { - s.url += ( ajax_rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; - } - - // Use data converter to retrieve json after script execution - s.converters["script json"] = function() { - if ( !responseContainer ) { - jQuery.error( callbackName + " was not called" ); - } - return responseContainer[ 0 ]; - }; - - // force json dataType - s.dataTypes[ 0 ] = "json"; - - // Install callback - overwritten = window[ callbackName ]; - window[ callbackName ] = function() { - responseContainer = arguments; - }; - - // Clean-up function (fires after converters) - jqXHR.always(function() { - // Restore preexisting value - window[ callbackName ] = overwritten; - - // Save back as free - if ( s[ callbackName ] ) { - // make sure that re-using the options doesn't screw things around - s.jsonpCallback = originalSettings.jsonpCallback; - - // save the callback name for future use - oldCallbacks.push( callbackName ); - } - - // Call if it was a function and we have a response - if ( responseContainer && jQuery.isFunction( overwritten ) ) { - overwritten( responseContainer[ 0 ] ); - } - - responseContainer = overwritten = undefined; - }); - - // Delegate to script - return "script"; - } -}); -var xhrCallbacks, xhrSupported, - xhrId = 0, - // #5280: Internet Explorer will keep connections alive if we don't abort on unload - xhrOnUnloadAbort = window.ActiveXObject && function() { - // Abort all pending requests - var key; - for ( key in xhrCallbacks ) { - xhrCallbacks[ key ]( undefined, true ); - } - }; - -// Functions to create xhrs -function createStandardXHR() { - try { - return new window.XMLHttpRequest(); - } catch( e ) {} -} - -function createActiveXHR() { - try { - return new window.ActiveXObject("Microsoft.XMLHTTP"); - } catch( e ) {} -} - -// Create the request object -// (This is still attached to ajaxSettings for backward compatibility) -jQuery.ajaxSettings.xhr = window.ActiveXObject ? - /* Microsoft failed to properly - * implement the XMLHttpRequest in IE7 (can't request local files), - * so we use the ActiveXObject when it is available - * Additionally XMLHttpRequest can be disabled in IE7/IE8 so - * we need a fallback. - */ - function() { - return !this.isLocal && createStandardXHR() || createActiveXHR(); - } : - // For all other browsers, use the standard XMLHttpRequest object - createStandardXHR; - -// Determine support properties -xhrSupported = jQuery.ajaxSettings.xhr(); -jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); -xhrSupported = jQuery.support.ajax = !!xhrSupported; - -// Create transport if the browser can provide an xhr -if ( xhrSupported ) { - - jQuery.ajaxTransport(function( s ) { - // Cross domain only allowed if supported through XMLHttpRequest - if ( !s.crossDomain || jQuery.support.cors ) { - - var callback; - - return { - send: function( headers, complete ) { - - // Get a new xhr - var handle, i, - xhr = s.xhr(); - - // Open the socket - // Passing null username, generates a login popup on Opera (#2865) - if ( s.username ) { - xhr.open( s.type, s.url, s.async, s.username, s.password ); - } else { - xhr.open( s.type, s.url, s.async ); - } - - // Apply custom fields if provided - if ( s.xhrFields ) { - for ( i in s.xhrFields ) { - xhr[ i ] = s.xhrFields[ i ]; - } - } - - // Override mime type if needed - if ( s.mimeType && xhr.overrideMimeType ) { - xhr.overrideMimeType( s.mimeType ); - } - - // X-Requested-With header - // For cross-domain requests, seeing as conditions for a preflight are - // akin to a jigsaw puzzle, we simply never set it to be sure. - // (it can always be set on a per-request basis or even using ajaxSetup) - // For same-domain requests, won't change header if already provided. - if ( !s.crossDomain && !headers["X-Requested-With"] ) { - headers["X-Requested-With"] = "XMLHttpRequest"; - } - - // Need an extra try/catch for cross domain requests in Firefox 3 - try { - for ( i in headers ) { - xhr.setRequestHeader( i, headers[ i ] ); - } - } catch( err ) {} - - // Do send the request - // This may raise an exception which is actually - // handled in jQuery.ajax (so no try/catch here) - xhr.send( ( s.hasContent && s.data ) || null ); - - // Listener - callback = function( _, isAbort ) { - var status, responseHeaders, statusText, responses; - - // Firefox throws exceptions when accessing properties - // of an xhr when a network error occurred - // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) - try { - - // Was never called and is aborted or complete - if ( callback && ( isAbort || xhr.readyState === 4 ) ) { - - // Only called once - callback = undefined; - - // Do not keep as active anymore - if ( handle ) { - xhr.onreadystatechange = jQuery.noop; - if ( xhrOnUnloadAbort ) { - delete xhrCallbacks[ handle ]; - } - } - - // If it's an abort - if ( isAbort ) { - // Abort it manually if needed - if ( xhr.readyState !== 4 ) { - xhr.abort(); - } - } else { - responses = {}; - status = xhr.status; - responseHeaders = xhr.getAllResponseHeaders(); - - // When requesting binary data, IE6-9 will throw an exception - // on any attempt to access responseText (#11426) - if ( typeof xhr.responseText === "string" ) { - responses.text = xhr.responseText; - } - - // Firefox throws an exception when accessing - // statusText for faulty cross-domain requests - try { - statusText = xhr.statusText; - } catch( e ) { - // We normalize with Webkit giving an empty statusText - statusText = ""; - } - - // Filter status for non standard behaviors - - // If the request is local and we have data: assume a success - // (success with no data won't get notified, that's the best we - // can do given current implementations) - if ( !status && s.isLocal && !s.crossDomain ) { - status = responses.text ? 200 : 404; - // IE - #1450: sometimes returns 1223 when it should be 204 - } else if ( status === 1223 ) { - status = 204; - } - } - } - } catch( firefoxAccessException ) { - if ( !isAbort ) { - complete( -1, firefoxAccessException ); - } - } - - // Call complete if needed - if ( responses ) { - complete( status, statusText, responses, responseHeaders ); - } - }; - - if ( !s.async ) { - // if we're in sync mode we fire the callback - callback(); - } else if ( xhr.readyState === 4 ) { - // (IE6 & IE7) if it's in cache and has been - // retrieved directly we need to fire the callback - setTimeout( callback ); - } else { - handle = ++xhrId; - if ( xhrOnUnloadAbort ) { - // Create the active xhrs callbacks list if needed - // and attach the unload handler - if ( !xhrCallbacks ) { - xhrCallbacks = {}; - jQuery( window ).unload( xhrOnUnloadAbort ); - } - // Add to list of active xhrs callbacks - xhrCallbacks[ handle ] = callback; - } - xhr.onreadystatechange = callback; - } - }, - - abort: function() { - if ( callback ) { - callback( undefined, true ); - } - } - }; - } - }); -} -var fxNow, timerId, - rfxtypes = /^(?:toggle|show|hide)$/, - rfxnum = new RegExp( "^(?:([+-])=|)(" + core_pnum + ")([a-z%]*)$", "i" ), - rrun = /queueHooks$/, - animationPrefilters = [ defaultPrefilter ], - tweeners = { - "*": [function( prop, value ) { - var end, unit, - tween = this.createTween( prop, value ), - parts = rfxnum.exec( value ), - target = tween.cur(), - start = +target || 0, - scale = 1, - maxIterations = 20; - - if ( parts ) { - end = +parts[2]; - unit = parts[3] || ( jQuery.cssNumber[ prop ] ? "" : "px" ); - - // We need to compute starting value - if ( unit !== "px" && start ) { - // Iteratively approximate from a nonzero starting point - // Prefer the current property, because this process will be trivial if it uses the same units - // Fallback to end or a simple constant - start = jQuery.css( tween.elem, prop, true ) || end || 1; - - do { - // If previous iteration zeroed out, double until we get *something* - // Use a string for doubling factor so we don't accidentally see scale as unchanged below - scale = scale || ".5"; - - // Adjust and apply - start = start / scale; - jQuery.style( tween.elem, prop, start + unit ); - - // Update scale, tolerating zero or NaN from tween.cur() - // And breaking the loop if scale is unchanged or perfect, or if we've just had enough - } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations ); - } - - tween.unit = unit; - tween.start = start; - // If a +=/-= token was provided, we're doing a relative animation - tween.end = parts[1] ? start + ( parts[1] + 1 ) * end : end; - } - return tween; - }] - }; - -// Animations created synchronously will run synchronously -function createFxNow() { - setTimeout(function() { - fxNow = undefined; - }); - return ( fxNow = jQuery.now() ); -} - -function createTweens( animation, props ) { - jQuery.each( props, function( prop, value ) { - var collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), - index = 0, - length = collection.length; - for ( ; index < length; index++ ) { - if ( collection[ index ].call( animation, prop, value ) ) { - - // we're done with this property - return; - } - } - }); -} - -function Animation( elem, properties, options ) { - var result, - stopped, - index = 0, - length = animationPrefilters.length, - deferred = jQuery.Deferred().always( function() { - // don't match elem in the :animated selector - delete tick.elem; - }), - tick = function() { - if ( stopped ) { - return false; - } - var currentTime = fxNow || createFxNow(), - remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), - // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) - temp = remaining / animation.duration || 0, - percent = 1 - temp, - index = 0, - length = animation.tweens.length; - - for ( ; index < length ; index++ ) { - animation.tweens[ index ].run( percent ); - } - - deferred.notifyWith( elem, [ animation, percent, remaining ]); - - if ( percent < 1 && length ) { - return remaining; - } else { - deferred.resolveWith( elem, [ animation ] ); - return false; - } - }, - animation = deferred.promise({ - elem: elem, - props: jQuery.extend( {}, properties ), - opts: jQuery.extend( true, { specialEasing: {} }, options ), - originalProperties: properties, - originalOptions: options, - startTime: fxNow || createFxNow(), - duration: options.duration, - tweens: [], - createTween: function( prop, end ) { - var tween = jQuery.Tween( elem, animation.opts, prop, end, - animation.opts.specialEasing[ prop ] || animation.opts.easing ); - animation.tweens.push( tween ); - return tween; - }, - stop: function( gotoEnd ) { - var index = 0, - // if we are going to the end, we want to run all the tweens - // otherwise we skip this part - length = gotoEnd ? animation.tweens.length : 0; - if ( stopped ) { - return this; - } - stopped = true; - for ( ; index < length ; index++ ) { - animation.tweens[ index ].run( 1 ); - } - - // resolve when we played the last frame - // otherwise, reject - if ( gotoEnd ) { - deferred.resolveWith( elem, [ animation, gotoEnd ] ); - } else { - deferred.rejectWith( elem, [ animation, gotoEnd ] ); - } - return this; - } - }), - props = animation.props; - - propFilter( props, animation.opts.specialEasing ); - - for ( ; index < length ; index++ ) { - result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); - if ( result ) { - return result; - } - } - - createTweens( animation, props ); - - if ( jQuery.isFunction( animation.opts.start ) ) { - animation.opts.start.call( elem, animation ); - } - - jQuery.fx.timer( - jQuery.extend( tick, { - elem: elem, - anim: animation, - queue: animation.opts.queue - }) - ); - - // attach callbacks from options - return animation.progress( animation.opts.progress ) - .done( animation.opts.done, animation.opts.complete ) - .fail( animation.opts.fail ) - .always( animation.opts.always ); -} - -function propFilter( props, specialEasing ) { - var value, name, index, easing, hooks; - - // camelCase, specialEasing and expand cssHook pass - for ( index in props ) { - name = jQuery.camelCase( index ); - easing = specialEasing[ name ]; - value = props[ index ]; - if ( jQuery.isArray( value ) ) { - easing = value[ 1 ]; - value = props[ index ] = value[ 0 ]; - } - - if ( index !== name ) { - props[ name ] = value; - delete props[ index ]; - } - - hooks = jQuery.cssHooks[ name ]; - if ( hooks && "expand" in hooks ) { - value = hooks.expand( value ); - delete props[ name ]; - - // not quite $.extend, this wont overwrite keys already present. - // also - reusing 'index' from above because we have the correct "name" - for ( index in value ) { - if ( !( index in props ) ) { - props[ index ] = value[ index ]; - specialEasing[ index ] = easing; - } - } - } else { - specialEasing[ name ] = easing; - } - } -} - -jQuery.Animation = jQuery.extend( Animation, { - - tweener: function( props, callback ) { - if ( jQuery.isFunction( props ) ) { - callback = props; - props = [ "*" ]; - } else { - props = props.split(" "); - } - - var prop, - index = 0, - length = props.length; - - for ( ; index < length ; index++ ) { - prop = props[ index ]; - tweeners[ prop ] = tweeners[ prop ] || []; - tweeners[ prop ].unshift( callback ); - } - }, - - prefilter: function( callback, prepend ) { - if ( prepend ) { - animationPrefilters.unshift( callback ); - } else { - animationPrefilters.push( callback ); - } - } -}); - -function defaultPrefilter( elem, props, opts ) { - /*jshint validthis:true */ - var prop, index, length, - value, dataShow, toggle, - tween, hooks, oldfire, - anim = this, - style = elem.style, - orig = {}, - handled = [], - hidden = elem.nodeType && isHidden( elem ); - - // handle queue: false promises - if ( !opts.queue ) { - hooks = jQuery._queueHooks( elem, "fx" ); - if ( hooks.unqueued == null ) { - hooks.unqueued = 0; - oldfire = hooks.empty.fire; - hooks.empty.fire = function() { - if ( !hooks.unqueued ) { - oldfire(); - } - }; - } - hooks.unqueued++; - - anim.always(function() { - // doing this makes sure that the complete handler will be called - // before this completes - anim.always(function() { - hooks.unqueued--; - if ( !jQuery.queue( elem, "fx" ).length ) { - hooks.empty.fire(); - } - }); - }); - } - - // height/width overflow pass - if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { - // Make sure that nothing sneaks out - // Record all 3 overflow attributes because IE does not - // change the overflow attribute when overflowX and - // overflowY are set to the same value - opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; - - // Set display property to inline-block for height/width - // animations on inline elements that are having width/height animated - if ( jQuery.css( elem, "display" ) === "inline" && - jQuery.css( elem, "float" ) === "none" ) { - - // inline-level elements accept inline-block; - // block-level elements need to be inline with layout - if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) { - style.display = "inline-block"; - - } else { - style.zoom = 1; - } - } - } - - if ( opts.overflow ) { - style.overflow = "hidden"; - if ( !jQuery.support.shrinkWrapBlocks ) { - anim.always(function() { - style.overflow = opts.overflow[ 0 ]; - style.overflowX = opts.overflow[ 1 ]; - style.overflowY = opts.overflow[ 2 ]; - }); - } - } - - - // show/hide pass - for ( index in props ) { - value = props[ index ]; - if ( rfxtypes.exec( value ) ) { - delete props[ index ]; - toggle = toggle || value === "toggle"; - if ( value === ( hidden ? "hide" : "show" ) ) { - continue; - } - handled.push( index ); - } - } - - length = handled.length; - if ( length ) { - dataShow = jQuery._data( elem, "fxshow" ) || jQuery._data( elem, "fxshow", {} ); - if ( "hidden" in dataShow ) { - hidden = dataShow.hidden; - } - - // store state if its toggle - enables .stop().toggle() to "reverse" - if ( toggle ) { - dataShow.hidden = !hidden; - } - if ( hidden ) { - jQuery( elem ).show(); - } else { - anim.done(function() { - jQuery( elem ).hide(); - }); - } - anim.done(function() { - var prop; - jQuery._removeData( elem, "fxshow" ); - for ( prop in orig ) { - jQuery.style( elem, prop, orig[ prop ] ); - } - }); - for ( index = 0 ; index < length ; index++ ) { - prop = handled[ index ]; - tween = anim.createTween( prop, hidden ? dataShow[ prop ] : 0 ); - orig[ prop ] = dataShow[ prop ] || jQuery.style( elem, prop ); - - if ( !( prop in dataShow ) ) { - dataShow[ prop ] = tween.start; - if ( hidden ) { - tween.end = tween.start; - tween.start = prop === "width" || prop === "height" ? 1 : 0; - } - } - } - } -} - -function Tween( elem, options, prop, end, easing ) { - return new Tween.prototype.init( elem, options, prop, end, easing ); -} -jQuery.Tween = Tween; - -Tween.prototype = { - constructor: Tween, - init: function( elem, options, prop, end, easing, unit ) { - this.elem = elem; - this.prop = prop; - this.easing = easing || "swing"; - this.options = options; - this.start = this.now = this.cur(); - this.end = end; - this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); - }, - cur: function() { - var hooks = Tween.propHooks[ this.prop ]; - - return hooks && hooks.get ? - hooks.get( this ) : - Tween.propHooks._default.get( this ); - }, - run: function( percent ) { - var eased, - hooks = Tween.propHooks[ this.prop ]; - - if ( this.options.duration ) { - this.pos = eased = jQuery.easing[ this.easing ]( - percent, this.options.duration * percent, 0, 1, this.options.duration - ); - } else { - this.pos = eased = percent; - } - this.now = ( this.end - this.start ) * eased + this.start; - - if ( this.options.step ) { - this.options.step.call( this.elem, this.now, this ); - } - - if ( hooks && hooks.set ) { - hooks.set( this ); - } else { - Tween.propHooks._default.set( this ); - } - return this; - } -}; - -Tween.prototype.init.prototype = Tween.prototype; - -Tween.propHooks = { - _default: { - get: function( tween ) { - var result; - - if ( tween.elem[ tween.prop ] != null && - (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) { - return tween.elem[ tween.prop ]; - } - - // passing an empty string as a 3rd parameter to .css will automatically - // attempt a parseFloat and fallback to a string if the parse fails - // so, simple values such as "10px" are parsed to Float. - // complex values such as "rotate(1rad)" are returned as is. - result = jQuery.css( tween.elem, tween.prop, "" ); - // Empty strings, null, undefined and "auto" are converted to 0. - return !result || result === "auto" ? 0 : result; - }, - set: function( tween ) { - // use step hook for back compat - use cssHook if its there - use .style if its - // available and use plain properties where available - if ( jQuery.fx.step[ tween.prop ] ) { - jQuery.fx.step[ tween.prop ]( tween ); - } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { - jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); - } else { - tween.elem[ tween.prop ] = tween.now; - } - } - } -}; - -// Remove in 2.0 - this supports IE8's panic based approach -// to setting things on disconnected nodes - -Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { - set: function( tween ) { - if ( tween.elem.nodeType && tween.elem.parentNode ) { - tween.elem[ tween.prop ] = tween.now; - } - } -}; - -jQuery.each([ "toggle", "show", "hide" ], function( i, name ) { - var cssFn = jQuery.fn[ name ]; - jQuery.fn[ name ] = function( speed, easing, callback ) { - return speed == null || typeof speed === "boolean" ? - cssFn.apply( this, arguments ) : - this.animate( genFx( name, true ), speed, easing, callback ); - }; -}); - -jQuery.fn.extend({ - fadeTo: function( speed, to, easing, callback ) { - - // show any hidden elements after setting opacity to 0 - return this.filter( isHidden ).css( "opacity", 0 ).show() - - // animate to the value specified - .end().animate({ opacity: to }, speed, easing, callback ); - }, - animate: function( prop, speed, easing, callback ) { - var empty = jQuery.isEmptyObject( prop ), - optall = jQuery.speed( speed, easing, callback ), - doAnimation = function() { - // Operate on a copy of prop so per-property easing won't be lost - var anim = Animation( this, jQuery.extend( {}, prop ), optall ); - doAnimation.finish = function() { - anim.stop( true ); - }; - // Empty animations, or finishing resolves immediately - if ( empty || jQuery._data( this, "finish" ) ) { - anim.stop( true ); - } - }; - doAnimation.finish = doAnimation; - - return empty || optall.queue === false ? - this.each( doAnimation ) : - this.queue( optall.queue, doAnimation ); - }, - stop: function( type, clearQueue, gotoEnd ) { - var stopQueue = function( hooks ) { - var stop = hooks.stop; - delete hooks.stop; - stop( gotoEnd ); - }; - - if ( typeof type !== "string" ) { - gotoEnd = clearQueue; - clearQueue = type; - type = undefined; - } - if ( clearQueue && type !== false ) { - this.queue( type || "fx", [] ); - } - - return this.each(function() { - var dequeue = true, - index = type != null && type + "queueHooks", - timers = jQuery.timers, - data = jQuery._data( this ); - - if ( index ) { - if ( data[ index ] && data[ index ].stop ) { - stopQueue( data[ index ] ); - } - } else { - for ( index in data ) { - if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { - stopQueue( data[ index ] ); - } - } - } - - for ( index = timers.length; index--; ) { - if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { - timers[ index ].anim.stop( gotoEnd ); - dequeue = false; - timers.splice( index, 1 ); - } - } - - // start the next in the queue if the last step wasn't forced - // timers currently will call their complete callbacks, which will dequeue - // but only if they were gotoEnd - if ( dequeue || !gotoEnd ) { - jQuery.dequeue( this, type ); - } - }); - }, - finish: function( type ) { - if ( type !== false ) { - type = type || "fx"; - } - return this.each(function() { - var index, - data = jQuery._data( this ), - queue = data[ type + "queue" ], - hooks = data[ type + "queueHooks" ], - timers = jQuery.timers, - length = queue ? queue.length : 0; - - // enable finishing flag on private data - data.finish = true; - - // empty the queue first - jQuery.queue( this, type, [] ); - - if ( hooks && hooks.cur && hooks.cur.finish ) { - hooks.cur.finish.call( this ); - } - - // look for any active animations, and finish them - for ( index = timers.length; index--; ) { - if ( timers[ index ].elem === this && timers[ index ].queue === type ) { - timers[ index ].anim.stop( true ); - timers.splice( index, 1 ); - } - } - - // look for any animations in the old queue and finish them - for ( index = 0; index < length; index++ ) { - if ( queue[ index ] && queue[ index ].finish ) { - queue[ index ].finish.call( this ); - } - } - - // turn off finishing flag - delete data.finish; - }); - } -}); - -// Generate parameters to create a standard animation -function genFx( type, includeWidth ) { - var which, - attrs = { height: type }, - i = 0; - - // if we include width, step value is 1 to do all cssExpand values, - // if we don't include width, step value is 2 to skip over Left and Right - includeWidth = includeWidth? 1 : 0; - for( ; i < 4 ; i += 2 - includeWidth ) { - which = cssExpand[ i ]; - attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; - } - - if ( includeWidth ) { - attrs.opacity = attrs.width = type; - } - - return attrs; -} - -// Generate shortcuts for custom animations -jQuery.each({ - slideDown: genFx("show"), - slideUp: genFx("hide"), - slideToggle: genFx("toggle"), - fadeIn: { opacity: "show" }, - fadeOut: { opacity: "hide" }, - fadeToggle: { opacity: "toggle" } -}, function( name, props ) { - jQuery.fn[ name ] = function( speed, easing, callback ) { - return this.animate( props, speed, easing, callback ); - }; -}); - -jQuery.speed = function( speed, easing, fn ) { - var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { - complete: fn || !fn && easing || - jQuery.isFunction( speed ) && speed, - duration: speed, - easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing - }; - - opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : - opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; - - // normalize opt.queue - true/undefined/null -> "fx" - if ( opt.queue == null || opt.queue === true ) { - opt.queue = "fx"; - } - - // Queueing - opt.old = opt.complete; - - opt.complete = function() { - if ( jQuery.isFunction( opt.old ) ) { - opt.old.call( this ); - } - - if ( opt.queue ) { - jQuery.dequeue( this, opt.queue ); - } - }; - - return opt; -}; - -jQuery.easing = { - linear: function( p ) { - return p; - }, - swing: function( p ) { - return 0.5 - Math.cos( p*Math.PI ) / 2; - } -}; - -jQuery.timers = []; -jQuery.fx = Tween.prototype.init; -jQuery.fx.tick = function() { - var timer, - timers = jQuery.timers, - i = 0; - - fxNow = jQuery.now(); - - for ( ; i < timers.length; i++ ) { - timer = timers[ i ]; - // Checks the timer has not already been removed - if ( !timer() && timers[ i ] === timer ) { - timers.splice( i--, 1 ); - } - } - - if ( !timers.length ) { - jQuery.fx.stop(); - } - fxNow = undefined; -}; - -jQuery.fx.timer = function( timer ) { - if ( timer() && jQuery.timers.push( timer ) ) { - jQuery.fx.start(); - } -}; - -jQuery.fx.interval = 13; - -jQuery.fx.start = function() { - if ( !timerId ) { - timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); - } -}; - -jQuery.fx.stop = function() { - clearInterval( timerId ); - timerId = null; -}; - -jQuery.fx.speeds = { - slow: 600, - fast: 200, - // Default speed - _default: 400 -}; - -// Back Compat <1.8 extension point -jQuery.fx.step = {}; - -if ( jQuery.expr && jQuery.expr.filters ) { - jQuery.expr.filters.animated = function( elem ) { - return jQuery.grep(jQuery.timers, function( fn ) { - return elem === fn.elem; - }).length; - }; -} -jQuery.fn.offset = function( options ) { - if ( arguments.length ) { - return options === undefined ? - this : - this.each(function( i ) { - jQuery.offset.setOffset( this, options, i ); - }); - } - - var docElem, win, - box = { top: 0, left: 0 }, - elem = this[ 0 ], - doc = elem && elem.ownerDocument; - - if ( !doc ) { - return; - } - - docElem = doc.documentElement; - - // Make sure it's not a disconnected DOM node - if ( !jQuery.contains( docElem, elem ) ) { - return box; - } - - // If we don't have gBCR, just use 0,0 rather than error - // BlackBerry 5, iOS 3 (original iPhone) - if ( typeof elem.getBoundingClientRect !== core_strundefined ) { - box = elem.getBoundingClientRect(); - } - win = getWindow( doc ); - return { - top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ), - left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 ) - }; -}; - -jQuery.offset = { - - setOffset: function( elem, options, i ) { - var position = jQuery.css( elem, "position" ); - - // set position first, in-case top/left are set even on static elem - if ( position === "static" ) { - elem.style.position = "relative"; - } - - var curElem = jQuery( elem ), - curOffset = curElem.offset(), - curCSSTop = jQuery.css( elem, "top" ), - curCSSLeft = jQuery.css( elem, "left" ), - calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, - props = {}, curPosition = {}, curTop, curLeft; - - // need to be able to calculate position if either top or left is auto and position is either absolute or fixed - if ( calculatePosition ) { - curPosition = curElem.position(); - curTop = curPosition.top; - curLeft = curPosition.left; - } else { - curTop = parseFloat( curCSSTop ) || 0; - curLeft = parseFloat( curCSSLeft ) || 0; - } - - if ( jQuery.isFunction( options ) ) { - options = options.call( elem, i, curOffset ); - } - - if ( options.top != null ) { - props.top = ( options.top - curOffset.top ) + curTop; - } - if ( options.left != null ) { - props.left = ( options.left - curOffset.left ) + curLeft; - } - - if ( "using" in options ) { - options.using.call( elem, props ); - } else { - curElem.css( props ); - } - } -}; - - -jQuery.fn.extend({ - - position: function() { - if ( !this[ 0 ] ) { - return; - } - - var offsetParent, offset, - parentOffset = { top: 0, left: 0 }, - elem = this[ 0 ]; - - // fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent - if ( jQuery.css( elem, "position" ) === "fixed" ) { - // we assume that getBoundingClientRect is available when computed position is fixed - offset = elem.getBoundingClientRect(); - } else { - // Get *real* offsetParent - offsetParent = this.offsetParent(); - - // Get correct offsets - offset = this.offset(); - if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) { - parentOffset = offsetParent.offset(); - } - - // Add offsetParent borders - parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ); - parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ); - } - - // Subtract parent offsets and element margins - // note: when an element has margin: auto the offsetLeft and marginLeft - // are the same in Safari causing offset.left to incorrectly be 0 - return { - top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), - left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true) - }; - }, - - offsetParent: function() { - return this.map(function() { - var offsetParent = this.offsetParent || document.documentElement; - while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position") === "static" ) ) { - offsetParent = offsetParent.offsetParent; - } - return offsetParent || document.documentElement; - }); - } -}); - - -// Create scrollLeft and scrollTop methods -jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) { - var top = /Y/.test( prop ); - - jQuery.fn[ method ] = function( val ) { - return jQuery.access( this, function( elem, method, val ) { - var win = getWindow( elem ); - - if ( val === undefined ) { - return win ? (prop in win) ? win[ prop ] : - win.document.documentElement[ method ] : - elem[ method ]; - } - - if ( win ) { - win.scrollTo( - !top ? val : jQuery( win ).scrollLeft(), - top ? val : jQuery( win ).scrollTop() - ); - - } else { - elem[ method ] = val; - } - }, method, val, arguments.length, null ); - }; -}); - -function getWindow( elem ) { - return jQuery.isWindow( elem ) ? - elem : - elem.nodeType === 9 ? - elem.defaultView || elem.parentWindow : - false; -} -// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods -jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { - jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { - // margin is only for outerHeight, outerWidth - jQuery.fn[ funcName ] = function( margin, value ) { - var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), - extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); - - return jQuery.access( this, function( elem, type, value ) { - var doc; - - if ( jQuery.isWindow( elem ) ) { - // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there - // isn't a whole lot we can do. See pull request at this URL for discussion: - // https://github.com/jquery/jquery/pull/764 - return elem.document.documentElement[ "client" + name ]; - } - - // Get document width or height - if ( elem.nodeType === 9 ) { - doc = elem.documentElement; - - // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest - // unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it. - return Math.max( - elem.body[ "scroll" + name ], doc[ "scroll" + name ], - elem.body[ "offset" + name ], doc[ "offset" + name ], - doc[ "client" + name ] - ); - } - - return value === undefined ? - // Get width or height on the element, requesting but not forcing parseFloat - jQuery.css( elem, type, extra ) : - - // Set width or height on the element - jQuery.style( elem, type, value, extra ); - }, type, chainable ? margin : undefined, chainable, null ); - }; - }); -}); -// Limit scope pollution from any deprecated API -// (function() { - -// })(); -// Expose jQuery to the global object -window.jQuery = window.$ = jQuery; - -// Expose jQuery as an AMD module, but only for AMD loaders that -// understand the issues with loading multiple versions of jQuery -// in a page that all might call define(). The loader will indicate -// they have special allowances for multiple jQuery versions by -// specifying define.amd.jQuery = true. Register as a named module, -// since jQuery can be concatenated with other files that may use define, -// but not use a proper concatenation script that understands anonymous -// AMD modules. A named AMD is safest and most robust way to register. -// Lowercase jquery is used because AMD module names are derived from -// file names, and jQuery is normally delivered in a lowercase file name. -// Do this after creating the global so that if an AMD module wants to call -// noConflict to hide this version of jQuery, it will work. -if ( typeof define === "function" && define.amd && define.amd.jQuery ) { - define( "jquery", [], function () { return jQuery; } ); -} - -})( window ); - diff --git a/js/jquery-ui.js b/js/jquery-ui.js deleted file mode 100755 index 4b585b2..0000000 --- a/js/jquery-ui.js +++ /dev/null @@ -1,15004 +0,0 @@ -/*! jQuery UI - v1.10.3 - 2013-05-03 -* http://jqueryui.com -* Includes: jquery.ui.core.js, jquery.ui.widget.js, jquery.ui.mouse.js, jquery.ui.draggable.js, jquery.ui.droppable.js, jquery.ui.resizable.js, jquery.ui.selectable.js, jquery.ui.sortable.js, jquery.ui.effect.js, jquery.ui.accordion.js, jquery.ui.autocomplete.js, jquery.ui.button.js, jquery.ui.datepicker.js, jquery.ui.dialog.js, jquery.ui.effect-blind.js, jquery.ui.effect-bounce.js, jquery.ui.effect-clip.js, jquery.ui.effect-drop.js, jquery.ui.effect-explode.js, jquery.ui.effect-fade.js, jquery.ui.effect-fold.js, jquery.ui.effect-highlight.js, jquery.ui.effect-pulsate.js, jquery.ui.effect-scale.js, jquery.ui.effect-shake.js, jquery.ui.effect-slide.js, jquery.ui.effect-transfer.js, jquery.ui.menu.js, jquery.ui.position.js, jquery.ui.progressbar.js, jquery.ui.slider.js, jquery.ui.spinner.js, jquery.ui.tabs.js, jquery.ui.tooltip.js -* Copyright 2013 jQuery Foundation and other contributors; Licensed MIT */ -(function( $, undefined ) { - -var uuid = 0, - runiqueId = /^ui-id-\d+$/; - -// $.ui might exist from components with no dependencies, e.g., $.ui.position -$.ui = $.ui || {}; - -$.extend( $.ui, { - version: "1.10.3", - - keyCode: { - BACKSPACE: 8, - COMMA: 188, - DELETE: 46, - DOWN: 40, - END: 35, - ENTER: 13, - ESCAPE: 27, - HOME: 36, - LEFT: 37, - NUMPAD_ADD: 107, - NUMPAD_DECIMAL: 110, - NUMPAD_DIVIDE: 111, - NUMPAD_ENTER: 108, - NUMPAD_MULTIPLY: 106, - NUMPAD_SUBTRACT: 109, - PAGE_DOWN: 34, - PAGE_UP: 33, - PERIOD: 190, - RIGHT: 39, - SPACE: 32, - TAB: 9, - UP: 38 - } -}); - -// plugins -$.fn.extend({ - focus: (function( orig ) { - return function( delay, fn ) { - return typeof delay === "number" ? - this.each(function() { - var elem = this; - setTimeout(function() { - $( elem ).focus(); - if ( fn ) { - fn.call( elem ); - } - }, delay ); - }) : - orig.apply( this, arguments ); - }; - })( $.fn.focus ), - - scrollParent: function() { - var scrollParent; - if (($.ui.ie && (/(static|relative)/).test(this.css("position"))) || (/absolute/).test(this.css("position"))) { - scrollParent = this.parents().filter(function() { - return (/(relative|absolute|fixed)/).test($.css(this,"position")) && (/(auto|scroll)/).test($.css(this,"overflow")+$.css(this,"overflow-y")+$.css(this,"overflow-x")); - }).eq(0); - } else { - scrollParent = this.parents().filter(function() { - return (/(auto|scroll)/).test($.css(this,"overflow")+$.css(this,"overflow-y")+$.css(this,"overflow-x")); - }).eq(0); - } - - return (/fixed/).test(this.css("position")) || !scrollParent.length ? $(document) : scrollParent; - }, - - zIndex: function( zIndex ) { - if ( zIndex !== undefined ) { - return this.css( "zIndex", zIndex ); - } - - if ( this.length ) { - var elem = $( this[ 0 ] ), position, value; - while ( elem.length && elem[ 0 ] !== document ) { - // Ignore z-index if position is set to a value where z-index is ignored by the browser - // This makes behavior of this function consistent across browsers - // WebKit always returns auto if the element is positioned - position = elem.css( "position" ); - if ( position === "absolute" || position === "relative" || position === "fixed" ) { - // IE returns 0 when zIndex is not specified - // other browsers return a string - // we ignore the case of nested elements with an explicit value of 0 - // <div style="z-index: -10;"><div style="z-index: 0;"></div></div> - value = parseInt( elem.css( "zIndex" ), 10 ); - if ( !isNaN( value ) && value !== 0 ) { - return value; - } - } - elem = elem.parent(); - } - } - - return 0; - }, - - uniqueId: function() { - return this.each(function() { - if ( !this.id ) { - this.id = "ui-id-" + (++uuid); - } - }); - }, - - removeUniqueId: function() { - return this.each(function() { - if ( runiqueId.test( this.id ) ) { - $( this ).removeAttr( "id" ); - } - }); - } -}); - -// selectors -function focusable( element, isTabIndexNotNaN ) { - var map, mapName, img, - nodeName = element.nodeName.toLowerCase(); - if ( "area" === nodeName ) { - map = element.parentNode; - mapName = map.name; - if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) { - return false; - } - img = $( "img[usemap=#" + mapName + "]" )[0]; - return !!img && visible( img ); - } - return ( /input|select|textarea|button|object/.test( nodeName ) ? - !element.disabled : - "a" === nodeName ? - element.href || isTabIndexNotNaN : - isTabIndexNotNaN) && - // the element and all of its ancestors must be visible - visible( element ); -} - -function visible( element ) { - return $.expr.filters.visible( element ) && - !$( element ).parents().addBack().filter(function() { - return $.css( this, "visibility" ) === "hidden"; - }).length; -} - -$.extend( $.expr[ ":" ], { - data: $.expr.createPseudo ? - $.expr.createPseudo(function( dataName ) { - return function( elem ) { - return !!$.data( elem, dataName ); - }; - }) : - // support: jQuery <1.8 - function( elem, i, match ) { - return !!$.data( elem, match[ 3 ] ); - }, - - focusable: function( element ) { - return focusable( element, !isNaN( $.attr( element, "tabindex" ) ) ); - }, - - tabbable: function( element ) { - var tabIndex = $.attr( element, "tabindex" ), - isTabIndexNaN = isNaN( tabIndex ); - return ( isTabIndexNaN || tabIndex >= 0 ) && focusable( element, !isTabIndexNaN ); - } -}); - -// support: jQuery <1.8 -if ( !$( "<a>" ).outerWidth( 1 ).jquery ) { - $.each( [ "Width", "Height" ], function( i, name ) { - var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ], - type = name.toLowerCase(), - orig = { - innerWidth: $.fn.innerWidth, - innerHeight: $.fn.innerHeight, - outerWidth: $.fn.outerWidth, - outerHeight: $.fn.outerHeight - }; - - function reduce( elem, size, border, margin ) { - $.each( side, function() { - size -= parseFloat( $.css( elem, "padding" + this ) ) || 0; - if ( border ) { - size -= parseFloat( $.css( elem, "border" + this + "Width" ) ) || 0; - } - if ( margin ) { - size -= parseFloat( $.css( elem, "margin" + this ) ) || 0; - } - }); - return size; - } - - $.fn[ "inner" + name ] = function( size ) { - if ( size === undefined ) { - return orig[ "inner" + name ].call( this ); - } - - return this.each(function() { - $( this ).css( type, reduce( this, size ) + "px" ); - }); - }; - - $.fn[ "outer" + name] = function( size, margin ) { - if ( typeof size !== "number" ) { - return orig[ "outer" + name ].call( this, size ); - } - - return this.each(function() { - $( this).css( type, reduce( this, size, true, margin ) + "px" ); - }); - }; - }); -} - -// support: jQuery <1.8 -if ( !$.fn.addBack ) { - $.fn.addBack = function( selector ) { - return this.add( selector == null ? - this.prevObject : this.prevObject.filter( selector ) - ); - }; -} - -// support: jQuery 1.6.1, 1.6.2 (http://bugs.jquery.com/ticket/9413) -if ( $( "<a>" ).data( "a-b", "a" ).removeData( "a-b" ).data( "a-b" ) ) { - $.fn.removeData = (function( removeData ) { - return function( key ) { - if ( arguments.length ) { - return removeData.call( this, $.camelCase( key ) ); - } else { - return removeData.call( this ); - } - }; - })( $.fn.removeData ); -} - - - - - -// deprecated -$.ui.ie = !!/msie [\w.]+/.exec( navigator.userAgent.toLowerCase() ); - -$.support.selectstart = "onselectstart" in document.createElement( "div" ); -$.fn.extend({ - disableSelection: function() { - return this.bind( ( $.support.selectstart ? "selectstart" : "mousedown" ) + - ".ui-disableSelection", function( event ) { - event.preventDefault(); - }); - }, - - enableSelection: function() { - return this.unbind( ".ui-disableSelection" ); - } -}); - -$.extend( $.ui, { - // $.ui.plugin is deprecated. Use $.widget() extensions instead. - plugin: { - add: function( module, option, set ) { - var i, - proto = $.ui[ module ].prototype; - for ( i in set ) { - proto.plugins[ i ] = proto.plugins[ i ] || []; - proto.plugins[ i ].push( [ option, set[ i ] ] ); - } - }, - call: function( instance, name, args ) { - var i, - set = instance.plugins[ name ]; - if ( !set || !instance.element[ 0 ].parentNode || instance.element[ 0 ].parentNode.nodeType === 11 ) { - return; - } - - for ( i = 0; i < set.length; i++ ) { - if ( instance.options[ set[ i ][ 0 ] ] ) { - set[ i ][ 1 ].apply( instance.element, args ); - } - } - } - }, - - // only used by resizable - hasScroll: function( el, a ) { - - //If overflow is hidden, the element might have extra content, but the user wants to hide it - if ( $( el ).css( "overflow" ) === "hidden") { - return false; - } - - var scroll = ( a && a === "left" ) ? "scrollLeft" : "scrollTop", - has = false; - - if ( el[ scroll ] > 0 ) { - return true; - } - - // TODO: determine which cases actually cause this to happen - // if the element doesn't have the scroll set, see if it's possible to - // set the scroll - el[ scroll ] = 1; - has = ( el[ scroll ] > 0 ); - el[ scroll ] = 0; - return has; - } -}); - -})( jQuery ); - -(function( $, undefined ) { - -var uuid = 0, - slice = Array.prototype.slice, - _cleanData = $.cleanData; -$.cleanData = function( elems ) { - for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { - try { - $( elem ).triggerHandler( "remove" ); - // http://bugs.jquery.com/ticket/8235 - } catch( e ) {} - } - _cleanData( elems ); -}; - -$.widget = function( name, base, prototype ) { - var fullName, existingConstructor, constructor, basePrototype, - // proxiedPrototype allows the provided prototype to remain unmodified - // so that it can be used as a mixin for multiple widgets (#8876) - proxiedPrototype = {}, - namespace = name.split( "." )[ 0 ]; - - name = name.split( "." )[ 1 ]; - fullName = namespace + "-" + name; - - if ( !prototype ) { - prototype = base; - base = $.Widget; - } - - // create selector for plugin - $.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) { - return !!$.data( elem, fullName ); - }; - - $[ namespace ] = $[ namespace ] || {}; - existingConstructor = $[ namespace ][ name ]; - constructor = $[ namespace ][ name ] = function( options, element ) { - // allow instantiation without "new" keyword - if ( !this._createWidget ) { - return new constructor( options, element ); - } - - // allow instantiation without initializing for simple inheritance - // must use "new" keyword (the code above always passes args) - if ( arguments.length ) { - this._createWidget( options, element ); - } - }; - // extend with the existing constructor to carry over any static properties - $.extend( constructor, existingConstructor, { - version: prototype.version, - // copy the object used to create the prototype in case we need to - // redefine the widget later - _proto: $.extend( {}, prototype ), - // track widgets that inherit from this widget in case this widget is - // redefined after a widget inherits from it - _childConstructors: [] - }); - - basePrototype = new base(); - // we need to make the options hash a property directly on the new instance - // otherwise we'll modify the options hash on the prototype that we're - // inheriting from - basePrototype.options = $.widget.extend( {}, basePrototype.options ); - $.each( prototype, function( prop, value ) { - if ( !$.isFunction( value ) ) { - proxiedPrototype[ prop ] = value; - return; - } - proxiedPrototype[ prop ] = (function() { - var _super = function() { - return base.prototype[ prop ].apply( this, arguments ); - }, - _superApply = function( args ) { - return base.prototype[ prop ].apply( this, args ); - }; - return function() { - var __super = this._super, - __superApply = this._superApply, - returnValue; - - this._super = _super; - this._superApply = _superApply; - - returnValue = value.apply( this, arguments ); - - this._super = __super; - this._superApply = __superApply; - - return returnValue; - }; - })(); - }); - constructor.prototype = $.widget.extend( basePrototype, { - // TODO: remove support for widgetEventPrefix - // always use the name + a colon as the prefix, e.g., draggable:start - // don't prefix for widgets that aren't DOM-based - widgetEventPrefix: existingConstructor ? basePrototype.widgetEventPrefix : name - }, proxiedPrototype, { - constructor: constructor, - namespace: namespace, - widgetName: name, - widgetFullName: fullName - }); - - // If this widget is being redefined then we need to find all widgets that - // are inheriting from it and redefine all of them so that they inherit from - // the new version of this widget. We're essentially trying to replace one - // level in the prototype chain. - if ( existingConstructor ) { - $.each( existingConstructor._childConstructors, function( i, child ) { - var childPrototype = child.prototype; - - // redefine the child widget using the same prototype that was - // originally used, but inherit from the new version of the base - $.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto ); - }); - // remove the list of existing child constructors from the old constructor - // so the old child constructors can be garbage collected - delete existingConstructor._childConstructors; - } else { - base._childConstructors.push( constructor ); - } - - $.widget.bridge( name, constructor ); -}; - -$.widget.extend = function( target ) { - var input = slice.call( arguments, 1 ), - inputIndex = 0, - inputLength = input.length, - key, - value; - for ( ; inputIndex < inputLength; inputIndex++ ) { - for ( key in input[ inputIndex ] ) { - value = input[ inputIndex ][ key ]; - if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) { - // Clone objects - if ( $.isPlainObject( value ) ) { - target[ key ] = $.isPlainObject( target[ key ] ) ? - $.widget.extend( {}, target[ key ], value ) : - // Don't extend strings, arrays, etc. with objects - $.widget.extend( {}, value ); - // Copy everything else by reference - } else { - target[ key ] = value; - } - } - } - } - return target; -}; - -$.widget.bridge = function( name, object ) { - var fullName = object.prototype.widgetFullName || name; - $.fn[ name ] = function( options ) { - var isMethodCall = typeof options === "string", - args = slice.call( arguments, 1 ), - returnValue = this; - - // allow multiple hashes to be passed on init - options = !isMethodCall && args.length ? - $.widget.extend.apply( null, [ options ].concat(args) ) : - options; - - if ( isMethodCall ) { - this.each(function() { - var methodValue, - instance = $.data( this, fullName ); - if ( !instance ) { - return $.error( "cannot call methods on " + name + " prior to initialization; " + - "attempted to call method '" + options + "'" ); - } - if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) { - return $.error( "no such method '" + options + "' for " + name + " widget instance" ); - } - methodValue = instance[ options ].apply( instance, args ); - if ( methodValue !== instance && methodValue !== undefined ) { - returnValue = methodValue && methodValue.jquery ? - returnValue.pushStack( methodValue.get() ) : - methodValue; - return false; - } - }); - } else { - this.each(function() { - var instance = $.data( this, fullName ); - if ( instance ) { - instance.option( options || {} )._init(); - } else { - $.data( this, fullName, new object( options, this ) ); - } - }); - } - - return returnValue; - }; -}; - -$.Widget = function( /* options, element */ ) {}; -$.Widget._childConstructors = []; - -$.Widget.prototype = { - widgetName: "widget", - widgetEventPrefix: "", - defaultElement: "<div>", - options: { - disabled: false, - - // callbacks - create: null - }, - _createWidget: function( options, element ) { - element = $( element || this.defaultElement || this )[ 0 ]; - this.element = $( element ); - this.uuid = uuid++; - this.eventNamespace = "." + this.widgetName + this.uuid; - this.options = $.widget.extend( {}, - this.options, - this._getCreateOptions(), - options ); - - this.bindings = $(); - this.hoverable = $(); - this.focusable = $(); - - if ( element !== this ) { - $.data( element, this.widgetFullName, this ); - this._on( true, this.element, { - remove: function( event ) { - if ( event.target === element ) { - this.destroy(); - } - } - }); - this.document = $( element.style ? - // element within the document - element.ownerDocument : - // element is window or document - element.document || element ); - this.window = $( this.document[0].defaultView || this.document[0].parentWindow ); - } - - this._create(); - this._trigger( "create", null, this._getCreateEventData() ); - this._init(); - }, - _getCreateOptions: $.noop, - _getCreateEventData: $.noop, - _create: $.noop, - _init: $.noop, - - destroy: function() { - this._destroy(); - // we can probably remove the unbind calls in 2.0 - // all event bindings should go through this._on() - this.element - .unbind( this.eventNamespace ) - // 1.9 BC for #7810 - // TODO remove dual storage - .removeData( this.widgetName ) - .removeData( this.widgetFullName ) - // support: jquery <1.6.3 - // http://bugs.jquery.com/ticket/9413 - .removeData( $.camelCase( this.widgetFullName ) ); - this.widget() - .unbind( this.eventNamespace ) - .removeAttr( "aria-disabled" ) - .removeClass( - this.widgetFullName + "-disabled " + - "ui-state-disabled" ); - - // clean up events and states - this.bindings.unbind( this.eventNamespace ); - this.hoverable.removeClass( "ui-state-hover" ); - this.focusable.removeClass( "ui-state-focus" ); - }, - _destroy: $.noop, - - widget: function() { - return this.element; - }, - - option: function( key, value ) { - var options = key, - parts, - curOption, - i; - - if ( arguments.length === 0 ) { - // don't return a reference to the internal hash - return $.widget.extend( {}, this.options ); - } - - if ( typeof key === "string" ) { - // handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } } - options = {}; - parts = key.split( "." ); - key = parts.shift(); - if ( parts.length ) { - curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] ); - for ( i = 0; i < parts.length - 1; i++ ) { - curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {}; - curOption = curOption[ parts[ i ] ]; - } - key = parts.pop(); - if ( value === undefined ) { - return curOption[ key ] === undefined ? null : curOption[ key ]; - } - curOption[ key ] = value; - } else { - if ( value === undefined ) { - return this.options[ key ] === undefined ? null : this.options[ key ]; - } - options[ key ] = value; - } - } - - this._setOptions( options ); - - return this; - }, - _setOptions: function( options ) { - var key; - - for ( key in options ) { - this._setOption( key, options[ key ] ); - } - - return this; - }, - _setOption: function( key, value ) { - this.options[ key ] = value; - - if ( key === "disabled" ) { - this.widget() - .toggleClass( this.widgetFullName + "-disabled ui-state-disabled", !!value ) - .attr( "aria-disabled", value ); - this.hoverable.removeClass( "ui-state-hover" ); - this.focusable.removeClass( "ui-state-focus" ); - } - - return this; - }, - - enable: function() { - return this._setOption( "disabled", false ); - }, - disable: function() { - return this._setOption( "disabled", true ); - }, - - _on: function( suppressDisabledCheck, element, handlers ) { - var delegateElement, - instance = this; - - // no suppressDisabledCheck flag, shuffle arguments - if ( typeof suppressDisabledCheck !== "boolean" ) { - handlers = element; - element = suppressDisabledCheck; - suppressDisabledCheck = false; - } - - // no element argument, shuffle and use this.element - if ( !handlers ) { - handlers = element; - element = this.element; - delegateElement = this.widget(); - } else { - // accept selectors, DOM elements - element = delegateElement = $( element ); - this.bindings = this.bindings.add( element ); - } - - $.each( handlers, function( event, handler ) { - function handlerProxy() { - // allow widgets to customize the disabled handling - // - disabled as an array instead of boolean - // - disabled class as method for disabling individual parts - if ( !suppressDisabledCheck && - ( instance.options.disabled === true || - $( this ).hasClass( "ui-state-disabled" ) ) ) { - return; - } - return ( typeof handler === "string" ? instance[ handler ] : handler ) - .apply( instance, arguments ); - } - - // copy the guid so direct unbinding works - if ( typeof handler !== "string" ) { - handlerProxy.guid = handler.guid = - handler.guid || handlerProxy.guid || $.guid++; - } - - var match = event.match( /^(\w+)\s*(.*)$/ ), - eventName = match[1] + instance.eventNamespace, - selector = match[2]; - if ( selector ) { - delegateElement.delegate( selector, eventName, handlerProxy ); - } else { - element.bind( eventName, handlerProxy ); - } - }); - }, - - _off: function( element, eventName ) { - eventName = (eventName || "").split( " " ).join( this.eventNamespace + " " ) + this.eventNamespace; - element.unbind( eventName ).undelegate( eventName ); - }, - - _delay: function( handler, delay ) { - function handlerProxy() { - return ( typeof handler === "string" ? instance[ handler ] : handler ) - .apply( instance, arguments ); - } - var instance = this; - return setTimeout( handlerProxy, delay || 0 ); - }, - - _hoverable: function( element ) { - this.hoverable = this.hoverable.add( element ); - this._on( element, { - mouseenter: function( event ) { - $( event.currentTarget ).addClass( "ui-state-hover" ); - }, - mouseleave: function( event ) { - $( event.currentTarget ).removeClass( "ui-state-hover" ); - } - }); - }, - - _focusable: function( element ) { - this.focusable = this.focusable.add( element ); - this._on( element, { - focusin: function( event ) { - $( event.currentTarget ).addClass( "ui-state-focus" ); - }, - focusout: function( event ) { - $( event.currentTarget ).removeClass( "ui-state-focus" ); - } - }); - }, - - _trigger: function( type, event, data ) { - var prop, orig, - callback = this.options[ type ]; - - data = data || {}; - event = $.Event( event ); - event.type = ( type === this.widgetEventPrefix ? - type : - this.widgetEventPrefix + type ).toLowerCase(); - // the original event may come from any element - // so we need to reset the target on the new event - event.target = this.element[ 0 ]; - - // copy original event properties over to the new event - orig = event.originalEvent; - if ( orig ) { - for ( prop in orig ) { - if ( !( prop in event ) ) { - event[ prop ] = orig[ prop ]; - } - } - } - - this.element.trigger( event, data ); - return !( $.isFunction( callback ) && - callback.apply( this.element[0], [ event ].concat( data ) ) === false || - event.isDefaultPrevented() ); - } -}; - -$.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) { - $.Widget.prototype[ "_" + method ] = function( element, options, callback ) { - if ( typeof options === "string" ) { - options = { effect: options }; - } - var hasOptions, - effectName = !options ? - method : - options === true || typeof options === "number" ? - defaultEffect : - options.effect || defaultEffect; - options = options || {}; - if ( typeof options === "number" ) { - options = { duration: options }; - } - hasOptions = !$.isEmptyObject( options ); - options.complete = callback; - if ( options.delay ) { - element.delay( options.delay ); - } - if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) { - element[ method ]( options ); - } else if ( effectName !== method && element[ effectName ] ) { - element[ effectName ]( options.duration, options.easing, callback ); - } else { - element.queue(function( next ) { - $( this )[ method ](); - if ( callback ) { - callback.call( element[ 0 ] ); - } - next(); - }); - } - }; -}); - -})( jQuery ); - -(function( $, undefined ) { - -var mouseHandled = false; -$( document ).mouseup( function() { - mouseHandled = false; -}); - -$.widget("ui.mouse", { - version: "1.10.3", - options: { - cancel: "input,textarea,button,select,option", - distance: 1, - delay: 0 - }, - _mouseInit: function() { - var that = this; - - this.element - .bind("mousedown."+this.widgetName, function(event) { - return that._mouseDown(event); - }) - .bind("click."+this.widgetName, function(event) { - if (true === $.data(event.target, that.widgetName + ".preventClickEvent")) { - $.removeData(event.target, that.widgetName + ".preventClickEvent"); - event.stopImmediatePropagation(); - return false; - } - }); - - this.started = false; - }, - - // TODO: make sure destroying one instance of mouse doesn't mess with - // other instances of mouse - _mouseDestroy: function() { - this.element.unbind("."+this.widgetName); - if ( this._mouseMoveDelegate ) { - $(document) - .unbind("mousemove."+this.widgetName, this._mouseMoveDelegate) - .unbind("mouseup."+this.widgetName, this._mouseUpDelegate); - } - }, - - _mouseDown: function(event) { - // don't let more than one widget handle mouseStart - if( mouseHandled ) { return; } - - // we may have missed mouseup (out of window) - (this._mouseStarted && this._mouseUp(event)); - - this._mouseDownEvent = event; - - var that = this, - btnIsLeft = (event.which === 1), - // event.target.nodeName works around a bug in IE 8 with - // disabled inputs (#7620) - elIsCancel = (typeof this.options.cancel === "string" && event.target.nodeName ? $(event.target).closest(this.options.cancel).length : false); - if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) { - return true; - } - - this.mouseDelayMet = !this.options.delay; - if (!this.mouseDelayMet) { - this._mouseDelayTimer = setTimeout(function() { - that.mouseDelayMet = true; - }, this.options.delay); - } - - if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) { - this._mouseStarted = (this._mouseStart(event) !== false); - if (!this._mouseStarted) { - event.preventDefault(); - return true; - } - } - - // Click event may never have fired (Gecko & Opera) - if (true === $.data(event.target, this.widgetName + ".preventClickEvent")) { - $.removeData(event.target, this.widgetName + ".preventClickEvent"); - } - - // these delegates are required to keep context - this._mouseMoveDelegate = function(event) { - return that._mouseMove(event); - }; - this._mouseUpDelegate = function(event) { - return that._mouseUp(event); - }; - $(document) - .bind("mousemove."+this.widgetName, this._mouseMoveDelegate) - .bind("mouseup."+this.widgetName, this._mouseUpDelegate); - - event.preventDefault(); - - mouseHandled = true; - return true; - }, - - _mouseMove: function(event) { - // IE mouseup check - mouseup happened when mouse was out of window - if ($.ui.ie && ( !document.documentMode || document.documentMode < 9 ) && !event.button) { - return this._mouseUp(event); - } - - if (this._mouseStarted) { - this._mouseDrag(event); - return event.preventDefault(); - } - - if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) { - this._mouseStarted = - (this._mouseStart(this._mouseDownEvent, event) !== false); - (this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event)); - } - - return !this._mouseStarted; - }, - - _mouseUp: function(event) { - $(document) - .unbind("mousemove."+this.widgetName, this._mouseMoveDelegate) - .unbind("mouseup."+this.widgetName, this._mouseUpDelegate); - - if (this._mouseStarted) { - this._mouseStarted = false; - - if (event.target === this._mouseDownEvent.target) { - $.data(event.target, this.widgetName + ".preventClickEvent", true); - } - - this._mouseStop(event); - } - - return false; - }, - - _mouseDistanceMet: function(event) { - return (Math.max( - Math.abs(this._mouseDownEvent.pageX - event.pageX), - Math.abs(this._mouseDownEvent.pageY - event.pageY) - ) >= this.options.distance - ); - }, - - _mouseDelayMet: function(/* event */) { - return this.mouseDelayMet; - }, - - // These are placeholder methods, to be overriden by extending plugin - _mouseStart: function(/* event */) {}, - _mouseDrag: function(/* event */) {}, - _mouseStop: function(/* event */) {}, - _mouseCapture: function(/* event */) { return true; } -}); - -})(jQuery); - -(function( $, undefined ) { - -$.widget("ui.draggable", $.ui.mouse, { - version: "1.10.3", - widgetEventPrefix: "drag", - options: { - addClasses: true, - appendTo: "parent", - axis: false, - connectToSortable: false, - containment: false, - cursor: "auto", - cursorAt: false, - grid: false, - handle: false, - helper: "original", - iframeFix: false, - opacity: false, - refreshPositions: false, - revert: false, - revertDuration: 500, - scope: "default", - scroll: true, - scrollSensitivity: 20, - scrollSpeed: 20, - snap: false, - snapMode: "both", - snapTolerance: 20, - stack: false, - zIndex: false, - - // callbacks - drag: null, - start: null, - stop: null - }, - _create: function() { - - if (this.options.helper === "original" && !(/^(?:r|a|f)/).test(this.element.css("position"))) { - this.element[0].style.position = "relative"; - } - if (this.options.addClasses){ - this.element.addClass("ui-draggable"); - } - if (this.options.disabled){ - this.element.addClass("ui-draggable-disabled"); - } - - this._mouseInit(); - - }, - - _destroy: function() { - this.element.removeClass( "ui-draggable ui-draggable-dragging ui-draggable-disabled" ); - this._mouseDestroy(); - }, - - _mouseCapture: function(event) { - - var o = this.options; - - // among others, prevent a drag on a resizable-handle - if (this.helper || o.disabled || $(event.target).closest(".ui-resizable-handle").length > 0) { - return false; - } - - //Quit if we're not on a valid handle - this.handle = this._getHandle(event); - if (!this.handle) { - return false; - } - - $(o.iframeFix === true ? "iframe" : o.iframeFix).each(function() { - $("<div class='ui-draggable-iframeFix' style='background: #fff;'></div>") - .css({ - width: this.offsetWidth+"px", height: this.offsetHeight+"px", - position: "absolute", opacity: "0.001", zIndex: 1000 - }) - .css($(this).offset()) - .appendTo("body"); - }); - - return true; - - }, - - _mouseStart: function(event) { - - var o = this.options; - - //Create and append the visible helper - this.helper = this._createHelper(event); - - this.helper.addClass("ui-draggable-dragging"); - - //Cache the helper size - this._cacheHelperProportions(); - - //If ddmanager is used for droppables, set the global draggable - if($.ui.ddmanager) { - $.ui.ddmanager.current = this; - } - - /* - * - Position generation - - * This block generates everything position related - it's the core of draggables. - */ - - //Cache the margins of the original element - this._cacheMargins(); - - //Store the helper's css position - this.cssPosition = this.helper.css( "position" ); - this.scrollParent = this.helper.scrollParent(); - this.offsetParent = this.helper.offsetParent(); - this.offsetParentCssPosition = this.offsetParent.css( "position" ); - - //The element's absolute position on the page minus margins - this.offset = this.positionAbs = this.element.offset(); - this.offset = { - top: this.offset.top - this.margins.top, - left: this.offset.left - this.margins.left - }; - - //Reset scroll cache - this.offset.scroll = false; - - $.extend(this.offset, { - click: { //Where the click happened, relative to the element - left: event.pageX - this.offset.left, - top: event.pageY - this.offset.top - }, - parent: this._getParentOffset(), - relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper - }); - - //Generate the original position - this.originalPosition = this.position = this._generatePosition(event); - this.originalPageX = event.pageX; - this.originalPageY = event.pageY; - - //Adjust the mouse offset relative to the helper if "cursorAt" is supplied - (o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt)); - - //Set a containment if given in the options - this._setContainment(); - - //Trigger event + callbacks - if(this._trigger("start", event) === false) { - this._clear(); - return false; - } - - //Recache the helper size - this._cacheHelperProportions(); - - //Prepare the droppable offsets - if ($.ui.ddmanager && !o.dropBehaviour) { - $.ui.ddmanager.prepareOffsets(this, event); - } - - - this._mouseDrag(event, true); //Execute the drag once - this causes the helper not to be visible before getting its correct position - - //If the ddmanager is used for droppables, inform the manager that dragging has started (see #5003) - if ( $.ui.ddmanager ) { - $.ui.ddmanager.dragStart(this, event); - } - - return true; - }, - - _mouseDrag: function(event, noPropagation) { - // reset any necessary cached properties (see #5009) - if ( this.offsetParentCssPosition === "fixed" ) { - this.offset.parent = this._getParentOffset(); - } - - //Compute the helpers position - this.position = this._generatePosition(event); - this.positionAbs = this._convertPositionTo("absolute"); - - //Call plugins and callbacks and use the resulting position if something is returned - if (!noPropagation) { - var ui = this._uiHash(); - if(this._trigger("drag", event, ui) === false) { - this._mouseUp({}); - return false; - } - this.position = ui.position; - } - - if(!this.options.axis || this.options.axis !== "y") { - this.helper[0].style.left = this.position.left+"px"; - } - if(!this.options.axis || this.options.axis !== "x") { - this.helper[0].style.top = this.position.top+"px"; - } - if($.ui.ddmanager) { - $.ui.ddmanager.drag(this, event); - } - - return false; - }, - - _mouseStop: function(event) { - - //If we are using droppables, inform the manager about the drop - var that = this, - dropped = false; - if ($.ui.ddmanager && !this.options.dropBehaviour) { - dropped = $.ui.ddmanager.drop(this, event); - } - - //if a drop comes from outside (a sortable) - if(this.dropped) { - dropped = this.dropped; - this.dropped = false; - } - - //if the original element is no longer in the DOM don't bother to continue (see #8269) - if ( this.options.helper === "original" && !$.contains( this.element[ 0 ].ownerDocument, this.element[ 0 ] ) ) { - return false; - } - - if((this.options.revert === "invalid" && !dropped) || (this.options.revert === "valid" && dropped) || this.options.revert === true || ($.isFunction(this.options.revert) && this.options.revert.call(this.element, dropped))) { - $(this.helper).animate(this.originalPosition, parseInt(this.options.revertDuration, 10), function() { - if(that._trigger("stop", event) !== false) { - that._clear(); - } - }); - } else { - if(this._trigger("stop", event) !== false) { - this._clear(); - } - } - - return false; - }, - - _mouseUp: function(event) { - //Remove frame helpers - $("div.ui-draggable-iframeFix").each(function() { - this.parentNode.removeChild(this); - }); - - //If the ddmanager is used for droppables, inform the manager that dragging has stopped (see #5003) - if( $.ui.ddmanager ) { - $.ui.ddmanager.dragStop(this, event); - } - - return $.ui.mouse.prototype._mouseUp.call(this, event); - }, - - cancel: function() { - - if(this.helper.is(".ui-draggable-dragging")) { - this._mouseUp({}); - } else { - this._clear(); - } - - return this; - - }, - - _getHandle: function(event) { - return this.options.handle ? - !!$( event.target ).closest( this.element.find( this.options.handle ) ).length : - true; - }, - - _createHelper: function(event) { - - var o = this.options, - helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event])) : (o.helper === "clone" ? this.element.clone().removeAttr("id") : this.element); - - if(!helper.parents("body").length) { - helper.appendTo((o.appendTo === "parent" ? this.element[0].parentNode : o.appendTo)); - } - - if(helper[0] !== this.element[0] && !(/(fixed|absolute)/).test(helper.css("position"))) { - helper.css("position", "absolute"); - } - - return helper; - - }, - - _adjustOffsetFromHelper: function(obj) { - if (typeof obj === "string") { - obj = obj.split(" "); - } - if ($.isArray(obj)) { - obj = {left: +obj[0], top: +obj[1] || 0}; - } - if ("left" in obj) { - this.offset.click.left = obj.left + this.margins.left; - } - if ("right" in obj) { - this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left; - } - if ("top" in obj) { - this.offset.click.top = obj.top + this.margins.top; - } - if ("bottom" in obj) { - this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top; - } - }, - - _getParentOffset: function() { - - //Get the offsetParent and cache its position - var po = this.offsetParent.offset(); - - // This is a special case where we need to modify a offset calculated on start, since the following happened: - // 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent - // 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that - // the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag - if(this.cssPosition === "absolute" && this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) { - po.left += this.scrollParent.scrollLeft(); - po.top += this.scrollParent.scrollTop(); - } - - //This needs to be actually done for all browsers, since pageX/pageY includes this information - //Ugly IE fix - if((this.offsetParent[0] === document.body) || - (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() === "html" && $.ui.ie)) { - po = { top: 0, left: 0 }; - } - - return { - top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0), - left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0) - }; - - }, - - _getRelativeOffset: function() { - - if(this.cssPosition === "relative") { - var p = this.element.position(); - return { - top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(), - left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft() - }; - } else { - return { top: 0, left: 0 }; - } - - }, - - _cacheMargins: function() { - this.margins = { - left: (parseInt(this.element.css("marginLeft"),10) || 0), - top: (parseInt(this.element.css("marginTop"),10) || 0), - right: (parseInt(this.element.css("marginRight"),10) || 0), - bottom: (parseInt(this.element.css("marginBottom"),10) || 0) - }; - }, - - _cacheHelperProportions: function() { - this.helperProportions = { - width: this.helper.outerWidth(), - height: this.helper.outerHeight() - }; - }, - - _setContainment: function() { - - var over, c, ce, - o = this.options; - - if ( !o.containment ) { - this.containment = null; - return; - } - - if ( o.containment === "window" ) { - this.containment = [ - $( window ).scrollLeft() - this.offset.relative.left - this.offset.parent.left, - $( window ).scrollTop() - this.offset.relative.top - this.offset.parent.top, - $( window ).scrollLeft() + $( window ).width() - this.helperProportions.width - this.margins.left, - $( window ).scrollTop() + ( $( window ).height() || document.body.parentNode.scrollHeight ) - this.helperProportions.height - this.margins.top - ]; - return; - } - - if ( o.containment === "document") { - this.containment = [ - 0, - 0, - $( document ).width() - this.helperProportions.width - this.margins.left, - ( $( document ).height() || document.body.parentNode.scrollHeight ) - this.helperProportions.height - this.margins.top - ]; - return; - } - - if ( o.containment.constructor === Array ) { - this.containment = o.containment; - return; - } - - if ( o.containment === "parent" ) { - o.containment = this.helper[ 0 ].parentNode; - } - - c = $( o.containment ); - ce = c[ 0 ]; - - if( !ce ) { - return; - } - - over = c.css( "overflow" ) !== "hidden"; - - this.containment = [ - ( parseInt( c.css( "borderLeftWidth" ), 10 ) || 0 ) + ( parseInt( c.css( "paddingLeft" ), 10 ) || 0 ), - ( parseInt( c.css( "borderTopWidth" ), 10 ) || 0 ) + ( parseInt( c.css( "paddingTop" ), 10 ) || 0 ) , - ( over ? Math.max( ce.scrollWidth, ce.offsetWidth ) : ce.offsetWidth ) - ( parseInt( c.css( "borderRightWidth" ), 10 ) || 0 ) - ( parseInt( c.css( "paddingRight" ), 10 ) || 0 ) - this.helperProportions.width - this.margins.left - this.margins.right, - ( over ? Math.max( ce.scrollHeight, ce.offsetHeight ) : ce.offsetHeight ) - ( parseInt( c.css( "borderBottomWidth" ), 10 ) || 0 ) - ( parseInt( c.css( "paddingBottom" ), 10 ) || 0 ) - this.helperProportions.height - this.margins.top - this.margins.bottom - ]; - this.relative_container = c; - }, - - _convertPositionTo: function(d, pos) { - - if(!pos) { - pos = this.position; - } - - var mod = d === "absolute" ? 1 : -1, - scroll = this.cssPosition === "absolute" && !( this.scrollParent[ 0 ] !== document && $.contains( this.scrollParent[ 0 ], this.offsetParent[ 0 ] ) ) ? this.offsetParent : this.scrollParent; - - //Cache the scroll - if (!this.offset.scroll) { - this.offset.scroll = {top : scroll.scrollTop(), left : scroll.scrollLeft()}; - } - - return { - top: ( - pos.top + // The absolute mouse position - this.offset.relative.top * mod + // Only for relative positioned nodes: Relative offset from element to offset parent - this.offset.parent.top * mod - // The offsetParent's offset without borders (offset + border) - ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : this.offset.scroll.top ) * mod ) - ), - left: ( - pos.left + // The absolute mouse position - this.offset.relative.left * mod + // Only for relative positioned nodes: Relative offset from element to offset parent - this.offset.parent.left * mod - // The offsetParent's offset without borders (offset + border) - ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : this.offset.scroll.left ) * mod ) - ) - }; - - }, - - _generatePosition: function(event) { - - var containment, co, top, left, - o = this.options, - scroll = this.cssPosition === "absolute" && !( this.scrollParent[ 0 ] !== document && $.contains( this.scrollParent[ 0 ], this.offsetParent[ 0 ] ) ) ? this.offsetParent : this.scrollParent, - pageX = event.pageX, - pageY = event.pageY; - - //Cache the scroll - if (!this.offset.scroll) { - this.offset.scroll = {top : scroll.scrollTop(), left : scroll.scrollLeft()}; - } - - /* - * - Position constraining - - * Constrain the position to a mix of grid, containment. - */ - - // If we are not dragging yet, we won't check for options - if ( this.originalPosition ) { - if ( this.containment ) { - if ( this.relative_container ){ - co = this.relative_container.offset(); - containment = [ - this.containment[ 0 ] + co.left, - this.containment[ 1 ] + co.top, - this.containment[ 2 ] + co.left, - this.containment[ 3 ] + co.top - ]; - } - else { - containment = this.containment; - } - - if(event.pageX - this.offset.click.left < containment[0]) { - pageX = containment[0] + this.offset.click.left; - } - if(event.pageY - this.offset.click.top < containment[1]) { - pageY = containment[1] + this.offset.click.top; - } - if(event.pageX - this.offset.click.left > containment[2]) { - pageX = containment[2] + this.offset.click.left; - } - if(event.pageY - this.offset.click.top > containment[3]) { - pageY = containment[3] + this.offset.click.top; - } - } - - if(o.grid) { - //Check for grid elements set to 0 to prevent divide by 0 error causing invalid argument errors in IE (see ticket #6950) - top = o.grid[1] ? this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1] : this.originalPageY; - pageY = containment ? ((top - this.offset.click.top >= containment[1] || top - this.offset.click.top > containment[3]) ? top : ((top - this.offset.click.top >= containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top; - - left = o.grid[0] ? this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0] : this.originalPageX; - pageX = containment ? ((left - this.offset.click.left >= containment[0] || left - this.offset.click.left > containment[2]) ? left : ((left - this.offset.click.left >= containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left; - } - - } - - return { - top: ( - pageY - // The absolute mouse position - this.offset.click.top - // Click offset (relative to the element) - this.offset.relative.top - // Only for relative positioned nodes: Relative offset from element to offset parent - this.offset.parent.top + // The offsetParent's offset without borders (offset + border) - ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : this.offset.scroll.top ) - ), - left: ( - pageX - // The absolute mouse position - this.offset.click.left - // Click offset (relative to the element) - this.offset.relative.left - // Only for relative positioned nodes: Relative offset from element to offset parent - this.offset.parent.left + // The offsetParent's offset without borders (offset + border) - ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : this.offset.scroll.left ) - ) - }; - - }, - - _clear: function() { - this.helper.removeClass("ui-draggable-dragging"); - if(this.helper[0] !== this.element[0] && !this.cancelHelperRemoval) { - this.helper.remove(); - } - this.helper = null; - this.cancelHelperRemoval = false; - }, - - // From now on bulk stuff - mainly helpers - - _trigger: function(type, event, ui) { - ui = ui || this._uiHash(); - $.ui.plugin.call(this, type, [event, ui]); - //The absolute position has to be recalculated after plugins - if(type === "drag") { - this.positionAbs = this._convertPositionTo("absolute"); - } - return $.Widget.prototype._trigger.call(this, type, event, ui); - }, - - plugins: {}, - - _uiHash: function() { - return { - helper: this.helper, - position: this.position, - originalPosition: this.originalPosition, - offset: this.positionAbs - }; - } - -}); - -$.ui.plugin.add("draggable", "connectToSortable", { - start: function(event, ui) { - - var inst = $(this).data("ui-draggable"), o = inst.options, - uiSortable = $.extend({}, ui, { item: inst.element }); - inst.sortables = []; - $(o.connectToSortable).each(function() { - var sortable = $.data(this, "ui-sortable"); - if (sortable && !sortable.options.disabled) { - inst.sortables.push({ - instance: sortable, - shouldRevert: sortable.options.revert - }); - sortable.refreshPositions(); // Call the sortable's refreshPositions at drag start to refresh the containerCache since the sortable container cache is used in drag and needs to be up to date (this will ensure it's initialised as well as being kept in step with any changes that might have happened on the page). - sortable._trigger("activate", event, uiSortable); - } - }); - - }, - stop: function(event, ui) { - - //If we are still over the sortable, we fake the stop event of the sortable, but also remove helper - var inst = $(this).data("ui-draggable"), - uiSortable = $.extend({}, ui, { item: inst.element }); - - $.each(inst.sortables, function() { - if(this.instance.isOver) { - - this.instance.isOver = 0; - - inst.cancelHelperRemoval = true; //Don't remove the helper in the draggable instance - this.instance.cancelHelperRemoval = false; //Remove it in the sortable instance (so sortable plugins like revert still work) - - //The sortable revert is supported, and we have to set a temporary dropped variable on the draggable to support revert: "valid/invalid" - if(this.shouldRevert) { - this.instance.options.revert = this.shouldRevert; - } - - //Trigger the stop of the sortable - this.instance._mouseStop(event); - - this.instance.options.helper = this.instance.options._helper; - - //If the helper has been the original item, restore properties in the sortable - if(inst.options.helper === "original") { - this.instance.currentItem.css({ top: "auto", left: "auto" }); - } - - } else { - this.instance.cancelHelperRemoval = false; //Remove the helper in the sortable instance - this.instance._trigger("deactivate", event, uiSortable); - } - - }); - - }, - drag: function(event, ui) { - - var inst = $(this).data("ui-draggable"), that = this; - - $.each(inst.sortables, function() { - - var innermostIntersecting = false, - thisSortable = this; - - //Copy over some variables to allow calling the sortable's native _intersectsWith - this.instance.positionAbs = inst.positionAbs; - this.instance.helperProportions = inst.helperProportions; - this.instance.offset.click = inst.offset.click; - - if(this.instance._intersectsWith(this.instance.containerCache)) { - innermostIntersecting = true; - $.each(inst.sortables, function () { - this.instance.positionAbs = inst.positionAbs; - this.instance.helperProportions = inst.helperProportions; - this.instance.offset.click = inst.offset.click; - if (this !== thisSortable && - this.instance._intersectsWith(this.instance.containerCache) && - $.contains(thisSortable.instance.element[0], this.instance.element[0]) - ) { - innermostIntersecting = false; - } - return innermostIntersecting; - }); - } - - - if(innermostIntersecting) { - //If it intersects, we use a little isOver variable and set it once, so our move-in stuff gets fired only once - if(!this.instance.isOver) { - - this.instance.isOver = 1; - //Now we fake the start of dragging for the sortable instance, - //by cloning the list group item, appending it to the sortable and using it as inst.currentItem - //We can then fire the start event of the sortable with our passed browser event, and our own helper (so it doesn't create a new one) - this.instance.currentItem = $(that).clone().removeAttr("id").appendTo(this.instance.element).data("ui-sortable-item", true); - this.instance.options._helper = this.instance.options.helper; //Store helper option to later restore it - this.instance.options.helper = function() { return ui.helper[0]; }; - - event.target = this.instance.currentItem[0]; - this.instance._mouseCapture(event, true); - this.instance._mouseStart(event, true, true); - - //Because the browser event is way off the new appended portlet, we modify a couple of variables to reflect the changes - this.instance.offset.click.top = inst.offset.click.top; - this.instance.offset.click.left = inst.offset.click.left; - this.instance.offset.parent.left -= inst.offset.parent.left - this.instance.offset.parent.left; - this.instance.offset.parent.top -= inst.offset.parent.top - this.instance.offset.parent.top; - - inst._trigger("toSortable", event); - inst.dropped = this.instance.element; //draggable revert needs that - //hack so receive/update callbacks work (mostly) - inst.currentItem = inst.element; - this.instance.fromOutside = inst; - - } - - //Provided we did all the previous steps, we can fire the drag event of the sortable on every draggable drag, when it intersects with the sortable - if(this.instance.currentItem) { - this.instance._mouseDrag(event); - } - - } else { - - //If it doesn't intersect with the sortable, and it intersected before, - //we fake the drag stop of the sortable, but make sure it doesn't remove the helper by using cancelHelperRemoval - if(this.instance.isOver) { - - this.instance.isOver = 0; - this.instance.cancelHelperRemoval = true; - - //Prevent reverting on this forced stop - this.instance.options.revert = false; - - // The out event needs to be triggered independently - this.instance._trigger("out", event, this.instance._uiHash(this.instance)); - - this.instance._mouseStop(event, true); - this.instance.options.helper = this.instance.options._helper; - - //Now we remove our currentItem, the list group clone again, and the placeholder, and animate the helper back to it's original size - this.instance.currentItem.remove(); - if(this.instance.placeholder) { - this.instance.placeholder.remove(); - } - - inst._trigger("fromSortable", event); - inst.dropped = false; //draggable revert needs that - } - - } - - }); - - } -}); - -$.ui.plugin.add("draggable", "cursor", { - start: function() { - var t = $("body"), o = $(this).data("ui-draggable").options; - if (t.css("cursor")) { - o._cursor = t.css("cursor"); - } - t.css("cursor", o.cursor); - }, - stop: function() { - var o = $(this).data("ui-draggable").options; - if (o._cursor) { - $("body").css("cursor", o._cursor); - } - } -}); - -$.ui.plugin.add("draggable", "opacity", { - start: function(event, ui) { - var t = $(ui.helper), o = $(this).data("ui-draggable").options; - if(t.css("opacity")) { - o._opacity = t.css("opacity"); - } - t.css("opacity", o.opacity); - }, - stop: function(event, ui) { - var o = $(this).data("ui-draggable").options; - if(o._opacity) { - $(ui.helper).css("opacity", o._opacity); - } - } -}); - -$.ui.plugin.add("draggable", "scroll", { - start: function() { - var i = $(this).data("ui-draggable"); - if(i.scrollParent[0] !== document && i.scrollParent[0].tagName !== "HTML") { - i.overflowOffset = i.scrollParent.offset(); - } - }, - drag: function( event ) { - - var i = $(this).data("ui-draggable"), o = i.options, scrolled = false; - - if(i.scrollParent[0] !== document && i.scrollParent[0].tagName !== "HTML") { - - if(!o.axis || o.axis !== "x") { - if((i.overflowOffset.top + i.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity) { - i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop + o.scrollSpeed; - } else if(event.pageY - i.overflowOffset.top < o.scrollSensitivity) { - i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop - o.scrollSpeed; - } - } - - if(!o.axis || o.axis !== "y") { - if((i.overflowOffset.left + i.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity) { - i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft + o.scrollSpeed; - } else if(event.pageX - i.overflowOffset.left < o.scrollSensitivity) { - i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft - o.scrollSpeed; - } - } - - } else { - - if(!o.axis || o.axis !== "x") { - if(event.pageY - $(document).scrollTop() < o.scrollSensitivity) { - scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed); - } else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity) { - scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed); - } - } - - if(!o.axis || o.axis !== "y") { - if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity) { - scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed); - } else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity) { - scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed); - } - } - - } - - if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) { - $.ui.ddmanager.prepareOffsets(i, event); - } - - } -}); - -$.ui.plugin.add("draggable", "snap", { - start: function() { - - var i = $(this).data("ui-draggable"), - o = i.options; - - i.snapElements = []; - - $(o.snap.constructor !== String ? ( o.snap.items || ":data(ui-draggable)" ) : o.snap).each(function() { - var $t = $(this), - $o = $t.offset(); - if(this !== i.element[0]) { - i.snapElements.push({ - item: this, - width: $t.outerWidth(), height: $t.outerHeight(), - top: $o.top, left: $o.left - }); - } - }); - - }, - drag: function(event, ui) { - - var ts, bs, ls, rs, l, r, t, b, i, first, - inst = $(this).data("ui-draggable"), - o = inst.options, - d = o.snapTolerance, - x1 = ui.offset.left, x2 = x1 + inst.helperProportions.width, - y1 = ui.offset.top, y2 = y1 + inst.helperProportions.height; - - for (i = inst.snapElements.length - 1; i >= 0; i--){ - - l = inst.snapElements[i].left; - r = l + inst.snapElements[i].width; - t = inst.snapElements[i].top; - b = t + inst.snapElements[i].height; - - if ( x2 < l - d || x1 > r + d || y2 < t - d || y1 > b + d || !$.contains( inst.snapElements[ i ].item.ownerDocument, inst.snapElements[ i ].item ) ) { - if(inst.snapElements[i].snapping) { - (inst.options.snap.release && inst.options.snap.release.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item }))); - } - inst.snapElements[i].snapping = false; - continue; - } - - if(o.snapMode !== "inner") { - ts = Math.abs(t - y2) <= d; - bs = Math.abs(b - y1) <= d; - ls = Math.abs(l - x2) <= d; - rs = Math.abs(r - x1) <= d; - if(ts) { - ui.position.top = inst._convertPositionTo("relative", { top: t - inst.helperProportions.height, left: 0 }).top - inst.margins.top; - } - if(bs) { - ui.position.top = inst._convertPositionTo("relative", { top: b, left: 0 }).top - inst.margins.top; - } - if(ls) { - ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l - inst.helperProportions.width }).left - inst.margins.left; - } - if(rs) { - ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r }).left - inst.margins.left; - } - } - - first = (ts || bs || ls || rs); - - if(o.snapMode !== "outer") { - ts = Math.abs(t - y1) <= d; - bs = Math.abs(b - y2) <= d; - ls = Math.abs(l - x1) <= d; - rs = Math.abs(r - x2) <= d; - if(ts) { - ui.position.top = inst._convertPositionTo("relative", { top: t, left: 0 }).top - inst.margins.top; - } - if(bs) { - ui.position.top = inst._convertPositionTo("relative", { top: b - inst.helperProportions.height, left: 0 }).top - inst.margins.top; - } - if(ls) { - ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l }).left - inst.margins.left; - } - if(rs) { - ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r - inst.helperProportions.width }).left - inst.margins.left; - } - } - - if(!inst.snapElements[i].snapping && (ts || bs || ls || rs || first)) { - (inst.options.snap.snap && inst.options.snap.snap.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item }))); - } - inst.snapElements[i].snapping = (ts || bs || ls || rs || first); - - } - - } -}); - -$.ui.plugin.add("draggable", "stack", { - start: function() { - var min, - o = this.data("ui-draggable").options, - group = $.makeArray($(o.stack)).sort(function(a,b) { - return (parseInt($(a).css("zIndex"),10) || 0) - (parseInt($(b).css("zIndex"),10) || 0); - }); - - if (!group.length) { return; } - - min = parseInt($(group[0]).css("zIndex"), 10) || 0; - $(group).each(function(i) { - $(this).css("zIndex", min + i); - }); - this.css("zIndex", (min + group.length)); - } -}); - -$.ui.plugin.add("draggable", "zIndex", { - start: function(event, ui) { - var t = $(ui.helper), o = $(this).data("ui-draggable").options; - if(t.css("zIndex")) { - o._zIndex = t.css("zIndex"); - } - t.css("zIndex", o.zIndex); - }, - stop: function(event, ui) { - var o = $(this).data("ui-draggable").options; - if(o._zIndex) { - $(ui.helper).css("zIndex", o._zIndex); - } - } -}); - -})(jQuery); - -(function( $, undefined ) { - -function isOverAxis( x, reference, size ) { - return ( x > reference ) && ( x < ( reference + size ) ); -} - -$.widget("ui.droppable", { - version: "1.10.3", - widgetEventPrefix: "drop", - options: { - accept: "*", - activeClass: false, - addClasses: true, - greedy: false, - hoverClass: false, - scope: "default", - tolerance: "intersect", - - // callbacks - activate: null, - deactivate: null, - drop: null, - out: null, - over: null - }, - _create: function() { - - var o = this.options, - accept = o.accept; - - this.isover = false; - this.isout = true; - - this.accept = $.isFunction(accept) ? accept : function(d) { - return d.is(accept); - }; - - //Store the droppable's proportions - this.proportions = { width: this.element[0].offsetWidth, height: this.element[0].offsetHeight }; - - // Add the reference and positions to the manager - $.ui.ddmanager.droppables[o.scope] = $.ui.ddmanager.droppables[o.scope] || []; - $.ui.ddmanager.droppables[o.scope].push(this); - - (o.addClasses && this.element.addClass("ui-droppable")); - - }, - - _destroy: function() { - var i = 0, - drop = $.ui.ddmanager.droppables[this.options.scope]; - - for ( ; i < drop.length; i++ ) { - if ( drop[i] === this ) { - drop.splice(i, 1); - } - } - - this.element.removeClass("ui-droppable ui-droppable-disabled"); - }, - - _setOption: function(key, value) { - - if(key === "accept") { - this.accept = $.isFunction(value) ? value : function(d) { - return d.is(value); - }; - } - $.Widget.prototype._setOption.apply(this, arguments); - }, - - _activate: function(event) { - var draggable = $.ui.ddmanager.current; - if(this.options.activeClass) { - this.element.addClass(this.options.activeClass); - } - if(draggable){ - this._trigger("activate", event, this.ui(draggable)); - } - }, - - _deactivate: function(event) { - var draggable = $.ui.ddmanager.current; - if(this.options.activeClass) { - this.element.removeClass(this.options.activeClass); - } - if(draggable){ - this._trigger("deactivate", event, this.ui(draggable)); - } - }, - - _over: function(event) { - - var draggable = $.ui.ddmanager.current; - - // Bail if draggable and droppable are same element - if (!draggable || (draggable.currentItem || draggable.element)[0] === this.element[0]) { - return; - } - - if (this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) { - if(this.options.hoverClass) { - this.element.addClass(this.options.hoverClass); - } - this._trigger("over", event, this.ui(draggable)); - } - - }, - - _out: function(event) { - - var draggable = $.ui.ddmanager.current; - - // Bail if draggable and droppable are same element - if (!draggable || (draggable.currentItem || draggable.element)[0] === this.element[0]) { - return; - } - - if (this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) { - if(this.options.hoverClass) { - this.element.removeClass(this.options.hoverClass); - } - this._trigger("out", event, this.ui(draggable)); - } - - }, - - _drop: function(event,custom) { - - var draggable = custom || $.ui.ddmanager.current, - childrenIntersection = false; - - // Bail if draggable and droppable are same element - if (!draggable || (draggable.currentItem || draggable.element)[0] === this.element[0]) { - return false; - } - - this.element.find(":data(ui-droppable)").not(".ui-draggable-dragging").each(function() { - var inst = $.data(this, "ui-droppable"); - if( - inst.options.greedy && - !inst.options.disabled && - inst.options.scope === draggable.options.scope && - inst.accept.call(inst.element[0], (draggable.currentItem || draggable.element)) && - $.ui.intersect(draggable, $.extend(inst, { offset: inst.element.offset() }), inst.options.tolerance) - ) { childrenIntersection = true; return false; } - }); - if(childrenIntersection) { - return false; - } - - if(this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) { - if(this.options.activeClass) { - this.element.removeClass(this.options.activeClass); - } - if(this.options.hoverClass) { - this.element.removeClass(this.options.hoverClass); - } - this._trigger("drop", event, this.ui(draggable)); - return this.element; - } - - return false; - - }, - - ui: function(c) { - return { - draggable: (c.currentItem || c.element), - helper: c.helper, - position: c.position, - offset: c.positionAbs - }; - } - -}); - -$.ui.intersect = function(draggable, droppable, toleranceMode) { - - if (!droppable.offset) { - return false; - } - - var draggableLeft, draggableTop, - x1 = (draggable.positionAbs || draggable.position.absolute).left, x2 = x1 + draggable.helperProportions.width, - y1 = (draggable.positionAbs || draggable.position.absolute).top, y2 = y1 + draggable.helperProportions.height, - l = droppable.offset.left, r = l + droppable.proportions.width, - t = droppable.offset.top, b = t + droppable.proportions.height; - - switch (toleranceMode) { - case "fit": - return (l <= x1 && x2 <= r && t <= y1 && y2 <= b); - case "intersect": - return (l < x1 + (draggable.helperProportions.width / 2) && // Right Half - x2 - (draggable.helperProportions.width / 2) < r && // Left Half - t < y1 + (draggable.helperProportions.height / 2) && // Bottom Half - y2 - (draggable.helperProportions.height / 2) < b ); // Top Half - case "pointer": - draggableLeft = ((draggable.positionAbs || draggable.position.absolute).left + (draggable.clickOffset || draggable.offset.click).left); - draggableTop = ((draggable.positionAbs || draggable.position.absolute).top + (draggable.clickOffset || draggable.offset.click).top); - return isOverAxis( draggableTop, t, droppable.proportions.height ) && isOverAxis( draggableLeft, l, droppable.proportions.width ); - case "touch": - return ( - (y1 >= t && y1 <= b) || // Top edge touching - (y2 >= t && y2 <= b) || // Bottom edge touching - (y1 < t && y2 > b) // Surrounded vertically - ) && ( - (x1 >= l && x1 <= r) || // Left edge touching - (x2 >= l && x2 <= r) || // Right edge touching - (x1 < l && x2 > r) // Surrounded horizontally - ); - default: - return false; - } - -}; - -/* - This manager tracks offsets of draggables and droppables -*/ -$.ui.ddmanager = { - current: null, - droppables: { "default": [] }, - prepareOffsets: function(t, event) { - - var i, j, - m = $.ui.ddmanager.droppables[t.options.scope] || [], - type = event ? event.type : null, // workaround for #2317 - list = (t.currentItem || t.element).find(":data(ui-droppable)").addBack(); - - droppablesLoop: for (i = 0; i < m.length; i++) { - - //No disabled and non-accepted - if(m[i].options.disabled || (t && !m[i].accept.call(m[i].element[0],(t.currentItem || t.element)))) { - continue; - } - - // Filter out elements in the current dragged item - for (j=0; j < list.length; j++) { - if(list[j] === m[i].element[0]) { - m[i].proportions.height = 0; - continue droppablesLoop; - } - } - - m[i].visible = m[i].element.css("display") !== "none"; - if(!m[i].visible) { - continue; - } - - //Activate the droppable if used directly from draggables - if(type === "mousedown") { - m[i]._activate.call(m[i], event); - } - - m[i].offset = m[i].element.offset(); - m[i].proportions = { width: m[i].element[0].offsetWidth, height: m[i].element[0].offsetHeight }; - - } - - }, - drop: function(draggable, event) { - - var dropped = false; - // Create a copy of the droppables in case the list changes during the drop (#9116) - $.each(($.ui.ddmanager.droppables[draggable.options.scope] || []).slice(), function() { - - if(!this.options) { - return; - } - if (!this.options.disabled && this.visible && $.ui.intersect(draggable, this, this.options.tolerance)) { - dropped = this._drop.call(this, event) || dropped; - } - - if (!this.options.disabled && this.visible && this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) { - this.isout = true; - this.isover = false; - this._deactivate.call(this, event); - } - - }); - return dropped; - - }, - dragStart: function( draggable, event ) { - //Listen for scrolling so that if the dragging causes scrolling the position of the droppables can be recalculated (see #5003) - draggable.element.parentsUntil( "body" ).bind( "scroll.droppable", function() { - if( !draggable.options.refreshPositions ) { - $.ui.ddmanager.prepareOffsets( draggable, event ); - } - }); - }, - drag: function(draggable, event) { - - //If you have a highly dynamic page, you might try this option. It renders positions every time you move the mouse. - if(draggable.options.refreshPositions) { - $.ui.ddmanager.prepareOffsets(draggable, event); - } - - //Run through all droppables and check their positions based on specific tolerance options - $.each($.ui.ddmanager.droppables[draggable.options.scope] || [], function() { - - if(this.options.disabled || this.greedyChild || !this.visible) { - return; - } - - var parentInstance, scope, parent, - intersects = $.ui.intersect(draggable, this, this.options.tolerance), - c = !intersects && this.isover ? "isout" : (intersects && !this.isover ? "isover" : null); - if(!c) { - return; - } - - if (this.options.greedy) { - // find droppable parents with same scope - scope = this.options.scope; - parent = this.element.parents(":data(ui-droppable)").filter(function () { - return $.data(this, "ui-droppable").options.scope === scope; - }); - - if (parent.length) { - parentInstance = $.data(parent[0], "ui-droppable"); - parentInstance.greedyChild = (c === "isover"); - } - } - - // we just moved into a greedy child - if (parentInstance && c === "isover") { - parentInstance.isover = false; - parentInstance.isout = true; - parentInstance._out.call(parentInstance, event); - } - - this[c] = true; - this[c === "isout" ? "isover" : "isout"] = false; - this[c === "isover" ? "_over" : "_out"].call(this, event); - - // we just moved out of a greedy child - if (parentInstance && c === "isout") { - parentInstance.isout = false; - parentInstance.isover = true; - parentInstance._over.call(parentInstance, event); - } - }); - - }, - dragStop: function( draggable, event ) { - draggable.element.parentsUntil( "body" ).unbind( "scroll.droppable" ); - //Call prepareOffsets one final time since IE does not fire return scroll events when overflow was caused by drag (see #5003) - if( !draggable.options.refreshPositions ) { - $.ui.ddmanager.prepareOffsets( draggable, event ); - } - } -}; - -})(jQuery); - -(function( $, undefined ) { - -function num(v) { - return parseInt(v, 10) || 0; -} - -function isNumber(value) { - return !isNaN(parseInt(value, 10)); -} - -$.widget("ui.resizable", $.ui.mouse, { - version: "1.10.3", - widgetEventPrefix: "resize", - options: { - alsoResize: false, - animate: false, - animateDuration: "slow", - animateEasing: "swing", - aspectRatio: false, - autoHide: false, - containment: false, - ghost: false, - grid: false, - handles: "e,s,se", - helper: false, - maxHeight: null, - maxWidth: null, - minHeight: 10, - minWidth: 10, - // See #7960 - zIndex: 90, - - // callbacks - resize: null, - start: null, - stop: null - }, - _create: function() { - - var n, i, handle, axis, hname, - that = this, - o = this.options; - this.element.addClass("ui-resizable"); - - $.extend(this, { - _aspectRatio: !!(o.aspectRatio), - aspectRatio: o.aspectRatio, - originalElement: this.element, - _proportionallyResizeElements: [], - _helper: o.helper || o.ghost || o.animate ? o.helper || "ui-resizable-helper" : null - }); - - //Wrap the element if it cannot hold child nodes - if(this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)) { - - //Create a wrapper element and set the wrapper to the new current internal element - this.element.wrap( - $("<div class='ui-wrapper' style='overflow: hidden;'></div>").css({ - position: this.element.css("position"), - width: this.element.outerWidth(), - height: this.element.outerHeight(), - top: this.element.css("top"), - left: this.element.css("left") - }) - ); - - //Overwrite the original this.element - this.element = this.element.parent().data( - "ui-resizable", this.element.data("ui-resizable") - ); - - this.elementIsWrapper = true; - - //Move margins to the wrapper - this.element.css({ marginLeft: this.originalElement.css("marginLeft"), marginTop: this.originalElement.css("marginTop"), marginRight: this.originalElement.css("marginRight"), marginBottom: this.originalElement.css("marginBottom") }); - this.originalElement.css({ marginLeft: 0, marginTop: 0, marginRight: 0, marginBottom: 0}); - - //Prevent Safari textarea resize - this.originalResizeStyle = this.originalElement.css("resize"); - this.originalElement.css("resize", "none"); - - //Push the actual element to our proportionallyResize internal array - this._proportionallyResizeElements.push(this.originalElement.css({ position: "static", zoom: 1, display: "block" })); - - // avoid IE jump (hard set the margin) - this.originalElement.css({ margin: this.originalElement.css("margin") }); - - // fix handlers offset - this._proportionallyResize(); - - } - - this.handles = o.handles || (!$(".ui-resizable-handle", this.element).length ? "e,s,se" : { n: ".ui-resizable-n", e: ".ui-resizable-e", s: ".ui-resizable-s", w: ".ui-resizable-w", se: ".ui-resizable-se", sw: ".ui-resizable-sw", ne: ".ui-resizable-ne", nw: ".ui-resizable-nw" }); - if(this.handles.constructor === String) { - - if ( this.handles === "all") { - this.handles = "n,e,s,w,se,sw,ne,nw"; - } - - n = this.handles.split(","); - this.handles = {}; - - for(i = 0; i < n.length; i++) { - - handle = $.trim(n[i]); - hname = "ui-resizable-"+handle; - axis = $("<div class='ui-resizable-handle " + hname + "'></div>"); - - // Apply zIndex to all handles - see #7960 - axis.css({ zIndex: o.zIndex }); - - //TODO : What's going on here? - if ("se" === handle) { - axis.addClass("ui-icon ui-icon-gripsmall-diagonal-se"); - } - - //Insert into internal handles object and append to element - this.handles[handle] = ".ui-resizable-"+handle; - this.element.append(axis); - } - - } - - this._renderAxis = function(target) { - - var i, axis, padPos, padWrapper; - - target = target || this.element; - - for(i in this.handles) { - - if(this.handles[i].constructor === String) { - this.handles[i] = $(this.handles[i], this.element).show(); - } - - //Apply pad to wrapper element, needed to fix axis position (textarea, inputs, scrolls) - if (this.elementIsWrapper && this.originalElement[0].nodeName.match(/textarea|input|select|button/i)) { - - axis = $(this.handles[i], this.element); - - //Checking the correct pad and border - padWrapper = /sw|ne|nw|se|n|s/.test(i) ? axis.outerHeight() : axis.outerWidth(); - - //The padding type i have to apply... - padPos = [ "padding", - /ne|nw|n/.test(i) ? "Top" : - /se|sw|s/.test(i) ? "Bottom" : - /^e$/.test(i) ? "Right" : "Left" ].join(""); - - target.css(padPos, padWrapper); - - this._proportionallyResize(); - - } - - //TODO: What's that good for? There's not anything to be executed left - if(!$(this.handles[i]).length) { - continue; - } - } - }; - - //TODO: make renderAxis a prototype function - this._renderAxis(this.element); - - this._handles = $(".ui-resizable-handle", this.element) - .disableSelection(); - - //Matching axis name - this._handles.mouseover(function() { - if (!that.resizing) { - if (this.className) { - axis = this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i); - } - //Axis, default = se - that.axis = axis && axis[1] ? axis[1] : "se"; - } - }); - - //If we want to auto hide the elements - if (o.autoHide) { - this._handles.hide(); - $(this.element) - .addClass("ui-resizable-autohide") - .mouseenter(function() { - if (o.disabled) { - return; - } - $(this).removeClass("ui-resizable-autohide"); - that._handles.show(); - }) - .mouseleave(function(){ - if (o.disabled) { - return; - } - if (!that.resizing) { - $(this).addClass("ui-resizable-autohide"); - that._handles.hide(); - } - }); - } - - //Initialize the mouse interaction - this._mouseInit(); - - }, - - _destroy: function() { - - this._mouseDestroy(); - - var wrapper, - _destroy = function(exp) { - $(exp).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing") - .removeData("resizable").removeData("ui-resizable").unbind(".resizable").find(".ui-resizable-handle").remove(); - }; - - //TODO: Unwrap at same DOM position - if (this.elementIsWrapper) { - _destroy(this.element); - wrapper = this.element; - this.originalElement.css({ - position: wrapper.css("position"), - width: wrapper.outerWidth(), - height: wrapper.outerHeight(), - top: wrapper.css("top"), - left: wrapper.css("left") - }).insertAfter( wrapper ); - wrapper.remove(); - } - - this.originalElement.css("resize", this.originalResizeStyle); - _destroy(this.originalElement); - - return this; - }, - - _mouseCapture: function(event) { - var i, handle, - capture = false; - - for (i in this.handles) { - handle = $(this.handles[i])[0]; - if (handle === event.target || $.contains(handle, event.target)) { - capture = true; - } - } - - return !this.options.disabled && capture; - }, - - _mouseStart: function(event) { - - var curleft, curtop, cursor, - o = this.options, - iniPos = this.element.position(), - el = this.element; - - this.resizing = true; - - // bugfix for http://dev.jquery.com/ticket/1749 - if ( (/absolute/).test( el.css("position") ) ) { - el.css({ position: "absolute", top: el.css("top"), left: el.css("left") }); - } else if (el.is(".ui-draggable")) { - el.css({ position: "absolute", top: iniPos.top, left: iniPos.left }); - } - - this._renderProxy(); - - curleft = num(this.helper.css("left")); - curtop = num(this.helper.css("top")); - - if (o.containment) { - curleft += $(o.containment).scrollLeft() || 0; - curtop += $(o.containment).scrollTop() || 0; - } - - //Store needed variables - this.offset = this.helper.offset(); - this.position = { left: curleft, top: curtop }; - this.size = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() }; - this.originalSize = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() }; - this.originalPosition = { left: curleft, top: curtop }; - this.sizeDiff = { width: el.outerWidth() - el.width(), height: el.outerHeight() - el.height() }; - this.originalMousePosition = { left: event.pageX, top: event.pageY }; - - //Aspect Ratio - this.aspectRatio = (typeof o.aspectRatio === "number") ? o.aspectRatio : ((this.originalSize.width / this.originalSize.height) || 1); - - cursor = $(".ui-resizable-" + this.axis).css("cursor"); - $("body").css("cursor", cursor === "auto" ? this.axis + "-resize" : cursor); - - el.addClass("ui-resizable-resizing"); - this._propagate("start", event); - return true; - }, - - _mouseDrag: function(event) { - - //Increase performance, avoid regex - var data, - el = this.helper, props = {}, - smp = this.originalMousePosition, - a = this.axis, - prevTop = this.position.top, - prevLeft = this.position.left, - prevWidth = this.size.width, - prevHeight = this.size.height, - dx = (event.pageX-smp.left)||0, - dy = (event.pageY-smp.top)||0, - trigger = this._change[a]; - - if (!trigger) { - return false; - } - - // Calculate the attrs that will be change - data = trigger.apply(this, [event, dx, dy]); - - // Put this in the mouseDrag handler since the user can start pressing shift while resizing - this._updateVirtualBoundaries(event.shiftKey); - if (this._aspectRatio || event.shiftKey) { - data = this._updateRatio(data, event); - } - - data = this._respectSize(data, event); - - this._updateCache(data); - - // plugins callbacks need to be called first - this._propagate("resize", event); - - if (this.position.top !== prevTop) { - props.top = this.position.top + "px"; - } - if (this.position.left !== prevLeft) { - props.left = this.position.left + "px"; - } - if (this.size.width !== prevWidth) { - props.width = this.size.width + "px"; - } - if (this.size.height !== prevHeight) { - props.height = this.size.height + "px"; - } - el.css(props); - - if (!this._helper && this._proportionallyResizeElements.length) { - this._proportionallyResize(); - } - - // Call the user callback if the element was resized - if ( ! $.isEmptyObject(props) ) { - this._trigger("resize", event, this.ui()); - } - - return false; - }, - - _mouseStop: function(event) { - - this.resizing = false; - var pr, ista, soffseth, soffsetw, s, left, top, - o = this.options, that = this; - - if(this._helper) { - - pr = this._proportionallyResizeElements; - ista = pr.length && (/textarea/i).test(pr[0].nodeName); - soffseth = ista && $.ui.hasScroll(pr[0], "left") /* TODO - jump height */ ? 0 : that.sizeDiff.height; - soffsetw = ista ? 0 : that.sizeDiff.width; - - s = { width: (that.helper.width() - soffsetw), height: (that.helper.height() - soffseth) }; - left = (parseInt(that.element.css("left"), 10) + (that.position.left - that.originalPosition.left)) || null; - top = (parseInt(that.element.css("top"), 10) + (that.position.top - that.originalPosition.top)) || null; - - if (!o.animate) { - this.element.css($.extend(s, { top: top, left: left })); - } - - that.helper.height(that.size.height); - that.helper.width(that.size.width); - - if (this._helper && !o.animate) { - this._proportionallyResize(); - } - } - - $("body").css("cursor", "auto"); - - this.element.removeClass("ui-resizable-resizing"); - - this._propagate("stop", event); - - if (this._helper) { - this.helper.remove(); - } - - return false; - - }, - - _updateVirtualBoundaries: function(forceAspectRatio) { - var pMinWidth, pMaxWidth, pMinHeight, pMaxHeight, b, - o = this.options; - - b = { - minWidth: isNumber(o.minWidth) ? o.minWidth : 0, - maxWidth: isNumber(o.maxWidth) ? o.maxWidth : Infinity, - minHeight: isNumber(o.minHeight) ? o.minHeight : 0, - maxHeight: isNumber(o.maxHeight) ? o.maxHeight : Infinity - }; - - if(this._aspectRatio || forceAspectRatio) { - // We want to create an enclosing box whose aspect ration is the requested one - // First, compute the "projected" size for each dimension based on the aspect ratio and other dimension - pMinWidth = b.minHeight * this.aspectRatio; - pMinHeight = b.minWidth / this.aspectRatio; - pMaxWidth = b.maxHeight * this.aspectRatio; - pMaxHeight = b.maxWidth / this.aspectRatio; - - if(pMinWidth > b.minWidth) { - b.minWidth = pMinWidth; - } - if(pMinHeight > b.minHeight) { - b.minHeight = pMinHeight; - } - if(pMaxWidth < b.maxWidth) { - b.maxWidth = pMaxWidth; - } - if(pMaxHeight < b.maxHeight) { - b.maxHeight = pMaxHeight; - } - } - this._vBoundaries = b; - }, - - _updateCache: function(data) { - this.offset = this.helper.offset(); - if (isNumber(data.left)) { - this.position.left = data.left; - } - if (isNumber(data.top)) { - this.position.top = data.top; - } - if (isNumber(data.height)) { - this.size.height = data.height; - } - if (isNumber(data.width)) { - this.size.width = data.width; - } - }, - - _updateRatio: function( data ) { - - var cpos = this.position, - csize = this.size, - a = this.axis; - - if (isNumber(data.height)) { - data.width = (data.height * this.aspectRatio); - } else if (isNumber(data.width)) { - data.height = (data.width / this.aspectRatio); - } - - if (a === "sw") { - data.left = cpos.left + (csize.width - data.width); - data.top = null; - } - if (a === "nw") { - data.top = cpos.top + (csize.height - data.height); - data.left = cpos.left + (csize.width - data.width); - } - - return data; - }, - - _respectSize: function( data ) { - - var o = this._vBoundaries, - a = this.axis, - ismaxw = isNumber(data.width) && o.maxWidth && (o.maxWidth < data.width), ismaxh = isNumber(data.height) && o.maxHeight && (o.maxHeight < data.height), - isminw = isNumber(data.width) && o.minWidth && (o.minWidth > data.width), isminh = isNumber(data.height) && o.minHeight && (o.minHeight > data.height), - dw = this.originalPosition.left + this.originalSize.width, - dh = this.position.top + this.size.height, - cw = /sw|nw|w/.test(a), ch = /nw|ne|n/.test(a); - if (isminw) { - data.width = o.minWidth; - } - if (isminh) { - data.height = o.minHeight; - } - if (ismaxw) { - data.width = o.maxWidth; - } - if (ismaxh) { - data.height = o.maxHeight; - } - - if (isminw && cw) { - data.left = dw - o.minWidth; - } - if (ismaxw && cw) { - data.left = dw - o.maxWidth; - } - if (isminh && ch) { - data.top = dh - o.minHeight; - } - if (ismaxh && ch) { - data.top = dh - o.maxHeight; - } - - // fixing jump error on top/left - bug #2330 - if (!data.width && !data.height && !data.left && data.top) { - data.top = null; - } else if (!data.width && !data.height && !data.top && data.left) { - data.left = null; - } - - return data; - }, - - _proportionallyResize: function() { - - if (!this._proportionallyResizeElements.length) { - return; - } - - var i, j, borders, paddings, prel, - element = this.helper || this.element; - - for ( i=0; i < this._proportionallyResizeElements.length; i++) { - - prel = this._proportionallyResizeElements[i]; - - if (!this.borderDif) { - this.borderDif = []; - borders = [prel.css("borderTopWidth"), prel.css("borderRightWidth"), prel.css("borderBottomWidth"), prel.css("borderLeftWidth")]; - paddings = [prel.css("paddingTop"), prel.css("paddingRight"), prel.css("paddingBottom"), prel.css("paddingLeft")]; - - for ( j = 0; j < borders.length; j++ ) { - this.borderDif[ j ] = ( parseInt( borders[ j ], 10 ) || 0 ) + ( parseInt( paddings[ j ], 10 ) || 0 ); - } - } - - prel.css({ - height: (element.height() - this.borderDif[0] - this.borderDif[2]) || 0, - width: (element.width() - this.borderDif[1] - this.borderDif[3]) || 0 - }); - - } - - }, - - _renderProxy: function() { - - var el = this.element, o = this.options; - this.elementOffset = el.offset(); - - if(this._helper) { - - this.helper = this.helper || $("<div style='overflow:hidden;'></div>"); - - this.helper.addClass(this._helper).css({ - width: this.element.outerWidth() - 1, - height: this.element.outerHeight() - 1, - position: "absolute", - left: this.elementOffset.left +"px", - top: this.elementOffset.top +"px", - zIndex: ++o.zIndex //TODO: Don't modify option - }); - - this.helper - .appendTo("body") - .disableSelection(); - - } else { - this.helper = this.element; - } - - }, - - _change: { - e: function(event, dx) { - return { width: this.originalSize.width + dx }; - }, - w: function(event, dx) { - var cs = this.originalSize, sp = this.originalPosition; - return { left: sp.left + dx, width: cs.width - dx }; - }, - n: function(event, dx, dy) { - var cs = this.originalSize, sp = this.originalPosition; - return { top: sp.top + dy, height: cs.height - dy }; - }, - s: function(event, dx, dy) { - return { height: this.originalSize.height + dy }; - }, - se: function(event, dx, dy) { - return $.extend(this._change.s.apply(this, arguments), this._change.e.apply(this, [event, dx, dy])); - }, - sw: function(event, dx, dy) { - return $.extend(this._change.s.apply(this, arguments), this._change.w.apply(this, [event, dx, dy])); - }, - ne: function(event, dx, dy) { - return $.extend(this._change.n.apply(this, arguments), this._change.e.apply(this, [event, dx, dy])); - }, - nw: function(event, dx, dy) { - return $.extend(this._change.n.apply(this, arguments), this._change.w.apply(this, [event, dx, dy])); - } - }, - - _propagate: function(n, event) { - $.ui.plugin.call(this, n, [event, this.ui()]); - (n !== "resize" && this._trigger(n, event, this.ui())); - }, - - plugins: {}, - - ui: function() { - return { - originalElement: this.originalElement, - element: this.element, - helper: this.helper, - position: this.position, - size: this.size, - originalSize: this.originalSize, - originalPosition: this.originalPosition - }; - } - -}); - -/* - * Resizable Extensions - */ - -$.ui.plugin.add("resizable", "animate", { - - stop: function( event ) { - var that = $(this).data("ui-resizable"), - o = that.options, - pr = that._proportionallyResizeElements, - ista = pr.length && (/textarea/i).test(pr[0].nodeName), - soffseth = ista && $.ui.hasScroll(pr[0], "left") /* TODO - jump height */ ? 0 : that.sizeDiff.height, - soffsetw = ista ? 0 : that.sizeDiff.width, - style = { width: (that.size.width - soffsetw), height: (that.size.height - soffseth) }, - left = (parseInt(that.element.css("left"), 10) + (that.position.left - that.originalPosition.left)) || null, - top = (parseInt(that.element.css("top"), 10) + (that.position.top - that.originalPosition.top)) || null; - - that.element.animate( - $.extend(style, top && left ? { top: top, left: left } : {}), { - duration: o.animateDuration, - easing: o.animateEasing, - step: function() { - - var data = { - width: parseInt(that.element.css("width"), 10), - height: parseInt(that.element.css("height"), 10), - top: parseInt(that.element.css("top"), 10), - left: parseInt(that.element.css("left"), 10) - }; - - if (pr && pr.length) { - $(pr[0]).css({ width: data.width, height: data.height }); - } - - // propagating resize, and updating values for each animation step - that._updateCache(data); - that._propagate("resize", event); - - } - } - ); - } - -}); - -$.ui.plugin.add("resizable", "containment", { - - start: function() { - var element, p, co, ch, cw, width, height, - that = $(this).data("ui-resizable"), - o = that.options, - el = that.element, - oc = o.containment, - ce = (oc instanceof $) ? oc.get(0) : (/parent/.test(oc)) ? el.parent().get(0) : oc; - - if (!ce) { - return; - } - - that.containerElement = $(ce); - - if (/document/.test(oc) || oc === document) { - that.containerOffset = { left: 0, top: 0 }; - that.containerPosition = { left: 0, top: 0 }; - - that.parentData = { - element: $(document), left: 0, top: 0, - width: $(document).width(), height: $(document).height() || document.body.parentNode.scrollHeight - }; - } - - // i'm a node, so compute top, left, right, bottom - else { - element = $(ce); - p = []; - $([ "Top", "Right", "Left", "Bottom" ]).each(function(i, name) { p[i] = num(element.css("padding" + name)); }); - - that.containerOffset = element.offset(); - that.containerPosition = element.position(); - that.containerSize = { height: (element.innerHeight() - p[3]), width: (element.innerWidth() - p[1]) }; - - co = that.containerOffset; - ch = that.containerSize.height; - cw = that.containerSize.width; - width = ($.ui.hasScroll(ce, "left") ? ce.scrollWidth : cw ); - height = ($.ui.hasScroll(ce) ? ce.scrollHeight : ch); - - that.parentData = { - element: ce, left: co.left, top: co.top, width: width, height: height - }; - } - }, - - resize: function( event ) { - var woset, hoset, isParent, isOffsetRelative, - that = $(this).data("ui-resizable"), - o = that.options, - co = that.containerOffset, cp = that.position, - pRatio = that._aspectRatio || event.shiftKey, - cop = { top:0, left:0 }, ce = that.containerElement; - - if (ce[0] !== document && (/static/).test(ce.css("position"))) { - cop = co; - } - - if (cp.left < (that._helper ? co.left : 0)) { - that.size.width = that.size.width + (that._helper ? (that.position.left - co.left) : (that.position.left - cop.left)); - if (pRatio) { - that.size.height = that.size.width / that.aspectRatio; - } - that.position.left = o.helper ? co.left : 0; - } - - if (cp.top < (that._helper ? co.top : 0)) { - that.size.height = that.size.height + (that._helper ? (that.position.top - co.top) : that.position.top); - if (pRatio) { - that.size.width = that.size.height * that.aspectRatio; - } - that.position.top = that._helper ? co.top : 0; - } - - that.offset.left = that.parentData.left+that.position.left; - that.offset.top = that.parentData.top+that.position.top; - - woset = Math.abs( (that._helper ? that.offset.left - cop.left : (that.offset.left - cop.left)) + that.sizeDiff.width ); - hoset = Math.abs( (that._helper ? that.offset.top - cop.top : (that.offset.top - co.top)) + that.sizeDiff.height ); - - isParent = that.containerElement.get(0) === that.element.parent().get(0); - isOffsetRelative = /relative|absolute/.test(that.containerElement.css("position")); - - if(isParent && isOffsetRelative) { - woset -= that.parentData.left; - } - - if (woset + that.size.width >= that.parentData.width) { - that.size.width = that.parentData.width - woset; - if (pRatio) { - that.size.height = that.size.width / that.aspectRatio; - } - } - - if (hoset + that.size.height >= that.parentData.height) { - that.size.height = that.parentData.height - hoset; - if (pRatio) { - that.size.width = that.size.height * that.aspectRatio; - } - } - }, - - stop: function(){ - var that = $(this).data("ui-resizable"), - o = that.options, - co = that.containerOffset, - cop = that.containerPosition, - ce = that.containerElement, - helper = $(that.helper), - ho = helper.offset(), - w = helper.outerWidth() - that.sizeDiff.width, - h = helper.outerHeight() - that.sizeDiff.height; - - if (that._helper && !o.animate && (/relative/).test(ce.css("position"))) { - $(this).css({ left: ho.left - cop.left - co.left, width: w, height: h }); - } - - if (that._helper && !o.animate && (/static/).test(ce.css("position"))) { - $(this).css({ left: ho.left - cop.left - co.left, width: w, height: h }); - } - - } -}); - -$.ui.plugin.add("resizable", "alsoResize", { - - start: function () { - var that = $(this).data("ui-resizable"), - o = that.options, - _store = function (exp) { - $(exp).each(function() { - var el = $(this); - el.data("ui-resizable-alsoresize", { - width: parseInt(el.width(), 10), height: parseInt(el.height(), 10), - left: parseInt(el.css("left"), 10), top: parseInt(el.css("top"), 10) - }); - }); - }; - - if (typeof(o.alsoResize) === "object" && !o.alsoResize.parentNode) { - if (o.alsoResize.length) { o.alsoResize = o.alsoResize[0]; _store(o.alsoResize); } - else { $.each(o.alsoResize, function (exp) { _store(exp); }); } - }else{ - _store(o.alsoResize); - } - }, - - resize: function (event, ui) { - var that = $(this).data("ui-resizable"), - o = that.options, - os = that.originalSize, - op = that.originalPosition, - delta = { - height: (that.size.height - os.height) || 0, width: (that.size.width - os.width) || 0, - top: (that.position.top - op.top) || 0, left: (that.position.left - op.left) || 0 - }, - - _alsoResize = function (exp, c) { - $(exp).each(function() { - var el = $(this), start = $(this).data("ui-resizable-alsoresize"), style = {}, - css = c && c.length ? c : el.parents(ui.originalElement[0]).length ? ["width", "height"] : ["width", "height", "top", "left"]; - - $.each(css, function (i, prop) { - var sum = (start[prop]||0) + (delta[prop]||0); - if (sum && sum >= 0) { - style[prop] = sum || null; - } - }); - - el.css(style); - }); - }; - - if (typeof(o.alsoResize) === "object" && !o.alsoResize.nodeType) { - $.each(o.alsoResize, function (exp, c) { _alsoResize(exp, c); }); - }else{ - _alsoResize(o.alsoResize); - } - }, - - stop: function () { - $(this).removeData("resizable-alsoresize"); - } -}); - -$.ui.plugin.add("resizable", "ghost", { - - start: function() { - - var that = $(this).data("ui-resizable"), o = that.options, cs = that.size; - - that.ghost = that.originalElement.clone(); - that.ghost - .css({ opacity: 0.25, display: "block", position: "relative", height: cs.height, width: cs.width, margin: 0, left: 0, top: 0 }) - .addClass("ui-resizable-ghost") - .addClass(typeof o.ghost === "string" ? o.ghost : ""); - - that.ghost.appendTo(that.helper); - - }, - - resize: function(){ - var that = $(this).data("ui-resizable"); - if (that.ghost) { - that.ghost.css({ position: "relative", height: that.size.height, width: that.size.width }); - } - }, - - stop: function() { - var that = $(this).data("ui-resizable"); - if (that.ghost && that.helper) { - that.helper.get(0).removeChild(that.ghost.get(0)); - } - } - -}); - -$.ui.plugin.add("resizable", "grid", { - - resize: function() { - var that = $(this).data("ui-resizable"), - o = that.options, - cs = that.size, - os = that.originalSize, - op = that.originalPosition, - a = that.axis, - grid = typeof o.grid === "number" ? [o.grid, o.grid] : o.grid, - gridX = (grid[0]||1), - gridY = (grid[1]||1), - ox = Math.round((cs.width - os.width) / gridX) * gridX, - oy = Math.round((cs.height - os.height) / gridY) * gridY, - newWidth = os.width + ox, - newHeight = os.height + oy, - isMaxWidth = o.maxWidth && (o.maxWidth < newWidth), - isMaxHeight = o.maxHeight && (o.maxHeight < newHeight), - isMinWidth = o.minWidth && (o.minWidth > newWidth), - isMinHeight = o.minHeight && (o.minHeight > newHeight); - - o.grid = grid; - - if (isMinWidth) { - newWidth = newWidth + gridX; - } - if (isMinHeight) { - newHeight = newHeight + gridY; - } - if (isMaxWidth) { - newWidth = newWidth - gridX; - } - if (isMaxHeight) { - newHeight = newHeight - gridY; - } - - if (/^(se|s|e)$/.test(a)) { - that.size.width = newWidth; - that.size.height = newHeight; - } else if (/^(ne)$/.test(a)) { - that.size.width = newWidth; - that.size.height = newHeight; - that.position.top = op.top - oy; - } else if (/^(sw)$/.test(a)) { - that.size.width = newWidth; - that.size.height = newHeight; - that.position.left = op.left - ox; - } else { - that.size.width = newWidth; - that.size.height = newHeight; - that.position.top = op.top - oy; - that.position.left = op.left - ox; - } - } - -}); - -})(jQuery); - -(function( $, undefined ) { - -$.widget("ui.selectable", $.ui.mouse, { - version: "1.10.3", - options: { - appendTo: "body", - autoRefresh: true, - distance: 0, - filter: "*", - tolerance: "touch", - - // callbacks - selected: null, - selecting: null, - start: null, - stop: null, - unselected: null, - unselecting: null - }, - _create: function() { - var selectees, - that = this; - - this.element.addClass("ui-selectable"); - - this.dragged = false; - - // cache selectee children based on filter - this.refresh = function() { - selectees = $(that.options.filter, that.element[0]); - selectees.addClass("ui-selectee"); - selectees.each(function() { - var $this = $(this), - pos = $this.offset(); - $.data(this, "selectable-item", { - element: this, - $element: $this, - left: pos.left, - top: pos.top, - right: pos.left + $this.outerWidth(), - bottom: pos.top + $this.outerHeight(), - startselected: false, - selected: $this.hasClass("ui-selected"), - selecting: $this.hasClass("ui-selecting"), - unselecting: $this.hasClass("ui-unselecting") - }); - }); - }; - this.refresh(); - - this.selectees = selectees.addClass("ui-selectee"); - - this._mouseInit(); - - this.helper = $("<div class='ui-selectable-helper'></div>"); - }, - - _destroy: function() { - this.selectees - .removeClass("ui-selectee") - .removeData("selectable-item"); - this.element - .removeClass("ui-selectable ui-selectable-disabled"); - this._mouseDestroy(); - }, - - _mouseStart: function(event) { - var that = this, - options = this.options; - - this.opos = [event.pageX, event.pageY]; - - if (this.options.disabled) { - return; - } - - this.selectees = $(options.filter, this.element[0]); - - this._trigger("start", event); - - $(options.appendTo).append(this.helper); - // position helper (lasso) - this.helper.css({ - "left": event.pageX, - "top": event.pageY, - "width": 0, - "height": 0 - }); - - if (options.autoRefresh) { - this.refresh(); - } - - this.selectees.filter(".ui-selected").each(function() { - var selectee = $.data(this, "selectable-item"); - selectee.startselected = true; - if (!event.metaKey && !event.ctrlKey) { - selectee.$element.removeClass("ui-selected"); - selectee.selected = false; - selectee.$element.addClass("ui-unselecting"); - selectee.unselecting = true; - // selectable UNSELECTING callback - that._trigger("unselecting", event, { - unselecting: selectee.element - }); - } - }); - - $(event.target).parents().addBack().each(function() { - var doSelect, - selectee = $.data(this, "selectable-item"); - if (selectee) { - doSelect = (!event.metaKey && !event.ctrlKey) || !selectee.$element.hasClass("ui-selected"); - selectee.$element - .removeClass(doSelect ? "ui-unselecting" : "ui-selected") - .addClass(doSelect ? "ui-selecting" : "ui-unselecting"); - selectee.unselecting = !doSelect; - selectee.selecting = doSelect; - selectee.selected = doSelect; - // selectable (UN)SELECTING callback - if (doSelect) { - that._trigger("selecting", event, { - selecting: selectee.element - }); - } else { - that._trigger("unselecting", event, { - unselecting: selectee.element - }); - } - return false; - } - }); - - }, - - _mouseDrag: function(event) { - - this.dragged = true; - - if (this.options.disabled) { - return; - } - - var tmp, - that = this, - options = this.options, - x1 = this.opos[0], - y1 = this.opos[1], - x2 = event.pageX, - y2 = event.pageY; - - if (x1 > x2) { tmp = x2; x2 = x1; x1 = tmp; } - if (y1 > y2) { tmp = y2; y2 = y1; y1 = tmp; } - this.helper.css({left: x1, top: y1, width: x2-x1, height: y2-y1}); - - this.selectees.each(function() { - var selectee = $.data(this, "selectable-item"), - hit = false; - - //prevent helper from being selected if appendTo: selectable - if (!selectee || selectee.element === that.element[0]) { - return; - } - - if (options.tolerance === "touch") { - hit = ( !(selectee.left > x2 || selectee.right < x1 || selectee.top > y2 || selectee.bottom < y1) ); - } else if (options.tolerance === "fit") { - hit = (selectee.left > x1 && selectee.right < x2 && selectee.top > y1 && selectee.bottom < y2); - } - - if (hit) { - // SELECT - if (selectee.selected) { - selectee.$element.removeClass("ui-selected"); - selectee.selected = false; - } - if (selectee.unselecting) { - selectee.$element.removeClass("ui-unselecting"); - selectee.unselecting = false; - } - if (!selectee.selecting) { - selectee.$element.addClass("ui-selecting"); - selectee.selecting = true; - // selectable SELECTING callback - that._trigger("selecting", event, { - selecting: selectee.element - }); - } - } else { - // UNSELECT - if (selectee.selecting) { - if ((event.metaKey || event.ctrlKey) && selectee.startselected) { - selectee.$element.removeClass("ui-selecting"); - selectee.selecting = false; - selectee.$element.addClass("ui-selected"); - selectee.selected = true; - } else { - selectee.$element.removeClass("ui-selecting"); - selectee.selecting = false; - if (selectee.startselected) { - selectee.$element.addClass("ui-unselecting"); - selectee.unselecting = true; - } - // selectable UNSELECTING callback - that._trigger("unselecting", event, { - unselecting: selectee.element - }); - } - } - if (selectee.selected) { - if (!event.metaKey && !event.ctrlKey && !selectee.startselected) { - selectee.$element.removeClass("ui-selected"); - selectee.selected = false; - - selectee.$element.addClass("ui-unselecting"); - selectee.unselecting = true; - // selectable UNSELECTING callback - that._trigger("unselecting", event, { - unselecting: selectee.element - }); - } - } - } - }); - - return false; - }, - - _mouseStop: function(event) { - var that = this; - - this.dragged = false; - - $(".ui-unselecting", this.element[0]).each(function() { - var selectee = $.data(this, "selectable-item"); - selectee.$element.removeClass("ui-unselecting"); - selectee.unselecting = false; - selectee.startselected = false; - that._trigger("unselected", event, { - unselected: selectee.element - }); - }); - $(".ui-selecting", this.element[0]).each(function() { - var selectee = $.data(this, "selectable-item"); - selectee.$element.removeClass("ui-selecting").addClass("ui-selected"); - selectee.selecting = false; - selectee.selected = true; - selectee.startselected = true; - that._trigger("selected", event, { - selected: selectee.element - }); - }); - this._trigger("stop", event); - - this.helper.remove(); - - return false; - } - -}); - -})(jQuery); - -(function( $, undefined ) { - -/*jshint loopfunc: true */ - -function isOverAxis( x, reference, size ) { - return ( x > reference ) && ( x < ( reference + size ) ); -} - -function isFloating(item) { - return (/left|right/).test(item.css("float")) || (/inline|table-cell/).test(item.css("display")); -} - -$.widget("ui.sortable", $.ui.mouse, { - version: "1.10.3", - widgetEventPrefix: "sort", - ready: false, - options: { - appendTo: "parent", - axis: false, - connectWith: false, - containment: false, - cursor: "auto", - cursorAt: false, - dropOnEmpty: true, - forcePlaceholderSize: false, - forceHelperSize: false, - grid: false, - handle: false, - helper: "original", - items: "> *", - opacity: false, - placeholder: false, - revert: false, - scroll: true, - scrollSensitivity: 20, - scrollSpeed: 20, - scope: "default", - tolerance: "intersect", - zIndex: 1000, - - // callbacks - activate: null, - beforeStop: null, - change: null, - deactivate: null, - out: null, - over: null, - receive: null, - remove: null, - sort: null, - start: null, - stop: null, - update: null - }, - _create: function() { - - var o = this.options; - this.containerCache = {}; - this.element.addClass("ui-sortable"); - - //Get the items - this.refresh(); - - //Let's determine if the items are being displayed horizontally - this.floating = this.items.length ? o.axis === "x" || isFloating(this.items[0].item) : false; - - //Let's determine the parent's offset - this.offset = this.element.offset(); - - //Initialize mouse events for interaction - this._mouseInit(); - - //We're ready to go - this.ready = true; - - }, - - _destroy: function() { - this.element - .removeClass("ui-sortable ui-sortable-disabled"); - this._mouseDestroy(); - - for ( var i = this.items.length - 1; i >= 0; i-- ) { - this.items[i].item.removeData(this.widgetName + "-item"); - } - - return this; - }, - - _setOption: function(key, value){ - if ( key === "disabled" ) { - this.options[ key ] = value; - - this.widget().toggleClass( "ui-sortable-disabled", !!value ); - } else { - // Don't call widget base _setOption for disable as it adds ui-state-disabled class - $.Widget.prototype._setOption.apply(this, arguments); - } - }, - - _mouseCapture: function(event, overrideHandle) { - var currentItem = null, - validHandle = false, - that = this; - - if (this.reverting) { - return false; - } - - if(this.options.disabled || this.options.type === "static") { - return false; - } - - //We have to refresh the items data once first - this._refreshItems(event); - - //Find out if the clicked node (or one of its parents) is a actual item in this.items - $(event.target).parents().each(function() { - if($.data(this, that.widgetName + "-item") === that) { - currentItem = $(this); - return false; - } - }); - if($.data(event.target, that.widgetName + "-item") === that) { - currentItem = $(event.target); - } - - if(!currentItem) { - return false; - } - if(this.options.handle && !overrideHandle) { - $(this.options.handle, currentItem).find("*").addBack().each(function() { - if(this === event.target) { - validHandle = true; - } - }); - if(!validHandle) { - return false; - } - } - - this.currentItem = currentItem; - this._removeCurrentsFromItems(); - return true; - - }, - - _mouseStart: function(event, overrideHandle, noActivation) { - - var i, body, - o = this.options; - - this.currentContainer = this; - - //We only need to call refreshPositions, because the refreshItems call has been moved to mouseCapture - this.refreshPositions(); - - //Create and append the visible helper - this.helper = this._createHelper(event); - - //Cache the helper size - this._cacheHelperProportions(); - - /* - * - Position generation - - * This block generates everything position related - it's the core of draggables. - */ - - //Cache the margins of the original element - this._cacheMargins(); - - //Get the next scrolling parent - this.scrollParent = this.helper.scrollParent(); - - //The element's absolute position on the page minus margins - this.offset = this.currentItem.offset(); - this.offset = { - top: this.offset.top - this.margins.top, - left: this.offset.left - this.margins.left - }; - - $.extend(this.offset, { - click: { //Where the click happened, relative to the element - left: event.pageX - this.offset.left, - top: event.pageY - this.offset.top - }, - parent: this._getParentOffset(), - relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper - }); - - // Only after we got the offset, we can change the helper's position to absolute - // TODO: Still need to figure out a way to make relative sorting possible - this.helper.css("position", "absolute"); - this.cssPosition = this.helper.css("position"); - - //Generate the original position - this.originalPosition = this._generatePosition(event); - this.originalPageX = event.pageX; - this.originalPageY = event.pageY; - - //Adjust the mouse offset relative to the helper if "cursorAt" is supplied - (o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt)); - - //Cache the former DOM position - this.domPosition = { prev: this.currentItem.prev()[0], parent: this.currentItem.parent()[0] }; - - //If the helper is not the original, hide the original so it's not playing any role during the drag, won't cause anything bad this way - if(this.helper[0] !== this.currentItem[0]) { - this.currentItem.hide(); - } - - //Create the placeholder - this._createPlaceholder(); - - //Set a containment if given in the options - if(o.containment) { - this._setContainment(); - } - - if( o.cursor && o.cursor !== "auto" ) { // cursor option - body = this.document.find( "body" ); - - // support: IE - this.storedCursor = body.css( "cursor" ); - body.css( "cursor", o.cursor ); - - this.storedStylesheet = $( "<style>*{ cursor: "+o.cursor+" !important; }</style>" ).appendTo( body ); - } - - if(o.opacity) { // opacity option - if (this.helper.css("opacity")) { - this._storedOpacity = this.helper.css("opacity"); - } - this.helper.css("opacity", o.opacity); - } - - if(o.zIndex) { // zIndex option - if (this.helper.css("zIndex")) { - this._storedZIndex = this.helper.css("zIndex"); - } - this.helper.css("zIndex", o.zIndex); - } - - //Prepare scrolling - if(this.scrollParent[0] !== document && this.scrollParent[0].tagName !== "HTML") { - this.overflowOffset = this.scrollParent.offset(); - } - - //Call callbacks - this._trigger("start", event, this._uiHash()); - - //Recache the helper size - if(!this._preserveHelperProportions) { - this._cacheHelperProportions(); - } - - - //Post "activate" events to possible containers - if( !noActivation ) { - for ( i = this.containers.length - 1; i >= 0; i-- ) { - this.containers[ i ]._trigger( "activate", event, this._uiHash( this ) ); - } - } - - //Prepare possible droppables - if($.ui.ddmanager) { - $.ui.ddmanager.current = this; - } - - if ($.ui.ddmanager && !o.dropBehaviour) { - $.ui.ddmanager.prepareOffsets(this, event); - } - - this.dragging = true; - - this.helper.addClass("ui-sortable-helper"); - this._mouseDrag(event); //Execute the drag once - this causes the helper not to be visible before getting its correct position - return true; - - }, - - _mouseDrag: function(event) { - var i, item, itemElement, intersection, - o = this.options, - scrolled = false; - - //Compute the helpers position - this.position = this._generatePosition(event); - this.positionAbs = this._convertPositionTo("absolute"); - - if (!this.lastPositionAbs) { - this.lastPositionAbs = this.positionAbs; - } - - //Do scrolling - if(this.options.scroll) { - if(this.scrollParent[0] !== document && this.scrollParent[0].tagName !== "HTML") { - - if((this.overflowOffset.top + this.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity) { - this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop + o.scrollSpeed; - } else if(event.pageY - this.overflowOffset.top < o.scrollSensitivity) { - this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop - o.scrollSpeed; - } - - if((this.overflowOffset.left + this.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity) { - this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft + o.scrollSpeed; - } else if(event.pageX - this.overflowOffset.left < o.scrollSensitivity) { - this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft - o.scrollSpeed; - } - - } else { - - if(event.pageY - $(document).scrollTop() < o.scrollSensitivity) { - scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed); - } else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity) { - scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed); - } - - if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity) { - scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed); - } else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity) { - scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed); - } - - } - - if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) { - $.ui.ddmanager.prepareOffsets(this, event); - } - } - - //Regenerate the absolute position used for position checks - this.positionAbs = this._convertPositionTo("absolute"); - - //Set the helper position - if(!this.options.axis || this.options.axis !== "y") { - this.helper[0].style.left = this.position.left+"px"; - } - if(!this.options.axis || this.options.axis !== "x") { - this.helper[0].style.top = this.position.top+"px"; - } - - //Rearrange - for (i = this.items.length - 1; i >= 0; i--) { - - //Cache variables and intersection, continue if no intersection - item = this.items[i]; - itemElement = item.item[0]; - intersection = this._intersectsWithPointer(item); - if (!intersection) { - continue; - } - - // Only put the placeholder inside the current Container, skip all - // items form other containers. This works because when moving - // an item from one container to another the - // currentContainer is switched before the placeholder is moved. - // - // Without this moving items in "sub-sortables" can cause the placeholder to jitter - // beetween the outer and inner container. - if (item.instance !== this.currentContainer) { - continue; - } - - // cannot intersect with itself - // no useless actions that have been done before - // no action if the item moved is the parent of the item checked - if (itemElement !== this.currentItem[0] && - this.placeholder[intersection === 1 ? "next" : "prev"]()[0] !== itemElement && - !$.contains(this.placeholder[0], itemElement) && - (this.options.type === "semi-dynamic" ? !$.contains(this.element[0], itemElement) : true) - ) { - - this.direction = intersection === 1 ? "down" : "up"; - - if (this.options.tolerance === "pointer" || this._intersectsWithSides(item)) { - this._rearrange(event, item); - } else { - break; - } - - this._trigger("change", event, this._uiHash()); - break; - } - } - - //Post events to containers - this._contactContainers(event); - - //Interconnect with droppables - if($.ui.ddmanager) { - $.ui.ddmanager.drag(this, event); - } - - //Call callbacks - this._trigger("sort", event, this._uiHash()); - - this.lastPositionAbs = this.positionAbs; - return false; - - }, - - _mouseStop: function(event, noPropagation) { - - if(!event) { - return; - } - - //If we are using droppables, inform the manager about the drop - if ($.ui.ddmanager && !this.options.dropBehaviour) { - $.ui.ddmanager.drop(this, event); - } - - if(this.options.revert) { - var that = this, - cur = this.placeholder.offset(), - axis = this.options.axis, - animation = {}; - - if ( !axis || axis === "x" ) { - animation.left = cur.left - this.offset.parent.left - this.margins.left + (this.offsetParent[0] === document.body ? 0 : this.offsetParent[0].scrollLeft); - } - if ( !axis || axis === "y" ) { - animation.top = cur.top - this.offset.parent.top - this.margins.top + (this.offsetParent[0] === document.body ? 0 : this.offsetParent[0].scrollTop); - } - this.reverting = true; - $(this.helper).animate( animation, parseInt(this.options.revert, 10) || 500, function() { - that._clear(event); - }); - } else { - this._clear(event, noPropagation); - } - - return false; - - }, - - cancel: function() { - - if(this.dragging) { - - this._mouseUp({ target: null }); - - if(this.options.helper === "original") { - this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"); - } else { - this.currentItem.show(); - } - - //Post deactivating events to containers - for (var i = this.containers.length - 1; i >= 0; i--){ - this.containers[i]._trigger("deactivate", null, this._uiHash(this)); - if(this.containers[i].containerCache.over) { - this.containers[i]._trigger("out", null, this._uiHash(this)); - this.containers[i].containerCache.over = 0; - } - } - - } - - if (this.placeholder) { - //$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node! - if(this.placeholder[0].parentNode) { - this.placeholder[0].parentNode.removeChild(this.placeholder[0]); - } - if(this.options.helper !== "original" && this.helper && this.helper[0].parentNode) { - this.helper.remove(); - } - - $.extend(this, { - helper: null, - dragging: false, - reverting: false, - _noFinalSort: null - }); - - if(this.domPosition.prev) { - $(this.domPosition.prev).after(this.currentItem); - } else { - $(this.domPosition.parent).prepend(this.currentItem); - } - } - - return this; - - }, - - serialize: function(o) { - - var items = this._getItemsAsjQuery(o && o.connected), - str = []; - o = o || {}; - - $(items).each(function() { - var res = ($(o.item || this).attr(o.attribute || "id") || "").match(o.expression || (/(.+)[\-=_](.+)/)); - if (res) { - str.push((o.key || res[1]+"[]")+"="+(o.key && o.expression ? res[1] : res[2])); - } - }); - - if(!str.length && o.key) { - str.push(o.key + "="); - } - - return str.join("&"); - - }, - - toArray: function(o) { - - var items = this._getItemsAsjQuery(o && o.connected), - ret = []; - - o = o || {}; - - items.each(function() { ret.push($(o.item || this).attr(o.attribute || "id") || ""); }); - return ret; - - }, - - /* Be careful with the following core functions */ - _intersectsWith: function(item) { - - var x1 = this.positionAbs.left, - x2 = x1 + this.helperProportions.width, - y1 = this.positionAbs.top, - y2 = y1 + this.helperProportions.height, - l = item.left, - r = l + item.width, - t = item.top, - b = t + item.height, - dyClick = this.offset.click.top, - dxClick = this.offset.click.left, - isOverElementHeight = ( this.options.axis === "x" ) || ( ( y1 + dyClick ) > t && ( y1 + dyClick ) < b ), - isOverElementWidth = ( this.options.axis === "y" ) || ( ( x1 + dxClick ) > l && ( x1 + dxClick ) < r ), - isOverElement = isOverElementHeight && isOverElementWidth; - - if ( this.options.tolerance === "pointer" || - this.options.forcePointerForContainers || - (this.options.tolerance !== "pointer" && this.helperProportions[this.floating ? "width" : "height"] > item[this.floating ? "width" : "height"]) - ) { - return isOverElement; - } else { - - return (l < x1 + (this.helperProportions.width / 2) && // Right Half - x2 - (this.helperProportions.width / 2) < r && // Left Half - t < y1 + (this.helperProportions.height / 2) && // Bottom Half - y2 - (this.helperProportions.height / 2) < b ); // Top Half - - } - }, - - _intersectsWithPointer: function(item) { - - var isOverElementHeight = (this.options.axis === "x") || isOverAxis(this.positionAbs.top + this.offset.click.top, item.top, item.height), - isOverElementWidth = (this.options.axis === "y") || isOverAxis(this.positionAbs.left + this.offset.click.left, item.left, item.width), - isOverElement = isOverElementHeight && isOverElementWidth, - verticalDirection = this._getDragVerticalDirection(), - horizontalDirection = this._getDragHorizontalDirection(); - - if (!isOverElement) { - return false; - } - - return this.floating ? - ( ((horizontalDirection && horizontalDirection === "right") || verticalDirection === "down") ? 2 : 1 ) - : ( verticalDirection && (verticalDirection === "down" ? 2 : 1) ); - - }, - - _intersectsWithSides: function(item) { - - var isOverBottomHalf = isOverAxis(this.positionAbs.top + this.offset.click.top, item.top + (item.height/2), item.height), - isOverRightHalf = isOverAxis(this.positionAbs.left + this.offset.click.left, item.left + (item.width/2), item.width), - verticalDirection = this._getDragVerticalDirection(), - horizontalDirection = this._getDragHorizontalDirection(); - - if (this.floating && horizontalDirection) { - return ((horizontalDirection === "right" && isOverRightHalf) || (horizontalDirection === "left" && !isOverRightHalf)); - } else { - return verticalDirection && ((verticalDirection === "down" && isOverBottomHalf) || (verticalDirection === "up" && !isOverBottomHalf)); - } - - }, - - _getDragVerticalDirection: function() { - var delta = this.positionAbs.top - this.lastPositionAbs.top; - return delta !== 0 && (delta > 0 ? "down" : "up"); - }, - - _getDragHorizontalDirection: function() { - var delta = this.positionAbs.left - this.lastPositionAbs.left; - return delta !== 0 && (delta > 0 ? "right" : "left"); - }, - - refresh: function(event) { - this._refreshItems(event); - this.refreshPositions(); - return this; - }, - - _connectWith: function() { - var options = this.options; - return options.connectWith.constructor === String ? [options.connectWith] : options.connectWith; - }, - - _getItemsAsjQuery: function(connected) { - - var i, j, cur, inst, - items = [], - queries = [], - connectWith = this._connectWith(); - - if(connectWith && connected) { - for (i = connectWith.length - 1; i >= 0; i--){ - cur = $(connectWith[i]); - for ( j = cur.length - 1; j >= 0; j--){ - inst = $.data(cur[j], this.widgetFullName); - if(inst && inst !== this && !inst.options.disabled) { - queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element) : $(inst.options.items, inst.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"), inst]); - } - } - } - } - - queries.push([$.isFunction(this.options.items) ? this.options.items.call(this.element, null, { options: this.options, item: this.currentItem }) : $(this.options.items, this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"), this]); - - for (i = queries.length - 1; i >= 0; i--){ - queries[i][0].each(function() { - items.push(this); - }); - } - - return $(items); - - }, - - _removeCurrentsFromItems: function() { - - var list = this.currentItem.find(":data(" + this.widgetName + "-item)"); - - this.items = $.grep(this.items, function (item) { - for (var j=0; j < list.length; j++) { - if(list[j] === item.item[0]) { - return false; - } - } - return true; - }); - - }, - - _refreshItems: function(event) { - - this.items = []; - this.containers = [this]; - - var i, j, cur, inst, targetData, _queries, item, queriesLength, - items = this.items, - queries = [[$.isFunction(this.options.items) ? this.options.items.call(this.element[0], event, { item: this.currentItem }) : $(this.options.items, this.element), this]], - connectWith = this._connectWith(); - - if(connectWith && this.ready) { //Shouldn't be run the first time through due to massive slow-down - for (i = connectWith.length - 1; i >= 0; i--){ - cur = $(connectWith[i]); - for (j = cur.length - 1; j >= 0; j--){ - inst = $.data(cur[j], this.widgetFullName); - if(inst && inst !== this && !inst.options.disabled) { - queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element[0], event, { item: this.currentItem }) : $(inst.options.items, inst.element), inst]); - this.containers.push(inst); - } - } - } - } - - for (i = queries.length - 1; i >= 0; i--) { - targetData = queries[i][1]; - _queries = queries[i][0]; - - for (j=0, queriesLength = _queries.length; j < queriesLength; j++) { - item = $(_queries[j]); - - item.data(this.widgetName + "-item", targetData); // Data for target checking (mouse manager) - - items.push({ - item: item, - instance: targetData, - width: 0, height: 0, - left: 0, top: 0 - }); - } - } - - }, - - refreshPositions: function(fast) { - - //This has to be redone because due to the item being moved out/into the offsetParent, the offsetParent's position will change - if(this.offsetParent && this.helper) { - this.offset.parent = this._getParentOffset(); - } - - var i, item, t, p; - - for (i = this.items.length - 1; i >= 0; i--){ - item = this.items[i]; - - //We ignore calculating positions of all connected containers when we're not over them - if(item.instance !== this.currentContainer && this.currentContainer && item.item[0] !== this.currentItem[0]) { - continue; - } - - t = this.options.toleranceElement ? $(this.options.toleranceElement, item.item) : item.item; - - if (!fast) { - item.width = t.outerWidth(); - item.height = t.outerHeight(); - } - - p = t.offset(); - item.left = p.left; - item.top = p.top; - } - - if(this.options.custom && this.options.custom.refreshContainers) { - this.options.custom.refreshContainers.call(this); - } else { - for (i = this.containers.length - 1; i >= 0; i--){ - p = this.containers[i].element.offset(); - this.containers[i].containerCache.left = p.left; - this.containers[i].containerCache.top = p.top; - this.containers[i].containerCache.width = this.containers[i].element.outerWidth(); - this.containers[i].containerCache.height = this.containers[i].element.outerHeight(); - } - } - - return this; - }, - - _createPlaceholder: function(that) { - that = that || this; - var className, - o = that.options; - - if(!o.placeholder || o.placeholder.constructor === String) { - className = o.placeholder; - o.placeholder = { - element: function() { - - var nodeName = that.currentItem[0].nodeName.toLowerCase(), - element = $( "<" + nodeName + ">", that.document[0] ) - .addClass(className || that.currentItem[0].className+" ui-sortable-placeholder") - .removeClass("ui-sortable-helper"); - - if ( nodeName === "tr" ) { - that.currentItem.children().each(function() { - $( "<td> </td>", that.document[0] ) - .attr( "colspan", $( this ).attr( "colspan" ) || 1 ) - .appendTo( element ); - }); - } else if ( nodeName === "img" ) { - element.attr( "src", that.currentItem.attr( "src" ) ); - } - - if ( !className ) { - element.css( "visibility", "hidden" ); - } - - return element; - }, - update: function(container, p) { - - // 1. If a className is set as 'placeholder option, we don't force sizes - the class is responsible for that - // 2. The option 'forcePlaceholderSize can be enabled to force it even if a class name is specified - if(className && !o.forcePlaceholderSize) { - return; - } - - //If the element doesn't have a actual height by itself (without styles coming from a stylesheet), it receives the inline height from the dragged item - if(!p.height()) { p.height(that.currentItem.innerHeight() - parseInt(that.currentItem.css("paddingTop")||0, 10) - parseInt(that.currentItem.css("paddingBottom")||0, 10)); } - if(!p.width()) { p.width(that.currentItem.innerWidth() - parseInt(that.currentItem.css("paddingLeft")||0, 10) - parseInt(that.currentItem.css("paddingRight")||0, 10)); } - } - }; - } - - //Create the placeholder - that.placeholder = $(o.placeholder.element.call(that.element, that.currentItem)); - - //Append it after the actual current item - that.currentItem.after(that.placeholder); - - //Update the size of the placeholder (TODO: Logic to fuzzy, see line 316/317) - o.placeholder.update(that, that.placeholder); - - }, - - _contactContainers: function(event) { - var i, j, dist, itemWithLeastDistance, posProperty, sizeProperty, base, cur, nearBottom, floating, - innermostContainer = null, - innermostIndex = null; - - // get innermost container that intersects with item - for (i = this.containers.length - 1; i >= 0; i--) { - - // never consider a container that's located within the item itself - if($.contains(this.currentItem[0], this.containers[i].element[0])) { - continue; - } - - if(this._intersectsWith(this.containers[i].containerCache)) { - - // if we've already found a container and it's more "inner" than this, then continue - if(innermostContainer && $.contains(this.containers[i].element[0], innermostContainer.element[0])) { - continue; - } - - innermostContainer = this.containers[i]; - innermostIndex = i; - - } else { - // container doesn't intersect. trigger "out" event if necessary - if(this.containers[i].containerCache.over) { - this.containers[i]._trigger("out", event, this._uiHash(this)); - this.containers[i].containerCache.over = 0; - } - } - - } - - // if no intersecting containers found, return - if(!innermostContainer) { - return; - } - - // move the item into the container if it's not there already - if(this.containers.length === 1) { - if (!this.containers[innermostIndex].containerCache.over) { - this.containers[innermostIndex]._trigger("over", event, this._uiHash(this)); - this.containers[innermostIndex].containerCache.over = 1; - } - } else { - - //When entering a new container, we will find the item with the least distance and append our item near it - dist = 10000; - itemWithLeastDistance = null; - floating = innermostContainer.floating || isFloating(this.currentItem); - posProperty = floating ? "left" : "top"; - sizeProperty = floating ? "width" : "height"; - base = this.positionAbs[posProperty] + this.offset.click[posProperty]; - for (j = this.items.length - 1; j >= 0; j--) { - if(!$.contains(this.containers[innermostIndex].element[0], this.items[j].item[0])) { - continue; - } - if(this.items[j].item[0] === this.currentItem[0]) { - continue; - } - if (floating && !isOverAxis(this.positionAbs.top + this.offset.click.top, this.items[j].top, this.items[j].height)) { - continue; - } - cur = this.items[j].item.offset()[posProperty]; - nearBottom = false; - if(Math.abs(cur - base) > Math.abs(cur + this.items[j][sizeProperty] - base)){ - nearBottom = true; - cur += this.items[j][sizeProperty]; - } - - if(Math.abs(cur - base) < dist) { - dist = Math.abs(cur - base); itemWithLeastDistance = this.items[j]; - this.direction = nearBottom ? "up": "down"; - } - } - - //Check if dropOnEmpty is enabled - if(!itemWithLeastDistance && !this.options.dropOnEmpty) { - return; - } - - if(this.currentContainer === this.containers[innermostIndex]) { - return; - } - - itemWithLeastDistance ? this._rearrange(event, itemWithLeastDistance, null, true) : this._rearrange(event, null, this.containers[innermostIndex].element, true); - this._trigger("change", event, this._uiHash()); - this.containers[innermostIndex]._trigger("change", event, this._uiHash(this)); - this.currentContainer = this.containers[innermostIndex]; - - //Update the placeholder - this.options.placeholder.update(this.currentContainer, this.placeholder); - - this.containers[innermostIndex]._trigger("over", event, this._uiHash(this)); - this.containers[innermostIndex].containerCache.over = 1; - } - - - }, - - _createHelper: function(event) { - - var o = this.options, - helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event, this.currentItem])) : (o.helper === "clone" ? this.currentItem.clone() : this.currentItem); - - //Add the helper to the DOM if that didn't happen already - if(!helper.parents("body").length) { - $(o.appendTo !== "parent" ? o.appendTo : this.currentItem[0].parentNode)[0].appendChild(helper[0]); - } - - if(helper[0] === this.currentItem[0]) { - this._storedCSS = { width: this.currentItem[0].style.width, height: this.currentItem[0].style.height, position: this.currentItem.css("position"), top: this.currentItem.css("top"), left: this.currentItem.css("left") }; - } - - if(!helper[0].style.width || o.forceHelperSize) { - helper.width(this.currentItem.width()); - } - if(!helper[0].style.height || o.forceHelperSize) { - helper.height(this.currentItem.height()); - } - - return helper; - - }, - - _adjustOffsetFromHelper: function(obj) { - if (typeof obj === "string") { - obj = obj.split(" "); - } - if ($.isArray(obj)) { - obj = {left: +obj[0], top: +obj[1] || 0}; - } - if ("left" in obj) { - this.offset.click.left = obj.left + this.margins.left; - } - if ("right" in obj) { - this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left; - } - if ("top" in obj) { - this.offset.click.top = obj.top + this.margins.top; - } - if ("bottom" in obj) { - this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top; - } - }, - - _getParentOffset: function() { - - - //Get the offsetParent and cache its position - this.offsetParent = this.helper.offsetParent(); - var po = this.offsetParent.offset(); - - // This is a special case where we need to modify a offset calculated on start, since the following happened: - // 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent - // 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that - // the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag - if(this.cssPosition === "absolute" && this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) { - po.left += this.scrollParent.scrollLeft(); - po.top += this.scrollParent.scrollTop(); - } - - // This needs to be actually done for all browsers, since pageX/pageY includes this information - // with an ugly IE fix - if( this.offsetParent[0] === document.body || (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() === "html" && $.ui.ie)) { - po = { top: 0, left: 0 }; - } - - return { - top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0), - left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0) - }; - - }, - - _getRelativeOffset: function() { - - if(this.cssPosition === "relative") { - var p = this.currentItem.position(); - return { - top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(), - left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft() - }; - } else { - return { top: 0, left: 0 }; - } - - }, - - _cacheMargins: function() { - this.margins = { - left: (parseInt(this.currentItem.css("marginLeft"),10) || 0), - top: (parseInt(this.currentItem.css("marginTop"),10) || 0) - }; - }, - - _cacheHelperProportions: function() { - this.helperProportions = { - width: this.helper.outerWidth(), - height: this.helper.outerHeight() - }; - }, - - _setContainment: function() { - - var ce, co, over, - o = this.options; - if(o.containment === "parent") { - o.containment = this.helper[0].parentNode; - } - if(o.containment === "document" || o.containment === "window") { - this.containment = [ - 0 - this.offset.relative.left - this.offset.parent.left, - 0 - this.offset.relative.top - this.offset.parent.top, - $(o.containment === "document" ? document : window).width() - this.helperProportions.width - this.margins.left, - ($(o.containment === "document" ? document : window).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top - ]; - } - - if(!(/^(document|window|parent)$/).test(o.containment)) { - ce = $(o.containment)[0]; - co = $(o.containment).offset(); - over = ($(ce).css("overflow") !== "hidden"); - - this.containment = [ - co.left + (parseInt($(ce).css("borderLeftWidth"),10) || 0) + (parseInt($(ce).css("paddingLeft"),10) || 0) - this.margins.left, - co.top + (parseInt($(ce).css("borderTopWidth"),10) || 0) + (parseInt($(ce).css("paddingTop"),10) || 0) - this.margins.top, - co.left+(over ? Math.max(ce.scrollWidth,ce.offsetWidth) : ce.offsetWidth) - (parseInt($(ce).css("borderLeftWidth"),10) || 0) - (parseInt($(ce).css("paddingRight"),10) || 0) - this.helperProportions.width - this.margins.left, - co.top+(over ? Math.max(ce.scrollHeight,ce.offsetHeight) : ce.offsetHeight) - (parseInt($(ce).css("borderTopWidth"),10) || 0) - (parseInt($(ce).css("paddingBottom"),10) || 0) - this.helperProportions.height - this.margins.top - ]; - } - - }, - - _convertPositionTo: function(d, pos) { - - if(!pos) { - pos = this.position; - } - var mod = d === "absolute" ? 1 : -1, - scroll = this.cssPosition === "absolute" && !(this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, - scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName); - - return { - top: ( - pos.top + // The absolute mouse position - this.offset.relative.top * mod + // Only for relative positioned nodes: Relative offset from element to offset parent - this.offset.parent.top * mod - // The offsetParent's offset without borders (offset + border) - ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod) - ), - left: ( - pos.left + // The absolute mouse position - this.offset.relative.left * mod + // Only for relative positioned nodes: Relative offset from element to offset parent - this.offset.parent.left * mod - // The offsetParent's offset without borders (offset + border) - ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ) * mod) - ) - }; - - }, - - _generatePosition: function(event) { - - var top, left, - o = this.options, - pageX = event.pageX, - pageY = event.pageY, - scroll = this.cssPosition === "absolute" && !(this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName); - - // This is another very weird special case that only happens for relative elements: - // 1. If the css position is relative - // 2. and the scroll parent is the document or similar to the offset parent - // we have to refresh the relative offset during the scroll so there are no jumps - if(this.cssPosition === "relative" && !(this.scrollParent[0] !== document && this.scrollParent[0] !== this.offsetParent[0])) { - this.offset.relative = this._getRelativeOffset(); - } - - /* - * - Position constraining - - * Constrain the position to a mix of grid, containment. - */ - - if(this.originalPosition) { //If we are not dragging yet, we won't check for options - - if(this.containment) { - if(event.pageX - this.offset.click.left < this.containment[0]) { - pageX = this.containment[0] + this.offset.click.left; - } - if(event.pageY - this.offset.click.top < this.containment[1]) { - pageY = this.containment[1] + this.offset.click.top; - } - if(event.pageX - this.offset.click.left > this.containment[2]) { - pageX = this.containment[2] + this.offset.click.left; - } - if(event.pageY - this.offset.click.top > this.containment[3]) { - pageY = this.containment[3] + this.offset.click.top; - } - } - - if(o.grid) { - top = this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1]; - pageY = this.containment ? ( (top - this.offset.click.top >= this.containment[1] && top - this.offset.click.top <= this.containment[3]) ? top : ((top - this.offset.click.top >= this.containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top; - - left = this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0]; - pageX = this.containment ? ( (left - this.offset.click.left >= this.containment[0] && left - this.offset.click.left <= this.containment[2]) ? left : ((left - this.offset.click.left >= this.containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left; - } - - } - - return { - top: ( - pageY - // The absolute mouse position - this.offset.click.top - // Click offset (relative to the element) - this.offset.relative.top - // Only for relative positioned nodes: Relative offset from element to offset parent - this.offset.parent.top + // The offsetParent's offset without borders (offset + border) - ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) )) - ), - left: ( - pageX - // The absolute mouse position - this.offset.click.left - // Click offset (relative to the element) - this.offset.relative.left - // Only for relative positioned nodes: Relative offset from element to offset parent - this.offset.parent.left + // The offsetParent's offset without borders (offset + border) - ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() )) - ) - }; - - }, - - _rearrange: function(event, i, a, hardRefresh) { - - a ? a[0].appendChild(this.placeholder[0]) : i.item[0].parentNode.insertBefore(this.placeholder[0], (this.direction === "down" ? i.item[0] : i.item[0].nextSibling)); - - //Various things done here to improve the performance: - // 1. we create a setTimeout, that calls refreshPositions - // 2. on the instance, we have a counter variable, that get's higher after every append - // 3. on the local scope, we copy the counter variable, and check in the timeout, if it's still the same - // 4. this lets only the last addition to the timeout stack through - this.counter = this.counter ? ++this.counter : 1; - var counter = this.counter; - - this._delay(function() { - if(counter === this.counter) { - this.refreshPositions(!hardRefresh); //Precompute after each DOM insertion, NOT on mousemove - } - }); - - }, - - _clear: function(event, noPropagation) { - - this.reverting = false; - // We delay all events that have to be triggered to after the point where the placeholder has been removed and - // everything else normalized again - var i, - delayedTriggers = []; - - // We first have to update the dom position of the actual currentItem - // Note: don't do it if the current item is already removed (by a user), or it gets reappended (see #4088) - if(!this._noFinalSort && this.currentItem.parent().length) { - this.placeholder.before(this.currentItem); - } - this._noFinalSort = null; - - if(this.helper[0] === this.currentItem[0]) { - for(i in this._storedCSS) { - if(this._storedCSS[i] === "auto" || this._storedCSS[i] === "static") { - this._storedCSS[i] = ""; - } - } - this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"); - } else { - this.currentItem.show(); - } - - if(this.fromOutside && !noPropagation) { - delayedTriggers.push(function(event) { this._trigger("receive", event, this._uiHash(this.fromOutside)); }); - } - if((this.fromOutside || this.domPosition.prev !== this.currentItem.prev().not(".ui-sortable-helper")[0] || this.domPosition.parent !== this.currentItem.parent()[0]) && !noPropagation) { - delayedTriggers.push(function(event) { this._trigger("update", event, this._uiHash()); }); //Trigger update callback if the DOM position has changed - } - - // Check if the items Container has Changed and trigger appropriate - // events. - if (this !== this.currentContainer) { - if(!noPropagation) { - delayedTriggers.push(function(event) { this._trigger("remove", event, this._uiHash()); }); - delayedTriggers.push((function(c) { return function(event) { c._trigger("receive", event, this._uiHash(this)); }; }).call(this, this.currentContainer)); - delayedTriggers.push((function(c) { return function(event) { c._trigger("update", event, this._uiHash(this)); }; }).call(this, this.currentContainer)); - } - } - - - //Post events to containers - for (i = this.containers.length - 1; i >= 0; i--){ - if(!noPropagation) { - delayedTriggers.push((function(c) { return function(event) { c._trigger("deactivate", event, this._uiHash(this)); }; }).call(this, this.containers[i])); - } - if(this.containers[i].containerCache.over) { - delayedTriggers.push((function(c) { return function(event) { c._trigger("out", event, this._uiHash(this)); }; }).call(this, this.containers[i])); - this.containers[i].containerCache.over = 0; - } - } - - //Do what was originally in plugins - if ( this.storedCursor ) { - this.document.find( "body" ).css( "cursor", this.storedCursor ); - this.storedStylesheet.remove(); - } - if(this._storedOpacity) { - this.helper.css("opacity", this._storedOpacity); - } - if(this._storedZIndex) { - this.helper.css("zIndex", this._storedZIndex === "auto" ? "" : this._storedZIndex); - } - - this.dragging = false; - if(this.cancelHelperRemoval) { - if(!noPropagation) { - this._trigger("beforeStop", event, this._uiHash()); - for (i=0; i < delayedTriggers.length; i++) { - delayedTriggers[i].call(this, event); - } //Trigger all delayed events - this._trigger("stop", event, this._uiHash()); - } - - this.fromOutside = false; - return false; - } - - if(!noPropagation) { - this._trigger("beforeStop", event, this._uiHash()); - } - - //$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node! - this.placeholder[0].parentNode.removeChild(this.placeholder[0]); - - if(this.helper[0] !== this.currentItem[0]) { - this.helper.remove(); - } - this.helper = null; - - if(!noPropagation) { - for (i=0; i < delayedTriggers.length; i++) { - delayedTriggers[i].call(this, event); - } //Trigger all delayed events - this._trigger("stop", event, this._uiHash()); - } - - this.fromOutside = false; - return true; - - }, - - _trigger: function() { - if ($.Widget.prototype._trigger.apply(this, arguments) === false) { - this.cancel(); - } - }, - - _uiHash: function(_inst) { - var inst = _inst || this; - return { - helper: inst.helper, - placeholder: inst.placeholder || $([]), - position: inst.position, - originalPosition: inst.originalPosition, - offset: inst.positionAbs, - item: inst.currentItem, - sender: _inst ? _inst.element : null - }; - } - -}); - -})(jQuery); - -(function($, undefined) { - -var dataSpace = "ui-effects-"; - -$.effects = { - effect: {} -}; - -/*! - * jQuery Color Animations v2.1.2 - * https://github.com/jquery/jquery-color - * - * Copyright 2013 jQuery Foundation and other contributors - * Released under the MIT license. - * http://jquery.org/license - * - * Date: Wed Jan 16 08:47:09 2013 -0600 - */ -(function( jQuery, undefined ) { - - var stepHooks = "backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor", - - // plusequals test for += 100 -= 100 - rplusequals = /^([\-+])=\s*(\d+\.?\d*)/, - // a set of RE's that can match strings and generate color tuples. - stringParsers = [{ - re: /rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/, - parse: function( execResult ) { - return [ - execResult[ 1 ], - execResult[ 2 ], - execResult[ 3 ], - execResult[ 4 ] - ]; - } - }, { - re: /rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/, - parse: function( execResult ) { - return [ - execResult[ 1 ] * 2.55, - execResult[ 2 ] * 2.55, - execResult[ 3 ] * 2.55, - execResult[ 4 ] - ]; - } - }, { - // this regex ignores A-F because it's compared against an already lowercased string - re: /#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/, - parse: function( execResult ) { - return [ - parseInt( execResult[ 1 ], 16 ), - parseInt( execResult[ 2 ], 16 ), - parseInt( execResult[ 3 ], 16 ) - ]; - } - }, { - // this regex ignores A-F because it's compared against an already lowercased string - re: /#([a-f0-9])([a-f0-9])([a-f0-9])/, - parse: function( execResult ) { - return [ - parseInt( execResult[ 1 ] + execResult[ 1 ], 16 ), - parseInt( execResult[ 2 ] + execResult[ 2 ], 16 ), - parseInt( execResult[ 3 ] + execResult[ 3 ], 16 ) - ]; - } - }, { - re: /hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/, - space: "hsla", - parse: function( execResult ) { - return [ - execResult[ 1 ], - execResult[ 2 ] / 100, - execResult[ 3 ] / 100, - execResult[ 4 ] - ]; - } - }], - - // jQuery.Color( ) - color = jQuery.Color = function( color, green, blue, alpha ) { - return new jQuery.Color.fn.parse( color, green, blue, alpha ); - }, - spaces = { - rgba: { - props: { - red: { - idx: 0, - type: "byte" - }, - green: { - idx: 1, - type: "byte" - }, - blue: { - idx: 2, - type: "byte" - } - } - }, - - hsla: { - props: { - hue: { - idx: 0, - type: "degrees" - }, - saturation: { - idx: 1, - type: "percent" - }, - lightness: { - idx: 2, - type: "percent" - } - } - } - }, - propTypes = { - "byte": { - floor: true, - max: 255 - }, - "percent": { - max: 1 - }, - "degrees": { - mod: 360, - floor: true - } - }, - support = color.support = {}, - - // element for support tests - supportElem = jQuery( "<p>" )[ 0 ], - - // colors = jQuery.Color.names - colors, - - // local aliases of functions called often - each = jQuery.each; - -// determine rgba support immediately -supportElem.style.cssText = "background-color:rgba(1,1,1,.5)"; -support.rgba = supportElem.style.backgroundColor.indexOf( "rgba" ) > -1; - -// define cache name and alpha properties -// for rgba and hsla spaces -each( spaces, function( spaceName, space ) { - space.cache = "_" + spaceName; - space.props.alpha = { - idx: 3, - type: "percent", - def: 1 - }; -}); - -function clamp( value, prop, allowEmpty ) { - var type = propTypes[ prop.type ] || {}; - - if ( value == null ) { - return (allowEmpty || !prop.def) ? null : prop.def; - } - - // ~~ is an short way of doing floor for positive numbers - value = type.floor ? ~~value : parseFloat( value ); - - // IE will pass in empty strings as value for alpha, - // which will hit this case - if ( isNaN( value ) ) { - return prop.def; - } - - if ( type.mod ) { - // we add mod before modding to make sure that negatives values - // get converted properly: -10 -> 350 - return (value + type.mod) % type.mod; - } - - // for now all property types without mod have min and max - return 0 > value ? 0 : type.max < value ? type.max : value; -} - -function stringParse( string ) { - var inst = color(), - rgba = inst._rgba = []; - - string = string.toLowerCase(); - - each( stringParsers, function( i, parser ) { - var parsed, - match = parser.re.exec( string ), - values = match && parser.parse( match ), - spaceName = parser.space || "rgba"; - - if ( values ) { - parsed = inst[ spaceName ]( values ); - - // if this was an rgba parse the assignment might happen twice - // oh well.... - inst[ spaces[ spaceName ].cache ] = parsed[ spaces[ spaceName ].cache ]; - rgba = inst._rgba = parsed._rgba; - - // exit each( stringParsers ) here because we matched - return false; - } - }); - - // Found a stringParser that handled it - if ( rgba.length ) { - - // if this came from a parsed string, force "transparent" when alpha is 0 - // chrome, (and maybe others) return "transparent" as rgba(0,0,0,0) - if ( rgba.join() === "0,0,0,0" ) { - jQuery.extend( rgba, colors.transparent ); - } - return inst; - } - - // named colors - return colors[ string ]; -} - -color.fn = jQuery.extend( color.prototype, { - parse: function( red, green, blue, alpha ) { - if ( red === undefined ) { - this._rgba = [ null, null, null, null ]; - return this; - } - if ( red.jquery || red.nodeType ) { - red = jQuery( red ).css( green ); - green = undefined; - } - - var inst = this, - type = jQuery.type( red ), - rgba = this._rgba = []; - - // more than 1 argument specified - assume ( red, green, blue, alpha ) - if ( green !== undefined ) { - red = [ red, green, blue, alpha ]; - type = "array"; - } - - if ( type === "string" ) { - return this.parse( stringParse( red ) || colors._default ); - } - - if ( type === "array" ) { - each( spaces.rgba.props, function( key, prop ) { - rgba[ prop.idx ] = clamp( red[ prop.idx ], prop ); - }); - return this; - } - - if ( type === "object" ) { - if ( red instanceof color ) { - each( spaces, function( spaceName, space ) { - if ( red[ space.cache ] ) { - inst[ space.cache ] = red[ space.cache ].slice(); - } - }); - } else { - each( spaces, function( spaceName, space ) { - var cache = space.cache; - each( space.props, function( key, prop ) { - - // if the cache doesn't exist, and we know how to convert - if ( !inst[ cache ] && space.to ) { - - // if the value was null, we don't need to copy it - // if the key was alpha, we don't need to copy it either - if ( key === "alpha" || red[ key ] == null ) { - return; - } - inst[ cache ] = space.to( inst._rgba ); - } - - // this is the only case where we allow nulls for ALL properties. - // call clamp with alwaysAllowEmpty - inst[ cache ][ prop.idx ] = clamp( red[ key ], prop, true ); - }); - - // everything defined but alpha? - if ( inst[ cache ] && jQuery.inArray( null, inst[ cache ].slice( 0, 3 ) ) < 0 ) { - // use the default of 1 - inst[ cache ][ 3 ] = 1; - if ( space.from ) { - inst._rgba = space.from( inst[ cache ] ); - } - } - }); - } - return this; - } - }, - is: function( compare ) { - var is = color( compare ), - same = true, - inst = this; - - each( spaces, function( _, space ) { - var localCache, - isCache = is[ space.cache ]; - if (isCache) { - localCache = inst[ space.cache ] || space.to && space.to( inst._rgba ) || []; - each( space.props, function( _, prop ) { - if ( isCache[ prop.idx ] != null ) { - same = ( isCache[ prop.idx ] === localCache[ prop.idx ] ); - return same; - } - }); - } - return same; - }); - return same; - }, - _space: function() { - var used = [], - inst = this; - each( spaces, function( spaceName, space ) { - if ( inst[ space.cache ] ) { - used.push( spaceName ); - } - }); - return used.pop(); - }, - transition: function( other, distance ) { - var end = color( other ), - spaceName = end._space(), - space = spaces[ spaceName ], - startColor = this.alpha() === 0 ? color( "transparent" ) : this, - start = startColor[ space.cache ] || space.to( startColor._rgba ), - result = start.slice(); - - end = end[ space.cache ]; - each( space.props, function( key, prop ) { - var index = prop.idx, - startValue = start[ index ], - endValue = end[ index ], - type = propTypes[ prop.type ] || {}; - - // if null, don't override start value - if ( endValue === null ) { - return; - } - // if null - use end - if ( startValue === null ) { - result[ index ] = endValue; - } else { - if ( type.mod ) { - if ( endValue - startValue > type.mod / 2 ) { - startValue += type.mod; - } else if ( startValue - endValue > type.mod / 2 ) { - startValue -= type.mod; - } - } - result[ index ] = clamp( ( endValue - startValue ) * distance + startValue, prop ); - } - }); - return this[ spaceName ]( result ); - }, - blend: function( opaque ) { - // if we are already opaque - return ourself - if ( this._rgba[ 3 ] === 1 ) { - return this; - } - - var rgb = this._rgba.slice(), - a = rgb.pop(), - blend = color( opaque )._rgba; - - return color( jQuery.map( rgb, function( v, i ) { - return ( 1 - a ) * blend[ i ] + a * v; - })); - }, - toRgbaString: function() { - var prefix = "rgba(", - rgba = jQuery.map( this._rgba, function( v, i ) { - return v == null ? ( i > 2 ? 1 : 0 ) : v; - }); - - if ( rgba[ 3 ] === 1 ) { - rgba.pop(); - prefix = "rgb("; - } - - return prefix + rgba.join() + ")"; - }, - toHslaString: function() { - var prefix = "hsla(", - hsla = jQuery.map( this.hsla(), function( v, i ) { - if ( v == null ) { - v = i > 2 ? 1 : 0; - } - - // catch 1 and 2 - if ( i && i < 3 ) { - v = Math.round( v * 100 ) + "%"; - } - return v; - }); - - if ( hsla[ 3 ] === 1 ) { - hsla.pop(); - prefix = "hsl("; - } - return prefix + hsla.join() + ")"; - }, - toHexString: function( includeAlpha ) { - var rgba = this._rgba.slice(), - alpha = rgba.pop(); - - if ( includeAlpha ) { - rgba.push( ~~( alpha * 255 ) ); - } - - return "#" + jQuery.map( rgba, function( v ) { - - // default to 0 when nulls exist - v = ( v || 0 ).toString( 16 ); - return v.length === 1 ? "0" + v : v; - }).join(""); - }, - toString: function() { - return this._rgba[ 3 ] === 0 ? "transparent" : this.toRgbaString(); - } -}); -color.fn.parse.prototype = color.fn; - -// hsla conversions adapted from: -// https://code.google.com/p/maashaack/source/browse/packages/graphics/trunk/src/graphics/colors/HUE2RGB.as?r=5021 - -function hue2rgb( p, q, h ) { - h = ( h + 1 ) % 1; - if ( h * 6 < 1 ) { - return p + (q - p) * h * 6; - } - if ( h * 2 < 1) { - return q; - } - if ( h * 3 < 2 ) { - return p + (q - p) * ((2/3) - h) * 6; - } - return p; -} - -spaces.hsla.to = function ( rgba ) { - if ( rgba[ 0 ] == null || rgba[ 1 ] == null || rgba[ 2 ] == null ) { - return [ null, null, null, rgba[ 3 ] ]; - } - var r = rgba[ 0 ] / 255, - g = rgba[ 1 ] / 255, - b = rgba[ 2 ] / 255, - a = rgba[ 3 ], - max = Math.max( r, g, b ), - min = Math.min( r, g, b ), - diff = max - min, - add = max + min, - l = add * 0.5, - h, s; - - if ( min === max ) { - h = 0; - } else if ( r === max ) { - h = ( 60 * ( g - b ) / diff ) + 360; - } else if ( g === max ) { - h = ( 60 * ( b - r ) / diff ) + 120; - } else { - h = ( 60 * ( r - g ) / diff ) + 240; - } - - // chroma (diff) == 0 means greyscale which, by definition, saturation = 0% - // otherwise, saturation is based on the ratio of chroma (diff) to lightness (add) - if ( diff === 0 ) { - s = 0; - } else if ( l <= 0.5 ) { - s = diff / add; - } else { - s = diff / ( 2 - add ); - } - return [ Math.round(h) % 360, s, l, a == null ? 1 : a ]; -}; - -spaces.hsla.from = function ( hsla ) { - if ( hsla[ 0 ] == null || hsla[ 1 ] == null || hsla[ 2 ] == null ) { - return [ null, null, null, hsla[ 3 ] ]; - } - var h = hsla[ 0 ] / 360, - s = hsla[ 1 ], - l = hsla[ 2 ], - a = hsla[ 3 ], - q = l <= 0.5 ? l * ( 1 + s ) : l + s - l * s, - p = 2 * l - q; - - return [ - Math.round( hue2rgb( p, q, h + ( 1 / 3 ) ) * 255 ), - Math.round( hue2rgb( p, q, h ) * 255 ), - Math.round( hue2rgb( p, q, h - ( 1 / 3 ) ) * 255 ), - a - ]; -}; - - -each( spaces, function( spaceName, space ) { - var props = space.props, - cache = space.cache, - to = space.to, - from = space.from; - - // makes rgba() and hsla() - color.fn[ spaceName ] = function( value ) { - - // generate a cache for this space if it doesn't exist - if ( to && !this[ cache ] ) { - this[ cache ] = to( this._rgba ); - } - if ( value === undefined ) { - return this[ cache ].slice(); - } - - var ret, - type = jQuery.type( value ), - arr = ( type === "array" || type === "object" ) ? value : arguments, - local = this[ cache ].slice(); - - each( props, function( key, prop ) { - var val = arr[ type === "object" ? key : prop.idx ]; - if ( val == null ) { - val = local[ prop.idx ]; - } - local[ prop.idx ] = clamp( val, prop ); - }); - - if ( from ) { - ret = color( from( local ) ); - ret[ cache ] = local; - return ret; - } else { - return color( local ); - } - }; - - // makes red() green() blue() alpha() hue() saturation() lightness() - each( props, function( key, prop ) { - // alpha is included in more than one space - if ( color.fn[ key ] ) { - return; - } - color.fn[ key ] = function( value ) { - var vtype = jQuery.type( value ), - fn = ( key === "alpha" ? ( this._hsla ? "hsla" : "rgba" ) : spaceName ), - local = this[ fn ](), - cur = local[ prop.idx ], - match; - - if ( vtype === "undefined" ) { - return cur; - } - - if ( vtype === "function" ) { - value = value.call( this, cur ); - vtype = jQuery.type( value ); - } - if ( value == null && prop.empty ) { - return this; - } - if ( vtype === "string" ) { - match = rplusequals.exec( value ); - if ( match ) { - value = cur + parseFloat( match[ 2 ] ) * ( match[ 1 ] === "+" ? 1 : -1 ); - } - } - local[ prop.idx ] = value; - return this[ fn ]( local ); - }; - }); -}); - -// add cssHook and .fx.step function for each named hook. -// accept a space separated string of properties -color.hook = function( hook ) { - var hooks = hook.split( " " ); - each( hooks, function( i, hook ) { - jQuery.cssHooks[ hook ] = { - set: function( elem, value ) { - var parsed, curElem, - backgroundColor = ""; - - if ( value !== "transparent" && ( jQuery.type( value ) !== "string" || ( parsed = stringParse( value ) ) ) ) { - value = color( parsed || value ); - if ( !support.rgba && value._rgba[ 3 ] !== 1 ) { - curElem = hook === "backgroundColor" ? elem.parentNode : elem; - while ( - (backgroundColor === "" || backgroundColor === "transparent") && - curElem && curElem.style - ) { - try { - backgroundColor = jQuery.css( curElem, "backgroundColor" ); - curElem = curElem.parentNode; - } catch ( e ) { - } - } - - value = value.blend( backgroundColor && backgroundColor !== "transparent" ? - backgroundColor : - "_default" ); - } - - value = value.toRgbaString(); - } - try { - elem.style[ hook ] = value; - } catch( e ) { - // wrapped to prevent IE from throwing errors on "invalid" values like 'auto' or 'inherit' - } - } - }; - jQuery.fx.step[ hook ] = function( fx ) { - if ( !fx.colorInit ) { - fx.start = color( fx.elem, hook ); - fx.end = color( fx.end ); - fx.colorInit = true; - } - jQuery.cssHooks[ hook ].set( fx.elem, fx.start.transition( fx.end, fx.pos ) ); - }; - }); - -}; - -color.hook( stepHooks ); - -jQuery.cssHooks.borderColor = { - expand: function( value ) { - var expanded = {}; - - each( [ "Top", "Right", "Bottom", "Left" ], function( i, part ) { - expanded[ "border" + part + "Color" ] = value; - }); - return expanded; - } -}; - -// Basic color names only. -// Usage of any of the other color names requires adding yourself or including -// jquery.color.svg-names.js. -colors = jQuery.Color.names = { - // 4.1. Basic color keywords - aqua: "#00ffff", - black: "#000000", - blue: "#0000ff", - fuchsia: "#ff00ff", - gray: "#808080", - green: "#008000", - lime: "#00ff00", - maroon: "#800000", - navy: "#000080", - olive: "#808000", - purple: "#800080", - red: "#ff0000", - silver: "#c0c0c0", - teal: "#008080", - white: "#ffffff", - yellow: "#ffff00", - - // 4.2.3. "transparent" color keyword - transparent: [ null, null, null, 0 ], - - _default: "#ffffff" -}; - -})( jQuery ); - - -/******************************************************************************/ -/****************************** CLASS ANIMATIONS ******************************/ -/******************************************************************************/ -(function() { - -var classAnimationActions = [ "add", "remove", "toggle" ], - shorthandStyles = { - border: 1, - borderBottom: 1, - borderColor: 1, - borderLeft: 1, - borderRight: 1, - borderTop: 1, - borderWidth: 1, - margin: 1, - padding: 1 - }; - -$.each([ "borderLeftStyle", "borderRightStyle", "borderBottomStyle", "borderTopStyle" ], function( _, prop ) { - $.fx.step[ prop ] = function( fx ) { - if ( fx.end !== "none" && !fx.setAttr || fx.pos === 1 && !fx.setAttr ) { - jQuery.style( fx.elem, prop, fx.end ); - fx.setAttr = true; - } - }; -}); - -function getElementStyles( elem ) { - var key, len, - style = elem.ownerDocument.defaultView ? - elem.ownerDocument.defaultView.getComputedStyle( elem, null ) : - elem.currentStyle, - styles = {}; - - if ( style && style.length && style[ 0 ] && style[ style[ 0 ] ] ) { - len = style.length; - while ( len-- ) { - key = style[ len ]; - if ( typeof style[ key ] === "string" ) { - styles[ $.camelCase( key ) ] = style[ key ]; - } - } - // support: Opera, IE <9 - } else { - for ( key in style ) { - if ( typeof style[ key ] === "string" ) { - styles[ key ] = style[ key ]; - } - } - } - - return styles; -} - - -function styleDifference( oldStyle, newStyle ) { - var diff = {}, - name, value; - - for ( name in newStyle ) { - value = newStyle[ name ]; - if ( oldStyle[ name ] !== value ) { - if ( !shorthandStyles[ name ] ) { - if ( $.fx.step[ name ] || !isNaN( parseFloat( value ) ) ) { - diff[ name ] = value; - } - } - } - } - - return diff; -} - -// support: jQuery <1.8 -if ( !$.fn.addBack ) { - $.fn.addBack = function( selector ) { - return this.add( selector == null ? - this.prevObject : this.prevObject.filter( selector ) - ); - }; -} - -$.effects.animateClass = function( value, duration, easing, callback ) { - var o = $.speed( duration, easing, callback ); - - return this.queue( function() { - var animated = $( this ), - baseClass = animated.attr( "class" ) || "", - applyClassChange, - allAnimations = o.children ? animated.find( "*" ).addBack() : animated; - - // map the animated objects to store the original styles. - allAnimations = allAnimations.map(function() { - var el = $( this ); - return { - el: el, - start: getElementStyles( this ) - }; - }); - - // apply class change - applyClassChange = function() { - $.each( classAnimationActions, function(i, action) { - if ( value[ action ] ) { - animated[ action + "Class" ]( value[ action ] ); - } - }); - }; - applyClassChange(); - - // map all animated objects again - calculate new styles and diff - allAnimations = allAnimations.map(function() { - this.end = getElementStyles( this.el[ 0 ] ); - this.diff = styleDifference( this.start, this.end ); - return this; - }); - - // apply original class - animated.attr( "class", baseClass ); - - // map all animated objects again - this time collecting a promise - allAnimations = allAnimations.map(function() { - var styleInfo = this, - dfd = $.Deferred(), - opts = $.extend({}, o, { - queue: false, - complete: function() { - dfd.resolve( styleInfo ); - } - }); - - this.el.animate( this.diff, opts ); - return dfd.promise(); - }); - - // once all animations have completed: - $.when.apply( $, allAnimations.get() ).done(function() { - - // set the final class - applyClassChange(); - - // for each animated element, - // clear all css properties that were animated - $.each( arguments, function() { - var el = this.el; - $.each( this.diff, function(key) { - el.css( key, "" ); - }); - }); - - // this is guarnteed to be there if you use jQuery.speed() - // it also handles dequeuing the next anim... - o.complete.call( animated[ 0 ] ); - }); - }); -}; - -$.fn.extend({ - addClass: (function( orig ) { - return function( classNames, speed, easing, callback ) { - return speed ? - $.effects.animateClass.call( this, - { add: classNames }, speed, easing, callback ) : - orig.apply( this, arguments ); - }; - })( $.fn.addClass ), - - removeClass: (function( orig ) { - return function( classNames, speed, easing, callback ) { - return arguments.length > 1 ? - $.effects.animateClass.call( this, - { remove: classNames }, speed, easing, callback ) : - orig.apply( this, arguments ); - }; - })( $.fn.removeClass ), - - toggleClass: (function( orig ) { - return function( classNames, force, speed, easing, callback ) { - if ( typeof force === "boolean" || force === undefined ) { - if ( !speed ) { - // without speed parameter - return orig.apply( this, arguments ); - } else { - return $.effects.animateClass.call( this, - (force ? { add: classNames } : { remove: classNames }), - speed, easing, callback ); - } - } else { - // without force parameter - return $.effects.animateClass.call( this, - { toggle: classNames }, force, speed, easing ); - } - }; - })( $.fn.toggleClass ), - - switchClass: function( remove, add, speed, easing, callback) { - return $.effects.animateClass.call( this, { - add: add, - remove: remove - }, speed, easing, callback ); - } -}); - -})(); - -/******************************************************************************/ -/*********************************** EFFECTS **********************************/ -/******************************************************************************/ - -(function() { - -$.extend( $.effects, { - version: "1.10.3", - - // Saves a set of properties in a data storage - save: function( element, set ) { - for( var i=0; i < set.length; i++ ) { - if ( set[ i ] !== null ) { - element.data( dataSpace + set[ i ], element[ 0 ].style[ set[ i ] ] ); - } - } - }, - - // Restores a set of previously saved properties from a data storage - restore: function( element, set ) { - var val, i; - for( i=0; i < set.length; i++ ) { - if ( set[ i ] !== null ) { - val = element.data( dataSpace + set[ i ] ); - // support: jQuery 1.6.2 - // http://bugs.jquery.com/ticket/9917 - // jQuery 1.6.2 incorrectly returns undefined for any falsy value. - // We can't differentiate between "" and 0 here, so we just assume - // empty string since it's likely to be a more common value... - if ( val === undefined ) { - val = ""; - } - element.css( set[ i ], val ); - } - } - }, - - setMode: function( el, mode ) { - if (mode === "toggle") { - mode = el.is( ":hidden" ) ? "show" : "hide"; - } - return mode; - }, - - // Translates a [top,left] array into a baseline value - // this should be a little more flexible in the future to handle a string & hash - getBaseline: function( origin, original ) { - var y, x; - switch ( origin[ 0 ] ) { - case "top": y = 0; break; - case "middle": y = 0.5; break; - case "bottom": y = 1; break; - default: y = origin[ 0 ] / original.height; - } - switch ( origin[ 1 ] ) { - case "left": x = 0; break; - case "center": x = 0.5; break; - case "right": x = 1; break; - default: x = origin[ 1 ] / original.width; - } - return { - x: x, - y: y - }; - }, - - // Wraps the element around a wrapper that copies position properties - createWrapper: function( element ) { - - // if the element is already wrapped, return it - if ( element.parent().is( ".ui-effects-wrapper" )) { - return element.parent(); - } - - // wrap the element - var props = { - width: element.outerWidth(true), - height: element.outerHeight(true), - "float": element.css( "float" ) - }, - wrapper = $( "<div></div>" ) - .addClass( "ui-effects-wrapper" ) - .css({ - fontSize: "100%", - background: "transparent", - border: "none", - margin: 0, - padding: 0 - }), - // Store the size in case width/height are defined in % - Fixes #5245 - size = { - width: element.width(), - height: element.height() - }, - active = document.activeElement; - - // support: Firefox - // Firefox incorrectly exposes anonymous content - // https://bugzilla.mozilla.org/show_bug.cgi?id=561664 - try { - active.id; - } catch( e ) { - active = document.body; - } - - element.wrap( wrapper ); - - // Fixes #7595 - Elements lose focus when wrapped. - if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) { - $( active ).focus(); - } - - wrapper = element.parent(); //Hotfix for jQuery 1.4 since some change in wrap() seems to actually lose the reference to the wrapped element - - // transfer positioning properties to the wrapper - if ( element.css( "position" ) === "static" ) { - wrapper.css({ position: "relative" }); - element.css({ position: "relative" }); - } else { - $.extend( props, { - position: element.css( "position" ), - zIndex: element.css( "z-index" ) - }); - $.each([ "top", "left", "bottom", "right" ], function(i, pos) { - props[ pos ] = element.css( pos ); - if ( isNaN( parseInt( props[ pos ], 10 ) ) ) { - props[ pos ] = "auto"; - } - }); - element.css({ - position: "relative", - top: 0, - left: 0, - right: "auto", - bottom: "auto" - }); - } - element.css(size); - - return wrapper.css( props ).show(); - }, - - removeWrapper: function( element ) { - var active = document.activeElement; - - if ( element.parent().is( ".ui-effects-wrapper" ) ) { - element.parent().replaceWith( element ); - - // Fixes #7595 - Elements lose focus when wrapped. - if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) { - $( active ).focus(); - } - } - - - return element; - }, - - setTransition: function( element, list, factor, value ) { - value = value || {}; - $.each( list, function( i, x ) { - var unit = element.cssUnit( x ); - if ( unit[ 0 ] > 0 ) { - value[ x ] = unit[ 0 ] * factor + unit[ 1 ]; - } - }); - return value; - } -}); - -// return an effect options object for the given parameters: -function _normalizeArguments( effect, options, speed, callback ) { - - // allow passing all options as the first parameter - if ( $.isPlainObject( effect ) ) { - options = effect; - effect = effect.effect; - } - - // convert to an object - effect = { effect: effect }; - - // catch (effect, null, ...) - if ( options == null ) { - options = {}; - } - - // catch (effect, callback) - if ( $.isFunction( options ) ) { - callback = options; - speed = null; - options = {}; - } - - // catch (effect, speed, ?) - if ( typeof options === "number" || $.fx.speeds[ options ] ) { - callback = speed; - speed = options; - options = {}; - } - - // catch (effect, options, callback) - if ( $.isFunction( speed ) ) { - callback = speed; - speed = null; - } - - // add options to effect - if ( options ) { - $.extend( effect, options ); - } - - speed = speed || options.duration; - effect.duration = $.fx.off ? 0 : - typeof speed === "number" ? speed : - speed in $.fx.speeds ? $.fx.speeds[ speed ] : - $.fx.speeds._default; - - effect.complete = callback || options.complete; - - return effect; -} - -function standardAnimationOption( option ) { - // Valid standard speeds (nothing, number, named speed) - if ( !option || typeof option === "number" || $.fx.speeds[ option ] ) { - return true; - } - - // Invalid strings - treat as "normal" speed - if ( typeof option === "string" && !$.effects.effect[ option ] ) { - return true; - } - - // Complete callback - if ( $.isFunction( option ) ) { - return true; - } - - // Options hash (but not naming an effect) - if ( typeof option === "object" && !option.effect ) { - return true; - } - - // Didn't match any standard API - return false; -} - -$.fn.extend({ - effect: function( /* effect, options, speed, callback */ ) { - var args = _normalizeArguments.apply( this, arguments ), - mode = args.mode, - queue = args.queue, - effectMethod = $.effects.effect[ args.effect ]; - - if ( $.fx.off || !effectMethod ) { - // delegate to the original method (e.g., .show()) if possible - if ( mode ) { - return this[ mode ]( args.duration, args.complete ); - } else { - return this.each( function() { - if ( args.complete ) { - args.complete.call( this ); - } - }); - } - } - - function run( next ) { - var elem = $( this ), - complete = args.complete, - mode = args.mode; - - function done() { - if ( $.isFunction( complete ) ) { - complete.call( elem[0] ); - } - if ( $.isFunction( next ) ) { - next(); - } - } - - // If the element already has the correct final state, delegate to - // the core methods so the internal tracking of "olddisplay" works. - if ( elem.is( ":hidden" ) ? mode === "hide" : mode === "show" ) { - elem[ mode ](); - done(); - } else { - effectMethod.call( elem[0], args, done ); - } - } - - return queue === false ? this.each( run ) : this.queue( queue || "fx", run ); - }, - - show: (function( orig ) { - return function( option ) { - if ( standardAnimationOption( option ) ) { - return orig.apply( this, arguments ); - } else { - var args = _normalizeArguments.apply( this, arguments ); - args.mode = "show"; - return this.effect.call( this, args ); - } - }; - })( $.fn.show ), - - hide: (function( orig ) { - return function( option ) { - if ( standardAnimationOption( option ) ) { - return orig.apply( this, arguments ); - } else { - var args = _normalizeArguments.apply( this, arguments ); - args.mode = "hide"; - return this.effect.call( this, args ); - } - }; - })( $.fn.hide ), - - toggle: (function( orig ) { - return function( option ) { - if ( standardAnimationOption( option ) || typeof option === "boolean" ) { - return orig.apply( this, arguments ); - } else { - var args = _normalizeArguments.apply( this, arguments ); - args.mode = "toggle"; - return this.effect.call( this, args ); - } - }; - })( $.fn.toggle ), - - // helper functions - cssUnit: function(key) { - var style = this.css( key ), - val = []; - - $.each( [ "em", "px", "%", "pt" ], function( i, unit ) { - if ( style.indexOf( unit ) > 0 ) { - val = [ parseFloat( style ), unit ]; - } - }); - return val; - } -}); - -})(); - -/******************************************************************************/ -/*********************************** EASING ***********************************/ -/******************************************************************************/ - -(function() { - -// based on easing equations from Robert Penner (http://www.robertpenner.com/easing) - -var baseEasings = {}; - -$.each( [ "Quad", "Cubic", "Quart", "Quint", "Expo" ], function( i, name ) { - baseEasings[ name ] = function( p ) { - return Math.pow( p, i + 2 ); - }; -}); - -$.extend( baseEasings, { - Sine: function ( p ) { - return 1 - Math.cos( p * Math.PI / 2 ); - }, - Circ: function ( p ) { - return 1 - Math.sqrt( 1 - p * p ); - }, - Elastic: function( p ) { - return p === 0 || p === 1 ? p : - -Math.pow( 2, 8 * (p - 1) ) * Math.sin( ( (p - 1) * 80 - 7.5 ) * Math.PI / 15 ); - }, - Back: function( p ) { - return p * p * ( 3 * p - 2 ); - }, - Bounce: function ( p ) { - var pow2, - bounce = 4; - - while ( p < ( ( pow2 = Math.pow( 2, --bounce ) ) - 1 ) / 11 ) {} - return 1 / Math.pow( 4, 3 - bounce ) - 7.5625 * Math.pow( ( pow2 * 3 - 2 ) / 22 - p, 2 ); - } -}); - -$.each( baseEasings, function( name, easeIn ) { - $.easing[ "easeIn" + name ] = easeIn; - $.easing[ "easeOut" + name ] = function( p ) { - return 1 - easeIn( 1 - p ); - }; - $.easing[ "easeInOut" + name ] = function( p ) { - return p < 0.5 ? - easeIn( p * 2 ) / 2 : - 1 - easeIn( p * -2 + 2 ) / 2; - }; -}); - -})(); - -})(jQuery); - -(function( $, undefined ) { - -var uid = 0, - hideProps = {}, - showProps = {}; - -hideProps.height = hideProps.paddingTop = hideProps.paddingBottom = - hideProps.borderTopWidth = hideProps.borderBottomWidth = "hide"; -showProps.height = showProps.paddingTop = showProps.paddingBottom = - showProps.borderTopWidth = showProps.borderBottomWidth = "show"; - -$.widget( "ui.accordion", { - version: "1.10.3", - options: { - active: 0, - animate: {}, - collapsible: false, - event: "click", - header: "> li > :first-child,> :not(li):even", - heightStyle: "auto", - icons: { - activeHeader: "ui-icon-triangle-1-s", - header: "ui-icon-triangle-1-e" - }, - - // callbacks - activate: null, - beforeActivate: null - }, - - _create: function() { - var options = this.options; - this.prevShow = this.prevHide = $(); - this.element.addClass( "ui-accordion ui-widget ui-helper-reset" ) - // ARIA - .attr( "role", "tablist" ); - - // don't allow collapsible: false and active: false / null - if ( !options.collapsible && (options.active === false || options.active == null) ) { - options.active = 0; - } - - this._processPanels(); - // handle negative values - if ( options.active < 0 ) { - options.active += this.headers.length; - } - this._refresh(); - }, - - _getCreateEventData: function() { - return { - header: this.active, - panel: !this.active.length ? $() : this.active.next(), - content: !this.active.length ? $() : this.active.next() - }; - }, - - _createIcons: function() { - var icons = this.options.icons; - if ( icons ) { - $( "<span>" ) - .addClass( "ui-accordion-header-icon ui-icon " + icons.header ) - .prependTo( this.headers ); - this.active.children( ".ui-accordion-header-icon" ) - .removeClass( icons.header ) - .addClass( icons.activeHeader ); - this.headers.addClass( "ui-accordion-icons" ); - } - }, - - _destroyIcons: function() { - this.headers - .removeClass( "ui-accordion-icons" ) - .children( ".ui-accordion-header-icon" ) - .remove(); - }, - - _destroy: function() { - var contents; - - // clean up main element - this.element - .removeClass( "ui-accordion ui-widget ui-helper-reset" ) - .removeAttr( "role" ); - - // clean up headers - this.headers - .removeClass( "ui-accordion-header ui-accordion-header-active ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-state-disabled ui-corner-top" ) - .removeAttr( "role" ) - .removeAttr( "aria-selected" ) - .removeAttr( "aria-controls" ) - .removeAttr( "tabIndex" ) - .each(function() { - if ( /^ui-accordion/.test( this.id ) ) { - this.removeAttribute( "id" ); - } - }); - this._destroyIcons(); - - // clean up content panels - contents = this.headers.next() - .css( "display", "" ) - .removeAttr( "role" ) - .removeAttr( "aria-expanded" ) - .removeAttr( "aria-hidden" ) - .removeAttr( "aria-labelledby" ) - .removeClass( "ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active ui-state-disabled" ) - .each(function() { - if ( /^ui-accordion/.test( this.id ) ) { - this.removeAttribute( "id" ); - } - }); - if ( this.options.heightStyle !== "content" ) { - contents.css( "height", "" ); - } - }, - - _setOption: function( key, value ) { - if ( key === "active" ) { - // _activate() will handle invalid values and update this.options - this._activate( value ); - return; - } - - if ( key === "event" ) { - if ( this.options.event ) { - this._off( this.headers, this.options.event ); - } - this._setupEvents( value ); - } - - this._super( key, value ); - - // setting collapsible: false while collapsed; open first panel - if ( key === "collapsible" && !value && this.options.active === false ) { - this._activate( 0 ); - } - - if ( key === "icons" ) { - this._destroyIcons(); - if ( value ) { - this._createIcons(); - } - } - - // #5332 - opacity doesn't cascade to positioned elements in IE - // so we need to add the disabled class to the headers and panels - if ( key === "disabled" ) { - this.headers.add( this.headers.next() ) - .toggleClass( "ui-state-disabled", !!value ); - } - }, - - _keydown: function( event ) { - /*jshint maxcomplexity:15*/ - if ( event.altKey || event.ctrlKey ) { - return; - } - - var keyCode = $.ui.keyCode, - length = this.headers.length, - currentIndex = this.headers.index( event.target ), - toFocus = false; - - switch ( event.keyCode ) { - case keyCode.RIGHT: - case keyCode.DOWN: - toFocus = this.headers[ ( currentIndex + 1 ) % length ]; - break; - case keyCode.LEFT: - case keyCode.UP: - toFocus = this.headers[ ( currentIndex - 1 + length ) % length ]; - break; - case keyCode.SPACE: - case keyCode.ENTER: - this._eventHandler( event ); - break; - case keyCode.HOME: - toFocus = this.headers[ 0 ]; - break; - case keyCode.END: - toFocus = this.headers[ length - 1 ]; - break; - } - - if ( toFocus ) { - $( event.target ).attr( "tabIndex", -1 ); - $( toFocus ).attr( "tabIndex", 0 ); - toFocus.focus(); - event.preventDefault(); - } - }, - - _panelKeyDown : function( event ) { - if ( event.keyCode === $.ui.keyCode.UP && event.ctrlKey ) { - $( event.currentTarget ).prev().focus(); - } - }, - - refresh: function() { - var options = this.options; - this._processPanels(); - - // was collapsed or no panel - if ( ( options.active === false && options.collapsible === true ) || !this.headers.length ) { - options.active = false; - this.active = $(); - // active false only when collapsible is true - } else if ( options.active === false ) { - this._activate( 0 ); - // was active, but active panel is gone - } else if ( this.active.length && !$.contains( this.element[ 0 ], this.active[ 0 ] ) ) { - // all remaining panel are disabled - if ( this.headers.length === this.headers.find(".ui-state-disabled").length ) { - options.active = false; - this.active = $(); - // activate previous panel - } else { - this._activate( Math.max( 0, options.active - 1 ) ); - } - // was active, active panel still exists - } else { - // make sure active index is correct - options.active = this.headers.index( this.active ); - } - - this._destroyIcons(); - - this._refresh(); - }, - - _processPanels: function() { - this.headers = this.element.find( this.options.header ) - .addClass( "ui-accordion-header ui-helper-reset ui-state-default ui-corner-all" ); - - this.headers.next() - .addClass( "ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom" ) - .filter(":not(.ui-accordion-content-active)") - .hide(); - }, - - _refresh: function() { - var maxHeight, - options = this.options, - heightStyle = options.heightStyle, - parent = this.element.parent(), - accordionId = this.accordionId = "ui-accordion-" + - (this.element.attr( "id" ) || ++uid); - - this.active = this._findActive( options.active ) - .addClass( "ui-accordion-header-active ui-state-active ui-corner-top" ) - .removeClass( "ui-corner-all" ); - this.active.next() - .addClass( "ui-accordion-content-active" ) - .show(); - - this.headers - .attr( "role", "tab" ) - .each(function( i ) { - var header = $( this ), - headerId = header.attr( "id" ), - panel = header.next(), - panelId = panel.attr( "id" ); - if ( !headerId ) { - headerId = accordionId + "-header-" + i; - header.attr( "id", headerId ); - } - if ( !panelId ) { - panelId = accordionId + "-panel-" + i; - panel.attr( "id", panelId ); - } - header.attr( "aria-controls", panelId ); - panel.attr( "aria-labelledby", headerId ); - }) - .next() - .attr( "role", "tabpanel" ); - - this.headers - .not( this.active ) - .attr({ - "aria-selected": "false", - tabIndex: -1 - }) - .next() - .attr({ - "aria-expanded": "false", - "aria-hidden": "true" - }) - .hide(); - - // make sure at least one header is in the tab order - if ( !this.active.length ) { - this.headers.eq( 0 ).attr( "tabIndex", 0 ); - } else { - this.active.attr({ - "aria-selected": "true", - tabIndex: 0 - }) - .next() - .attr({ - "aria-expanded": "true", - "aria-hidden": "false" - }); - } - - this._createIcons(); - - this._setupEvents( options.event ); - - if ( heightStyle === "fill" ) { - maxHeight = parent.height(); - this.element.siblings( ":visible" ).each(function() { - var elem = $( this ), - position = elem.css( "position" ); - - if ( position === "absolute" || position === "fixed" ) { - return; - } - maxHeight -= elem.outerHeight( true ); - }); - - this.headers.each(function() { - maxHeight -= $( this ).outerHeight( true ); - }); - - this.headers.next() - .each(function() { - $( this ).height( Math.max( 0, maxHeight - - $( this ).innerHeight() + $( this ).height() ) ); - }) - .css( "overflow", "auto" ); - } else if ( heightStyle === "auto" ) { - maxHeight = 0; - this.headers.next() - .each(function() { - maxHeight = Math.max( maxHeight, $( this ).css( "height", "" ).height() ); - }) - .height( maxHeight ); - } - }, - - _activate: function( index ) { - var active = this._findActive( index )[ 0 ]; - - // trying to activate the already active panel - if ( active === this.active[ 0 ] ) { - return; - } - - // trying to collapse, simulate a click on the currently active header - active = active || this.active[ 0 ]; - - this._eventHandler({ - target: active, - currentTarget: active, - preventDefault: $.noop - }); - }, - - _findActive: function( selector ) { - return typeof selector === "number" ? this.headers.eq( selector ) : $(); - }, - - _setupEvents: function( event ) { - var events = { - keydown: "_keydown" - }; - if ( event ) { - $.each( event.split(" "), function( index, eventName ) { - events[ eventName ] = "_eventHandler"; - }); - } - - this._off( this.headers.add( this.headers.next() ) ); - this._on( this.headers, events ); - this._on( this.headers.next(), { keydown: "_panelKeyDown" }); - this._hoverable( this.headers ); - this._focusable( this.headers ); - }, - - _eventHandler: function( event ) { - var options = this.options, - active = this.active, - clicked = $( event.currentTarget ), - clickedIsActive = clicked[ 0 ] === active[ 0 ], - collapsing = clickedIsActive && options.collapsible, - toShow = collapsing ? $() : clicked.next(), - toHide = active.next(), - eventData = { - oldHeader: active, - oldPanel: toHide, - newHeader: collapsing ? $() : clicked, - newPanel: toShow - }; - - event.preventDefault(); - - if ( - // click on active header, but not collapsible - ( clickedIsActive && !options.collapsible ) || - // allow canceling activation - ( this._trigger( "beforeActivate", event, eventData ) === false ) ) { - return; - } - - options.active = collapsing ? false : this.headers.index( clicked ); - - // when the call to ._toggle() comes after the class changes - // it causes a very odd bug in IE 8 (see #6720) - this.active = clickedIsActive ? $() : clicked; - this._toggle( eventData ); - - // switch classes - // corner classes on the previously active header stay after the animation - active.removeClass( "ui-accordion-header-active ui-state-active" ); - if ( options.icons ) { - active.children( ".ui-accordion-header-icon" ) - .removeClass( options.icons.activeHeader ) - .addClass( options.icons.header ); - } - - if ( !clickedIsActive ) { - clicked - .removeClass( "ui-corner-all" ) - .addClass( "ui-accordion-header-active ui-state-active ui-corner-top" ); - if ( options.icons ) { - clicked.children( ".ui-accordion-header-icon" ) - .removeClass( options.icons.header ) - .addClass( options.icons.activeHeader ); - } - - clicked - .next() - .addClass( "ui-accordion-content-active" ); - } - }, - - _toggle: function( data ) { - var toShow = data.newPanel, - toHide = this.prevShow.length ? this.prevShow : data.oldPanel; - - // handle activating a panel during the animation for another activation - this.prevShow.add( this.prevHide ).stop( true, true ); - this.prevShow = toShow; - this.prevHide = toHide; - - if ( this.options.animate ) { - this._animate( toShow, toHide, data ); - } else { - toHide.hide(); - toShow.show(); - this._toggleComplete( data ); - } - - toHide.attr({ - "aria-expanded": "false", - "aria-hidden": "true" - }); - toHide.prev().attr( "aria-selected", "false" ); - // if we're switching panels, remove the old header from the tab order - // if we're opening from collapsed state, remove the previous header from the tab order - // if we're collapsing, then keep the collapsing header in the tab order - if ( toShow.length && toHide.length ) { - toHide.prev().attr( "tabIndex", -1 ); - } else if ( toShow.length ) { - this.headers.filter(function() { - return $( this ).attr( "tabIndex" ) === 0; - }) - .attr( "tabIndex", -1 ); - } - - toShow - .attr({ - "aria-expanded": "true", - "aria-hidden": "false" - }) - .prev() - .attr({ - "aria-selected": "true", - tabIndex: 0 - }); - }, - - _animate: function( toShow, toHide, data ) { - var total, easing, duration, - that = this, - adjust = 0, - down = toShow.length && - ( !toHide.length || ( toShow.index() < toHide.index() ) ), - animate = this.options.animate || {}, - options = down && animate.down || animate, - complete = function() { - that._toggleComplete( data ); - }; - - if ( typeof options === "number" ) { - duration = options; - } - if ( typeof options === "string" ) { - easing = options; - } - // fall back from options to animation in case of partial down settings - easing = easing || options.easing || animate.easing; - duration = duration || options.duration || animate.duration; - - if ( !toHide.length ) { - return toShow.animate( showProps, duration, easing, complete ); - } - if ( !toShow.length ) { - return toHide.animate( hideProps, duration, easing, complete ); - } - - total = toShow.show().outerHeight(); - toHide.animate( hideProps, { - duration: duration, - easing: easing, - step: function( now, fx ) { - fx.now = Math.round( now ); - } - }); - toShow - .hide() - .animate( showProps, { - duration: duration, - easing: easing, - complete: complete, - step: function( now, fx ) { - fx.now = Math.round( now ); - if ( fx.prop !== "height" ) { - adjust += fx.now; - } else if ( that.options.heightStyle !== "content" ) { - fx.now = Math.round( total - toHide.outerHeight() - adjust ); - adjust = 0; - } - } - }); - }, - - _toggleComplete: function( data ) { - var toHide = data.oldPanel; - - toHide - .removeClass( "ui-accordion-content-active" ) - .prev() - .removeClass( "ui-corner-top" ) - .addClass( "ui-corner-all" ); - - // Work around for rendering bug in IE (#5421) - if ( toHide.length ) { - toHide.parent()[0].className = toHide.parent()[0].className; - } - - this._trigger( "activate", null, data ); - } -}); - -})( jQuery ); - -(function( $, undefined ) { - -// used to prevent race conditions with remote data sources -var requestIndex = 0; - -$.widget( "ui.autocomplete", { - version: "1.10.3", - defaultElement: "<input>", - options: { - appendTo: null, - autoFocus: false, - delay: 300, - minLength: 1, - position: { - my: "left top", - at: "left bottom", - collision: "none" - }, - source: null, - - // callbacks - change: null, - close: null, - focus: null, - open: null, - response: null, - search: null, - select: null - }, - - pending: 0, - - _create: function() { - // Some browsers only repeat keydown events, not keypress events, - // so we use the suppressKeyPress flag to determine if we've already - // handled the keydown event. #7269 - // Unfortunately the code for & in keypress is the same as the up arrow, - // so we use the suppressKeyPressRepeat flag to avoid handling keypress - // events when we know the keydown event was used to modify the - // search term. #7799 - var suppressKeyPress, suppressKeyPressRepeat, suppressInput, - nodeName = this.element[0].nodeName.toLowerCase(), - isTextarea = nodeName === "textarea", - isInput = nodeName === "input"; - - this.isMultiLine = - // Textareas are always multi-line - isTextarea ? true : - // Inputs are always single-line, even if inside a contentEditable element - // IE also treats inputs as contentEditable - isInput ? false : - // All other element types are determined by whether or not they're contentEditable - this.element.prop( "isContentEditable" ); - - this.valueMethod = this.element[ isTextarea || isInput ? "val" : "text" ]; - this.isNewMenu = true; - - this.element - .addClass( "ui-autocomplete-input" ) - .attr( "autocomplete", "off" ); - - this._on( this.element, { - keydown: function( event ) { - /*jshint maxcomplexity:15*/ - if ( this.element.prop( "readOnly" ) ) { - suppressKeyPress = true; - suppressInput = true; - suppressKeyPressRepeat = true; - return; - } - - suppressKeyPress = false; - suppressInput = false; - suppressKeyPressRepeat = false; - var keyCode = $.ui.keyCode; - switch( event.keyCode ) { - case keyCode.PAGE_UP: - suppressKeyPress = true; - this._move( "previousPage", event ); - break; - case keyCode.PAGE_DOWN: - suppressKeyPress = true; - this._move( "nextPage", event ); - break; - case keyCode.UP: - suppressKeyPress = true; - this._keyEvent( "previous", event ); - break; - case keyCode.DOWN: - suppressKeyPress = true; - this._keyEvent( "next", event ); - break; - case keyCode.ENTER: - case keyCode.NUMPAD_ENTER: - // when menu is open and has focus - if ( this.menu.active ) { - // #6055 - Opera still allows the keypress to occur - // which causes forms to submit - suppressKeyPress = true; - event.preventDefault(); - this.menu.select( event ); - } - break; - case keyCode.TAB: - if ( this.menu.active ) { - this.menu.select( event ); - } - break; - case keyCode.ESCAPE: - if ( this.menu.element.is( ":visible" ) ) { - this._value( this.term ); - this.close( event ); - // Different browsers have different default behavior for escape - // Single press can mean undo or clear - // Double press in IE means clear the whole form - event.preventDefault(); - } - break; - default: - suppressKeyPressRepeat = true; - // search timeout should be triggered before the input value is changed - this._searchTimeout( event ); - break; - } - }, - keypress: function( event ) { - if ( suppressKeyPress ) { - suppressKeyPress = false; - if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) { - event.preventDefault(); - } - return; - } - if ( suppressKeyPressRepeat ) { - return; - } - - // replicate some key handlers to allow them to repeat in Firefox and Opera - var keyCode = $.ui.keyCode; - switch( event.keyCode ) { - case keyCode.PAGE_UP: - this._move( "previousPage", event ); - break; - case keyCode.PAGE_DOWN: - this._move( "nextPage", event ); - break; - case keyCode.UP: - this._keyEvent( "previous", event ); - break; - case keyCode.DOWN: - this._keyEvent( "next", event ); - break; - } - }, - input: function( event ) { - if ( suppressInput ) { - suppressInput = false; - event.preventDefault(); - return; - } - this._searchTimeout( event ); - }, - focus: function() { - this.selectedItem = null; - this.previous = this._value(); - }, - blur: function( event ) { - if ( this.cancelBlur ) { - delete this.cancelBlur; - return; - } - - clearTimeout( this.searching ); - this.close( event ); - this._change( event ); - } - }); - - this._initSource(); - this.menu = $( "<ul>" ) - .addClass( "ui-autocomplete ui-front" ) - .appendTo( this._appendTo() ) - .menu({ - // disable ARIA support, the live region takes care of that - role: null - }) - .hide() - .data( "ui-menu" ); - - this._on( this.menu.element, { - mousedown: function( event ) { - // prevent moving focus out of the text field - event.preventDefault(); - - // IE doesn't prevent moving focus even with event.preventDefault() - // so we set a flag to know when we should ignore the blur event - this.cancelBlur = true; - this._delay(function() { - delete this.cancelBlur; - }); - - // clicking on the scrollbar causes focus to shift to the body - // but we can't detect a mouseup or a click immediately afterward - // so we have to track the next mousedown and close the menu if - // the user clicks somewhere outside of the autocomplete - var menuElement = this.menu.element[ 0 ]; - if ( !$( event.target ).closest( ".ui-menu-item" ).length ) { - this._delay(function() { - var that = this; - this.document.one( "mousedown", function( event ) { - if ( event.target !== that.element[ 0 ] && - event.target !== menuElement && - !$.contains( menuElement, event.target ) ) { - that.close(); - } - }); - }); - } - }, - menufocus: function( event, ui ) { - // support: Firefox - // Prevent accidental activation of menu items in Firefox (#7024 #9118) - if ( this.isNewMenu ) { - this.isNewMenu = false; - if ( event.originalEvent && /^mouse/.test( event.originalEvent.type ) ) { - this.menu.blur(); - - this.document.one( "mousemove", function() { - $( event.target ).trigger( event.originalEvent ); - }); - - return; - } - } - - var item = ui.item.data( "ui-autocomplete-item" ); - if ( false !== this._trigger( "focus", event, { item: item } ) ) { - // use value to match what will end up in the input, if it was a key event - if ( event.originalEvent && /^key/.test( event.originalEvent.type ) ) { - this._value( item.value ); - } - } else { - // Normally the input is populated with the item's value as the - // menu is navigated, causing screen readers to notice a change and - // announce the item. Since the focus event was canceled, this doesn't - // happen, so we update the live region so that screen readers can - // still notice the change and announce it. - this.liveRegion.text( item.value ); - } - }, - menuselect: function( event, ui ) { - var item = ui.item.data( "ui-autocomplete-item" ), - previous = this.previous; - - // only trigger when focus was lost (click on menu) - if ( this.element[0] !== this.document[0].activeElement ) { - this.element.focus(); - this.previous = previous; - // #6109 - IE triggers two focus events and the second - // is asynchronous, so we need to reset the previous - // term synchronously and asynchronously :-( - this._delay(function() { - this.previous = previous; - this.selectedItem = item; - }); - } - - if ( false !== this._trigger( "select", event, { item: item } ) ) { - this._value( item.value ); - } - // reset the term after the select event - // this allows custom select handling to work properly - this.term = this._value(); - - this.close( event ); - this.selectedItem = item; - } - }); - - this.liveRegion = $( "<span>", { - role: "status", - "aria-live": "polite" - }) - .addClass( "ui-helper-hidden-accessible" ) - .insertBefore( this.element ); - - // turning off autocomplete prevents the browser from remembering the - // value when navigating through history, so we re-enable autocomplete - // if the page is unloaded before the widget is destroyed. #7790 - this._on( this.window, { - beforeunload: function() { - this.element.removeAttr( "autocomplete" ); - } - }); - }, - - _destroy: function() { - clearTimeout( this.searching ); - this.element - .removeClass( "ui-autocomplete-input" ) - .removeAttr( "autocomplete" ); - this.menu.element.remove(); - this.liveRegion.remove(); - }, - - _setOption: function( key, value ) { - this._super( key, value ); - if ( key === "source" ) { - this._initSource(); - } - if ( key === "appendTo" ) { - this.menu.element.appendTo( this._appendTo() ); - } - if ( key === "disabled" && value && this.xhr ) { - this.xhr.abort(); - } - }, - - _appendTo: function() { - var element = this.options.appendTo; - - if ( element ) { - element = element.jquery || element.nodeType ? - $( element ) : - this.document.find( element ).eq( 0 ); - } - - if ( !element ) { - element = this.element.closest( ".ui-front" ); - } - - if ( !element.length ) { - element = this.document[0].body; - } - - return element; - }, - - _initSource: function() { - var array, url, - that = this; - if ( $.isArray(this.options.source) ) { - array = this.options.source; - this.source = function( request, response ) { - response( $.ui.autocomplete.filter( array, request.term ) ); - }; - } else if ( typeof this.options.source === "string" ) { - url = this.options.source; - this.source = function( request, response ) { - if ( that.xhr ) { - that.xhr.abort(); - } - that.xhr = $.ajax({ - url: url, - data: request, - dataType: "json", - success: function( data ) { - response( data ); - }, - error: function() { - response( [] ); - } - }); - }; - } else { - this.source = this.options.source; - } - }, - - _searchTimeout: function( event ) { - clearTimeout( this.searching ); - this.searching = this._delay(function() { - // only search if the value has changed - if ( this.term !== this._value() ) { - this.selectedItem = null; - this.search( null, event ); - } - }, this.options.delay ); - }, - - search: function( value, event ) { - value = value != null ? value : this._value(); - - // always save the actual value, not the one passed as an argument - this.term = this._value(); - - if ( value.length < this.options.minLength ) { - return this.close( event ); - } - - if ( this._trigger( "search", event ) === false ) { - return; - } - - return this._search( value ); - }, - - _search: function( value ) { - this.pending++; - this.element.addClass( "ui-autocomplete-loading" ); - this.cancelSearch = false; - - this.source( { term: value }, this._response() ); - }, - - _response: function() { - var that = this, - index = ++requestIndex; - - return function( content ) { - if ( index === requestIndex ) { - that.__response( content ); - } - - that.pending--; - if ( !that.pending ) { - that.element.removeClass( "ui-autocomplete-loading" ); - } - }; - }, - - __response: function( content ) { - if ( content ) { - content = this._normalize( content ); - } - this._trigger( "response", null, { content: content } ); - if ( !this.options.disabled && content && content.length && !this.cancelSearch ) { - this._suggest( content ); - this._trigger( "open" ); - } else { - // use ._close() instead of .close() so we don't cancel future searches - this._close(); - } - }, - - close: function( event ) { - this.cancelSearch = true; - this._close( event ); - }, - - _close: function( event ) { - if ( this.menu.element.is( ":visible" ) ) { - this.menu.element.hide(); - this.menu.blur(); - this.isNewMenu = true; - this._trigger( "close", event ); - } - }, - - _change: function( event ) { - if ( this.previous !== this._value() ) { - this._trigger( "change", event, { item: this.selectedItem } ); - } - }, - - _normalize: function( items ) { - // assume all items have the right format when the first item is complete - if ( items.length && items[0].label && items[0].value ) { - return items; - } - return $.map( items, function( item ) { - if ( typeof item === "string" ) { - return { - label: item, - value: item - }; - } - return $.extend({ - label: item.label || item.value, - value: item.value || item.label - }, item ); - }); - }, - - _suggest: function( items ) { - var ul = this.menu.element.empty(); - this._renderMenu( ul, items ); - this.isNewMenu = true; - this.menu.refresh(); - - // size and position menu - ul.show(); - this._resizeMenu(); - ul.position( $.extend({ - of: this.element - }, this.options.position )); - - if ( this.options.autoFocus ) { - this.menu.next(); - } - }, - - _resizeMenu: function() { - var ul = this.menu.element; - ul.outerWidth( Math.max( - // Firefox wraps long text (possibly a rounding bug) - // so we add 1px to avoid the wrapping (#7513) - ul.width( "" ).outerWidth() + 1, - this.element.outerWidth() - ) ); - }, - - _renderMenu: function( ul, items ) { - var that = this; - $.each( items, function( index, item ) { - that._renderItemData( ul, item ); - }); - }, - - _renderItemData: function( ul, item ) { - return this._renderItem( ul, item ).data( "ui-autocomplete-item", item ); - }, - - _renderItem: function( ul, item ) { - return $( "<li>" ) - .append( $( "<a>" ).text( item.label ) ) - .appendTo( ul ); - }, - - _move: function( direction, event ) { - if ( !this.menu.element.is( ":visible" ) ) { - this.search( null, event ); - return; - } - if ( this.menu.isFirstItem() && /^previous/.test( direction ) || - this.menu.isLastItem() && /^next/.test( direction ) ) { - this._value( this.term ); - this.menu.blur(); - return; - } - this.menu[ direction ]( event ); - }, - - widget: function() { - return this.menu.element; - }, - - _value: function() { - return this.valueMethod.apply( this.element, arguments ); - }, - - _keyEvent: function( keyEvent, event ) { - if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) { - this._move( keyEvent, event ); - - // prevents moving cursor to beginning/end of the text field in some browsers - event.preventDefault(); - } - } -}); - -$.extend( $.ui.autocomplete, { - escapeRegex: function( value ) { - return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&"); - }, - filter: function(array, term) { - var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" ); - return $.grep( array, function(value) { - return matcher.test( value.label || value.value || value ); - }); - } -}); - - -// live region extension, adding a `messages` option -// NOTE: This is an experimental API. We are still investigating -// a full solution for string manipulation and internationalization. -$.widget( "ui.autocomplete", $.ui.autocomplete, { - options: { - messages: { - noResults: "No search results.", - results: function( amount ) { - return amount + ( amount > 1 ? " results are" : " result is" ) + - " available, use up and down arrow keys to navigate."; - } - } - }, - - __response: function( content ) { - var message; - this._superApply( arguments ); - if ( this.options.disabled || this.cancelSearch ) { - return; - } - if ( content && content.length ) { - message = this.options.messages.results( content.length ); - } else { - message = this.options.messages.noResults; - } - this.liveRegion.text( message ); - } -}); - -}( jQuery )); - -(function( $, undefined ) { - -var lastActive, startXPos, startYPos, clickDragged, - baseClasses = "ui-button ui-widget ui-state-default ui-corner-all", - stateClasses = "ui-state-hover ui-state-active ", - typeClasses = "ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon-primary ui-button-text-icon-secondary ui-button-text-only", - formResetHandler = function() { - var form = $( this ); - setTimeout(function() { - form.find( ":ui-button" ).button( "refresh" ); - }, 1 ); - }, - radioGroup = function( radio ) { - var name = radio.name, - form = radio.form, - radios = $( [] ); - if ( name ) { - name = name.replace( /'/g, "\\'" ); - if ( form ) { - radios = $( form ).find( "[name='" + name + "']" ); - } else { - radios = $( "[name='" + name + "']", radio.ownerDocument ) - .filter(function() { - return !this.form; - }); - } - } - return radios; - }; - -$.widget( "ui.button", { - version: "1.10.3", - defaultElement: "<button>", - options: { - disabled: null, - text: true, - label: null, - icons: { - primary: null, - secondary: null - } - }, - _create: function() { - this.element.closest( "form" ) - .unbind( "reset" + this.eventNamespace ) - .bind( "reset" + this.eventNamespace, formResetHandler ); - - if ( typeof this.options.disabled !== "boolean" ) { - this.options.disabled = !!this.element.prop( "disabled" ); - } else { - this.element.prop( "disabled", this.options.disabled ); - } - - this._determineButtonType(); - this.hasTitle = !!this.buttonElement.attr( "title" ); - - var that = this, - options = this.options, - toggleButton = this.type === "checkbox" || this.type === "radio", - activeClass = !toggleButton ? "ui-state-active" : "", - focusClass = "ui-state-focus"; - - if ( options.label === null ) { - options.label = (this.type === "input" ? this.buttonElement.val() : this.buttonElement.html()); - } - - this._hoverable( this.buttonElement ); - - this.buttonElement - .addClass( baseClasses ) - .attr( "role", "button" ) - .bind( "mouseenter" + this.eventNamespace, function() { - if ( options.disabled ) { - return; - } - if ( this === lastActive ) { - $( this ).addClass( "ui-state-active" ); - } - }) - .bind( "mouseleave" + this.eventNamespace, function() { - if ( options.disabled ) { - return; - } - $( this ).removeClass( activeClass ); - }) - .bind( "click" + this.eventNamespace, function( event ) { - if ( options.disabled ) { - event.preventDefault(); - event.stopImmediatePropagation(); - } - }); - - this.element - .bind( "focus" + this.eventNamespace, function() { - // no need to check disabled, focus won't be triggered anyway - that.buttonElement.addClass( focusClass ); - }) - .bind( "blur" + this.eventNamespace, function() { - that.buttonElement.removeClass( focusClass ); - }); - - if ( toggleButton ) { - this.element.bind( "change" + this.eventNamespace, function() { - if ( clickDragged ) { - return; - } - that.refresh(); - }); - // if mouse moves between mousedown and mouseup (drag) set clickDragged flag - // prevents issue where button state changes but checkbox/radio checked state - // does not in Firefox (see ticket #6970) - this.buttonElement - .bind( "mousedown" + this.eventNamespace, function( event ) { - if ( options.disabled ) { - return; - } - clickDragged = false; - startXPos = event.pageX; - startYPos = event.pageY; - }) - .bind( "mouseup" + this.eventNamespace, function( event ) { - if ( options.disabled ) { - return; - } - if ( startXPos !== event.pageX || startYPos !== event.pageY ) { - clickDragged = true; - } - }); - } - - if ( this.type === "checkbox" ) { - this.buttonElement.bind( "click" + this.eventNamespace, function() { - if ( options.disabled || clickDragged ) { - return false; - } - }); - } else if ( this.type === "radio" ) { - this.buttonElement.bind( "click" + this.eventNamespace, function() { - if ( options.disabled || clickDragged ) { - return false; - } - $( this ).addClass( "ui-state-active" ); - that.buttonElement.attr( "aria-pressed", "true" ); - - var radio = that.element[ 0 ]; - radioGroup( radio ) - .not( radio ) - .map(function() { - return $( this ).button( "widget" )[ 0 ]; - }) - .removeClass( "ui-state-active" ) - .attr( "aria-pressed", "false" ); - }); - } else { - this.buttonElement - .bind( "mousedown" + this.eventNamespace, function() { - if ( options.disabled ) { - return false; - } - $( this ).addClass( "ui-state-active" ); - lastActive = this; - that.document.one( "mouseup", function() { - lastActive = null; - }); - }) - .bind( "mouseup" + this.eventNamespace, function() { - if ( options.disabled ) { - return false; - } - $( this ).removeClass( "ui-state-active" ); - }) - .bind( "keydown" + this.eventNamespace, function(event) { - if ( options.disabled ) { - return false; - } - if ( event.keyCode === $.ui.keyCode.SPACE || event.keyCode === $.ui.keyCode.ENTER ) { - $( this ).addClass( "ui-state-active" ); - } - }) - // see #8559, we bind to blur here in case the button element loses - // focus between keydown and keyup, it would be left in an "active" state - .bind( "keyup" + this.eventNamespace + " blur" + this.eventNamespace, function() { - $( this ).removeClass( "ui-state-active" ); - }); - - if ( this.buttonElement.is("a") ) { - this.buttonElement.keyup(function(event) { - if ( event.keyCode === $.ui.keyCode.SPACE ) { - // TODO pass through original event correctly (just as 2nd argument doesn't work) - $( this ).click(); - } - }); - } - } - - // TODO: pull out $.Widget's handling for the disabled option into - // $.Widget.prototype._setOptionDisabled so it's easy to proxy and can - // be overridden by individual plugins - this._setOption( "disabled", options.disabled ); - this._resetButton(); - }, - - _determineButtonType: function() { - var ancestor, labelSelector, checked; - - if ( this.element.is("[type=checkbox]") ) { - this.type = "checkbox"; - } else if ( this.element.is("[type=radio]") ) { - this.type = "radio"; - } else if ( this.element.is("input") ) { - this.type = "input"; - } else { - this.type = "button"; - } - - if ( this.type === "checkbox" || this.type === "radio" ) { - // we don't search against the document in case the element - // is disconnected from the DOM - ancestor = this.element.parents().last(); - labelSelector = "label[for='" + this.element.attr("id") + "']"; - this.buttonElement = ancestor.find( labelSelector ); - if ( !this.buttonElement.length ) { - ancestor = ancestor.length ? ancestor.siblings() : this.element.siblings(); - this.buttonElement = ancestor.filter( labelSelector ); - if ( !this.buttonElement.length ) { - this.buttonElement = ancestor.find( labelSelector ); - } - } - this.element.addClass( "ui-helper-hidden-accessible" ); - - checked = this.element.is( ":checked" ); - if ( checked ) { - this.buttonElement.addClass( "ui-state-active" ); - } - this.buttonElement.prop( "aria-pressed", checked ); - } else { - this.buttonElement = this.element; - } - }, - - widget: function() { - return this.buttonElement; - }, - - _destroy: function() { - this.element - .removeClass( "ui-helper-hidden-accessible" ); - this.buttonElement - .removeClass( baseClasses + " " + stateClasses + " " + typeClasses ) - .removeAttr( "role" ) - .removeAttr( "aria-pressed" ) - .html( this.buttonElement.find(".ui-button-text").html() ); - - if ( !this.hasTitle ) { - this.buttonElement.removeAttr( "title" ); - } - }, - - _setOption: function( key, value ) { - this._super( key, value ); - if ( key === "disabled" ) { - if ( value ) { - this.element.prop( "disabled", true ); - } else { - this.element.prop( "disabled", false ); - } - return; - } - this._resetButton(); - }, - - refresh: function() { - //See #8237 & #8828 - var isDisabled = this.element.is( "input, button" ) ? this.element.is( ":disabled" ) : this.element.hasClass( "ui-button-disabled" ); - - if ( isDisabled !== this.options.disabled ) { - this._setOption( "disabled", isDisabled ); - } - if ( this.type === "radio" ) { - radioGroup( this.element[0] ).each(function() { - if ( $( this ).is( ":checked" ) ) { - $( this ).button( "widget" ) - .addClass( "ui-state-active" ) - .attr( "aria-pressed", "true" ); - } else { - $( this ).button( "widget" ) - .removeClass( "ui-state-active" ) - .attr( "aria-pressed", "false" ); - } - }); - } else if ( this.type === "checkbox" ) { - if ( this.element.is( ":checked" ) ) { - this.buttonElement - .addClass( "ui-state-active" ) - .attr( "aria-pressed", "true" ); - } else { - this.buttonElement - .removeClass( "ui-state-active" ) - .attr( "aria-pressed", "false" ); - } - } - }, - - _resetButton: function() { - if ( this.type === "input" ) { - if ( this.options.label ) { - this.element.val( this.options.label ); - } - return; - } - var buttonElement = this.buttonElement.removeClass( typeClasses ), - buttonText = $( "<span></span>", this.document[0] ) - .addClass( "ui-button-text" ) - .html( this.options.label ) - .appendTo( buttonElement.empty() ) - .text(), - icons = this.options.icons, - multipleIcons = icons.primary && icons.secondary, - buttonClasses = []; - - if ( icons.primary || icons.secondary ) { - if ( this.options.text ) { - buttonClasses.push( "ui-button-text-icon" + ( multipleIcons ? "s" : ( icons.primary ? "-primary" : "-secondary" ) ) ); - } - - if ( icons.primary ) { - buttonElement.prepend( "<span class='ui-button-icon-primary ui-icon " + icons.primary + "'></span>" ); - } - - if ( icons.secondary ) { - buttonElement.append( "<span class='ui-button-icon-secondary ui-icon " + icons.secondary + "'></span>" ); - } - - if ( !this.options.text ) { - buttonClasses.push( multipleIcons ? "ui-button-icons-only" : "ui-button-icon-only" ); - - if ( !this.hasTitle ) { - buttonElement.attr( "title", $.trim( buttonText ) ); - } - } - } else { - buttonClasses.push( "ui-button-text-only" ); - } - buttonElement.addClass( buttonClasses.join( " " ) ); - } -}); - -$.widget( "ui.buttonset", { - version: "1.10.3", - options: { - items: "button, input[type=button], input[type=submit], input[type=reset], input[type=checkbox], input[type=radio], a, :data(ui-button)" - }, - - _create: function() { - this.element.addClass( "ui-buttonset" ); - }, - - _init: function() { - this.refresh(); - }, - - _setOption: function( key, value ) { - if ( key === "disabled" ) { - this.buttons.button( "option", key, value ); - } - - this._super( key, value ); - }, - - refresh: function() { - var rtl = this.element.css( "direction" ) === "rtl"; - - this.buttons = this.element.find( this.options.items ) - .filter( ":ui-button" ) - .button( "refresh" ) - .end() - .not( ":ui-button" ) - .button() - .end() - .map(function() { - return $( this ).button( "widget" )[ 0 ]; - }) - .removeClass( "ui-corner-all ui-corner-left ui-corner-right" ) - .filter( ":first" ) - .addClass( rtl ? "ui-corner-right" : "ui-corner-left" ) - .end() - .filter( ":last" ) - .addClass( rtl ? "ui-corner-left" : "ui-corner-right" ) - .end() - .end(); - }, - - _destroy: function() { - this.element.removeClass( "ui-buttonset" ); - this.buttons - .map(function() { - return $( this ).button( "widget" )[ 0 ]; - }) - .removeClass( "ui-corner-left ui-corner-right" ) - .end() - .button( "destroy" ); - } -}); - -}( jQuery ) ); - -(function( $, undefined ) { - -$.extend($.ui, { datepicker: { version: "1.10.3" } }); - -var PROP_NAME = "datepicker", - instActive; - -/* Date picker manager. - Use the singleton instance of this class, $.datepicker, to interact with the date picker. - Settings for (groups of) date pickers are maintained in an instance object, - allowing multiple different settings on the same page. */ - -function Datepicker() { - this._curInst = null; // The current instance in use - this._keyEvent = false; // If the last event was a key event - this._disabledInputs = []; // List of date picker inputs that have been disabled - this._datepickerShowing = false; // True if the popup picker is showing , false if not - this._inDialog = false; // True if showing within a "dialog", false if not - this._mainDivId = "ui-datepicker-div"; // The ID of the main datepicker division - this._inlineClass = "ui-datepicker-inline"; // The name of the inline marker class - this._appendClass = "ui-datepicker-append"; // The name of the append marker class - this._triggerClass = "ui-datepicker-trigger"; // The name of the trigger marker class - this._dialogClass = "ui-datepicker-dialog"; // The name of the dialog marker class - this._disableClass = "ui-datepicker-disabled"; // The name of the disabled covering marker class - this._unselectableClass = "ui-datepicker-unselectable"; // The name of the unselectable cell marker class - this._currentClass = "ui-datepicker-current-day"; // The name of the current day marker class - this._dayOverClass = "ui-datepicker-days-cell-over"; // The name of the day hover marker class - this.regional = []; // Available regional settings, indexed by language code - this.regional[""] = { // Default regional settings - closeText: "Done", // Display text for close link - prevText: "Prev", // Display text for previous month link - nextText: "Next", // Display text for next month link - currentText: "Today", // Display text for current month link - monthNames: ["January","February","March","April","May","June", - "July","August","September","October","November","December"], // Names of months for drop-down and formatting - monthNamesShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], // For formatting - dayNames: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], // For formatting - dayNamesShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], // For formatting - dayNamesMin: ["Su","Mo","Tu","We","Th","Fr","Sa"], // Column headings for days starting at Sunday - weekHeader: "Wk", // Column header for week of the year - dateFormat: "mm/dd/yy", // See format options on parseDate - firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ... - isRTL: false, // True if right-to-left language, false if left-to-right - showMonthAfterYear: false, // True if the year select precedes month, false for month then year - yearSuffix: "" // Additional text to append to the year in the month headers - }; - this._defaults = { // Global defaults for all the date picker instances - showOn: "focus", // "focus" for popup on focus, - // "button" for trigger button, or "both" for either - showAnim: "fadeIn", // Name of jQuery animation for popup - showOptions: {}, // Options for enhanced animations - defaultDate: null, // Used when field is blank: actual date, - // +/-number for offset from today, null for today - appendText: "", // Display text following the input box, e.g. showing the format - buttonText: "...", // Text for trigger button - buttonImage: "", // URL for trigger button image - buttonImageOnly: false, // True if the image appears alone, false if it appears on a button - hideIfNoPrevNext: false, // True to hide next/previous month links - // if not applicable, false to just disable them - navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links - gotoCurrent: false, // True if today link goes back to current selection instead - changeMonth: false, // True if month can be selected directly, false if only prev/next - changeYear: false, // True if year can be selected directly, false if only prev/next - yearRange: "c-10:c+10", // Range of years to display in drop-down, - // either relative to today's year (-nn:+nn), relative to currently displayed year - // (c-nn:c+nn), absolute (nnnn:nnnn), or a combination of the above (nnnn:-n) - showOtherMonths: false, // True to show dates in other months, false to leave blank - selectOtherMonths: false, // True to allow selection of dates in other months, false for unselectable - showWeek: false, // True to show week of the year, false to not show it - calculateWeek: this.iso8601Week, // How to calculate the week of the year, - // takes a Date and returns the number of the week for it - shortYearCutoff: "+10", // Short year values < this are in the current century, - // > this are in the previous century, - // string value starting with "+" for current year + value - minDate: null, // The earliest selectable date, or null for no limit - maxDate: null, // The latest selectable date, or null for no limit - duration: "fast", // Duration of display/closure - beforeShowDay: null, // Function that takes a date and returns an array with - // [0] = true if selectable, false if not, [1] = custom CSS class name(s) or "", - // [2] = cell title (optional), e.g. $.datepicker.noWeekends - beforeShow: null, // Function that takes an input field and - // returns a set of custom settings for the date picker - onSelect: null, // Define a callback function when a date is selected - onChangeMonthYear: null, // Define a callback function when the month or year is changed - onClose: null, // Define a callback function when the datepicker is closed - numberOfMonths: 1, // Number of months to show at a time - showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0) - stepMonths: 1, // Number of months to step back/forward - stepBigMonths: 12, // Number of months to step back/forward for the big links - altField: "", // Selector for an alternate field to store selected dates into - altFormat: "", // The date format to use for the alternate field - constrainInput: true, // The input is constrained by the current date format - showButtonPanel: false, // True to show button panel, false to not show it - autoSize: false, // True to size the input for the date format, false to leave as is - disabled: false // The initial disabled state - }; - $.extend(this._defaults, this.regional[""]); - this.dpDiv = bindHover($("<div id='" + this._mainDivId + "' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")); -} - -$.extend(Datepicker.prototype, { - /* Class name added to elements to indicate already configured with a date picker. */ - markerClassName: "hasDatepicker", - - //Keep track of the maximum number of rows displayed (see #7043) - maxRows: 4, - - // TODO rename to "widget" when switching to widget factory - _widgetDatepicker: function() { - return this.dpDiv; - }, - - /* Override the default settings for all instances of the date picker. - * @param settings object - the new settings to use as defaults (anonymous object) - * @return the manager object - */ - setDefaults: function(settings) { - extendRemove(this._defaults, settings || {}); - return this; - }, - - /* Attach the date picker to a jQuery selection. - * @param target element - the target input field or division or span - * @param settings object - the new settings to use for this date picker instance (anonymous) - */ - _attachDatepicker: function(target, settings) { - var nodeName, inline, inst; - nodeName = target.nodeName.toLowerCase(); - inline = (nodeName === "div" || nodeName === "span"); - if (!target.id) { - this.uuid += 1; - target.id = "dp" + this.uuid; - } - inst = this._newInst($(target), inline); - inst.settings = $.extend({}, settings || {}); - if (nodeName === "input") { - this._connectDatepicker(target, inst); - } else if (inline) { - this._inlineDatepicker(target, inst); - } - }, - - /* Create a new instance object. */ - _newInst: function(target, inline) { - var id = target[0].id.replace(/([^A-Za-z0-9_\-])/g, "\\\\$1"); // escape jQuery meta chars - return {id: id, input: target, // associated target - selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection - drawMonth: 0, drawYear: 0, // month being drawn - inline: inline, // is datepicker inline or not - dpDiv: (!inline ? this.dpDiv : // presentation div - bindHover($("<div class='" + this._inlineClass + " ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")))}; - }, - - /* Attach the date picker to an input field. */ - _connectDatepicker: function(target, inst) { - var input = $(target); - inst.append = $([]); - inst.trigger = $([]); - if (input.hasClass(this.markerClassName)) { - return; - } - this._attachments(input, inst); - input.addClass(this.markerClassName).keydown(this._doKeyDown). - keypress(this._doKeyPress).keyup(this._doKeyUp); - this._autoSize(inst); - $.data(target, PROP_NAME, inst); - //If disabled option is true, disable the datepicker once it has been attached to the input (see ticket #5665) - if( inst.settings.disabled ) { - this._disableDatepicker( target ); - } - }, - - /* Make attachments based on settings. */ - _attachments: function(input, inst) { - var showOn, buttonText, buttonImage, - appendText = this._get(inst, "appendText"), - isRTL = this._get(inst, "isRTL"); - - if (inst.append) { - inst.append.remove(); - } - if (appendText) { - inst.append = $("<span class='" + this._appendClass + "'>" + appendText + "</span>"); - input[isRTL ? "before" : "after"](inst.append); - } - - input.unbind("focus", this._showDatepicker); - - if (inst.trigger) { - inst.trigger.remove(); - } - - showOn = this._get(inst, "showOn"); - if (showOn === "focus" || showOn === "both") { // pop-up date picker when in the marked field - input.focus(this._showDatepicker); - } - if (showOn === "button" || showOn === "both") { // pop-up date picker when button clicked - buttonText = this._get(inst, "buttonText"); - buttonImage = this._get(inst, "buttonImage"); - inst.trigger = $(this._get(inst, "buttonImageOnly") ? - $("<img/>").addClass(this._triggerClass). - attr({ src: buttonImage, alt: buttonText, title: buttonText }) : - $("<button type='button'></button>").addClass(this._triggerClass). - html(!buttonImage ? buttonText : $("<img/>").attr( - { src:buttonImage, alt:buttonText, title:buttonText }))); - input[isRTL ? "before" : "after"](inst.trigger); - inst.trigger.click(function() { - if ($.datepicker._datepickerShowing && $.datepicker._lastInput === input[0]) { - $.datepicker._hideDatepicker(); - } else if ($.datepicker._datepickerShowing && $.datepicker._lastInput !== input[0]) { - $.datepicker._hideDatepicker(); - $.datepicker._showDatepicker(input[0]); - } else { - $.datepicker._showDatepicker(input[0]); - } - return false; - }); - } - }, - - /* Apply the maximum length for the date format. */ - _autoSize: function(inst) { - if (this._get(inst, "autoSize") && !inst.inline) { - var findMax, max, maxI, i, - date = new Date(2009, 12 - 1, 20), // Ensure double digits - dateFormat = this._get(inst, "dateFormat"); - - if (dateFormat.match(/[DM]/)) { - findMax = function(names) { - max = 0; - maxI = 0; - for (i = 0; i < names.length; i++) { - if (names[i].length > max) { - max = names[i].length; - maxI = i; - } - } - return maxI; - }; - date.setMonth(findMax(this._get(inst, (dateFormat.match(/MM/) ? - "monthNames" : "monthNamesShort")))); - date.setDate(findMax(this._get(inst, (dateFormat.match(/DD/) ? - "dayNames" : "dayNamesShort"))) + 20 - date.getDay()); - } - inst.input.attr("size", this._formatDate(inst, date).length); - } - }, - - /* Attach an inline date picker to a div. */ - _inlineDatepicker: function(target, inst) { - var divSpan = $(target); - if (divSpan.hasClass(this.markerClassName)) { - return; - } - divSpan.addClass(this.markerClassName).append(inst.dpDiv); - $.data(target, PROP_NAME, inst); - this._setDate(inst, this._getDefaultDate(inst), true); - this._updateDatepicker(inst); - this._updateAlternate(inst); - //If disabled option is true, disable the datepicker before showing it (see ticket #5665) - if( inst.settings.disabled ) { - this._disableDatepicker( target ); - } - // Set display:block in place of inst.dpDiv.show() which won't work on disconnected elements - // http://bugs.jqueryui.com/ticket/7552 - A Datepicker created on a detached div has zero height - inst.dpDiv.css( "display", "block" ); - }, - - /* Pop-up the date picker in a "dialog" box. - * @param input element - ignored - * @param date string or Date - the initial date to display - * @param onSelect function - the function to call when a date is selected - * @param settings object - update the dialog date picker instance's settings (anonymous object) - * @param pos int[2] - coordinates for the dialog's position within the screen or - * event - with x/y coordinates or - * leave empty for default (screen centre) - * @return the manager object - */ - _dialogDatepicker: function(input, date, onSelect, settings, pos) { - var id, browserWidth, browserHeight, scrollX, scrollY, - inst = this._dialogInst; // internal instance - - if (!inst) { - this.uuid += 1; - id = "dp" + this.uuid; - this._dialogInput = $("<input type='text' id='" + id + - "' style='position: absolute; top: -100px; width: 0px;'/>"); - this._dialogInput.keydown(this._doKeyDown); - $("body").append(this._dialogInput); - inst = this._dialogInst = this._newInst(this._dialogInput, false); - inst.settings = {}; - $.data(this._dialogInput[0], PROP_NAME, inst); - } - extendRemove(inst.settings, settings || {}); - date = (date && date.constructor === Date ? this._formatDate(inst, date) : date); - this._dialogInput.val(date); - - this._pos = (pos ? (pos.length ? pos : [pos.pageX, pos.pageY]) : null); - if (!this._pos) { - browserWidth = document.documentElement.clientWidth; - browserHeight = document.documentElement.clientHeight; - scrollX = document.documentElement.scrollLeft || document.body.scrollLeft; - scrollY = document.documentElement.scrollTop || document.body.scrollTop; - this._pos = // should use actual width/height below - [(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY]; - } - - // move input on screen for focus, but hidden behind dialog - this._dialogInput.css("left", (this._pos[0] + 20) + "px").css("top", this._pos[1] + "px"); - inst.settings.onSelect = onSelect; - this._inDialog = true; - this.dpDiv.addClass(this._dialogClass); - this._showDatepicker(this._dialogInput[0]); - if ($.blockUI) { - $.blockUI(this.dpDiv); - } - $.data(this._dialogInput[0], PROP_NAME, inst); - return this; - }, - - /* Detach a datepicker from its control. - * @param target element - the target input field or division or span - */ - _destroyDatepicker: function(target) { - var nodeName, - $target = $(target), - inst = $.data(target, PROP_NAME); - - if (!$target.hasClass(this.markerClassName)) { - return; - } - - nodeName = target.nodeName.toLowerCase(); - $.removeData(target, PROP_NAME); - if (nodeName === "input") { - inst.append.remove(); - inst.trigger.remove(); - $target.removeClass(this.markerClassName). - unbind("focus", this._showDatepicker). - unbind("keydown", this._doKeyDown). - unbind("keypress", this._doKeyPress). - unbind("keyup", this._doKeyUp); - } else if (nodeName === "div" || nodeName === "span") { - $target.removeClass(this.markerClassName).empty(); - } - }, - - /* Enable the date picker to a jQuery selection. - * @param target element - the target input field or division or span - */ - _enableDatepicker: function(target) { - var nodeName, inline, - $target = $(target), - inst = $.data(target, PROP_NAME); - - if (!$target.hasClass(this.markerClassName)) { - return; - } - - nodeName = target.nodeName.toLowerCase(); - if (nodeName === "input") { - target.disabled = false; - inst.trigger.filter("button"). - each(function() { this.disabled = false; }).end(). - filter("img").css({opacity: "1.0", cursor: ""}); - } else if (nodeName === "div" || nodeName === "span") { - inline = $target.children("." + this._inlineClass); - inline.children().removeClass("ui-state-disabled"); - inline.find("select.ui-datepicker-month, select.ui-datepicker-year"). - prop("disabled", false); - } - this._disabledInputs = $.map(this._disabledInputs, - function(value) { return (value === target ? null : value); }); // delete entry - }, - - /* Disable the date picker to a jQuery selection. - * @param target element - the target input field or division or span - */ - _disableDatepicker: function(target) { - var nodeName, inline, - $target = $(target), - inst = $.data(target, PROP_NAME); - - if (!$target.hasClass(this.markerClassName)) { - return; - } - - nodeName = target.nodeName.toLowerCase(); - if (nodeName === "input") { - target.disabled = true; - inst.trigger.filter("button"). - each(function() { this.disabled = true; }).end(). - filter("img").css({opacity: "0.5", cursor: "default"}); - } else if (nodeName === "div" || nodeName === "span") { - inline = $target.children("." + this._inlineClass); - inline.children().addClass("ui-state-disabled"); - inline.find("select.ui-datepicker-month, select.ui-datepicker-year"). - prop("disabled", true); - } - this._disabledInputs = $.map(this._disabledInputs, - function(value) { return (value === target ? null : value); }); // delete entry - this._disabledInputs[this._disabledInputs.length] = target; - }, - - /* Is the first field in a jQuery collection disabled as a datepicker? - * @param target element - the target input field or division or span - * @return boolean - true if disabled, false if enabled - */ - _isDisabledDatepicker: function(target) { - if (!target) { - return false; - } - for (var i = 0; i < this._disabledInputs.length; i++) { - if (this._disabledInputs[i] === target) { - return true; - } - } - return false; - }, - - /* Retrieve the instance data for the target control. - * @param target element - the target input field or division or span - * @return object - the associated instance data - * @throws error if a jQuery problem getting data - */ - _getInst: function(target) { - try { - return $.data(target, PROP_NAME); - } - catch (err) { - throw "Missing instance data for this datepicker"; - } - }, - - /* Update or retrieve the settings for a date picker attached to an input field or division. - * @param target element - the target input field or division or span - * @param name object - the new settings to update or - * string - the name of the setting to change or retrieve, - * when retrieving also "all" for all instance settings or - * "defaults" for all global defaults - * @param value any - the new value for the setting - * (omit if above is an object or to retrieve a value) - */ - _optionDatepicker: function(target, name, value) { - var settings, date, minDate, maxDate, - inst = this._getInst(target); - - if (arguments.length === 2 && typeof name === "string") { - return (name === "defaults" ? $.extend({}, $.datepicker._defaults) : - (inst ? (name === "all" ? $.extend({}, inst.settings) : - this._get(inst, name)) : null)); - } - - settings = name || {}; - if (typeof name === "string") { - settings = {}; - settings[name] = value; - } - - if (inst) { - if (this._curInst === inst) { - this._hideDatepicker(); - } - - date = this._getDateDatepicker(target, true); - minDate = this._getMinMaxDate(inst, "min"); - maxDate = this._getMinMaxDate(inst, "max"); - extendRemove(inst.settings, settings); - // reformat the old minDate/maxDate values if dateFormat changes and a new minDate/maxDate isn't provided - if (minDate !== null && settings.dateFormat !== undefined && settings.minDate === undefined) { - inst.settings.minDate = this._formatDate(inst, minDate); - } - if (maxDate !== null && settings.dateFormat !== undefined && settings.maxDate === undefined) { - inst.settings.maxDate = this._formatDate(inst, maxDate); - } - if ( "disabled" in settings ) { - if ( settings.disabled ) { - this._disableDatepicker(target); - } else { - this._enableDatepicker(target); - } - } - this._attachments($(target), inst); - this._autoSize(inst); - this._setDate(inst, date); - this._updateAlternate(inst); - this._updateDatepicker(inst); - } - }, - - // change method deprecated - _changeDatepicker: function(target, name, value) { - this._optionDatepicker(target, name, value); - }, - - /* Redraw the date picker attached to an input field or division. - * @param target element - the target input field or division or span - */ - _refreshDatepicker: function(target) { - var inst = this._getInst(target); - if (inst) { - this._updateDatepicker(inst); - } - }, - - /* Set the dates for a jQuery selection. - * @param target element - the target input field or division or span - * @param date Date - the new date - */ - _setDateDatepicker: function(target, date) { - var inst = this._getInst(target); - if (inst) { - this._setDate(inst, date); - this._updateDatepicker(inst); - this._updateAlternate(inst); - } - }, - - /* Get the date(s) for the first entry in a jQuery selection. - * @param target element - the target input field or division or span - * @param noDefault boolean - true if no default date is to be used - * @return Date - the current date - */ - _getDateDatepicker: function(target, noDefault) { - var inst = this._getInst(target); - if (inst && !inst.inline) { - this._setDateFromField(inst, noDefault); - } - return (inst ? this._getDate(inst) : null); - }, - - /* Handle keystrokes. */ - _doKeyDown: function(event) { - var onSelect, dateStr, sel, - inst = $.datepicker._getInst(event.target), - handled = true, - isRTL = inst.dpDiv.is(".ui-datepicker-rtl"); - - inst._keyEvent = true; - if ($.datepicker._datepickerShowing) { - switch (event.keyCode) { - case 9: $.datepicker._hideDatepicker(); - handled = false; - break; // hide on tab out - case 13: sel = $("td." + $.datepicker._dayOverClass + ":not(." + - $.datepicker._currentClass + ")", inst.dpDiv); - if (sel[0]) { - $.datepicker._selectDay(event.target, inst.selectedMonth, inst.selectedYear, sel[0]); - } - - onSelect = $.datepicker._get(inst, "onSelect"); - if (onSelect) { - dateStr = $.datepicker._formatDate(inst); - - // trigger custom callback - onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); - } else { - $.datepicker._hideDatepicker(); - } - - return false; // don't submit the form - case 27: $.datepicker._hideDatepicker(); - break; // hide on escape - case 33: $.datepicker._adjustDate(event.target, (event.ctrlKey ? - -$.datepicker._get(inst, "stepBigMonths") : - -$.datepicker._get(inst, "stepMonths")), "M"); - break; // previous month/year on page up/+ ctrl - case 34: $.datepicker._adjustDate(event.target, (event.ctrlKey ? - +$.datepicker._get(inst, "stepBigMonths") : - +$.datepicker._get(inst, "stepMonths")), "M"); - break; // next month/year on page down/+ ctrl - case 35: if (event.ctrlKey || event.metaKey) { - $.datepicker._clearDate(event.target); - } - handled = event.ctrlKey || event.metaKey; - break; // clear on ctrl or command +end - case 36: if (event.ctrlKey || event.metaKey) { - $.datepicker._gotoToday(event.target); - } - handled = event.ctrlKey || event.metaKey; - break; // current on ctrl or command +home - case 37: if (event.ctrlKey || event.metaKey) { - $.datepicker._adjustDate(event.target, (isRTL ? +1 : -1), "D"); - } - handled = event.ctrlKey || event.metaKey; - // -1 day on ctrl or command +left - if (event.originalEvent.altKey) { - $.datepicker._adjustDate(event.target, (event.ctrlKey ? - -$.datepicker._get(inst, "stepBigMonths") : - -$.datepicker._get(inst, "stepMonths")), "M"); - } - // next month/year on alt +left on Mac - break; - case 38: if (event.ctrlKey || event.metaKey) { - $.datepicker._adjustDate(event.target, -7, "D"); - } - handled = event.ctrlKey || event.metaKey; - break; // -1 week on ctrl or command +up - case 39: if (event.ctrlKey || event.metaKey) { - $.datepicker._adjustDate(event.target, (isRTL ? -1 : +1), "D"); - } - handled = event.ctrlKey || event.metaKey; - // +1 day on ctrl or command +right - if (event.originalEvent.altKey) { - $.datepicker._adjustDate(event.target, (event.ctrlKey ? - +$.datepicker._get(inst, "stepBigMonths") : - +$.datepicker._get(inst, "stepMonths")), "M"); - } - // next month/year on alt +right - break; - case 40: if (event.ctrlKey || event.metaKey) { - $.datepicker._adjustDate(event.target, +7, "D"); - } - handled = event.ctrlKey || event.metaKey; - break; // +1 week on ctrl or command +down - default: handled = false; - } - } else if (event.keyCode === 36 && event.ctrlKey) { // display the date picker on ctrl+home - $.datepicker._showDatepicker(this); - } else { - handled = false; - } - - if (handled) { - event.preventDefault(); - event.stopPropagation(); - } - }, - - /* Filter entered characters - based on date format. */ - _doKeyPress: function(event) { - var chars, chr, - inst = $.datepicker._getInst(event.target); - - if ($.datepicker._get(inst, "constrainInput")) { - chars = $.datepicker._possibleChars($.datepicker._get(inst, "dateFormat")); - chr = String.fromCharCode(event.charCode == null ? event.keyCode : event.charCode); - return event.ctrlKey || event.metaKey || (chr < " " || !chars || chars.indexOf(chr) > -1); - } - }, - - /* Synchronise manual entry and field/alternate field. */ - _doKeyUp: function(event) { - var date, - inst = $.datepicker._getInst(event.target); - - if (inst.input.val() !== inst.lastVal) { - try { - date = $.datepicker.parseDate($.datepicker._get(inst, "dateFormat"), - (inst.input ? inst.input.val() : null), - $.datepicker._getFormatConfig(inst)); - - if (date) { // only if valid - $.datepicker._setDateFromField(inst); - $.datepicker._updateAlternate(inst); - $.datepicker._updateDatepicker(inst); - } - } - catch (err) { - } - } - return true; - }, - - /* Pop-up the date picker for a given input field. - * If false returned from beforeShow event handler do not show. - * @param input element - the input field attached to the date picker or - * event - if triggered by focus - */ - _showDatepicker: function(input) { - input = input.target || input; - if (input.nodeName.toLowerCase() !== "input") { // find from button/image trigger - input = $("input", input.parentNode)[0]; - } - - if ($.datepicker._isDisabledDatepicker(input) || $.datepicker._lastInput === input) { // already here - return; - } - - var inst, beforeShow, beforeShowSettings, isFixed, - offset, showAnim, duration; - - inst = $.datepicker._getInst(input); - if ($.datepicker._curInst && $.datepicker._curInst !== inst) { - $.datepicker._curInst.dpDiv.stop(true, true); - if ( inst && $.datepicker._datepickerShowing ) { - $.datepicker._hideDatepicker( $.datepicker._curInst.input[0] ); - } - } - - beforeShow = $.datepicker._get(inst, "beforeShow"); - beforeShowSettings = beforeShow ? beforeShow.apply(input, [input, inst]) : {}; - if(beforeShowSettings === false){ - return; - } - extendRemove(inst.settings, beforeShowSettings); - - inst.lastVal = null; - $.datepicker._lastInput = input; - $.datepicker._setDateFromField(inst); - - if ($.datepicker._inDialog) { // hide cursor - input.value = ""; - } - if (!$.datepicker._pos) { // position below input - $.datepicker._pos = $.datepicker._findPos(input); - $.datepicker._pos[1] += input.offsetHeight; // add the height - } - - isFixed = false; - $(input).parents().each(function() { - isFixed |= $(this).css("position") === "fixed"; - return !isFixed; - }); - - offset = {left: $.datepicker._pos[0], top: $.datepicker._pos[1]}; - $.datepicker._pos = null; - //to avoid flashes on Firefox - inst.dpDiv.empty(); - // determine sizing offscreen - inst.dpDiv.css({position: "absolute", display: "block", top: "-1000px"}); - $.datepicker._updateDatepicker(inst); - // fix width for dynamic number of date pickers - // and adjust position before showing - offset = $.datepicker._checkOffset(inst, offset, isFixed); - inst.dpDiv.css({position: ($.datepicker._inDialog && $.blockUI ? - "static" : (isFixed ? "fixed" : "absolute")), display: "none", - left: offset.left + "px", top: offset.top + "px"}); - - if (!inst.inline) { - showAnim = $.datepicker._get(inst, "showAnim"); - duration = $.datepicker._get(inst, "duration"); - inst.dpDiv.zIndex($(input).zIndex()+1); - $.datepicker._datepickerShowing = true; - - if ( $.effects && $.effects.effect[ showAnim ] ) { - inst.dpDiv.show(showAnim, $.datepicker._get(inst, "showOptions"), duration); - } else { - inst.dpDiv[showAnim || "show"](showAnim ? duration : null); - } - - if ( $.datepicker._shouldFocusInput( inst ) ) { - inst.input.focus(); - } - - $.datepicker._curInst = inst; - } - }, - - /* Generate the date picker content. */ - _updateDatepicker: function(inst) { - this.maxRows = 4; //Reset the max number of rows being displayed (see #7043) - instActive = inst; // for delegate hover events - inst.dpDiv.empty().append(this._generateHTML(inst)); - this._attachHandlers(inst); - inst.dpDiv.find("." + this._dayOverClass + " a").mouseover(); - - var origyearshtml, - numMonths = this._getNumberOfMonths(inst), - cols = numMonths[1], - width = 17; - - inst.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width(""); - if (cols > 1) { - inst.dpDiv.addClass("ui-datepicker-multi-" + cols).css("width", (width * cols) + "em"); - } - inst.dpDiv[(numMonths[0] !== 1 || numMonths[1] !== 1 ? "add" : "remove") + - "Class"]("ui-datepicker-multi"); - inst.dpDiv[(this._get(inst, "isRTL") ? "add" : "remove") + - "Class"]("ui-datepicker-rtl"); - - if (inst === $.datepicker._curInst && $.datepicker._datepickerShowing && $.datepicker._shouldFocusInput( inst ) ) { - inst.input.focus(); - } - - // deffered render of the years select (to avoid flashes on Firefox) - if( inst.yearshtml ){ - origyearshtml = inst.yearshtml; - setTimeout(function(){ - //assure that inst.yearshtml didn't change. - if( origyearshtml === inst.yearshtml && inst.yearshtml ){ - inst.dpDiv.find("select.ui-datepicker-year:first").replaceWith(inst.yearshtml); - } - origyearshtml = inst.yearshtml = null; - }, 0); - } - }, - - // #6694 - don't focus the input if it's already focused - // this breaks the change event in IE - // Support: IE and jQuery <1.9 - _shouldFocusInput: function( inst ) { - return inst.input && inst.input.is( ":visible" ) && !inst.input.is( ":disabled" ) && !inst.input.is( ":focus" ); - }, - - /* Check positioning to remain on screen. */ - _checkOffset: function(inst, offset, isFixed) { - var dpWidth = inst.dpDiv.outerWidth(), - dpHeight = inst.dpDiv.outerHeight(), - inputWidth = inst.input ? inst.input.outerWidth() : 0, - inputHeight = inst.input ? inst.input.outerHeight() : 0, - viewWidth = document.documentElement.clientWidth + (isFixed ? 0 : $(document).scrollLeft()), - viewHeight = document.documentElement.clientHeight + (isFixed ? 0 : $(document).scrollTop()); - - offset.left -= (this._get(inst, "isRTL") ? (dpWidth - inputWidth) : 0); - offset.left -= (isFixed && offset.left === inst.input.offset().left) ? $(document).scrollLeft() : 0; - offset.top -= (isFixed && offset.top === (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0; - - // now check if datepicker is showing outside window viewport - move to a better place if so. - offset.left -= Math.min(offset.left, (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ? - Math.abs(offset.left + dpWidth - viewWidth) : 0); - offset.top -= Math.min(offset.top, (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ? - Math.abs(dpHeight + inputHeight) : 0); - - return offset; - }, - - /* Find an object's position on the screen. */ - _findPos: function(obj) { - var position, - inst = this._getInst(obj), - isRTL = this._get(inst, "isRTL"); - - while (obj && (obj.type === "hidden" || obj.nodeType !== 1 || $.expr.filters.hidden(obj))) { - obj = obj[isRTL ? "previousSibling" : "nextSibling"]; - } - - position = $(obj).offset(); - return [position.left, position.top]; - }, - - /* Hide the date picker from view. - * @param input element - the input field attached to the date picker - */ - _hideDatepicker: function(input) { - var showAnim, duration, postProcess, onClose, - inst = this._curInst; - - if (!inst || (input && inst !== $.data(input, PROP_NAME))) { - return; - } - - if (this._datepickerShowing) { - showAnim = this._get(inst, "showAnim"); - duration = this._get(inst, "duration"); - postProcess = function() { - $.datepicker._tidyDialog(inst); - }; - - // DEPRECATED: after BC for 1.8.x $.effects[ showAnim ] is not needed - if ( $.effects && ( $.effects.effect[ showAnim ] || $.effects[ showAnim ] ) ) { - inst.dpDiv.hide(showAnim, $.datepicker._get(inst, "showOptions"), duration, postProcess); - } else { - inst.dpDiv[(showAnim === "slideDown" ? "slideUp" : - (showAnim === "fadeIn" ? "fadeOut" : "hide"))]((showAnim ? duration : null), postProcess); - } - - if (!showAnim) { - postProcess(); - } - this._datepickerShowing = false; - - onClose = this._get(inst, "onClose"); - if (onClose) { - onClose.apply((inst.input ? inst.input[0] : null), [(inst.input ? inst.input.val() : ""), inst]); - } - - this._lastInput = null; - if (this._inDialog) { - this._dialogInput.css({ position: "absolute", left: "0", top: "-100px" }); - if ($.blockUI) { - $.unblockUI(); - $("body").append(this.dpDiv); - } - } - this._inDialog = false; - } - }, - - /* Tidy up after a dialog display. */ - _tidyDialog: function(inst) { - inst.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar"); - }, - - /* Close date picker if clicked elsewhere. */ - _checkExternalClick: function(event) { - if (!$.datepicker._curInst) { - return; - } - - var $target = $(event.target), - inst = $.datepicker._getInst($target[0]); - - if ( ( ( $target[0].id !== $.datepicker._mainDivId && - $target.parents("#" + $.datepicker._mainDivId).length === 0 && - !$target.hasClass($.datepicker.markerClassName) && - !$target.closest("." + $.datepicker._triggerClass).length && - $.datepicker._datepickerShowing && !($.datepicker._inDialog && $.blockUI) ) ) || - ( $target.hasClass($.datepicker.markerClassName) && $.datepicker._curInst !== inst ) ) { - $.datepicker._hideDatepicker(); - } - }, - - /* Adjust one of the date sub-fields. */ - _adjustDate: function(id, offset, period) { - var target = $(id), - inst = this._getInst(target[0]); - - if (this._isDisabledDatepicker(target[0])) { - return; - } - this._adjustInstDate(inst, offset + - (period === "M" ? this._get(inst, "showCurrentAtPos") : 0), // undo positioning - period); - this._updateDatepicker(inst); - }, - - /* Action for current link. */ - _gotoToday: function(id) { - var date, - target = $(id), - inst = this._getInst(target[0]); - - if (this._get(inst, "gotoCurrent") && inst.currentDay) { - inst.selectedDay = inst.currentDay; - inst.drawMonth = inst.selectedMonth = inst.currentMonth; - inst.drawYear = inst.selectedYear = inst.currentYear; - } else { - date = new Date(); - inst.selectedDay = date.getDate(); - inst.drawMonth = inst.selectedMonth = date.getMonth(); - inst.drawYear = inst.selectedYear = date.getFullYear(); - } - this._notifyChange(inst); - this._adjustDate(target); - }, - - /* Action for selecting a new month/year. */ - _selectMonthYear: function(id, select, period) { - var target = $(id), - inst = this._getInst(target[0]); - - inst["selected" + (period === "M" ? "Month" : "Year")] = - inst["draw" + (period === "M" ? "Month" : "Year")] = - parseInt(select.options[select.selectedIndex].value,10); - - this._notifyChange(inst); - this._adjustDate(target); - }, - - /* Action for selecting a day. */ - _selectDay: function(id, month, year, td) { - var inst, - target = $(id); - - if ($(td).hasClass(this._unselectableClass) || this._isDisabledDatepicker(target[0])) { - return; - } - - inst = this._getInst(target[0]); - inst.selectedDay = inst.currentDay = $("a", td).html(); - inst.selectedMonth = inst.currentMonth = month; - inst.selectedYear = inst.currentYear = year; - this._selectDate(id, this._formatDate(inst, - inst.currentDay, inst.currentMonth, inst.currentYear)); - }, - - /* Erase the input field and hide the date picker. */ - _clearDate: function(id) { - var target = $(id); - this._selectDate(target, ""); - }, - - /* Update the input field with the selected date. */ - _selectDate: function(id, dateStr) { - var onSelect, - target = $(id), - inst = this._getInst(target[0]); - - dateStr = (dateStr != null ? dateStr : this._formatDate(inst)); - if (inst.input) { - inst.input.val(dateStr); - } - this._updateAlternate(inst); - - onSelect = this._get(inst, "onSelect"); - if (onSelect) { - onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); // trigger custom callback - } else if (inst.input) { - inst.input.trigger("change"); // fire the change event - } - - if (inst.inline){ - this._updateDatepicker(inst); - } else { - this._hideDatepicker(); - this._lastInput = inst.input[0]; - if (typeof(inst.input[0]) !== "object") { - inst.input.focus(); // restore focus - } - this._lastInput = null; - } - }, - - /* Update any alternate field to synchronise with the main field. */ - _updateAlternate: function(inst) { - var altFormat, date, dateStr, - altField = this._get(inst, "altField"); - - if (altField) { // update alternate field too - altFormat = this._get(inst, "altFormat") || this._get(inst, "dateFormat"); - date = this._getDate(inst); - dateStr = this.formatDate(altFormat, date, this._getFormatConfig(inst)); - $(altField).each(function() { $(this).val(dateStr); }); - } - }, - - /* Set as beforeShowDay function to prevent selection of weekends. - * @param date Date - the date to customise - * @return [boolean, string] - is this date selectable?, what is its CSS class? - */ - noWeekends: function(date) { - var day = date.getDay(); - return [(day > 0 && day < 6), ""]; - }, - - /* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition. - * @param date Date - the date to get the week for - * @return number - the number of the week within the year that contains this date - */ - iso8601Week: function(date) { - var time, - checkDate = new Date(date.getTime()); - - // Find Thursday of this week starting on Monday - checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7)); - - time = checkDate.getTime(); - checkDate.setMonth(0); // Compare with Jan 1 - checkDate.setDate(1); - return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1; - }, - - /* Parse a string value into a date object. - * See formatDate below for the possible formats. - * - * @param format string - the expected format of the date - * @param value string - the date in the above format - * @param settings Object - attributes include: - * shortYearCutoff number - the cutoff year for determining the century (optional) - * dayNamesShort string[7] - abbreviated names of the days from Sunday (optional) - * dayNames string[7] - names of the days from Sunday (optional) - * monthNamesShort string[12] - abbreviated names of the months (optional) - * monthNames string[12] - names of the months (optional) - * @return Date - the extracted date value or null if value is blank - */ - parseDate: function (format, value, settings) { - if (format == null || value == null) { - throw "Invalid arguments"; - } - - value = (typeof value === "object" ? value.toString() : value + ""); - if (value === "") { - return null; - } - - var iFormat, dim, extra, - iValue = 0, - shortYearCutoffTemp = (settings ? settings.shortYearCutoff : null) || this._defaults.shortYearCutoff, - shortYearCutoff = (typeof shortYearCutoffTemp !== "string" ? shortYearCutoffTemp : - new Date().getFullYear() % 100 + parseInt(shortYearCutoffTemp, 10)), - dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort, - dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames, - monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort, - monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames, - year = -1, - month = -1, - day = -1, - doy = -1, - literal = false, - date, - // Check whether a format character is doubled - lookAhead = function(match) { - var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match); - if (matches) { - iFormat++; - } - return matches; - }, - // Extract a number from the string value - getNumber = function(match) { - var isDoubled = lookAhead(match), - size = (match === "@" ? 14 : (match === "!" ? 20 : - (match === "y" && isDoubled ? 4 : (match === "o" ? 3 : 2)))), - digits = new RegExp("^\\d{1," + size + "}"), - num = value.substring(iValue).match(digits); - if (!num) { - throw "Missing number at position " + iValue; - } - iValue += num[0].length; - return parseInt(num[0], 10); - }, - // Extract a name from the string value and convert to an index - getName = function(match, shortNames, longNames) { - var index = -1, - names = $.map(lookAhead(match) ? longNames : shortNames, function (v, k) { - return [ [k, v] ]; - }).sort(function (a, b) { - return -(a[1].length - b[1].length); - }); - - $.each(names, function (i, pair) { - var name = pair[1]; - if (value.substr(iValue, name.length).toLowerCase() === name.toLowerCase()) { - index = pair[0]; - iValue += name.length; - return false; - } - }); - if (index !== -1) { - return index + 1; - } else { - throw "Unknown name at position " + iValue; - } - }, - // Confirm that a literal character matches the string value - checkLiteral = function() { - if (value.charAt(iValue) !== format.charAt(iFormat)) { - throw "Unexpected literal at position " + iValue; - } - iValue++; - }; - - for (iFormat = 0; iFormat < format.length; iFormat++) { - if (literal) { - if (format.charAt(iFormat) === "'" && !lookAhead("'")) { - literal = false; - } else { - checkLiteral(); - } - } else { - switch (format.charAt(iFormat)) { - case "d": - day = getNumber("d"); - break; - case "D": - getName("D", dayNamesShort, dayNames); - break; - case "o": - doy = getNumber("o"); - break; - case "m": - month = getNumber("m"); - break; - case "M": - month = getName("M", monthNamesShort, monthNames); - break; - case "y": - year = getNumber("y"); - break; - case "@": - date = new Date(getNumber("@")); - year = date.getFullYear(); - month = date.getMonth() + 1; - day = date.getDate(); - break; - case "!": - date = new Date((getNumber("!") - this._ticksTo1970) / 10000); - year = date.getFullYear(); - month = date.getMonth() + 1; - day = date.getDate(); - break; - case "'": - if (lookAhead("'")){ - checkLiteral(); - } else { - literal = true; - } - break; - default: - checkLiteral(); - } - } - } - - if (iValue < value.length){ - extra = value.substr(iValue); - if (!/^\s+/.test(extra)) { - throw "Extra/unparsed characters found in date: " + extra; - } - } - - if (year === -1) { - year = new Date().getFullYear(); - } else if (year < 100) { - year += new Date().getFullYear() - new Date().getFullYear() % 100 + - (year <= shortYearCutoff ? 0 : -100); - } - - if (doy > -1) { - month = 1; - day = doy; - do { - dim = this._getDaysInMonth(year, month - 1); - if (day <= dim) { - break; - } - month++; - day -= dim; - } while (true); - } - - date = this._daylightSavingAdjust(new Date(year, month - 1, day)); - if (date.getFullYear() !== year || date.getMonth() + 1 !== month || date.getDate() !== day) { - throw "Invalid date"; // E.g. 31/02/00 - } - return date; - }, - - /* Standard date formats. */ - ATOM: "yy-mm-dd", // RFC 3339 (ISO 8601) - COOKIE: "D, dd M yy", - ISO_8601: "yy-mm-dd", - RFC_822: "D, d M y", - RFC_850: "DD, dd-M-y", - RFC_1036: "D, d M y", - RFC_1123: "D, d M yy", - RFC_2822: "D, d M yy", - RSS: "D, d M y", // RFC 822 - TICKS: "!", - TIMESTAMP: "@", - W3C: "yy-mm-dd", // ISO 8601 - - _ticksTo1970: (((1970 - 1) * 365 + Math.floor(1970 / 4) - Math.floor(1970 / 100) + - Math.floor(1970 / 400)) * 24 * 60 * 60 * 10000000), - - /* Format a date object into a string value. - * The format can be combinations of the following: - * d - day of month (no leading zero) - * dd - day of month (two digit) - * o - day of year (no leading zeros) - * oo - day of year (three digit) - * D - day name short - * DD - day name long - * m - month of year (no leading zero) - * mm - month of year (two digit) - * M - month name short - * MM - month name long - * y - year (two digit) - * yy - year (four digit) - * @ - Unix timestamp (ms since 01/01/1970) - * ! - Windows ticks (100ns since 01/01/0001) - * "..." - literal text - * '' - single quote - * - * @param format string - the desired format of the date - * @param date Date - the date value to format - * @param settings Object - attributes include: - * dayNamesShort string[7] - abbreviated names of the days from Sunday (optional) - * dayNames string[7] - names of the days from Sunday (optional) - * monthNamesShort string[12] - abbreviated names of the months (optional) - * monthNames string[12] - names of the months (optional) - * @return string - the date in the above format - */ - formatDate: function (format, date, settings) { - if (!date) { - return ""; - } - - var iFormat, - dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort, - dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames, - monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort, - monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames, - // Check whether a format character is doubled - lookAhead = function(match) { - var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match); - if (matches) { - iFormat++; - } - return matches; - }, - // Format a number, with leading zero if necessary - formatNumber = function(match, value, len) { - var num = "" + value; - if (lookAhead(match)) { - while (num.length < len) { - num = "0" + num; - } - } - return num; - }, - // Format a name, short or long as requested - formatName = function(match, value, shortNames, longNames) { - return (lookAhead(match) ? longNames[value] : shortNames[value]); - }, - output = "", - literal = false; - - if (date) { - for (iFormat = 0; iFormat < format.length; iFormat++) { - if (literal) { - if (format.charAt(iFormat) === "'" && !lookAhead("'")) { - literal = false; - } else { - output += format.charAt(iFormat); - } - } else { - switch (format.charAt(iFormat)) { - case "d": - output += formatNumber("d", date.getDate(), 2); - break; - case "D": - output += formatName("D", date.getDay(), dayNamesShort, dayNames); - break; - case "o": - output += formatNumber("o", - Math.round((new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime() - new Date(date.getFullYear(), 0, 0).getTime()) / 86400000), 3); - break; - case "m": - output += formatNumber("m", date.getMonth() + 1, 2); - break; - case "M": - output += formatName("M", date.getMonth(), monthNamesShort, monthNames); - break; - case "y": - output += (lookAhead("y") ? date.getFullYear() : - (date.getYear() % 100 < 10 ? "0" : "") + date.getYear() % 100); - break; - case "@": - output += date.getTime(); - break; - case "!": - output += date.getTime() * 10000 + this._ticksTo1970; - break; - case "'": - if (lookAhead("'")) { - output += "'"; - } else { - literal = true; - } - break; - default: - output += format.charAt(iFormat); - } - } - } - } - return output; - }, - - /* Extract all possible characters from the date format. */ - _possibleChars: function (format) { - var iFormat, - chars = "", - literal = false, - // Check whether a format character is doubled - lookAhead = function(match) { - var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match); - if (matches) { - iFormat++; - } - return matches; - }; - - for (iFormat = 0; iFormat < format.length; iFormat++) { - if (literal) { - if (format.charAt(iFormat) === "'" && !lookAhead("'")) { - literal = false; - } else { - chars += format.charAt(iFormat); - } - } else { - switch (format.charAt(iFormat)) { - case "d": case "m": case "y": case "@": - chars += "0123456789"; - break; - case "D": case "M": - return null; // Accept anything - case "'": - if (lookAhead("'")) { - chars += "'"; - } else { - literal = true; - } - break; - default: - chars += format.charAt(iFormat); - } - } - } - return chars; - }, - - /* Get a setting value, defaulting if necessary. */ - _get: function(inst, name) { - return inst.settings[name] !== undefined ? - inst.settings[name] : this._defaults[name]; - }, - - /* Parse existing date and initialise date picker. */ - _setDateFromField: function(inst, noDefault) { - if (inst.input.val() === inst.lastVal) { - return; - } - - var dateFormat = this._get(inst, "dateFormat"), - dates = inst.lastVal = inst.input ? inst.input.val() : null, - defaultDate = this._getDefaultDate(inst), - date = defaultDate, - settings = this._getFormatConfig(inst); - - try { - date = this.parseDate(dateFormat, dates, settings) || defaultDate; - } catch (event) { - dates = (noDefault ? "" : dates); - } - inst.selectedDay = date.getDate(); - inst.drawMonth = inst.selectedMonth = date.getMonth(); - inst.drawYear = inst.selectedYear = date.getFullYear(); - inst.currentDay = (dates ? date.getDate() : 0); - inst.currentMonth = (dates ? date.getMonth() : 0); - inst.currentYear = (dates ? date.getFullYear() : 0); - this._adjustInstDate(inst); - }, - - /* Retrieve the default date shown on opening. */ - _getDefaultDate: function(inst) { - return this._restrictMinMax(inst, - this._determineDate(inst, this._get(inst, "defaultDate"), new Date())); - }, - - /* A date may be specified as an exact value or a relative one. */ - _determineDate: function(inst, date, defaultDate) { - var offsetNumeric = function(offset) { - var date = new Date(); - date.setDate(date.getDate() + offset); - return date; - }, - offsetString = function(offset) { - try { - return $.datepicker.parseDate($.datepicker._get(inst, "dateFormat"), - offset, $.datepicker._getFormatConfig(inst)); - } - catch (e) { - // Ignore - } - - var date = (offset.toLowerCase().match(/^c/) ? - $.datepicker._getDate(inst) : null) || new Date(), - year = date.getFullYear(), - month = date.getMonth(), - day = date.getDate(), - pattern = /([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g, - matches = pattern.exec(offset); - - while (matches) { - switch (matches[2] || "d") { - case "d" : case "D" : - day += parseInt(matches[1],10); break; - case "w" : case "W" : - day += parseInt(matches[1],10) * 7; break; - case "m" : case "M" : - month += parseInt(matches[1],10); - day = Math.min(day, $.datepicker._getDaysInMonth(year, month)); - break; - case "y": case "Y" : - year += parseInt(matches[1],10); - day = Math.min(day, $.datepicker._getDaysInMonth(year, month)); - break; - } - matches = pattern.exec(offset); - } - return new Date(year, month, day); - }, - newDate = (date == null || date === "" ? defaultDate : (typeof date === "string" ? offsetString(date) : - (typeof date === "number" ? (isNaN(date) ? defaultDate : offsetNumeric(date)) : new Date(date.getTime())))); - - newDate = (newDate && newDate.toString() === "Invalid Date" ? defaultDate : newDate); - if (newDate) { - newDate.setHours(0); - newDate.setMinutes(0); - newDate.setSeconds(0); - newDate.setMilliseconds(0); - } - return this._daylightSavingAdjust(newDate); - }, - - /* Handle switch to/from daylight saving. - * Hours may be non-zero on daylight saving cut-over: - * > 12 when midnight changeover, but then cannot generate - * midnight datetime, so jump to 1AM, otherwise reset. - * @param date (Date) the date to check - * @return (Date) the corrected date - */ - _daylightSavingAdjust: function(date) { - if (!date) { - return null; - } - date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0); - return date; - }, - - /* Set the date(s) directly. */ - _setDate: function(inst, date, noChange) { - var clear = !date, - origMonth = inst.selectedMonth, - origYear = inst.selectedYear, - newDate = this._restrictMinMax(inst, this._determineDate(inst, date, new Date())); - - inst.selectedDay = inst.currentDay = newDate.getDate(); - inst.drawMonth = inst.selectedMonth = inst.currentMonth = newDate.getMonth(); - inst.drawYear = inst.selectedYear = inst.currentYear = newDate.getFullYear(); - if ((origMonth !== inst.selectedMonth || origYear !== inst.selectedYear) && !noChange) { - this._notifyChange(inst); - } - this._adjustInstDate(inst); - if (inst.input) { - inst.input.val(clear ? "" : this._formatDate(inst)); - } - }, - - /* Retrieve the date(s) directly. */ - _getDate: function(inst) { - var startDate = (!inst.currentYear || (inst.input && inst.input.val() === "") ? null : - this._daylightSavingAdjust(new Date( - inst.currentYear, inst.currentMonth, inst.currentDay))); - return startDate; - }, - - /* Attach the onxxx handlers. These are declared statically so - * they work with static code transformers like Caja. - */ - _attachHandlers: function(inst) { - var stepMonths = this._get(inst, "stepMonths"), - id = "#" + inst.id.replace( /\\\\/g, "\\" ); - inst.dpDiv.find("[data-handler]").map(function () { - var handler = { - prev: function () { - $.datepicker._adjustDate(id, -stepMonths, "M"); - }, - next: function () { - $.datepicker._adjustDate(id, +stepMonths, "M"); - }, - hide: function () { - $.datepicker._hideDatepicker(); - }, - today: function () { - $.datepicker._gotoToday(id); - }, - selectDay: function () { - $.datepicker._selectDay(id, +this.getAttribute("data-month"), +this.getAttribute("data-year"), this); - return false; - }, - selectMonth: function () { - $.datepicker._selectMonthYear(id, this, "M"); - return false; - }, - selectYear: function () { - $.datepicker._selectMonthYear(id, this, "Y"); - return false; - } - }; - $(this).bind(this.getAttribute("data-event"), handler[this.getAttribute("data-handler")]); - }); - }, - - /* Generate the HTML for the current state of the date picker. */ - _generateHTML: function(inst) { - var maxDraw, prevText, prev, nextText, next, currentText, gotoDate, - controls, buttonPanel, firstDay, showWeek, dayNames, dayNamesMin, - monthNames, monthNamesShort, beforeShowDay, showOtherMonths, - selectOtherMonths, defaultDate, html, dow, row, group, col, selectedDate, - cornerClass, calender, thead, day, daysInMonth, leadDays, curRows, numRows, - printDate, dRow, tbody, daySettings, otherMonth, unselectable, - tempDate = new Date(), - today = this._daylightSavingAdjust( - new Date(tempDate.getFullYear(), tempDate.getMonth(), tempDate.getDate())), // clear time - isRTL = this._get(inst, "isRTL"), - showButtonPanel = this._get(inst, "showButtonPanel"), - hideIfNoPrevNext = this._get(inst, "hideIfNoPrevNext"), - navigationAsDateFormat = this._get(inst, "navigationAsDateFormat"), - numMonths = this._getNumberOfMonths(inst), - showCurrentAtPos = this._get(inst, "showCurrentAtPos"), - stepMonths = this._get(inst, "stepMonths"), - isMultiMonth = (numMonths[0] !== 1 || numMonths[1] !== 1), - currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) : - new Date(inst.currentYear, inst.currentMonth, inst.currentDay))), - minDate = this._getMinMaxDate(inst, "min"), - maxDate = this._getMinMaxDate(inst, "max"), - drawMonth = inst.drawMonth - showCurrentAtPos, - drawYear = inst.drawYear; - - if (drawMonth < 0) { - drawMonth += 12; - drawYear--; - } - if (maxDate) { - maxDraw = this._daylightSavingAdjust(new Date(maxDate.getFullYear(), - maxDate.getMonth() - (numMonths[0] * numMonths[1]) + 1, maxDate.getDate())); - maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw); - while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) { - drawMonth--; - if (drawMonth < 0) { - drawMonth = 11; - drawYear--; - } - } - } - inst.drawMonth = drawMonth; - inst.drawYear = drawYear; - - prevText = this._get(inst, "prevText"); - prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText, - this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)), - this._getFormatConfig(inst))); - - prev = (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ? - "<a class='ui-datepicker-prev ui-corner-all' data-handler='prev' data-event='click'" + - " title='" + prevText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "e" : "w") + "'>" + prevText + "</span></a>" : - (hideIfNoPrevNext ? "" : "<a class='ui-datepicker-prev ui-corner-all ui-state-disabled' title='"+ prevText +"'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "e" : "w") + "'>" + prevText + "</span></a>")); - - nextText = this._get(inst, "nextText"); - nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText, - this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)), - this._getFormatConfig(inst))); - - next = (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ? - "<a class='ui-datepicker-next ui-corner-all' data-handler='next' data-event='click'" + - " title='" + nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "w" : "e") + "'>" + nextText + "</span></a>" : - (hideIfNoPrevNext ? "" : "<a class='ui-datepicker-next ui-corner-all ui-state-disabled' title='"+ nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "w" : "e") + "'>" + nextText + "</span></a>")); - - currentText = this._get(inst, "currentText"); - gotoDate = (this._get(inst, "gotoCurrent") && inst.currentDay ? currentDate : today); - currentText = (!navigationAsDateFormat ? currentText : - this.formatDate(currentText, gotoDate, this._getFormatConfig(inst))); - - controls = (!inst.inline ? "<button type='button' class='ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all' data-handler='hide' data-event='click'>" + - this._get(inst, "closeText") + "</button>" : ""); - - buttonPanel = (showButtonPanel) ? "<div class='ui-datepicker-buttonpane ui-widget-content'>" + (isRTL ? controls : "") + - (this._isInRange(inst, gotoDate) ? "<button type='button' class='ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all' data-handler='today' data-event='click'" + - ">" + currentText + "</button>" : "") + (isRTL ? "" : controls) + "</div>" : ""; - - firstDay = parseInt(this._get(inst, "firstDay"),10); - firstDay = (isNaN(firstDay) ? 0 : firstDay); - - showWeek = this._get(inst, "showWeek"); - dayNames = this._get(inst, "dayNames"); - dayNamesMin = this._get(inst, "dayNamesMin"); - monthNames = this._get(inst, "monthNames"); - monthNamesShort = this._get(inst, "monthNamesShort"); - beforeShowDay = this._get(inst, "beforeShowDay"); - showOtherMonths = this._get(inst, "showOtherMonths"); - selectOtherMonths = this._get(inst, "selectOtherMonths"); - defaultDate = this._getDefaultDate(inst); - html = ""; - dow; - for (row = 0; row < numMonths[0]; row++) { - group = ""; - this.maxRows = 4; - for (col = 0; col < numMonths[1]; col++) { - selectedDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay)); - cornerClass = " ui-corner-all"; - calender = ""; - if (isMultiMonth) { - calender += "<div class='ui-datepicker-group"; - if (numMonths[1] > 1) { - switch (col) { - case 0: calender += " ui-datepicker-group-first"; - cornerClass = " ui-corner-" + (isRTL ? "right" : "left"); break; - case numMonths[1]-1: calender += " ui-datepicker-group-last"; - cornerClass = " ui-corner-" + (isRTL ? "left" : "right"); break; - default: calender += " ui-datepicker-group-middle"; cornerClass = ""; break; - } - } - calender += "'>"; - } - calender += "<div class='ui-datepicker-header ui-widget-header ui-helper-clearfix" + cornerClass + "'>" + - (/all|left/.test(cornerClass) && row === 0 ? (isRTL ? next : prev) : "") + - (/all|right/.test(cornerClass) && row === 0 ? (isRTL ? prev : next) : "") + - this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate, - row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers - "</div><table class='ui-datepicker-calendar'><thead>" + - "<tr>"; - thead = (showWeek ? "<th class='ui-datepicker-week-col'>" + this._get(inst, "weekHeader") + "</th>" : ""); - for (dow = 0; dow < 7; dow++) { // days of the week - day = (dow + firstDay) % 7; - thead += "<th" + ((dow + firstDay + 6) % 7 >= 5 ? " class='ui-datepicker-week-end'" : "") + ">" + - "<span title='" + dayNames[day] + "'>" + dayNamesMin[day] + "</span></th>"; - } - calender += thead + "</tr></thead><tbody>"; - daysInMonth = this._getDaysInMonth(drawYear, drawMonth); - if (drawYear === inst.selectedYear && drawMonth === inst.selectedMonth) { - inst.selectedDay = Math.min(inst.selectedDay, daysInMonth); - } - leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7; - curRows = Math.ceil((leadDays + daysInMonth) / 7); // calculate the number of rows to generate - numRows = (isMultiMonth ? this.maxRows > curRows ? this.maxRows : curRows : curRows); //If multiple months, use the higher number of rows (see #7043) - this.maxRows = numRows; - printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays)); - for (dRow = 0; dRow < numRows; dRow++) { // create date picker rows - calender += "<tr>"; - tbody = (!showWeek ? "" : "<td class='ui-datepicker-week-col'>" + - this._get(inst, "calculateWeek")(printDate) + "</td>"); - for (dow = 0; dow < 7; dow++) { // create date picker days - daySettings = (beforeShowDay ? - beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, ""]); - otherMonth = (printDate.getMonth() !== drawMonth); - unselectable = (otherMonth && !selectOtherMonths) || !daySettings[0] || - (minDate && printDate < minDate) || (maxDate && printDate > maxDate); - tbody += "<td class='" + - ((dow + firstDay + 6) % 7 >= 5 ? " ui-datepicker-week-end" : "") + // highlight weekends - (otherMonth ? " ui-datepicker-other-month" : "") + // highlight days from other months - ((printDate.getTime() === selectedDate.getTime() && drawMonth === inst.selectedMonth && inst._keyEvent) || // user pressed key - (defaultDate.getTime() === printDate.getTime() && defaultDate.getTime() === selectedDate.getTime()) ? - // or defaultDate is current printedDate and defaultDate is selectedDate - " " + this._dayOverClass : "") + // highlight selected day - (unselectable ? " " + this._unselectableClass + " ui-state-disabled": "") + // highlight unselectable days - (otherMonth && !showOtherMonths ? "" : " " + daySettings[1] + // highlight custom dates - (printDate.getTime() === currentDate.getTime() ? " " + this._currentClass : "") + // highlight selected day - (printDate.getTime() === today.getTime() ? " ui-datepicker-today" : "")) + "'" + // highlight today (if different) - ((!otherMonth || showOtherMonths) && daySettings[2] ? " title='" + daySettings[2].replace(/'/g, "'") + "'" : "") + // cell title - (unselectable ? "" : " data-handler='selectDay' data-event='click' data-month='" + printDate.getMonth() + "' data-year='" + printDate.getFullYear() + "'") + ">" + // actions - (otherMonth && !showOtherMonths ? " " : // display for other months - (unselectable ? "<span class='ui-state-default'>" + printDate.getDate() + "</span>" : "<a class='ui-state-default" + - (printDate.getTime() === today.getTime() ? " ui-state-highlight" : "") + - (printDate.getTime() === currentDate.getTime() ? " ui-state-active" : "") + // highlight selected day - (otherMonth ? " ui-priority-secondary" : "") + // distinguish dates from other months - "' href='#'>" + printDate.getDate() + "</a>")) + "</td>"; // display selectable date - printDate.setDate(printDate.getDate() + 1); - printDate = this._daylightSavingAdjust(printDate); - } - calender += tbody + "</tr>"; - } - drawMonth++; - if (drawMonth > 11) { - drawMonth = 0; - drawYear++; - } - calender += "</tbody></table>" + (isMultiMonth ? "</div>" + - ((numMonths[0] > 0 && col === numMonths[1]-1) ? "<div class='ui-datepicker-row-break'></div>" : "") : ""); - group += calender; - } - html += group; - } - html += buttonPanel; - inst._keyEvent = false; - return html; - }, - - /* Generate the month and year header. */ - _generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate, - secondary, monthNames, monthNamesShort) { - - var inMinYear, inMaxYear, month, years, thisYear, determineYear, year, endYear, - changeMonth = this._get(inst, "changeMonth"), - changeYear = this._get(inst, "changeYear"), - showMonthAfterYear = this._get(inst, "showMonthAfterYear"), - html = "<div class='ui-datepicker-title'>", - monthHtml = ""; - - // month selection - if (secondary || !changeMonth) { - monthHtml += "<span class='ui-datepicker-month'>" + monthNames[drawMonth] + "</span>"; - } else { - inMinYear = (minDate && minDate.getFullYear() === drawYear); - inMaxYear = (maxDate && maxDate.getFullYear() === drawYear); - monthHtml += "<select class='ui-datepicker-month' data-handler='selectMonth' data-event='change'>"; - for ( month = 0; month < 12; month++) { - if ((!inMinYear || month >= minDate.getMonth()) && (!inMaxYear || month <= maxDate.getMonth())) { - monthHtml += "<option value='" + month + "'" + - (month === drawMonth ? " selected='selected'" : "") + - ">" + monthNamesShort[month] + "</option>"; - } - } - monthHtml += "</select>"; - } - - if (!showMonthAfterYear) { - html += monthHtml + (secondary || !(changeMonth && changeYear) ? " " : ""); - } - - // year selection - if ( !inst.yearshtml ) { - inst.yearshtml = ""; - if (secondary || !changeYear) { - html += "<span class='ui-datepicker-year'>" + drawYear + "</span>"; - } else { - // determine range of years to display - years = this._get(inst, "yearRange").split(":"); - thisYear = new Date().getFullYear(); - determineYear = function(value) { - var year = (value.match(/c[+\-].*/) ? drawYear + parseInt(value.substring(1), 10) : - (value.match(/[+\-].*/) ? thisYear + parseInt(value, 10) : - parseInt(value, 10))); - return (isNaN(year) ? thisYear : year); - }; - year = determineYear(years[0]); - endYear = Math.max(year, determineYear(years[1] || "")); - year = (minDate ? Math.max(year, minDate.getFullYear()) : year); - endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear); - inst.yearshtml += "<select class='ui-datepicker-year' data-handler='selectYear' data-event='change'>"; - for (; year <= endYear; year++) { - inst.yearshtml += "<option value='" + year + "'" + - (year === drawYear ? " selected='selected'" : "") + - ">" + year + "</option>"; - } - inst.yearshtml += "</select>"; - - html += inst.yearshtml; - inst.yearshtml = null; - } - } - - html += this._get(inst, "yearSuffix"); - if (showMonthAfterYear) { - html += (secondary || !(changeMonth && changeYear) ? " " : "") + monthHtml; - } - html += "</div>"; // Close datepicker_header - return html; - }, - - /* Adjust one of the date sub-fields. */ - _adjustInstDate: function(inst, offset, period) { - var year = inst.drawYear + (period === "Y" ? offset : 0), - month = inst.drawMonth + (period === "M" ? offset : 0), - day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) + (period === "D" ? offset : 0), - date = this._restrictMinMax(inst, this._daylightSavingAdjust(new Date(year, month, day))); - - inst.selectedDay = date.getDate(); - inst.drawMonth = inst.selectedMonth = date.getMonth(); - inst.drawYear = inst.selectedYear = date.getFullYear(); - if (period === "M" || period === "Y") { - this._notifyChange(inst); - } - }, - - /* Ensure a date is within any min/max bounds. */ - _restrictMinMax: function(inst, date) { - var minDate = this._getMinMaxDate(inst, "min"), - maxDate = this._getMinMaxDate(inst, "max"), - newDate = (minDate && date < minDate ? minDate : date); - return (maxDate && newDate > maxDate ? maxDate : newDate); - }, - - /* Notify change of month/year. */ - _notifyChange: function(inst) { - var onChange = this._get(inst, "onChangeMonthYear"); - if (onChange) { - onChange.apply((inst.input ? inst.input[0] : null), - [inst.selectedYear, inst.selectedMonth + 1, inst]); - } - }, - - /* Determine the number of months to show. */ - _getNumberOfMonths: function(inst) { - var numMonths = this._get(inst, "numberOfMonths"); - return (numMonths == null ? [1, 1] : (typeof numMonths === "number" ? [1, numMonths] : numMonths)); - }, - - /* Determine the current maximum date - ensure no time components are set. */ - _getMinMaxDate: function(inst, minMax) { - return this._determineDate(inst, this._get(inst, minMax + "Date"), null); - }, - - /* Find the number of days in a given month. */ - _getDaysInMonth: function(year, month) { - return 32 - this._daylightSavingAdjust(new Date(year, month, 32)).getDate(); - }, - - /* Find the day of the week of the first of a month. */ - _getFirstDayOfMonth: function(year, month) { - return new Date(year, month, 1).getDay(); - }, - - /* Determines if we should allow a "next/prev" month display change. */ - _canAdjustMonth: function(inst, offset, curYear, curMonth) { - var numMonths = this._getNumberOfMonths(inst), - date = this._daylightSavingAdjust(new Date(curYear, - curMonth + (offset < 0 ? offset : numMonths[0] * numMonths[1]), 1)); - - if (offset < 0) { - date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth())); - } - return this._isInRange(inst, date); - }, - - /* Is the given date in the accepted range? */ - _isInRange: function(inst, date) { - var yearSplit, currentYear, - minDate = this._getMinMaxDate(inst, "min"), - maxDate = this._getMinMaxDate(inst, "max"), - minYear = null, - maxYear = null, - years = this._get(inst, "yearRange"); - if (years){ - yearSplit = years.split(":"); - currentYear = new Date().getFullYear(); - minYear = parseInt(yearSplit[0], 10); - maxYear = parseInt(yearSplit[1], 10); - if ( yearSplit[0].match(/[+\-].*/) ) { - minYear += currentYear; - } - if ( yearSplit[1].match(/[+\-].*/) ) { - maxYear += currentYear; - } - } - - return ((!minDate || date.getTime() >= minDate.getTime()) && - (!maxDate || date.getTime() <= maxDate.getTime()) && - (!minYear || date.getFullYear() >= minYear) && - (!maxYear || date.getFullYear() <= maxYear)); - }, - - /* Provide the configuration settings for formatting/parsing. */ - _getFormatConfig: function(inst) { - var shortYearCutoff = this._get(inst, "shortYearCutoff"); - shortYearCutoff = (typeof shortYearCutoff !== "string" ? shortYearCutoff : - new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10)); - return {shortYearCutoff: shortYearCutoff, - dayNamesShort: this._get(inst, "dayNamesShort"), dayNames: this._get(inst, "dayNames"), - monthNamesShort: this._get(inst, "monthNamesShort"), monthNames: this._get(inst, "monthNames")}; - }, - - /* Format the given date for display. */ - _formatDate: function(inst, day, month, year) { - if (!day) { - inst.currentDay = inst.selectedDay; - inst.currentMonth = inst.selectedMonth; - inst.currentYear = inst.selectedYear; - } - var date = (day ? (typeof day === "object" ? day : - this._daylightSavingAdjust(new Date(year, month, day))) : - this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay))); - return this.formatDate(this._get(inst, "dateFormat"), date, this._getFormatConfig(inst)); - } -}); - -/* - * Bind hover events for datepicker elements. - * Done via delegate so the binding only occurs once in the lifetime of the parent div. - * Global instActive, set by _updateDatepicker allows the handlers to find their way back to the active picker. - */ -function bindHover(dpDiv) { - var selector = "button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a"; - return dpDiv.delegate(selector, "mouseout", function() { - $(this).removeClass("ui-state-hover"); - if (this.className.indexOf("ui-datepicker-prev") !== -1) { - $(this).removeClass("ui-datepicker-prev-hover"); - } - if (this.className.indexOf("ui-datepicker-next") !== -1) { - $(this).removeClass("ui-datepicker-next-hover"); - } - }) - .delegate(selector, "mouseover", function(){ - if (!$.datepicker._isDisabledDatepicker( instActive.inline ? dpDiv.parent()[0] : instActive.input[0])) { - $(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover"); - $(this).addClass("ui-state-hover"); - if (this.className.indexOf("ui-datepicker-prev") !== -1) { - $(this).addClass("ui-datepicker-prev-hover"); - } - if (this.className.indexOf("ui-datepicker-next") !== -1) { - $(this).addClass("ui-datepicker-next-hover"); - } - } - }); -} - -/* jQuery extend now ignores nulls! */ -function extendRemove(target, props) { - $.extend(target, props); - for (var name in props) { - if (props[name] == null) { - target[name] = props[name]; - } - } - return target; -} - -/* Invoke the datepicker functionality. - @param options string - a command, optionally followed by additional parameters or - Object - settings for attaching new datepicker functionality - @return jQuery object */ -$.fn.datepicker = function(options){ - - /* Verify an empty collection wasn't passed - Fixes #6976 */ - if ( !this.length ) { - return this; - } - - /* Initialise the date picker. */ - if (!$.datepicker.initialized) { - $(document).mousedown($.datepicker._checkExternalClick); - $.datepicker.initialized = true; - } - - /* Append datepicker main container to body if not exist. */ - if ($("#"+$.datepicker._mainDivId).length === 0) { - $("body").append($.datepicker.dpDiv); - } - - var otherArgs = Array.prototype.slice.call(arguments, 1); - if (typeof options === "string" && (options === "isDisabled" || options === "getDate" || options === "widget")) { - return $.datepicker["_" + options + "Datepicker"]. - apply($.datepicker, [this[0]].concat(otherArgs)); - } - if (options === "option" && arguments.length === 2 && typeof arguments[1] === "string") { - return $.datepicker["_" + options + "Datepicker"]. - apply($.datepicker, [this[0]].concat(otherArgs)); - } - return this.each(function() { - typeof options === "string" ? - $.datepicker["_" + options + "Datepicker"]. - apply($.datepicker, [this].concat(otherArgs)) : - $.datepicker._attachDatepicker(this, options); - }); -}; - -$.datepicker = new Datepicker(); // singleton instance -$.datepicker.initialized = false; -$.datepicker.uuid = new Date().getTime(); -$.datepicker.version = "1.10.3"; - -})(jQuery); - -(function( $, undefined ) { - -var sizeRelatedOptions = { - buttons: true, - height: true, - maxHeight: true, - maxWidth: true, - minHeight: true, - minWidth: true, - width: true - }, - resizableRelatedOptions = { - maxHeight: true, - maxWidth: true, - minHeight: true, - minWidth: true - }; - -$.widget( "ui.dialog", { - version: "1.10.3", - options: { - appendTo: "body", - autoOpen: true, - buttons: [], - closeOnEscape: true, - closeText: "close", - dialogClass: "", - draggable: true, - hide: null, - height: "auto", - maxHeight: null, - maxWidth: null, - minHeight: 150, - minWidth: 150, - modal: false, - position: { - my: "center", - at: "center", - of: window, - collision: "fit", - // Ensure the titlebar is always visible - using: function( pos ) { - var topOffset = $( this ).css( pos ).offset().top; - if ( topOffset < 0 ) { - $( this ).css( "top", pos.top - topOffset ); - } - } - }, - resizable: true, - show: null, - title: null, - width: 300, - - // callbacks - beforeClose: null, - close: null, - drag: null, - dragStart: null, - dragStop: null, - focus: null, - open: null, - resize: null, - resizeStart: null, - resizeStop: null - }, - - _create: function() { - this.originalCss = { - display: this.element[0].style.display, - width: this.element[0].style.width, - minHeight: this.element[0].style.minHeight, - maxHeight: this.element[0].style.maxHeight, - height: this.element[0].style.height - }; - this.originalPosition = { - parent: this.element.parent(), - index: this.element.parent().children().index( this.element ) - }; - this.originalTitle = this.element.attr("title"); - this.options.title = this.options.title || this.originalTitle; - - this._createWrapper(); - - this.element - .show() - .removeAttr("title") - .addClass("ui-dialog-content ui-widget-content") - .appendTo( this.uiDialog ); - - this._createTitlebar(); - this._createButtonPane(); - - if ( this.options.draggable && $.fn.draggable ) { - this._makeDraggable(); - } - if ( this.options.resizable && $.fn.resizable ) { - this._makeResizable(); - } - - this._isOpen = false; - }, - - _init: function() { - if ( this.options.autoOpen ) { - this.open(); - } - }, - - _appendTo: function() { - var element = this.options.appendTo; - if ( element && (element.jquery || element.nodeType) ) { - return $( element ); - } - return this.document.find( element || "body" ).eq( 0 ); - }, - - _destroy: function() { - var next, - originalPosition = this.originalPosition; - - this._destroyOverlay(); - - this.element - .removeUniqueId() - .removeClass("ui-dialog-content ui-widget-content") - .css( this.originalCss ) - // Without detaching first, the following becomes really slow - .detach(); - - this.uiDialog.stop( true, true ).remove(); - - if ( this.originalTitle ) { - this.element.attr( "title", this.originalTitle ); - } - - next = originalPosition.parent.children().eq( originalPosition.index ); - // Don't try to place the dialog next to itself (#8613) - if ( next.length && next[0] !== this.element[0] ) { - next.before( this.element ); - } else { - originalPosition.parent.append( this.element ); - } - }, - - widget: function() { - return this.uiDialog; - }, - - disable: $.noop, - enable: $.noop, - - close: function( event ) { - var that = this; - - if ( !this._isOpen || this._trigger( "beforeClose", event ) === false ) { - return; - } - - this._isOpen = false; - this._destroyOverlay(); - - if ( !this.opener.filter(":focusable").focus().length ) { - // Hiding a focused element doesn't trigger blur in WebKit - // so in case we have nothing to focus on, explicitly blur the active element - // https://bugs.webkit.org/show_bug.cgi?id=47182 - $( this.document[0].activeElement ).blur(); - } - - this._hide( this.uiDialog, this.options.hide, function() { - that._trigger( "close", event ); - }); - }, - - isOpen: function() { - return this._isOpen; - }, - - moveToTop: function() { - this._moveToTop(); - }, - - _moveToTop: function( event, silent ) { - var moved = !!this.uiDialog.nextAll(":visible").insertBefore( this.uiDialog ).length; - if ( moved && !silent ) { - this._trigger( "focus", event ); - } - return moved; - }, - - open: function() { - var that = this; - if ( this._isOpen ) { - if ( this._moveToTop() ) { - this._focusTabbable(); - } - return; - } - - this._isOpen = true; - this.opener = $( this.document[0].activeElement ); - - this._size(); - this._position(); - this._createOverlay(); - this._moveToTop( null, true ); - this._show( this.uiDialog, this.options.show, function() { - that._focusTabbable(); - that._trigger("focus"); - }); - - this._trigger("open"); - }, - - _focusTabbable: function() { - // Set focus to the first match: - // 1. First element inside the dialog matching [autofocus] - // 2. Tabbable element inside the content element - // 3. Tabbable element inside the buttonpane - // 4. The close button - // 5. The dialog itself - var hasFocus = this.element.find("[autofocus]"); - if ( !hasFocus.length ) { - hasFocus = this.element.find(":tabbable"); - } - if ( !hasFocus.length ) { - hasFocus = this.uiDialogButtonPane.find(":tabbable"); - } - if ( !hasFocus.length ) { - hasFocus = this.uiDialogTitlebarClose.filter(":tabbable"); - } - if ( !hasFocus.length ) { - hasFocus = this.uiDialog; - } - hasFocus.eq( 0 ).focus(); - }, - - _keepFocus: function( event ) { - function checkFocus() { - var activeElement = this.document[0].activeElement, - isActive = this.uiDialog[0] === activeElement || - $.contains( this.uiDialog[0], activeElement ); - if ( !isActive ) { - this._focusTabbable(); - } - } - event.preventDefault(); - checkFocus.call( this ); - // support: IE - // IE <= 8 doesn't prevent moving focus even with event.preventDefault() - // so we check again later - this._delay( checkFocus ); - }, - - _createWrapper: function() { - this.uiDialog = $("<div>") - .addClass( "ui-dialog ui-widget ui-widget-content ui-corner-all ui-front " + - this.options.dialogClass ) - .hide() - .attr({ - // Setting tabIndex makes the div focusable - tabIndex: -1, - role: "dialog" - }) - .appendTo( this._appendTo() ); - - this._on( this.uiDialog, { - keydown: function( event ) { - if ( this.options.closeOnEscape && !event.isDefaultPrevented() && event.keyCode && - event.keyCode === $.ui.keyCode.ESCAPE ) { - event.preventDefault(); - this.close( event ); - return; - } - - // prevent tabbing out of dialogs - if ( event.keyCode !== $.ui.keyCode.TAB ) { - return; - } - var tabbables = this.uiDialog.find(":tabbable"), - first = tabbables.filter(":first"), - last = tabbables.filter(":last"); - - if ( ( event.target === last[0] || event.target === this.uiDialog[0] ) && !event.shiftKey ) { - first.focus( 1 ); - event.preventDefault(); - } else if ( ( event.target === first[0] || event.target === this.uiDialog[0] ) && event.shiftKey ) { - last.focus( 1 ); - event.preventDefault(); - } - }, - mousedown: function( event ) { - if ( this._moveToTop( event ) ) { - this._focusTabbable(); - } - } - }); - - // We assume that any existing aria-describedby attribute means - // that the dialog content is marked up properly - // otherwise we brute force the content as the description - if ( !this.element.find("[aria-describedby]").length ) { - this.uiDialog.attr({ - "aria-describedby": this.element.uniqueId().attr("id") - }); - } - }, - - _createTitlebar: function() { - var uiDialogTitle; - - this.uiDialogTitlebar = $("<div>") - .addClass("ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix") - .prependTo( this.uiDialog ); - this._on( this.uiDialogTitlebar, { - mousedown: function( event ) { - // Don't prevent click on close button (#8838) - // Focusing a dialog that is partially scrolled out of view - // causes the browser to scroll it into view, preventing the click event - if ( !$( event.target ).closest(".ui-dialog-titlebar-close") ) { - // Dialog isn't getting focus when dragging (#8063) - this.uiDialog.focus(); - } - } - }); - - this.uiDialogTitlebarClose = $("<button></button>") - .button({ - label: this.options.closeText, - icons: { - primary: "ui-icon-closethick" - }, - text: false - }) - .addClass("ui-dialog-titlebar-close") - .appendTo( this.uiDialogTitlebar ); - this._on( this.uiDialogTitlebarClose, { - click: function( event ) { - event.preventDefault(); - this.close( event ); - } - }); - - uiDialogTitle = $("<span>") - .uniqueId() - .addClass("ui-dialog-title") - .prependTo( this.uiDialogTitlebar ); - this._title( uiDialogTitle ); - - this.uiDialog.attr({ - "aria-labelledby": uiDialogTitle.attr("id") - }); - }, - - _title: function( title ) { - if ( !this.options.title ) { - title.html(" "); - } - title.text( this.options.title ); - }, - - _createButtonPane: function() { - this.uiDialogButtonPane = $("<div>") - .addClass("ui-dialog-buttonpane ui-widget-content ui-helper-clearfix"); - - this.uiButtonSet = $("<div>") - .addClass("ui-dialog-buttonset") - .appendTo( this.uiDialogButtonPane ); - - this._createButtons(); - }, - - _createButtons: function() { - var that = this, - buttons = this.options.buttons; - - // if we already have a button pane, remove it - this.uiDialogButtonPane.remove(); - this.uiButtonSet.empty(); - - if ( $.isEmptyObject( buttons ) || ($.isArray( buttons ) && !buttons.length) ) { - this.uiDialog.removeClass("ui-dialog-buttons"); - return; - } - - $.each( buttons, function( name, props ) { - var click, buttonOptions; - props = $.isFunction( props ) ? - { click: props, text: name } : - props; - // Default to a non-submitting button - props = $.extend( { type: "button" }, props ); - // Change the context for the click callback to be the main element - click = props.click; - props.click = function() { - click.apply( that.element[0], arguments ); - }; - buttonOptions = { - icons: props.icons, - text: props.showText - }; - delete props.icons; - delete props.showText; - $( "<button></button>", props ) - .button( buttonOptions ) - .appendTo( that.uiButtonSet ); - }); - this.uiDialog.addClass("ui-dialog-buttons"); - this.uiDialogButtonPane.appendTo( this.uiDialog ); - }, - - _makeDraggable: function() { - var that = this, - options = this.options; - - function filteredUi( ui ) { - return { - position: ui.position, - offset: ui.offset - }; - } - - this.uiDialog.draggable({ - cancel: ".ui-dialog-content, .ui-dialog-titlebar-close", - handle: ".ui-dialog-titlebar", - containment: "document", - start: function( event, ui ) { - $( this ).addClass("ui-dialog-dragging"); - that._blockFrames(); - that._trigger( "dragStart", event, filteredUi( ui ) ); - }, - drag: function( event, ui ) { - that._trigger( "drag", event, filteredUi( ui ) ); - }, - stop: function( event, ui ) { - options.position = [ - ui.position.left - that.document.scrollLeft(), - ui.position.top - that.document.scrollTop() - ]; - $( this ).removeClass("ui-dialog-dragging"); - that._unblockFrames(); - that._trigger( "dragStop", event, filteredUi( ui ) ); - } - }); - }, - - _makeResizable: function() { - var that = this, - options = this.options, - handles = options.resizable, - // .ui-resizable has position: relative defined in the stylesheet - // but dialogs have to use absolute or fixed positioning - position = this.uiDialog.css("position"), - resizeHandles = typeof handles === "string" ? - handles : - "n,e,s,w,se,sw,ne,nw"; - - function filteredUi( ui ) { - return { - originalPosition: ui.originalPosition, - originalSize: ui.originalSize, - position: ui.position, - size: ui.size - }; - } - - this.uiDialog.resizable({ - cancel: ".ui-dialog-content", - containment: "document", - alsoResize: this.element, - maxWidth: options.maxWidth, - maxHeight: options.maxHeight, - minWidth: options.minWidth, - minHeight: this._minHeight(), - handles: resizeHandles, - start: function( event, ui ) { - $( this ).addClass("ui-dialog-resizing"); - that._blockFrames(); - that._trigger( "resizeStart", event, filteredUi( ui ) ); - }, - resize: function( event, ui ) { - that._trigger( "resize", event, filteredUi( ui ) ); - }, - stop: function( event, ui ) { - options.height = $( this ).height(); - options.width = $( this ).width(); - $( this ).removeClass("ui-dialog-resizing"); - that._unblockFrames(); - that._trigger( "resizeStop", event, filteredUi( ui ) ); - } - }) - .css( "position", position ); - }, - - _minHeight: function() { - var options = this.options; - - return options.height === "auto" ? - options.minHeight : - Math.min( options.minHeight, options.height ); - }, - - _position: function() { - // Need to show the dialog to get the actual offset in the position plugin - var isVisible = this.uiDialog.is(":visible"); - if ( !isVisible ) { - this.uiDialog.show(); - } - this.uiDialog.position( this.options.position ); - if ( !isVisible ) { - this.uiDialog.hide(); - } - }, - - _setOptions: function( options ) { - var that = this, - resize = false, - resizableOptions = {}; - - $.each( options, function( key, value ) { - that._setOption( key, value ); - - if ( key in sizeRelatedOptions ) { - resize = true; - } - if ( key in resizableRelatedOptions ) { - resizableOptions[ key ] = value; - } - }); - - if ( resize ) { - this._size(); - this._position(); - } - if ( this.uiDialog.is(":data(ui-resizable)") ) { - this.uiDialog.resizable( "option", resizableOptions ); - } - }, - - _setOption: function( key, value ) { - /*jshint maxcomplexity:15*/ - var isDraggable, isResizable, - uiDialog = this.uiDialog; - - if ( key === "dialogClass" ) { - uiDialog - .removeClass( this.options.dialogClass ) - .addClass( value ); - } - - if ( key === "disabled" ) { - return; - } - - this._super( key, value ); - - if ( key === "appendTo" ) { - this.uiDialog.appendTo( this._appendTo() ); - } - - if ( key === "buttons" ) { - this._createButtons(); - } - - if ( key === "closeText" ) { - this.uiDialogTitlebarClose.button({ - // Ensure that we always pass a string - label: "" + value - }); - } - - if ( key === "draggable" ) { - isDraggable = uiDialog.is(":data(ui-draggable)"); - if ( isDraggable && !value ) { - uiDialog.draggable("destroy"); - } - - if ( !isDraggable && value ) { - this._makeDraggable(); - } - } - - if ( key === "position" ) { - this._position(); - } - - if ( key === "resizable" ) { - // currently resizable, becoming non-resizable - isResizable = uiDialog.is(":data(ui-resizable)"); - if ( isResizable && !value ) { - uiDialog.resizable("destroy"); - } - - // currently resizable, changing handles - if ( isResizable && typeof value === "string" ) { - uiDialog.resizable( "option", "handles", value ); - } - - // currently non-resizable, becoming resizable - if ( !isResizable && value !== false ) { - this._makeResizable(); - } - } - - if ( key === "title" ) { - this._title( this.uiDialogTitlebar.find(".ui-dialog-title") ); - } - }, - - _size: function() { - // If the user has resized the dialog, the .ui-dialog and .ui-dialog-content - // divs will both have width and height set, so we need to reset them - var nonContentHeight, minContentHeight, maxContentHeight, - options = this.options; - - // Reset content sizing - this.element.show().css({ - width: "auto", - minHeight: 0, - maxHeight: "none", - height: 0 - }); - - if ( options.minWidth > options.width ) { - options.width = options.minWidth; - } - - // reset wrapper sizing - // determine the height of all the non-content elements - nonContentHeight = this.uiDialog.css({ - height: "auto", - width: options.width - }) - .outerHeight(); - minContentHeight = Math.max( 0, options.minHeight - nonContentHeight ); - maxContentHeight = typeof options.maxHeight === "number" ? - Math.max( 0, options.maxHeight - nonContentHeight ) : - "none"; - - if ( options.height === "auto" ) { - this.element.css({ - minHeight: minContentHeight, - maxHeight: maxContentHeight, - height: "auto" - }); - } else { - this.element.height( Math.max( 0, options.height - nonContentHeight ) ); - } - - if (this.uiDialog.is(":data(ui-resizable)") ) { - this.uiDialog.resizable( "option", "minHeight", this._minHeight() ); - } - }, - - _blockFrames: function() { - this.iframeBlocks = this.document.find( "iframe" ).map(function() { - var iframe = $( this ); - - return $( "<div>" ) - .css({ - position: "absolute", - width: iframe.outerWidth(), - height: iframe.outerHeight() - }) - .appendTo( iframe.parent() ) - .offset( iframe.offset() )[0]; - }); - }, - - _unblockFrames: function() { - if ( this.iframeBlocks ) { - this.iframeBlocks.remove(); - delete this.iframeBlocks; - } - }, - - _allowInteraction: function( event ) { - if ( $( event.target ).closest(".ui-dialog").length ) { - return true; - } - - // TODO: Remove hack when datepicker implements - // the .ui-front logic (#8989) - return !!$( event.target ).closest(".ui-datepicker").length; - }, - - _createOverlay: function() { - if ( !this.options.modal ) { - return; - } - - var that = this, - widgetFullName = this.widgetFullName; - if ( !$.ui.dialog.overlayInstances ) { - // Prevent use of anchors and inputs. - // We use a delay in case the overlay is created from an - // event that we're going to be cancelling. (#2804) - this._delay(function() { - // Handle .dialog().dialog("close") (#4065) - if ( $.ui.dialog.overlayInstances ) { - this.document.bind( "focusin.dialog", function( event ) { - if ( !that._allowInteraction( event ) ) { - event.preventDefault(); - $(".ui-dialog:visible:last .ui-dialog-content") - .data( widgetFullName )._focusTabbable(); - } - }); - } - }); - } - - this.overlay = $("<div>") - .addClass("ui-widget-overlay ui-front") - .appendTo( this._appendTo() ); - this._on( this.overlay, { - mousedown: "_keepFocus" - }); - $.ui.dialog.overlayInstances++; - }, - - _destroyOverlay: function() { - if ( !this.options.modal ) { - return; - } - - if ( this.overlay ) { - $.ui.dialog.overlayInstances--; - - if ( !$.ui.dialog.overlayInstances ) { - this.document.unbind( "focusin.dialog" ); - } - this.overlay.remove(); - this.overlay = null; - } - } -}); - -$.ui.dialog.overlayInstances = 0; - -// DEPRECATED -if ( $.uiBackCompat !== false ) { - // position option with array notation - // just override with old implementation - $.widget( "ui.dialog", $.ui.dialog, { - _position: function() { - var position = this.options.position, - myAt = [], - offset = [ 0, 0 ], - isVisible; - - if ( position ) { - if ( typeof position === "string" || (typeof position === "object" && "0" in position ) ) { - myAt = position.split ? position.split(" ") : [ position[0], position[1] ]; - if ( myAt.length === 1 ) { - myAt[1] = myAt[0]; - } - - $.each( [ "left", "top" ], function( i, offsetPosition ) { - if ( +myAt[ i ] === myAt[ i ] ) { - offset[ i ] = myAt[ i ]; - myAt[ i ] = offsetPosition; - } - }); - - position = { - my: myAt[0] + (offset[0] < 0 ? offset[0] : "+" + offset[0]) + " " + - myAt[1] + (offset[1] < 0 ? offset[1] : "+" + offset[1]), - at: myAt.join(" ") - }; - } - - position = $.extend( {}, $.ui.dialog.prototype.options.position, position ); - } else { - position = $.ui.dialog.prototype.options.position; - } - - // need to show the dialog to get the actual offset in the position plugin - isVisible = this.uiDialog.is(":visible"); - if ( !isVisible ) { - this.uiDialog.show(); - } - this.uiDialog.position( position ); - if ( !isVisible ) { - this.uiDialog.hide(); - } - } - }); -} - -}( jQuery ) ); - -(function( $, undefined ) { - -var rvertical = /up|down|vertical/, - rpositivemotion = /up|left|vertical|horizontal/; - -$.effects.effect.blind = function( o, done ) { - // Create element - var el = $( this ), - props = [ "position", "top", "bottom", "left", "right", "height", "width" ], - mode = $.effects.setMode( el, o.mode || "hide" ), - direction = o.direction || "up", - vertical = rvertical.test( direction ), - ref = vertical ? "height" : "width", - ref2 = vertical ? "top" : "left", - motion = rpositivemotion.test( direction ), - animation = {}, - show = mode === "show", - wrapper, distance, margin; - - // if already wrapped, the wrapper's properties are my property. #6245 - if ( el.parent().is( ".ui-effects-wrapper" ) ) { - $.effects.save( el.parent(), props ); - } else { - $.effects.save( el, props ); - } - el.show(); - wrapper = $.effects.createWrapper( el ).css({ - overflow: "hidden" - }); - - distance = wrapper[ ref ](); - margin = parseFloat( wrapper.css( ref2 ) ) || 0; - - animation[ ref ] = show ? distance : 0; - if ( !motion ) { - el - .css( vertical ? "bottom" : "right", 0 ) - .css( vertical ? "top" : "left", "auto" ) - .css({ position: "absolute" }); - - animation[ ref2 ] = show ? margin : distance + margin; - } - - // start at 0 if we are showing - if ( show ) { - wrapper.css( ref, 0 ); - if ( ! motion ) { - wrapper.css( ref2, margin + distance ); - } - } - - // Animate - wrapper.animate( animation, { - duration: o.duration, - easing: o.easing, - queue: false, - complete: function() { - if ( mode === "hide" ) { - el.hide(); - } - $.effects.restore( el, props ); - $.effects.removeWrapper( el ); - done(); - } - }); - -}; - -})(jQuery); - -(function( $, undefined ) { - -$.effects.effect.bounce = function( o, done ) { - var el = $( this ), - props = [ "position", "top", "bottom", "left", "right", "height", "width" ], - - // defaults: - mode = $.effects.setMode( el, o.mode || "effect" ), - hide = mode === "hide", - show = mode === "show", - direction = o.direction || "up", - distance = o.distance, - times = o.times || 5, - - // number of internal animations - anims = times * 2 + ( show || hide ? 1 : 0 ), - speed = o.duration / anims, - easing = o.easing, - - // utility: - ref = ( direction === "up" || direction === "down" ) ? "top" : "left", - motion = ( direction === "up" || direction === "left" ), - i, - upAnim, - downAnim, - - // we will need to re-assemble the queue to stack our animations in place - queue = el.queue(), - queuelen = queue.length; - - // Avoid touching opacity to prevent clearType and PNG issues in IE - if ( show || hide ) { - props.push( "opacity" ); - } - - $.effects.save( el, props ); - el.show(); - $.effects.createWrapper( el ); // Create Wrapper - - // default distance for the BIGGEST bounce is the outer Distance / 3 - if ( !distance ) { - distance = el[ ref === "top" ? "outerHeight" : "outerWidth" ]() / 3; - } - - if ( show ) { - downAnim = { opacity: 1 }; - downAnim[ ref ] = 0; - - // if we are showing, force opacity 0 and set the initial position - // then do the "first" animation - el.css( "opacity", 0 ) - .css( ref, motion ? -distance * 2 : distance * 2 ) - .animate( downAnim, speed, easing ); - } - - // start at the smallest distance if we are hiding - if ( hide ) { - distance = distance / Math.pow( 2, times - 1 ); - } - - downAnim = {}; - downAnim[ ref ] = 0; - // Bounces up/down/left/right then back to 0 -- times * 2 animations happen here - for ( i = 0; i < times; i++ ) { - upAnim = {}; - upAnim[ ref ] = ( motion ? "-=" : "+=" ) + distance; - - el.animate( upAnim, speed, easing ) - .animate( downAnim, speed, easing ); - - distance = hide ? distance * 2 : distance / 2; - } - - // Last Bounce when Hiding - if ( hide ) { - upAnim = { opacity: 0 }; - upAnim[ ref ] = ( motion ? "-=" : "+=" ) + distance; - - el.animate( upAnim, speed, easing ); - } - - el.queue(function() { - if ( hide ) { - el.hide(); - } - $.effects.restore( el, props ); - $.effects.removeWrapper( el ); - done(); - }); - - // inject all the animations we just queued to be first in line (after "inprogress") - if ( queuelen > 1) { - queue.splice.apply( queue, - [ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) ); - } - el.dequeue(); - -}; - -})(jQuery); - -(function( $, undefined ) { - -$.effects.effect.clip = function( o, done ) { - // Create element - var el = $( this ), - props = [ "position", "top", "bottom", "left", "right", "height", "width" ], - mode = $.effects.setMode( el, o.mode || "hide" ), - show = mode === "show", - direction = o.direction || "vertical", - vert = direction === "vertical", - size = vert ? "height" : "width", - position = vert ? "top" : "left", - animation = {}, - wrapper, animate, distance; - - // Save & Show - $.effects.save( el, props ); - el.show(); - - // Create Wrapper - wrapper = $.effects.createWrapper( el ).css({ - overflow: "hidden" - }); - animate = ( el[0].tagName === "IMG" ) ? wrapper : el; - distance = animate[ size ](); - - // Shift - if ( show ) { - animate.css( size, 0 ); - animate.css( position, distance / 2 ); - } - - // Create Animation Object: - animation[ size ] = show ? distance : 0; - animation[ position ] = show ? 0 : distance / 2; - - // Animate - animate.animate( animation, { - queue: false, - duration: o.duration, - easing: o.easing, - complete: function() { - if ( !show ) { - el.hide(); - } - $.effects.restore( el, props ); - $.effects.removeWrapper( el ); - done(); - } - }); - -}; - -})(jQuery); - -(function( $, undefined ) { - -$.effects.effect.drop = function( o, done ) { - - var el = $( this ), - props = [ "position", "top", "bottom", "left", "right", "opacity", "height", "width" ], - mode = $.effects.setMode( el, o.mode || "hide" ), - show = mode === "show", - direction = o.direction || "left", - ref = ( direction === "up" || direction === "down" ) ? "top" : "left", - motion = ( direction === "up" || direction === "left" ) ? "pos" : "neg", - animation = { - opacity: show ? 1 : 0 - }, - distance; - - // Adjust - $.effects.save( el, props ); - el.show(); - $.effects.createWrapper( el ); - - distance = o.distance || el[ ref === "top" ? "outerHeight": "outerWidth" ]( true ) / 2; - - if ( show ) { - el - .css( "opacity", 0 ) - .css( ref, motion === "pos" ? -distance : distance ); - } - - // Animation - animation[ ref ] = ( show ? - ( motion === "pos" ? "+=" : "-=" ) : - ( motion === "pos" ? "-=" : "+=" ) ) + - distance; - - // Animate - el.animate( animation, { - queue: false, - duration: o.duration, - easing: o.easing, - complete: function() { - if ( mode === "hide" ) { - el.hide(); - } - $.effects.restore( el, props ); - $.effects.removeWrapper( el ); - done(); - } - }); -}; - -})(jQuery); - -(function( $, undefined ) { - -$.effects.effect.explode = function( o, done ) { - - var rows = o.pieces ? Math.round( Math.sqrt( o.pieces ) ) : 3, - cells = rows, - el = $( this ), - mode = $.effects.setMode( el, o.mode || "hide" ), - show = mode === "show", - - // show and then visibility:hidden the element before calculating offset - offset = el.show().css( "visibility", "hidden" ).offset(), - - // width and height of a piece - width = Math.ceil( el.outerWidth() / cells ), - height = Math.ceil( el.outerHeight() / rows ), - pieces = [], - - // loop - i, j, left, top, mx, my; - - // children animate complete: - function childComplete() { - pieces.push( this ); - if ( pieces.length === rows * cells ) { - animComplete(); - } - } - - // clone the element for each row and cell. - for( i = 0; i < rows ; i++ ) { // ===> - top = offset.top + i * height; - my = i - ( rows - 1 ) / 2 ; - - for( j = 0; j < cells ; j++ ) { // ||| - left = offset.left + j * width; - mx = j - ( cells - 1 ) / 2 ; - - // Create a clone of the now hidden main element that will be absolute positioned - // within a wrapper div off the -left and -top equal to size of our pieces - el - .clone() - .appendTo( "body" ) - .wrap( "<div></div>" ) - .css({ - position: "absolute", - visibility: "visible", - left: -j * width, - top: -i * height - }) - - // select the wrapper - make it overflow: hidden and absolute positioned based on - // where the original was located +left and +top equal to the size of pieces - .parent() - .addClass( "ui-effects-explode" ) - .css({ - position: "absolute", - overflow: "hidden", - width: width, - height: height, - left: left + ( show ? mx * width : 0 ), - top: top + ( show ? my * height : 0 ), - opacity: show ? 0 : 1 - }).animate({ - left: left + ( show ? 0 : mx * width ), - top: top + ( show ? 0 : my * height ), - opacity: show ? 1 : 0 - }, o.duration || 500, o.easing, childComplete ); - } - } - - function animComplete() { - el.css({ - visibility: "visible" - }); - $( pieces ).remove(); - if ( !show ) { - el.hide(); - } - done(); - } -}; - -})(jQuery); - -(function( $, undefined ) { - -$.effects.effect.fade = function( o, done ) { - var el = $( this ), - mode = $.effects.setMode( el, o.mode || "toggle" ); - - el.animate({ - opacity: mode - }, { - queue: false, - duration: o.duration, - easing: o.easing, - complete: done - }); -}; - -})( jQuery ); - -(function( $, undefined ) { - -$.effects.effect.fold = function( o, done ) { - - // Create element - var el = $( this ), - props = [ "position", "top", "bottom", "left", "right", "height", "width" ], - mode = $.effects.setMode( el, o.mode || "hide" ), - show = mode === "show", - hide = mode === "hide", - size = o.size || 15, - percent = /([0-9]+)%/.exec( size ), - horizFirst = !!o.horizFirst, - widthFirst = show !== horizFirst, - ref = widthFirst ? [ "width", "height" ] : [ "height", "width" ], - duration = o.duration / 2, - wrapper, distance, - animation1 = {}, - animation2 = {}; - - $.effects.save( el, props ); - el.show(); - - // Create Wrapper - wrapper = $.effects.createWrapper( el ).css({ - overflow: "hidden" - }); - distance = widthFirst ? - [ wrapper.width(), wrapper.height() ] : - [ wrapper.height(), wrapper.width() ]; - - if ( percent ) { - size = parseInt( percent[ 1 ], 10 ) / 100 * distance[ hide ? 0 : 1 ]; - } - if ( show ) { - wrapper.css( horizFirst ? { - height: 0, - width: size - } : { - height: size, - width: 0 - }); - } - - // Animation - animation1[ ref[ 0 ] ] = show ? distance[ 0 ] : size; - animation2[ ref[ 1 ] ] = show ? distance[ 1 ] : 0; - - // Animate - wrapper - .animate( animation1, duration, o.easing ) - .animate( animation2, duration, o.easing, function() { - if ( hide ) { - el.hide(); - } - $.effects.restore( el, props ); - $.effects.removeWrapper( el ); - done(); - }); - -}; - -})(jQuery); - -(function( $, undefined ) { - -$.effects.effect.highlight = function( o, done ) { - var elem = $( this ), - props = [ "backgroundImage", "backgroundColor", "opacity" ], - mode = $.effects.setMode( elem, o.mode || "show" ), - animation = { - backgroundColor: elem.css( "backgroundColor" ) - }; - - if (mode === "hide") { - animation.opacity = 0; - } - - $.effects.save( elem, props ); - - elem - .show() - .css({ - backgroundImage: "none", - backgroundColor: o.color || "#ffff99" - }) - .animate( animation, { - queue: false, - duration: o.duration, - easing: o.easing, - complete: function() { - if ( mode === "hide" ) { - elem.hide(); - } - $.effects.restore( elem, props ); - done(); - } - }); -}; - -})(jQuery); - -(function( $, undefined ) { - -$.effects.effect.pulsate = function( o, done ) { - var elem = $( this ), - mode = $.effects.setMode( elem, o.mode || "show" ), - show = mode === "show", - hide = mode === "hide", - showhide = ( show || mode === "hide" ), - - // showing or hiding leaves of the "last" animation - anims = ( ( o.times || 5 ) * 2 ) + ( showhide ? 1 : 0 ), - duration = o.duration / anims, - animateTo = 0, - queue = elem.queue(), - queuelen = queue.length, - i; - - if ( show || !elem.is(":visible")) { - elem.css( "opacity", 0 ).show(); - animateTo = 1; - } - - // anims - 1 opacity "toggles" - for ( i = 1; i < anims; i++ ) { - elem.animate({ - opacity: animateTo - }, duration, o.easing ); - animateTo = 1 - animateTo; - } - - elem.animate({ - opacity: animateTo - }, duration, o.easing); - - elem.queue(function() { - if ( hide ) { - elem.hide(); - } - done(); - }); - - // We just queued up "anims" animations, we need to put them next in the queue - if ( queuelen > 1 ) { - queue.splice.apply( queue, - [ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) ); - } - elem.dequeue(); -}; - -})(jQuery); - -(function( $, undefined ) { - -$.effects.effect.puff = function( o, done ) { - var elem = $( this ), - mode = $.effects.setMode( elem, o.mode || "hide" ), - hide = mode === "hide", - percent = parseInt( o.percent, 10 ) || 150, - factor = percent / 100, - original = { - height: elem.height(), - width: elem.width(), - outerHeight: elem.outerHeight(), - outerWidth: elem.outerWidth() - }; - - $.extend( o, { - effect: "scale", - queue: false, - fade: true, - mode: mode, - complete: done, - percent: hide ? percent : 100, - from: hide ? - original : - { - height: original.height * factor, - width: original.width * factor, - outerHeight: original.outerHeight * factor, - outerWidth: original.outerWidth * factor - } - }); - - elem.effect( o ); -}; - -$.effects.effect.scale = function( o, done ) { - - // Create element - var el = $( this ), - options = $.extend( true, {}, o ), - mode = $.effects.setMode( el, o.mode || "effect" ), - percent = parseInt( o.percent, 10 ) || - ( parseInt( o.percent, 10 ) === 0 ? 0 : ( mode === "hide" ? 0 : 100 ) ), - direction = o.direction || "both", - origin = o.origin, - original = { - height: el.height(), - width: el.width(), - outerHeight: el.outerHeight(), - outerWidth: el.outerWidth() - }, - factor = { - y: direction !== "horizontal" ? (percent / 100) : 1, - x: direction !== "vertical" ? (percent / 100) : 1 - }; - - // We are going to pass this effect to the size effect: - options.effect = "size"; - options.queue = false; - options.complete = done; - - // Set default origin and restore for show/hide - if ( mode !== "effect" ) { - options.origin = origin || ["middle","center"]; - options.restore = true; - } - - options.from = o.from || ( mode === "show" ? { - height: 0, - width: 0, - outerHeight: 0, - outerWidth: 0 - } : original ); - options.to = { - height: original.height * factor.y, - width: original.width * factor.x, - outerHeight: original.outerHeight * factor.y, - outerWidth: original.outerWidth * factor.x - }; - - // Fade option to support puff - if ( options.fade ) { - if ( mode === "show" ) { - options.from.opacity = 0; - options.to.opacity = 1; - } - if ( mode === "hide" ) { - options.from.opacity = 1; - options.to.opacity = 0; - } - } - - // Animate - el.effect( options ); - -}; - -$.effects.effect.size = function( o, done ) { - - // Create element - var original, baseline, factor, - el = $( this ), - props0 = [ "position", "top", "bottom", "left", "right", "width", "height", "overflow", "opacity" ], - - // Always restore - props1 = [ "position", "top", "bottom", "left", "right", "overflow", "opacity" ], - - // Copy for children - props2 = [ "width", "height", "overflow" ], - cProps = [ "fontSize" ], - vProps = [ "borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom" ], - hProps = [ "borderLeftWidth", "borderRightWidth", "paddingLeft", "paddingRight" ], - - // Set options - mode = $.effects.setMode( el, o.mode || "effect" ), - restore = o.restore || mode !== "effect", - scale = o.scale || "both", - origin = o.origin || [ "middle", "center" ], - position = el.css( "position" ), - props = restore ? props0 : props1, - zero = { - height: 0, - width: 0, - outerHeight: 0, - outerWidth: 0 - }; - - if ( mode === "show" ) { - el.show(); - } - original = { - height: el.height(), - width: el.width(), - outerHeight: el.outerHeight(), - outerWidth: el.outerWidth() - }; - - if ( o.mode === "toggle" && mode === "show" ) { - el.from = o.to || zero; - el.to = o.from || original; - } else { - el.from = o.from || ( mode === "show" ? zero : original ); - el.to = o.to || ( mode === "hide" ? zero : original ); - } - - // Set scaling factor - factor = { - from: { - y: el.from.height / original.height, - x: el.from.width / original.width - }, - to: { - y: el.to.height / original.height, - x: el.to.width / original.width - } - }; - - // Scale the css box - if ( scale === "box" || scale === "both" ) { - - // Vertical props scaling - if ( factor.from.y !== factor.to.y ) { - props = props.concat( vProps ); - el.from = $.effects.setTransition( el, vProps, factor.from.y, el.from ); - el.to = $.effects.setTransition( el, vProps, factor.to.y, el.to ); - } - - // Horizontal props scaling - if ( factor.from.x !== factor.to.x ) { - props = props.concat( hProps ); - el.from = $.effects.setTransition( el, hProps, factor.from.x, el.from ); - el.to = $.effects.setTransition( el, hProps, factor.to.x, el.to ); - } - } - - // Scale the content - if ( scale === "content" || scale === "both" ) { - - // Vertical props scaling - if ( factor.from.y !== factor.to.y ) { - props = props.concat( cProps ).concat( props2 ); - el.from = $.effects.setTransition( el, cProps, factor.from.y, el.from ); - el.to = $.effects.setTransition( el, cProps, factor.to.y, el.to ); - } - } - - $.effects.save( el, props ); - el.show(); - $.effects.createWrapper( el ); - el.css( "overflow", "hidden" ).css( el.from ); - - // Adjust - if (origin) { // Calculate baseline shifts - baseline = $.effects.getBaseline( origin, original ); - el.from.top = ( original.outerHeight - el.outerHeight() ) * baseline.y; - el.from.left = ( original.outerWidth - el.outerWidth() ) * baseline.x; - el.to.top = ( original.outerHeight - el.to.outerHeight ) * baseline.y; - el.to.left = ( original.outerWidth - el.to.outerWidth ) * baseline.x; - } - el.css( el.from ); // set top & left - - // Animate - if ( scale === "content" || scale === "both" ) { // Scale the children - - // Add margins/font-size - vProps = vProps.concat([ "marginTop", "marginBottom" ]).concat(cProps); - hProps = hProps.concat([ "marginLeft", "marginRight" ]); - props2 = props0.concat(vProps).concat(hProps); - - el.find( "*[width]" ).each( function(){ - var child = $( this ), - c_original = { - height: child.height(), - width: child.width(), - outerHeight: child.outerHeight(), - outerWidth: child.outerWidth() - }; - if (restore) { - $.effects.save(child, props2); - } - - child.from = { - height: c_original.height * factor.from.y, - width: c_original.width * factor.from.x, - outerHeight: c_original.outerHeight * factor.from.y, - outerWidth: c_original.outerWidth * factor.from.x - }; - child.to = { - height: c_original.height * factor.to.y, - width: c_original.width * factor.to.x, - outerHeight: c_original.height * factor.to.y, - outerWidth: c_original.width * factor.to.x - }; - - // Vertical props scaling - if ( factor.from.y !== factor.to.y ) { - child.from = $.effects.setTransition( child, vProps, factor.from.y, child.from ); - child.to = $.effects.setTransition( child, vProps, factor.to.y, child.to ); - } - - // Horizontal props scaling - if ( factor.from.x !== factor.to.x ) { - child.from = $.effects.setTransition( child, hProps, factor.from.x, child.from ); - child.to = $.effects.setTransition( child, hProps, factor.to.x, child.to ); - } - - // Animate children - child.css( child.from ); - child.animate( child.to, o.duration, o.easing, function() { - - // Restore children - if ( restore ) { - $.effects.restore( child, props2 ); - } - }); - }); - } - - // Animate - el.animate( el.to, { - queue: false, - duration: o.duration, - easing: o.easing, - complete: function() { - if ( el.to.opacity === 0 ) { - el.css( "opacity", el.from.opacity ); - } - if( mode === "hide" ) { - el.hide(); - } - $.effects.restore( el, props ); - if ( !restore ) { - - // we need to calculate our new positioning based on the scaling - if ( position === "static" ) { - el.css({ - position: "relative", - top: el.to.top, - left: el.to.left - }); - } else { - $.each([ "top", "left" ], function( idx, pos ) { - el.css( pos, function( _, str ) { - var val = parseInt( str, 10 ), - toRef = idx ? el.to.left : el.to.top; - - // if original was "auto", recalculate the new value from wrapper - if ( str === "auto" ) { - return toRef + "px"; - } - - return val + toRef + "px"; - }); - }); - } - } - - $.effects.removeWrapper( el ); - done(); - } - }); - -}; - -})(jQuery); - -(function( $, undefined ) { - -$.effects.effect.shake = function( o, done ) { - - var el = $( this ), - props = [ "position", "top", "bottom", "left", "right", "height", "width" ], - mode = $.effects.setMode( el, o.mode || "effect" ), - direction = o.direction || "left", - distance = o.distance || 20, - times = o.times || 3, - anims = times * 2 + 1, - speed = Math.round(o.duration/anims), - ref = (direction === "up" || direction === "down") ? "top" : "left", - positiveMotion = (direction === "up" || direction === "left"), - animation = {}, - animation1 = {}, - animation2 = {}, - i, - - // we will need to re-assemble the queue to stack our animations in place - queue = el.queue(), - queuelen = queue.length; - - $.effects.save( el, props ); - el.show(); - $.effects.createWrapper( el ); - - // Animation - animation[ ref ] = ( positiveMotion ? "-=" : "+=" ) + distance; - animation1[ ref ] = ( positiveMotion ? "+=" : "-=" ) + distance * 2; - animation2[ ref ] = ( positiveMotion ? "-=" : "+=" ) + distance * 2; - - // Animate - el.animate( animation, speed, o.easing ); - - // Shakes - for ( i = 1; i < times; i++ ) { - el.animate( animation1, speed, o.easing ).animate( animation2, speed, o.easing ); - } - el - .animate( animation1, speed, o.easing ) - .animate( animation, speed / 2, o.easing ) - .queue(function() { - if ( mode === "hide" ) { - el.hide(); - } - $.effects.restore( el, props ); - $.effects.removeWrapper( el ); - done(); - }); - - // inject all the animations we just queued to be first in line (after "inprogress") - if ( queuelen > 1) { - queue.splice.apply( queue, - [ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) ); - } - el.dequeue(); - -}; - -})(jQuery); - -(function( $, undefined ) { - -$.effects.effect.slide = function( o, done ) { - - // Create element - var el = $( this ), - props = [ "position", "top", "bottom", "left", "right", "width", "height" ], - mode = $.effects.setMode( el, o.mode || "show" ), - show = mode === "show", - direction = o.direction || "left", - ref = (direction === "up" || direction === "down") ? "top" : "left", - positiveMotion = (direction === "up" || direction === "left"), - distance, - animation = {}; - - // Adjust - $.effects.save( el, props ); - el.show(); - distance = o.distance || el[ ref === "top" ? "outerHeight" : "outerWidth" ]( true ); - - $.effects.createWrapper( el ).css({ - overflow: "hidden" - }); - - if ( show ) { - el.css( ref, positiveMotion ? (isNaN(distance) ? "-" + distance : -distance) : distance ); - } - - // Animation - animation[ ref ] = ( show ? - ( positiveMotion ? "+=" : "-=") : - ( positiveMotion ? "-=" : "+=")) + - distance; - - // Animate - el.animate( animation, { - queue: false, - duration: o.duration, - easing: o.easing, - complete: function() { - if ( mode === "hide" ) { - el.hide(); - } - $.effects.restore( el, props ); - $.effects.removeWrapper( el ); - done(); - } - }); -}; - -})(jQuery); - -(function( $, undefined ) { - -$.effects.effect.transfer = function( o, done ) { - var elem = $( this ), - target = $( o.to ), - targetFixed = target.css( "position" ) === "fixed", - body = $("body"), - fixTop = targetFixed ? body.scrollTop() : 0, - fixLeft = targetFixed ? body.scrollLeft() : 0, - endPosition = target.offset(), - animation = { - top: endPosition.top - fixTop , - left: endPosition.left - fixLeft , - height: target.innerHeight(), - width: target.innerWidth() - }, - startPosition = elem.offset(), - transfer = $( "<div class='ui-effects-transfer'></div>" ) - .appendTo( document.body ) - .addClass( o.className ) - .css({ - top: startPosition.top - fixTop , - left: startPosition.left - fixLeft , - height: elem.innerHeight(), - width: elem.innerWidth(), - position: targetFixed ? "fixed" : "absolute" - }) - .animate( animation, o.duration, o.easing, function() { - transfer.remove(); - done(); - }); -}; - -})(jQuery); - -(function( $, undefined ) { - -$.widget( "ui.menu", { - version: "1.10.3", - defaultElement: "<ul>", - delay: 300, - options: { - icons: { - submenu: "ui-icon-carat-1-e" - }, - menus: "ul", - position: { - my: "left top", - at: "right top" - }, - role: "menu", - - // callbacks - blur: null, - focus: null, - select: null - }, - - _create: function() { - this.activeMenu = this.element; - // flag used to prevent firing of the click handler - // as the event bubbles up through nested menus - this.mouseHandled = false; - this.element - .uniqueId() - .addClass( "ui-menu ui-widget ui-widget-content ui-corner-all" ) - .toggleClass( "ui-menu-icons", !!this.element.find( ".ui-icon" ).length ) - .attr({ - role: this.options.role, - tabIndex: 0 - }) - // need to catch all clicks on disabled menu - // not possible through _on - .bind( "click" + this.eventNamespace, $.proxy(function( event ) { - if ( this.options.disabled ) { - event.preventDefault(); - } - }, this )); - - if ( this.options.disabled ) { - this.element - .addClass( "ui-state-disabled" ) - .attr( "aria-disabled", "true" ); - } - - this._on({ - // Prevent focus from sticking to links inside menu after clicking - // them (focus should always stay on UL during navigation). - "mousedown .ui-menu-item > a": function( event ) { - event.preventDefault(); - }, - "click .ui-state-disabled > a": function( event ) { - event.preventDefault(); - }, - "click .ui-menu-item:has(a)": function( event ) { - var target = $( event.target ).closest( ".ui-menu-item" ); - if ( !this.mouseHandled && target.not( ".ui-state-disabled" ).length ) { - this.mouseHandled = true; - - this.select( event ); - // Open submenu on click - if ( target.has( ".ui-menu" ).length ) { - this.expand( event ); - } else if ( !this.element.is( ":focus" ) ) { - // Redirect focus to the menu - this.element.trigger( "focus", [ true ] ); - - // If the active item is on the top level, let it stay active. - // Otherwise, blur the active item since it is no longer visible. - if ( this.active && this.active.parents( ".ui-menu" ).length === 1 ) { - clearTimeout( this.timer ); - } - } - } - }, - "mouseenter .ui-menu-item": function( event ) { - var target = $( event.currentTarget ); - // Remove ui-state-active class from siblings of the newly focused menu item - // to avoid a jump caused by adjacent elements both having a class with a border - target.siblings().children( ".ui-state-active" ).removeClass( "ui-state-active" ); - this.focus( event, target ); - }, - mouseleave: "collapseAll", - "mouseleave .ui-menu": "collapseAll", - focus: function( event, keepActiveItem ) { - // If there's already an active item, keep it active - // If not, activate the first item - var item = this.active || this.element.children( ".ui-menu-item" ).eq( 0 ); - - if ( !keepActiveItem ) { - this.focus( event, item ); - } - }, - blur: function( event ) { - this._delay(function() { - if ( !$.contains( this.element[0], this.document[0].activeElement ) ) { - this.collapseAll( event ); - } - }); - }, - keydown: "_keydown" - }); - - this.refresh(); - - // Clicks outside of a menu collapse any open menus - this._on( this.document, { - click: function( event ) { - if ( !$( event.target ).closest( ".ui-menu" ).length ) { - this.collapseAll( event ); - } - - // Reset the mouseHandled flag - this.mouseHandled = false; - } - }); - }, - - _destroy: function() { - // Destroy (sub)menus - this.element - .removeAttr( "aria-activedescendant" ) - .find( ".ui-menu" ).addBack() - .removeClass( "ui-menu ui-widget ui-widget-content ui-corner-all ui-menu-icons" ) - .removeAttr( "role" ) - .removeAttr( "tabIndex" ) - .removeAttr( "aria-labelledby" ) - .removeAttr( "aria-expanded" ) - .removeAttr( "aria-hidden" ) - .removeAttr( "aria-disabled" ) - .removeUniqueId() - .show(); - - // Destroy menu items - this.element.find( ".ui-menu-item" ) - .removeClass( "ui-menu-item" ) - .removeAttr( "role" ) - .removeAttr( "aria-disabled" ) - .children( "a" ) - .removeUniqueId() - .removeClass( "ui-corner-all ui-state-hover" ) - .removeAttr( "tabIndex" ) - .removeAttr( "role" ) - .removeAttr( "aria-haspopup" ) - .children().each( function() { - var elem = $( this ); - if ( elem.data( "ui-menu-submenu-carat" ) ) { - elem.remove(); - } - }); - - // Destroy menu dividers - this.element.find( ".ui-menu-divider" ).removeClass( "ui-menu-divider ui-widget-content" ); - }, - - _keydown: function( event ) { - /*jshint maxcomplexity:20*/ - var match, prev, character, skip, regex, - preventDefault = true; - - function escape( value ) { - return value.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" ); - } - - switch ( event.keyCode ) { - case $.ui.keyCode.PAGE_UP: - this.previousPage( event ); - break; - case $.ui.keyCode.PAGE_DOWN: - this.nextPage( event ); - break; - case $.ui.keyCode.HOME: - this._move( "first", "first", event ); - break; - case $.ui.keyCode.END: - this._move( "last", "last", event ); - break; - case $.ui.keyCode.UP: - this.previous( event ); - break; - case $.ui.keyCode.DOWN: - this.next( event ); - break; - case $.ui.keyCode.LEFT: - this.collapse( event ); - break; - case $.ui.keyCode.RIGHT: - if ( this.active && !this.active.is( ".ui-state-disabled" ) ) { - this.expand( event ); - } - break; - case $.ui.keyCode.ENTER: - case $.ui.keyCode.SPACE: - this._activate( event ); - break; - case $.ui.keyCode.ESCAPE: - this.collapse( event ); - break; - default: - preventDefault = false; - prev = this.previousFilter || ""; - character = String.fromCharCode( event.keyCode ); - skip = false; - - clearTimeout( this.filterTimer ); - - if ( character === prev ) { - skip = true; - } else { - character = prev + character; - } - - regex = new RegExp( "^" + escape( character ), "i" ); - match = this.activeMenu.children( ".ui-menu-item" ).filter(function() { - return regex.test( $( this ).children( "a" ).text() ); - }); - match = skip && match.index( this.active.next() ) !== -1 ? - this.active.nextAll( ".ui-menu-item" ) : - match; - - // If no matches on the current filter, reset to the last character pressed - // to move down the menu to the first item that starts with that character - if ( !match.length ) { - character = String.fromCharCode( event.keyCode ); - regex = new RegExp( "^" + escape( character ), "i" ); - match = this.activeMenu.children( ".ui-menu-item" ).filter(function() { - return regex.test( $( this ).children( "a" ).text() ); - }); - } - - if ( match.length ) { - this.focus( event, match ); - if ( match.length > 1 ) { - this.previousFilter = character; - this.filterTimer = this._delay(function() { - delete this.previousFilter; - }, 1000 ); - } else { - delete this.previousFilter; - } - } else { - delete this.previousFilter; - } - } - - if ( preventDefault ) { - event.preventDefault(); - } - }, - - _activate: function( event ) { - if ( !this.active.is( ".ui-state-disabled" ) ) { - if ( this.active.children( "a[aria-haspopup='true']" ).length ) { - this.expand( event ); - } else { - this.select( event ); - } - } - }, - - refresh: function() { - var menus, - icon = this.options.icons.submenu, - submenus = this.element.find( this.options.menus ); - - // Initialize nested menus - submenus.filter( ":not(.ui-menu)" ) - .addClass( "ui-menu ui-widget ui-widget-content ui-corner-all" ) - .hide() - .attr({ - role: this.options.role, - "aria-hidden": "true", - "aria-expanded": "false" - }) - .each(function() { - var menu = $( this ), - item = menu.prev( "a" ), - submenuCarat = $( "<span>" ) - .addClass( "ui-menu-icon ui-icon " + icon ) - .data( "ui-menu-submenu-carat", true ); - - item - .attr( "aria-haspopup", "true" ) - .prepend( submenuCarat ); - menu.attr( "aria-labelledby", item.attr( "id" ) ); - }); - - menus = submenus.add( this.element ); - - // Don't refresh list items that are already adapted - menus.children( ":not(.ui-menu-item):has(a)" ) - .addClass( "ui-menu-item" ) - .attr( "role", "presentation" ) - .children( "a" ) - .uniqueId() - .addClass( "ui-corner-all" ) - .attr({ - tabIndex: -1, - role: this._itemRole() - }); - - // Initialize unlinked menu-items containing spaces and/or dashes only as dividers - menus.children( ":not(.ui-menu-item)" ).each(function() { - var item = $( this ); - // hyphen, em dash, en dash - if ( !/[^\-\u2014\u2013\s]/.test( item.text() ) ) { - item.addClass( "ui-widget-content ui-menu-divider" ); - } - }); - - // Add aria-disabled attribute to any disabled menu item - menus.children( ".ui-state-disabled" ).attr( "aria-disabled", "true" ); - - // If the active item has been removed, blur the menu - if ( this.active && !$.contains( this.element[ 0 ], this.active[ 0 ] ) ) { - this.blur(); - } - }, - - _itemRole: function() { - return { - menu: "menuitem", - listbox: "option" - }[ this.options.role ]; - }, - - _setOption: function( key, value ) { - if ( key === "icons" ) { - this.element.find( ".ui-menu-icon" ) - .removeClass( this.options.icons.submenu ) - .addClass( value.submenu ); - } - this._super( key, value ); - }, - - focus: function( event, item ) { - var nested, focused; - this.blur( event, event && event.type === "focus" ); - - this._scrollIntoView( item ); - - this.active = item.first(); - focused = this.active.children( "a" ).addClass( "ui-state-focus" ); - // Only update aria-activedescendant if there's a role - // otherwise we assume focus is managed elsewhere - if ( this.options.role ) { - this.element.attr( "aria-activedescendant", focused.attr( "id" ) ); - } - - // Highlight active parent menu item, if any - this.active - .parent() - .closest( ".ui-menu-item" ) - .children( "a:first" ) - .addClass( "ui-state-active" ); - - if ( event && event.type === "keydown" ) { - this._close(); - } else { - this.timer = this._delay(function() { - this._close(); - }, this.delay ); - } - - nested = item.children( ".ui-menu" ); - if ( nested.length && ( /^mouse/.test( event.type ) ) ) { - this._startOpening(nested); - } - this.activeMenu = item.parent(); - - this._trigger( "focus", event, { item: item } ); - }, - - _scrollIntoView: function( item ) { - var borderTop, paddingTop, offset, scroll, elementHeight, itemHeight; - if ( this._hasScroll() ) { - borderTop = parseFloat( $.css( this.activeMenu[0], "borderTopWidth" ) ) || 0; - paddingTop = parseFloat( $.css( this.activeMenu[0], "paddingTop" ) ) || 0; - offset = item.offset().top - this.activeMenu.offset().top - borderTop - paddingTop; - scroll = this.activeMenu.scrollTop(); - elementHeight = this.activeMenu.height(); - itemHeight = item.height(); - - if ( offset < 0 ) { - this.activeMenu.scrollTop( scroll + offset ); - } else if ( offset + itemHeight > elementHeight ) { - this.activeMenu.scrollTop( scroll + offset - elementHeight + itemHeight ); - } - } - }, - - blur: function( event, fromFocus ) { - if ( !fromFocus ) { - clearTimeout( this.timer ); - } - - if ( !this.active ) { - return; - } - - this.active.children( "a" ).removeClass( "ui-state-focus" ); - this.active = null; - - this._trigger( "blur", event, { item: this.active } ); - }, - - _startOpening: function( submenu ) { - clearTimeout( this.timer ); - - // Don't open if already open fixes a Firefox bug that caused a .5 pixel - // shift in the submenu position when mousing over the carat icon - if ( submenu.attr( "aria-hidden" ) !== "true" ) { - return; - } - - this.timer = this._delay(function() { - this._close(); - this._open( submenu ); - }, this.delay ); - }, - - _open: function( submenu ) { - var position = $.extend({ - of: this.active - }, this.options.position ); - - clearTimeout( this.timer ); - this.element.find( ".ui-menu" ).not( submenu.parents( ".ui-menu" ) ) - .hide() - .attr( "aria-hidden", "true" ); - - submenu - .show() - .removeAttr( "aria-hidden" ) - .attr( "aria-expanded", "true" ) - .position( position ); - }, - - collapseAll: function( event, all ) { - clearTimeout( this.timer ); - this.timer = this._delay(function() { - // If we were passed an event, look for the submenu that contains the event - var currentMenu = all ? this.element : - $( event && event.target ).closest( this.element.find( ".ui-menu" ) ); - - // If we found no valid submenu ancestor, use the main menu to close all sub menus anyway - if ( !currentMenu.length ) { - currentMenu = this.element; - } - - this._close( currentMenu ); - - this.blur( event ); - this.activeMenu = currentMenu; - }, this.delay ); - }, - - // With no arguments, closes the currently active menu - if nothing is active - // it closes all menus. If passed an argument, it will search for menus BELOW - _close: function( startMenu ) { - if ( !startMenu ) { - startMenu = this.active ? this.active.parent() : this.element; - } - - startMenu - .find( ".ui-menu" ) - .hide() - .attr( "aria-hidden", "true" ) - .attr( "aria-expanded", "false" ) - .end() - .find( "a.ui-state-active" ) - .removeClass( "ui-state-active" ); - }, - - collapse: function( event ) { - var newItem = this.active && - this.active.parent().closest( ".ui-menu-item", this.element ); - if ( newItem && newItem.length ) { - this._close(); - this.focus( event, newItem ); - } - }, - - expand: function( event ) { - var newItem = this.active && - this.active - .children( ".ui-menu " ) - .children( ".ui-menu-item" ) - .first(); - - if ( newItem && newItem.length ) { - this._open( newItem.parent() ); - - // Delay so Firefox will not hide activedescendant change in expanding submenu from AT - this._delay(function() { - this.focus( event, newItem ); - }); - } - }, - - next: function( event ) { - this._move( "next", "first", event ); - }, - - previous: function( event ) { - this._move( "prev", "last", event ); - }, - - isFirstItem: function() { - return this.active && !this.active.prevAll( ".ui-menu-item" ).length; - }, - - isLastItem: function() { - return this.active && !this.active.nextAll( ".ui-menu-item" ).length; - }, - - _move: function( direction, filter, event ) { - var next; - if ( this.active ) { - if ( direction === "first" || direction === "last" ) { - next = this.active - [ direction === "first" ? "prevAll" : "nextAll" ]( ".ui-menu-item" ) - .eq( -1 ); - } else { - next = this.active - [ direction + "All" ]( ".ui-menu-item" ) - .eq( 0 ); - } - } - if ( !next || !next.length || !this.active ) { - next = this.activeMenu.children( ".ui-menu-item" )[ filter ](); - } - - this.focus( event, next ); - }, - - nextPage: function( event ) { - var item, base, height; - - if ( !this.active ) { - this.next( event ); - return; - } - if ( this.isLastItem() ) { - return; - } - if ( this._hasScroll() ) { - base = this.active.offset().top; - height = this.element.height(); - this.active.nextAll( ".ui-menu-item" ).each(function() { - item = $( this ); - return item.offset().top - base - height < 0; - }); - - this.focus( event, item ); - } else { - this.focus( event, this.activeMenu.children( ".ui-menu-item" ) - [ !this.active ? "first" : "last" ]() ); - } - }, - - previousPage: function( event ) { - var item, base, height; - if ( !this.active ) { - this.next( event ); - return; - } - if ( this.isFirstItem() ) { - return; - } - if ( this._hasScroll() ) { - base = this.active.offset().top; - height = this.element.height(); - this.active.prevAll( ".ui-menu-item" ).each(function() { - item = $( this ); - return item.offset().top - base + height > 0; - }); - - this.focus( event, item ); - } else { - this.focus( event, this.activeMenu.children( ".ui-menu-item" ).first() ); - } - }, - - _hasScroll: function() { - return this.element.outerHeight() < this.element.prop( "scrollHeight" ); - }, - - select: function( event ) { - // TODO: It should never be possible to not have an active item at this - // point, but the tests don't trigger mouseenter before click. - this.active = this.active || $( event.target ).closest( ".ui-menu-item" ); - var ui = { item: this.active }; - if ( !this.active.has( ".ui-menu" ).length ) { - this.collapseAll( event, true ); - } - this._trigger( "select", event, ui ); - } -}); - -}( jQuery )); - -(function( $, undefined ) { - -$.ui = $.ui || {}; - -var cachedScrollbarWidth, - max = Math.max, - abs = Math.abs, - round = Math.round, - rhorizontal = /left|center|right/, - rvertical = /top|center|bottom/, - roffset = /[\+\-]\d+(\.[\d]+)?%?/, - rposition = /^\w+/, - rpercent = /%$/, - _position = $.fn.position; - -function getOffsets( offsets, width, height ) { - return [ - parseFloat( offsets[ 0 ] ) * ( rpercent.test( offsets[ 0 ] ) ? width / 100 : 1 ), - parseFloat( offsets[ 1 ] ) * ( rpercent.test( offsets[ 1 ] ) ? height / 100 : 1 ) - ]; -} - -function parseCss( element, property ) { - return parseInt( $.css( element, property ), 10 ) || 0; -} - -function getDimensions( elem ) { - var raw = elem[0]; - if ( raw.nodeType === 9 ) { - return { - width: elem.width(), - height: elem.height(), - offset: { top: 0, left: 0 } - }; - } - if ( $.isWindow( raw ) ) { - return { - width: elem.width(), - height: elem.height(), - offset: { top: elem.scrollTop(), left: elem.scrollLeft() } - }; - } - if ( raw.preventDefault ) { - return { - width: 0, - height: 0, - offset: { top: raw.pageY, left: raw.pageX } - }; - } - return { - width: elem.outerWidth(), - height: elem.outerHeight(), - offset: elem.offset() - }; -} - -$.position = { - scrollbarWidth: function() { - if ( cachedScrollbarWidth !== undefined ) { - return cachedScrollbarWidth; - } - var w1, w2, - div = $( "<div style='display:block;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>" ), - innerDiv = div.children()[0]; - - $( "body" ).append( div ); - w1 = innerDiv.offsetWidth; - div.css( "overflow", "scroll" ); - - w2 = innerDiv.offsetWidth; - - if ( w1 === w2 ) { - w2 = div[0].clientWidth; - } - - div.remove(); - - return (cachedScrollbarWidth = w1 - w2); - }, - getScrollInfo: function( within ) { - var overflowX = within.isWindow ? "" : within.element.css( "overflow-x" ), - overflowY = within.isWindow ? "" : within.element.css( "overflow-y" ), - hasOverflowX = overflowX === "scroll" || - ( overflowX === "auto" && within.width < within.element[0].scrollWidth ), - hasOverflowY = overflowY === "scroll" || - ( overflowY === "auto" && within.height < within.element[0].scrollHeight ); - return { - width: hasOverflowY ? $.position.scrollbarWidth() : 0, - height: hasOverflowX ? $.position.scrollbarWidth() : 0 - }; - }, - getWithinInfo: function( element ) { - var withinElement = $( element || window ), - isWindow = $.isWindow( withinElement[0] ); - return { - element: withinElement, - isWindow: isWindow, - offset: withinElement.offset() || { left: 0, top: 0 }, - scrollLeft: withinElement.scrollLeft(), - scrollTop: withinElement.scrollTop(), - width: isWindow ? withinElement.width() : withinElement.outerWidth(), - height: isWindow ? withinElement.height() : withinElement.outerHeight() - }; - } -}; - -$.fn.position = function( options ) { - if ( !options || !options.of ) { - return _position.apply( this, arguments ); - } - - // make a copy, we don't want to modify arguments - options = $.extend( {}, options ); - - var atOffset, targetWidth, targetHeight, targetOffset, basePosition, dimensions, - target = $( options.of ), - within = $.position.getWithinInfo( options.within ), - scrollInfo = $.position.getScrollInfo( within ), - collision = ( options.collision || "flip" ).split( " " ), - offsets = {}; - - dimensions = getDimensions( target ); - if ( target[0].preventDefault ) { - // force left top to allow flipping - options.at = "left top"; - } - targetWidth = dimensions.width; - targetHeight = dimensions.height; - targetOffset = dimensions.offset; - // clone to reuse original targetOffset later - basePosition = $.extend( {}, targetOffset ); - - // force my and at to have valid horizontal and vertical positions - // if a value is missing or invalid, it will be converted to center - $.each( [ "my", "at" ], function() { - var pos = ( options[ this ] || "" ).split( " " ), - horizontalOffset, - verticalOffset; - - if ( pos.length === 1) { - pos = rhorizontal.test( pos[ 0 ] ) ? - pos.concat( [ "center" ] ) : - rvertical.test( pos[ 0 ] ) ? - [ "center" ].concat( pos ) : - [ "center", "center" ]; - } - pos[ 0 ] = rhorizontal.test( pos[ 0 ] ) ? pos[ 0 ] : "center"; - pos[ 1 ] = rvertical.test( pos[ 1 ] ) ? pos[ 1 ] : "center"; - - // calculate offsets - horizontalOffset = roffset.exec( pos[ 0 ] ); - verticalOffset = roffset.exec( pos[ 1 ] ); - offsets[ this ] = [ - horizontalOffset ? horizontalOffset[ 0 ] : 0, - verticalOffset ? verticalOffset[ 0 ] : 0 - ]; - - // reduce to just the positions without the offsets - options[ this ] = [ - rposition.exec( pos[ 0 ] )[ 0 ], - rposition.exec( pos[ 1 ] )[ 0 ] - ]; - }); - - // normalize collision option - if ( collision.length === 1 ) { - collision[ 1 ] = collision[ 0 ]; - } - - if ( options.at[ 0 ] === "right" ) { - basePosition.left += targetWidth; - } else if ( options.at[ 0 ] === "center" ) { - basePosition.left += targetWidth / 2; - } - - if ( options.at[ 1 ] === "bottom" ) { - basePosition.top += targetHeight; - } else if ( options.at[ 1 ] === "center" ) { - basePosition.top += targetHeight / 2; - } - - atOffset = getOffsets( offsets.at, targetWidth, targetHeight ); - basePosition.left += atOffset[ 0 ]; - basePosition.top += atOffset[ 1 ]; - - return this.each(function() { - var collisionPosition, using, - elem = $( this ), - elemWidth = elem.outerWidth(), - elemHeight = elem.outerHeight(), - marginLeft = parseCss( this, "marginLeft" ), - marginTop = parseCss( this, "marginTop" ), - collisionWidth = elemWidth + marginLeft + parseCss( this, "marginRight" ) + scrollInfo.width, - collisionHeight = elemHeight + marginTop + parseCss( this, "marginBottom" ) + scrollInfo.height, - position = $.extend( {}, basePosition ), - myOffset = getOffsets( offsets.my, elem.outerWidth(), elem.outerHeight() ); - - if ( options.my[ 0 ] === "right" ) { - position.left -= elemWidth; - } else if ( options.my[ 0 ] === "center" ) { - position.left -= elemWidth / 2; - } - - if ( options.my[ 1 ] === "bottom" ) { - position.top -= elemHeight; - } else if ( options.my[ 1 ] === "center" ) { - position.top -= elemHeight / 2; - } - - position.left += myOffset[ 0 ]; - position.top += myOffset[ 1 ]; - - // if the browser doesn't support fractions, then round for consistent results - if ( !$.support.offsetFractions ) { - position.left = round( position.left ); - position.top = round( position.top ); - } - - collisionPosition = { - marginLeft: marginLeft, - marginTop: marginTop - }; - - $.each( [ "left", "top" ], function( i, dir ) { - if ( $.ui.position[ collision[ i ] ] ) { - $.ui.position[ collision[ i ] ][ dir ]( position, { - targetWidth: targetWidth, - targetHeight: targetHeight, - elemWidth: elemWidth, - elemHeight: elemHeight, - collisionPosition: collisionPosition, - collisionWidth: collisionWidth, - collisionHeight: collisionHeight, - offset: [ atOffset[ 0 ] + myOffset[ 0 ], atOffset [ 1 ] + myOffset[ 1 ] ], - my: options.my, - at: options.at, - within: within, - elem : elem - }); - } - }); - - if ( options.using ) { - // adds feedback as second argument to using callback, if present - using = function( props ) { - var left = targetOffset.left - position.left, - right = left + targetWidth - elemWidth, - top = targetOffset.top - position.top, - bottom = top + targetHeight - elemHeight, - feedback = { - target: { - element: target, - left: targetOffset.left, - top: targetOffset.top, - width: targetWidth, - height: targetHeight - }, - element: { - element: elem, - left: position.left, - top: position.top, - width: elemWidth, - height: elemHeight - }, - horizontal: right < 0 ? "left" : left > 0 ? "right" : "center", - vertical: bottom < 0 ? "top" : top > 0 ? "bottom" : "middle" - }; - if ( targetWidth < elemWidth && abs( left + right ) < targetWidth ) { - feedback.horizontal = "center"; - } - if ( targetHeight < elemHeight && abs( top + bottom ) < targetHeight ) { - feedback.vertical = "middle"; - } - if ( max( abs( left ), abs( right ) ) > max( abs( top ), abs( bottom ) ) ) { - feedback.important = "horizontal"; - } else { - feedback.important = "vertical"; - } - options.using.call( this, props, feedback ); - }; - } - - elem.offset( $.extend( position, { using: using } ) ); - }); -}; - -$.ui.position = { - fit: { - left: function( position, data ) { - var within = data.within, - withinOffset = within.isWindow ? within.scrollLeft : within.offset.left, - outerWidth = within.width, - collisionPosLeft = position.left - data.collisionPosition.marginLeft, - overLeft = withinOffset - collisionPosLeft, - overRight = collisionPosLeft + data.collisionWidth - outerWidth - withinOffset, - newOverRight; - - // element is wider than within - if ( data.collisionWidth > outerWidth ) { - // element is initially over the left side of within - if ( overLeft > 0 && overRight <= 0 ) { - newOverRight = position.left + overLeft + data.collisionWidth - outerWidth - withinOffset; - position.left += overLeft - newOverRight; - // element is initially over right side of within - } else if ( overRight > 0 && overLeft <= 0 ) { - position.left = withinOffset; - // element is initially over both left and right sides of within - } else { - if ( overLeft > overRight ) { - position.left = withinOffset + outerWidth - data.collisionWidth; - } else { - position.left = withinOffset; - } - } - // too far left -> align with left edge - } else if ( overLeft > 0 ) { - position.left += overLeft; - // too far right -> align with right edge - } else if ( overRight > 0 ) { - position.left -= overRight; - // adjust based on position and margin - } else { - position.left = max( position.left - collisionPosLeft, position.left ); - } - }, - top: function( position, data ) { - var within = data.within, - withinOffset = within.isWindow ? within.scrollTop : within.offset.top, - outerHeight = data.within.height, - collisionPosTop = position.top - data.collisionPosition.marginTop, - overTop = withinOffset - collisionPosTop, - overBottom = collisionPosTop + data.collisionHeight - outerHeight - withinOffset, - newOverBottom; - - // element is taller than within - if ( data.collisionHeight > outerHeight ) { - // element is initially over the top of within - if ( overTop > 0 && overBottom <= 0 ) { - newOverBottom = position.top + overTop + data.collisionHeight - outerHeight - withinOffset; - position.top += overTop - newOverBottom; - // element is initially over bottom of within - } else if ( overBottom > 0 && overTop <= 0 ) { - position.top = withinOffset; - // element is initially over both top and bottom of within - } else { - if ( overTop > overBottom ) { - position.top = withinOffset + outerHeight - data.collisionHeight; - } else { - position.top = withinOffset; - } - } - // too far up -> align with top - } else if ( overTop > 0 ) { - position.top += overTop; - // too far down -> align with bottom edge - } else if ( overBottom > 0 ) { - position.top -= overBottom; - // adjust based on position and margin - } else { - position.top = max( position.top - collisionPosTop, position.top ); - } - } - }, - flip: { - left: function( position, data ) { - var within = data.within, - withinOffset = within.offset.left + within.scrollLeft, - outerWidth = within.width, - offsetLeft = within.isWindow ? within.scrollLeft : within.offset.left, - collisionPosLeft = position.left - data.collisionPosition.marginLeft, - overLeft = collisionPosLeft - offsetLeft, - overRight = collisionPosLeft + data.collisionWidth - outerWidth - offsetLeft, - myOffset = data.my[ 0 ] === "left" ? - -data.elemWidth : - data.my[ 0 ] === "right" ? - data.elemWidth : - 0, - atOffset = data.at[ 0 ] === "left" ? - data.targetWidth : - data.at[ 0 ] === "right" ? - -data.targetWidth : - 0, - offset = -2 * data.offset[ 0 ], - newOverRight, - newOverLeft; - - if ( overLeft < 0 ) { - newOverRight = position.left + myOffset + atOffset + offset + data.collisionWidth - outerWidth - withinOffset; - if ( newOverRight < 0 || newOverRight < abs( overLeft ) ) { - position.left += myOffset + atOffset + offset; - } - } - else if ( overRight > 0 ) { - newOverLeft = position.left - data.collisionPosition.marginLeft + myOffset + atOffset + offset - offsetLeft; - if ( newOverLeft > 0 || abs( newOverLeft ) < overRight ) { - position.left += myOffset + atOffset + offset; - } - } - }, - top: function( position, data ) { - var within = data.within, - withinOffset = within.offset.top + within.scrollTop, - outerHeight = within.height, - offsetTop = within.isWindow ? within.scrollTop : within.offset.top, - collisionPosTop = position.top - data.collisionPosition.marginTop, - overTop = collisionPosTop - offsetTop, - overBottom = collisionPosTop + data.collisionHeight - outerHeight - offsetTop, - top = data.my[ 1 ] === "top", - myOffset = top ? - -data.elemHeight : - data.my[ 1 ] === "bottom" ? - data.elemHeight : - 0, - atOffset = data.at[ 1 ] === "top" ? - data.targetHeight : - data.at[ 1 ] === "bottom" ? - -data.targetHeight : - 0, - offset = -2 * data.offset[ 1 ], - newOverTop, - newOverBottom; - if ( overTop < 0 ) { - newOverBottom = position.top + myOffset + atOffset + offset + data.collisionHeight - outerHeight - withinOffset; - if ( ( position.top + myOffset + atOffset + offset) > overTop && ( newOverBottom < 0 || newOverBottom < abs( overTop ) ) ) { - position.top += myOffset + atOffset + offset; - } - } - else if ( overBottom > 0 ) { - newOverTop = position.top - data.collisionPosition.marginTop + myOffset + atOffset + offset - offsetTop; - if ( ( position.top + myOffset + atOffset + offset) > overBottom && ( newOverTop > 0 || abs( newOverTop ) < overBottom ) ) { - position.top += myOffset + atOffset + offset; - } - } - } - }, - flipfit: { - left: function() { - $.ui.position.flip.left.apply( this, arguments ); - $.ui.position.fit.left.apply( this, arguments ); - }, - top: function() { - $.ui.position.flip.top.apply( this, arguments ); - $.ui.position.fit.top.apply( this, arguments ); - } - } -}; - -// fraction support test -(function () { - var testElement, testElementParent, testElementStyle, offsetLeft, i, - body = document.getElementsByTagName( "body" )[ 0 ], - div = document.createElement( "div" ); - - //Create a "fake body" for testing based on method used in jQuery.support - testElement = document.createElement( body ? "div" : "body" ); - testElementStyle = { - visibility: "hidden", - width: 0, - height: 0, - border: 0, - margin: 0, - background: "none" - }; - if ( body ) { - $.extend( testElementStyle, { - position: "absolute", - left: "-1000px", - top: "-1000px" - }); - } - for ( i in testElementStyle ) { - testElement.style[ i ] = testElementStyle[ i ]; - } - testElement.appendChild( div ); - testElementParent = body || document.documentElement; - testElementParent.insertBefore( testElement, testElementParent.firstChild ); - - div.style.cssText = "position: absolute; left: 10.7432222px;"; - - offsetLeft = $( div ).offset().left; - $.support.offsetFractions = offsetLeft > 10 && offsetLeft < 11; - - testElement.innerHTML = ""; - testElementParent.removeChild( testElement ); -})(); - -}( jQuery ) ); - -(function( $, undefined ) { - -$.widget( "ui.progressbar", { - version: "1.10.3", - options: { - max: 100, - value: 0, - - change: null, - complete: null - }, - - min: 0, - - _create: function() { - // Constrain initial value - this.oldValue = this.options.value = this._constrainedValue(); - - this.element - .addClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" ) - .attr({ - // Only set static values, aria-valuenow and aria-valuemax are - // set inside _refreshValue() - role: "progressbar", - "aria-valuemin": this.min - }); - - this.valueDiv = $( "<div class='ui-progressbar-value ui-widget-header ui-corner-left'></div>" ) - .appendTo( this.element ); - - this._refreshValue(); - }, - - _destroy: function() { - this.element - .removeClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" ) - .removeAttr( "role" ) - .removeAttr( "aria-valuemin" ) - .removeAttr( "aria-valuemax" ) - .removeAttr( "aria-valuenow" ); - - this.valueDiv.remove(); - }, - - value: function( newValue ) { - if ( newValue === undefined ) { - return this.options.value; - } - - this.options.value = this._constrainedValue( newValue ); - this._refreshValue(); - }, - - _constrainedValue: function( newValue ) { - if ( newValue === undefined ) { - newValue = this.options.value; - } - - this.indeterminate = newValue === false; - - // sanitize value - if ( typeof newValue !== "number" ) { - newValue = 0; - } - - return this.indeterminate ? false : - Math.min( this.options.max, Math.max( this.min, newValue ) ); - }, - - _setOptions: function( options ) { - // Ensure "value" option is set after other values (like max) - var value = options.value; - delete options.value; - - this._super( options ); - - this.options.value = this._constrainedValue( value ); - this._refreshValue(); - }, - - _setOption: function( key, value ) { - if ( key === "max" ) { - // Don't allow a max less than min - value = Math.max( this.min, value ); - } - - this._super( key, value ); - }, - - _percentage: function() { - return this.indeterminate ? 100 : 100 * ( this.options.value - this.min ) / ( this.options.max - this.min ); - }, - - _refreshValue: function() { - var value = this.options.value, - percentage = this._percentage(); - - this.valueDiv - .toggle( this.indeterminate || value > this.min ) - .toggleClass( "ui-corner-right", value === this.options.max ) - .width( percentage.toFixed(0) + "%" ); - - this.element.toggleClass( "ui-progressbar-indeterminate", this.indeterminate ); - - if ( this.indeterminate ) { - this.element.removeAttr( "aria-valuenow" ); - if ( !this.overlayDiv ) { - this.overlayDiv = $( "<div class='ui-progressbar-overlay'></div>" ).appendTo( this.valueDiv ); - } - } else { - this.element.attr({ - "aria-valuemax": this.options.max, - "aria-valuenow": value - }); - if ( this.overlayDiv ) { - this.overlayDiv.remove(); - this.overlayDiv = null; - } - } - - if ( this.oldValue !== value ) { - this.oldValue = value; - this._trigger( "change" ); - } - if ( value === this.options.max ) { - this._trigger( "complete" ); - } - } -}); - -})( jQuery ); - -(function( $, undefined ) { - -// number of pages in a slider -// (how many times can you page up/down to go through the whole range) -var numPages = 5; - -$.widget( "ui.slider", $.ui.mouse, { - version: "1.10.3", - widgetEventPrefix: "slide", - - options: { - animate: false, - distance: 0, - max: 100, - min: 0, - orientation: "horizontal", - range: false, - step: 1, - value: 0, - values: null, - - // callbacks - change: null, - slide: null, - start: null, - stop: null - }, - - _create: function() { - this._keySliding = false; - this._mouseSliding = false; - this._animateOff = true; - this._handleIndex = null; - this._detectOrientation(); - this._mouseInit(); - - this.element - .addClass( "ui-slider" + - " ui-slider-" + this.orientation + - " ui-widget" + - " ui-widget-content" + - " ui-corner-all"); - - this._refresh(); - this._setOption( "disabled", this.options.disabled ); - - this._animateOff = false; - }, - - _refresh: function() { - this._createRange(); - this._createHandles(); - this._setupEvents(); - this._refreshValue(); - }, - - _createHandles: function() { - var i, handleCount, - options = this.options, - existingHandles = this.element.find( ".ui-slider-handle" ).addClass( "ui-state-default ui-corner-all" ), - handle = "<a class='ui-slider-handle ui-state-default ui-corner-all' href='#'></a>", - handles = []; - - handleCount = ( options.values && options.values.length ) || 1; - - if ( existingHandles.length > handleCount ) { - existingHandles.slice( handleCount ).remove(); - existingHandles = existingHandles.slice( 0, handleCount ); - } - - for ( i = existingHandles.length; i < handleCount; i++ ) { - handles.push( handle ); - } - - this.handles = existingHandles.add( $( handles.join( "" ) ).appendTo( this.element ) ); - - this.handle = this.handles.eq( 0 ); - - this.handles.each(function( i ) { - $( this ).data( "ui-slider-handle-index", i ); - }); - }, - - _createRange: function() { - var options = this.options, - classes = ""; - - if ( options.range ) { - if ( options.range === true ) { - if ( !options.values ) { - options.values = [ this._valueMin(), this._valueMin() ]; - } else if ( options.values.length && options.values.length !== 2 ) { - options.values = [ options.values[0], options.values[0] ]; - } else if ( $.isArray( options.values ) ) { - options.values = options.values.slice(0); - } - } - - if ( !this.range || !this.range.length ) { - this.range = $( "<div></div>" ) - .appendTo( this.element ); - - classes = "ui-slider-range" + - // note: this isn't the most fittingly semantic framework class for this element, - // but worked best visually with a variety of themes - " ui-widget-header ui-corner-all"; - } else { - this.range.removeClass( "ui-slider-range-min ui-slider-range-max" ) - // Handle range switching from true to min/max - .css({ - "left": "", - "bottom": "" - }); - } - - this.range.addClass( classes + - ( ( options.range === "min" || options.range === "max" ) ? " ui-slider-range-" + options.range : "" ) ); - } else { - this.range = $([]); - } - }, - - _setupEvents: function() { - var elements = this.handles.add( this.range ).filter( "a" ); - this._off( elements ); - this._on( elements, this._handleEvents ); - this._hoverable( elements ); - this._focusable( elements ); - }, - - _destroy: function() { - this.handles.remove(); - this.range.remove(); - - this.element - .removeClass( "ui-slider" + - " ui-slider-horizontal" + - " ui-slider-vertical" + - " ui-widget" + - " ui-widget-content" + - " ui-corner-all" ); - - this._mouseDestroy(); - }, - - _mouseCapture: function( event ) { - var position, normValue, distance, closestHandle, index, allowed, offset, mouseOverHandle, - that = this, - o = this.options; - - if ( o.disabled ) { - return false; - } - - this.elementSize = { - width: this.element.outerWidth(), - height: this.element.outerHeight() - }; - this.elementOffset = this.element.offset(); - - position = { x: event.pageX, y: event.pageY }; - normValue = this._normValueFromMouse( position ); - distance = this._valueMax() - this._valueMin() + 1; - this.handles.each(function( i ) { - var thisDistance = Math.abs( normValue - that.values(i) ); - if (( distance > thisDistance ) || - ( distance === thisDistance && - (i === that._lastChangedValue || that.values(i) === o.min ))) { - distance = thisDistance; - closestHandle = $( this ); - index = i; - } - }); - - allowed = this._start( event, index ); - if ( allowed === false ) { - return false; - } - this._mouseSliding = true; - - this._handleIndex = index; - - closestHandle - .addClass( "ui-state-active" ) - .focus(); - - offset = closestHandle.offset(); - mouseOverHandle = !$( event.target ).parents().addBack().is( ".ui-slider-handle" ); - this._clickOffset = mouseOverHandle ? { left: 0, top: 0 } : { - left: event.pageX - offset.left - ( closestHandle.width() / 2 ), - top: event.pageY - offset.top - - ( closestHandle.height() / 2 ) - - ( parseInt( closestHandle.css("borderTopWidth"), 10 ) || 0 ) - - ( parseInt( closestHandle.css("borderBottomWidth"), 10 ) || 0) + - ( parseInt( closestHandle.css("marginTop"), 10 ) || 0) - }; - - if ( !this.handles.hasClass( "ui-state-hover" ) ) { - this._slide( event, index, normValue ); - } - this._animateOff = true; - return true; - }, - - _mouseStart: function() { - return true; - }, - - _mouseDrag: function( event ) { - var position = { x: event.pageX, y: event.pageY }, - normValue = this._normValueFromMouse( position ); - - this._slide( event, this._handleIndex, normValue ); - - return false; - }, - - _mouseStop: function( event ) { - this.handles.removeClass( "ui-state-active" ); - this._mouseSliding = false; - - this._stop( event, this._handleIndex ); - this._change( event, this._handleIndex ); - - this._handleIndex = null; - this._clickOffset = null; - this._animateOff = false; - - return false; - }, - - _detectOrientation: function() { - this.orientation = ( this.options.orientation === "vertical" ) ? "vertical" : "horizontal"; - }, - - _normValueFromMouse: function( position ) { - var pixelTotal, - pixelMouse, - percentMouse, - valueTotal, - valueMouse; - - if ( this.orientation === "horizontal" ) { - pixelTotal = this.elementSize.width; - pixelMouse = position.x - this.elementOffset.left - ( this._clickOffset ? this._clickOffset.left : 0 ); - } else { - pixelTotal = this.elementSize.height; - pixelMouse = position.y - this.elementOffset.top - ( this._clickOffset ? this._clickOffset.top : 0 ); - } - - percentMouse = ( pixelMouse / pixelTotal ); - if ( percentMouse > 1 ) { - percentMouse = 1; - } - if ( percentMouse < 0 ) { - percentMouse = 0; - } - if ( this.orientation === "vertical" ) { - percentMouse = 1 - percentMouse; - } - - valueTotal = this._valueMax() - this._valueMin(); - valueMouse = this._valueMin() + percentMouse * valueTotal; - - return this._trimAlignValue( valueMouse ); - }, - - _start: function( event, index ) { - var uiHash = { - handle: this.handles[ index ], - value: this.value() - }; - if ( this.options.values && this.options.values.length ) { - uiHash.value = this.values( index ); - uiHash.values = this.values(); - } - return this._trigger( "start", event, uiHash ); - }, - - _slide: function( event, index, newVal ) { - var otherVal, - newValues, - allowed; - - if ( this.options.values && this.options.values.length ) { - otherVal = this.values( index ? 0 : 1 ); - - if ( ( this.options.values.length === 2 && this.options.range === true ) && - ( ( index === 0 && newVal > otherVal) || ( index === 1 && newVal < otherVal ) ) - ) { - newVal = otherVal; - } - - if ( newVal !== this.values( index ) ) { - newValues = this.values(); - newValues[ index ] = newVal; - // A slide can be canceled by returning false from the slide callback - allowed = this._trigger( "slide", event, { - handle: this.handles[ index ], - value: newVal, - values: newValues - } ); - otherVal = this.values( index ? 0 : 1 ); - if ( allowed !== false ) { - this.values( index, newVal, true ); - } - } - } else { - if ( newVal !== this.value() ) { - // A slide can be canceled by returning false from the slide callback - allowed = this._trigger( "slide", event, { - handle: this.handles[ index ], - value: newVal - } ); - if ( allowed !== false ) { - this.value( newVal ); - } - } - } - }, - - _stop: function( event, index ) { - var uiHash = { - handle: this.handles[ index ], - value: this.value() - }; - if ( this.options.values && this.options.values.length ) { - uiHash.value = this.values( index ); - uiHash.values = this.values(); - } - - this._trigger( "stop", event, uiHash ); - }, - - _change: function( event, index ) { - if ( !this._keySliding && !this._mouseSliding ) { - var uiHash = { - handle: this.handles[ index ], - value: this.value() - }; - if ( this.options.values && this.options.values.length ) { - uiHash.value = this.values( index ); - uiHash.values = this.values(); - } - - //store the last changed value index for reference when handles overlap - this._lastChangedValue = index; - - this._trigger( "change", event, uiHash ); - } - }, - - value: function( newValue ) { - if ( arguments.length ) { - this.options.value = this._trimAlignValue( newValue ); - this._refreshValue(); - this._change( null, 0 ); - return; - } - - return this._value(); - }, - - values: function( index, newValue ) { - var vals, - newValues, - i; - - if ( arguments.length > 1 ) { - this.options.values[ index ] = this._trimAlignValue( newValue ); - this._refreshValue(); - this._change( null, index ); - return; - } - - if ( arguments.length ) { - if ( $.isArray( arguments[ 0 ] ) ) { - vals = this.options.values; - newValues = arguments[ 0 ]; - for ( i = 0; i < vals.length; i += 1 ) { - vals[ i ] = this._trimAlignValue( newValues[ i ] ); - this._change( null, i ); - } - this._refreshValue(); - } else { - if ( this.options.values && this.options.values.length ) { - return this._values( index ); - } else { - return this.value(); - } - } - } else { - return this._values(); - } - }, - - _setOption: function( key, value ) { - var i, - valsLength = 0; - - if ( key === "range" && this.options.range === true ) { - if ( value === "min" ) { - this.options.value = this._values( 0 ); - this.options.values = null; - } else if ( value === "max" ) { - this.options.value = this._values( this.options.values.length-1 ); - this.options.values = null; - } - } - - if ( $.isArray( this.options.values ) ) { - valsLength = this.options.values.length; - } - - $.Widget.prototype._setOption.apply( this, arguments ); - - switch ( key ) { - case "orientation": - this._detectOrientation(); - this.element - .removeClass( "ui-slider-horizontal ui-slider-vertical" ) - .addClass( "ui-slider-" + this.orientation ); - this._refreshValue(); - break; - case "value": - this._animateOff = true; - this._refreshValue(); - this._change( null, 0 ); - this._animateOff = false; - break; - case "values": - this._animateOff = true; - this._refreshValue(); - for ( i = 0; i < valsLength; i += 1 ) { - this._change( null, i ); - } - this._animateOff = false; - break; - case "min": - case "max": - this._animateOff = true; - this._refreshValue(); - this._animateOff = false; - break; - case "range": - this._animateOff = true; - this._refresh(); - this._animateOff = false; - break; - } - }, - - //internal value getter - // _value() returns value trimmed by min and max, aligned by step - _value: function() { - var val = this.options.value; - val = this._trimAlignValue( val ); - - return val; - }, - - //internal values getter - // _values() returns array of values trimmed by min and max, aligned by step - // _values( index ) returns single value trimmed by min and max, aligned by step - _values: function( index ) { - var val, - vals, - i; - - if ( arguments.length ) { - val = this.options.values[ index ]; - val = this._trimAlignValue( val ); - - return val; - } else if ( this.options.values && this.options.values.length ) { - // .slice() creates a copy of the array - // this copy gets trimmed by min and max and then returned - vals = this.options.values.slice(); - for ( i = 0; i < vals.length; i+= 1) { - vals[ i ] = this._trimAlignValue( vals[ i ] ); - } - - return vals; - } else { - return []; - } - }, - - // returns the step-aligned value that val is closest to, between (inclusive) min and max - _trimAlignValue: function( val ) { - if ( val <= this._valueMin() ) { - return this._valueMin(); - } - if ( val >= this._valueMax() ) { - return this._valueMax(); - } - var step = ( this.options.step > 0 ) ? this.options.step : 1, - valModStep = (val - this._valueMin()) % step, - alignValue = val - valModStep; - - if ( Math.abs(valModStep) * 2 >= step ) { - alignValue += ( valModStep > 0 ) ? step : ( -step ); - } - - // Since JavaScript has problems with large floats, round - // the final value to 5 digits after the decimal point (see #4124) - return parseFloat( alignValue.toFixed(5) ); - }, - - _valueMin: function() { - return this.options.min; - }, - - _valueMax: function() { - return this.options.max; - }, - - _refreshValue: function() { - var lastValPercent, valPercent, value, valueMin, valueMax, - oRange = this.options.range, - o = this.options, - that = this, - animate = ( !this._animateOff ) ? o.animate : false, - _set = {}; - - if ( this.options.values && this.options.values.length ) { - this.handles.each(function( i ) { - valPercent = ( that.values(i) - that._valueMin() ) / ( that._valueMax() - that._valueMin() ) * 100; - _set[ that.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%"; - $( this ).stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate ); - if ( that.options.range === true ) { - if ( that.orientation === "horizontal" ) { - if ( i === 0 ) { - that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { left: valPercent + "%" }, o.animate ); - } - if ( i === 1 ) { - that.range[ animate ? "animate" : "css" ]( { width: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } ); - } - } else { - if ( i === 0 ) { - that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { bottom: ( valPercent ) + "%" }, o.animate ); - } - if ( i === 1 ) { - that.range[ animate ? "animate" : "css" ]( { height: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } ); - } - } - } - lastValPercent = valPercent; - }); - } else { - value = this.value(); - valueMin = this._valueMin(); - valueMax = this._valueMax(); - valPercent = ( valueMax !== valueMin ) ? - ( value - valueMin ) / ( valueMax - valueMin ) * 100 : - 0; - _set[ this.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%"; - this.handle.stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate ); - - if ( oRange === "min" && this.orientation === "horizontal" ) { - this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { width: valPercent + "%" }, o.animate ); - } - if ( oRange === "max" && this.orientation === "horizontal" ) { - this.range[ animate ? "animate" : "css" ]( { width: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } ); - } - if ( oRange === "min" && this.orientation === "vertical" ) { - this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { height: valPercent + "%" }, o.animate ); - } - if ( oRange === "max" && this.orientation === "vertical" ) { - this.range[ animate ? "animate" : "css" ]( { height: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } ); - } - } - }, - - _handleEvents: { - keydown: function( event ) { - /*jshint maxcomplexity:25*/ - var allowed, curVal, newVal, step, - index = $( event.target ).data( "ui-slider-handle-index" ); - - switch ( event.keyCode ) { - case $.ui.keyCode.HOME: - case $.ui.keyCode.END: - case $.ui.keyCode.PAGE_UP: - case $.ui.keyCode.PAGE_DOWN: - case $.ui.keyCode.UP: - case $.ui.keyCode.RIGHT: - case $.ui.keyCode.DOWN: - case $.ui.keyCode.LEFT: - event.preventDefault(); - if ( !this._keySliding ) { - this._keySliding = true; - $( event.target ).addClass( "ui-state-active" ); - allowed = this._start( event, index ); - if ( allowed === false ) { - return; - } - } - break; - } - - step = this.options.step; - if ( this.options.values && this.options.values.length ) { - curVal = newVal = this.values( index ); - } else { - curVal = newVal = this.value(); - } - - switch ( event.keyCode ) { - case $.ui.keyCode.HOME: - newVal = this._valueMin(); - break; - case $.ui.keyCode.END: - newVal = this._valueMax(); - break; - case $.ui.keyCode.PAGE_UP: - newVal = this._trimAlignValue( curVal + ( (this._valueMax() - this._valueMin()) / numPages ) ); - break; - case $.ui.keyCode.PAGE_DOWN: - newVal = this._trimAlignValue( curVal - ( (this._valueMax() - this._valueMin()) / numPages ) ); - break; - case $.ui.keyCode.UP: - case $.ui.keyCode.RIGHT: - if ( curVal === this._valueMax() ) { - return; - } - newVal = this._trimAlignValue( curVal + step ); - break; - case $.ui.keyCode.DOWN: - case $.ui.keyCode.LEFT: - if ( curVal === this._valueMin() ) { - return; - } - newVal = this._trimAlignValue( curVal - step ); - break; - } - - this._slide( event, index, newVal ); - }, - click: function( event ) { - event.preventDefault(); - }, - keyup: function( event ) { - var index = $( event.target ).data( "ui-slider-handle-index" ); - - if ( this._keySliding ) { - this._keySliding = false; - this._stop( event, index ); - this._change( event, index ); - $( event.target ).removeClass( "ui-state-active" ); - } - } - } - -}); - -}(jQuery)); - -(function( $ ) { - -function modifier( fn ) { - return function() { - var previous = this.element.val(); - fn.apply( this, arguments ); - this._refresh(); - if ( previous !== this.element.val() ) { - this._trigger( "change" ); - } - }; -} - -$.widget( "ui.spinner", { - version: "1.10.3", - defaultElement: "<input>", - widgetEventPrefix: "spin", - options: { - culture: null, - icons: { - down: "ui-icon-triangle-1-s", - up: "ui-icon-triangle-1-n" - }, - incremental: true, - max: null, - min: null, - numberFormat: null, - page: 10, - step: 1, - - change: null, - spin: null, - start: null, - stop: null - }, - - _create: function() { - // handle string values that need to be parsed - this._setOption( "max", this.options.max ); - this._setOption( "min", this.options.min ); - this._setOption( "step", this.options.step ); - - // format the value, but don't constrain - this._value( this.element.val(), true ); - - this._draw(); - this._on( this._events ); - this._refresh(); - - // turning off autocomplete prevents the browser from remembering the - // value when navigating through history, so we re-enable autocomplete - // if the page is unloaded before the widget is destroyed. #7790 - this._on( this.window, { - beforeunload: function() { - this.element.removeAttr( "autocomplete" ); - } - }); - }, - - _getCreateOptions: function() { - var options = {}, - element = this.element; - - $.each( [ "min", "max", "step" ], function( i, option ) { - var value = element.attr( option ); - if ( value !== undefined && value.length ) { - options[ option ] = value; - } - }); - - return options; - }, - - _events: { - keydown: function( event ) { - if ( this._start( event ) && this._keydown( event ) ) { - event.preventDefault(); - } - }, - keyup: "_stop", - focus: function() { - this.previous = this.element.val(); - }, - blur: function( event ) { - if ( this.cancelBlur ) { - delete this.cancelBlur; - return; - } - - this._stop(); - this._refresh(); - if ( this.previous !== this.element.val() ) { - this._trigger( "change", event ); - } - }, - mousewheel: function( event, delta ) { - if ( !delta ) { - return; - } - if ( !this.spinning && !this._start( event ) ) { - return false; - } - - this._spin( (delta > 0 ? 1 : -1) * this.options.step, event ); - clearTimeout( this.mousewheelTimer ); - this.mousewheelTimer = this._delay(function() { - if ( this.spinning ) { - this._stop( event ); - } - }, 100 ); - event.preventDefault(); - }, - "mousedown .ui-spinner-button": function( event ) { - var previous; - - // We never want the buttons to have focus; whenever the user is - // interacting with the spinner, the focus should be on the input. - // If the input is focused then this.previous is properly set from - // when the input first received focus. If the input is not focused - // then we need to set this.previous based on the value before spinning. - previous = this.element[0] === this.document[0].activeElement ? - this.previous : this.element.val(); - function checkFocus() { - var isActive = this.element[0] === this.document[0].activeElement; - if ( !isActive ) { - this.element.focus(); - this.previous = previous; - // support: IE - // IE sets focus asynchronously, so we need to check if focus - // moved off of the input because the user clicked on the button. - this._delay(function() { - this.previous = previous; - }); - } - } - - // ensure focus is on (or stays on) the text field - event.preventDefault(); - checkFocus.call( this ); - - // support: IE - // IE doesn't prevent moving focus even with event.preventDefault() - // so we set a flag to know when we should ignore the blur event - // and check (again) if focus moved off of the input. - this.cancelBlur = true; - this._delay(function() { - delete this.cancelBlur; - checkFocus.call( this ); - }); - - if ( this._start( event ) === false ) { - return; - } - - this._repeat( null, $( event.currentTarget ).hasClass( "ui-spinner-up" ) ? 1 : -1, event ); - }, - "mouseup .ui-spinner-button": "_stop", - "mouseenter .ui-spinner-button": function( event ) { - // button will add ui-state-active if mouse was down while mouseleave and kept down - if ( !$( event.currentTarget ).hasClass( "ui-state-active" ) ) { - return; - } - - if ( this._start( event ) === false ) { - return false; - } - this._repeat( null, $( event.currentTarget ).hasClass( "ui-spinner-up" ) ? 1 : -1, event ); - }, - // TODO: do we really want to consider this a stop? - // shouldn't we just stop the repeater and wait until mouseup before - // we trigger the stop event? - "mouseleave .ui-spinner-button": "_stop" - }, - - _draw: function() { - var uiSpinner = this.uiSpinner = this.element - .addClass( "ui-spinner-input" ) - .attr( "autocomplete", "off" ) - .wrap( this._uiSpinnerHtml() ) - .parent() - // add buttons - .append( this._buttonHtml() ); - - this.element.attr( "role", "spinbutton" ); - - // button bindings - this.buttons = uiSpinner.find( ".ui-spinner-button" ) - .attr( "tabIndex", -1 ) - .button() - .removeClass( "ui-corner-all" ); - - // IE 6 doesn't understand height: 50% for the buttons - // unless the wrapper has an explicit height - if ( this.buttons.height() > Math.ceil( uiSpinner.height() * 0.5 ) && - uiSpinner.height() > 0 ) { - uiSpinner.height( uiSpinner.height() ); - } - - // disable spinner if element was already disabled - if ( this.options.disabled ) { - this.disable(); - } - }, - - _keydown: function( event ) { - var options = this.options, - keyCode = $.ui.keyCode; - - switch ( event.keyCode ) { - case keyCode.UP: - this._repeat( null, 1, event ); - return true; - case keyCode.DOWN: - this._repeat( null, -1, event ); - return true; - case keyCode.PAGE_UP: - this._repeat( null, options.page, event ); - return true; - case keyCode.PAGE_DOWN: - this._repeat( null, -options.page, event ); - return true; - } - - return false; - }, - - _uiSpinnerHtml: function() { - return "<span class='ui-spinner ui-widget ui-widget-content ui-corner-all'></span>"; - }, - - _buttonHtml: function() { - return "" + - "<a class='ui-spinner-button ui-spinner-up ui-corner-tr'>" + - "<span class='ui-icon " + this.options.icons.up + "'>▲</span>" + - "</a>" + - "<a class='ui-spinner-button ui-spinner-down ui-corner-br'>" + - "<span class='ui-icon " + this.options.icons.down + "'>▼</span>" + - "</a>"; - }, - - _start: function( event ) { - if ( !this.spinning && this._trigger( "start", event ) === false ) { - return false; - } - - if ( !this.counter ) { - this.counter = 1; - } - this.spinning = true; - return true; - }, - - _repeat: function( i, steps, event ) { - i = i || 500; - - clearTimeout( this.timer ); - this.timer = this._delay(function() { - this._repeat( 40, steps, event ); - }, i ); - - this._spin( steps * this.options.step, event ); - }, - - _spin: function( step, event ) { - var value = this.value() || 0; - - if ( !this.counter ) { - this.counter = 1; - } - - value = this._adjustValue( value + step * this._increment( this.counter ) ); - - if ( !this.spinning || this._trigger( "spin", event, { value: value } ) !== false) { - this._value( value ); - this.counter++; - } - }, - - _increment: function( i ) { - var incremental = this.options.incremental; - - if ( incremental ) { - return $.isFunction( incremental ) ? - incremental( i ) : - Math.floor( i*i*i/50000 - i*i/500 + 17*i/200 + 1 ); - } - - return 1; - }, - - _precision: function() { - var precision = this._precisionOf( this.options.step ); - if ( this.options.min !== null ) { - precision = Math.max( precision, this._precisionOf( this.options.min ) ); - } - return precision; - }, - - _precisionOf: function( num ) { - var str = num.toString(), - decimal = str.indexOf( "." ); - return decimal === -1 ? 0 : str.length - decimal - 1; - }, - - _adjustValue: function( value ) { - var base, aboveMin, - options = this.options; - - // make sure we're at a valid step - // - find out where we are relative to the base (min or 0) - base = options.min !== null ? options.min : 0; - aboveMin = value - base; - // - round to the nearest step - aboveMin = Math.round(aboveMin / options.step) * options.step; - // - rounding is based on 0, so adjust back to our base - value = base + aboveMin; - - // fix precision from bad JS floating point math - value = parseFloat( value.toFixed( this._precision() ) ); - - // clamp the value - if ( options.max !== null && value > options.max) { - return options.max; - } - if ( options.min !== null && value < options.min ) { - return options.min; - } - - return value; - }, - - _stop: function( event ) { - if ( !this.spinning ) { - return; - } - - clearTimeout( this.timer ); - clearTimeout( this.mousewheelTimer ); - this.counter = 0; - this.spinning = false; - this._trigger( "stop", event ); - }, - - _setOption: function( key, value ) { - if ( key === "culture" || key === "numberFormat" ) { - var prevValue = this._parse( this.element.val() ); - this.options[ key ] = value; - this.element.val( this._format( prevValue ) ); - return; - } - - if ( key === "max" || key === "min" || key === "step" ) { - if ( typeof value === "string" ) { - value = this._parse( value ); - } - } - if ( key === "icons" ) { - this.buttons.first().find( ".ui-icon" ) - .removeClass( this.options.icons.up ) - .addClass( value.up ); - this.buttons.last().find( ".ui-icon" ) - .removeClass( this.options.icons.down ) - .addClass( value.down ); - } - - this._super( key, value ); - - if ( key === "disabled" ) { - if ( value ) { - this.element.prop( "disabled", true ); - this.buttons.button( "disable" ); - } else { - this.element.prop( "disabled", false ); - this.buttons.button( "enable" ); - } - } - }, - - _setOptions: modifier(function( options ) { - this._super( options ); - this._value( this.element.val() ); - }), - - _parse: function( val ) { - if ( typeof val === "string" && val !== "" ) { - val = window.Globalize && this.options.numberFormat ? - Globalize.parseFloat( val, 10, this.options.culture ) : +val; - } - return val === "" || isNaN( val ) ? null : val; - }, - - _format: function( value ) { - if ( value === "" ) { - return ""; - } - return window.Globalize && this.options.numberFormat ? - Globalize.format( value, this.options.numberFormat, this.options.culture ) : - value; - }, - - _refresh: function() { - this.element.attr({ - "aria-valuemin": this.options.min, - "aria-valuemax": this.options.max, - // TODO: what should we do with values that can't be parsed? - "aria-valuenow": this._parse( this.element.val() ) - }); - }, - - // update the value without triggering change - _value: function( value, allowAny ) { - var parsed; - if ( value !== "" ) { - parsed = this._parse( value ); - if ( parsed !== null ) { - if ( !allowAny ) { - parsed = this._adjustValue( parsed ); - } - value = this._format( parsed ); - } - } - this.element.val( value ); - this._refresh(); - }, - - _destroy: function() { - this.element - .removeClass( "ui-spinner-input" ) - .prop( "disabled", false ) - .removeAttr( "autocomplete" ) - .removeAttr( "role" ) - .removeAttr( "aria-valuemin" ) - .removeAttr( "aria-valuemax" ) - .removeAttr( "aria-valuenow" ); - this.uiSpinner.replaceWith( this.element ); - }, - - stepUp: modifier(function( steps ) { - this._stepUp( steps ); - }), - _stepUp: function( steps ) { - if ( this._start() ) { - this._spin( (steps || 1) * this.options.step ); - this._stop(); - } - }, - - stepDown: modifier(function( steps ) { - this._stepDown( steps ); - }), - _stepDown: function( steps ) { - if ( this._start() ) { - this._spin( (steps || 1) * -this.options.step ); - this._stop(); - } - }, - - pageUp: modifier(function( pages ) { - this._stepUp( (pages || 1) * this.options.page ); - }), - - pageDown: modifier(function( pages ) { - this._stepDown( (pages || 1) * this.options.page ); - }), - - value: function( newVal ) { - if ( !arguments.length ) { - return this._parse( this.element.val() ); - } - modifier( this._value ).call( this, newVal ); - }, - - widget: function() { - return this.uiSpinner; - } -}); - -}( jQuery ) ); - -(function( $, undefined ) { - -var tabId = 0, - rhash = /#.*$/; - -function getNextTabId() { - return ++tabId; -} - -function isLocal( anchor ) { - return anchor.hash.length > 1 && - decodeURIComponent( anchor.href.replace( rhash, "" ) ) === - decodeURIComponent( location.href.replace( rhash, "" ) ); -} - -$.widget( "ui.tabs", { - version: "1.10.3", - delay: 300, - options: { - active: null, - collapsible: false, - event: "click", - heightStyle: "content", - hide: null, - show: null, - - // callbacks - activate: null, - beforeActivate: null, - beforeLoad: null, - load: null - }, - - _create: function() { - var that = this, - options = this.options; - - this.running = false; - - this.element - .addClass( "ui-tabs ui-widget ui-widget-content ui-corner-all" ) - .toggleClass( "ui-tabs-collapsible", options.collapsible ) - // Prevent users from focusing disabled tabs via click - .delegate( ".ui-tabs-nav > li", "mousedown" + this.eventNamespace, function( event ) { - if ( $( this ).is( ".ui-state-disabled" ) ) { - event.preventDefault(); - } - }) - // support: IE <9 - // Preventing the default action in mousedown doesn't prevent IE - // from focusing the element, so if the anchor gets focused, blur. - // We don't have to worry about focusing the previously focused - // element since clicking on a non-focusable element should focus - // the body anyway. - .delegate( ".ui-tabs-anchor", "focus" + this.eventNamespace, function() { - if ( $( this ).closest( "li" ).is( ".ui-state-disabled" ) ) { - this.blur(); - } - }); - - this._processTabs(); - options.active = this._initialActive(); - - // Take disabling tabs via class attribute from HTML - // into account and update option properly. - if ( $.isArray( options.disabled ) ) { - options.disabled = $.unique( options.disabled.concat( - $.map( this.tabs.filter( ".ui-state-disabled" ), function( li ) { - return that.tabs.index( li ); - }) - ) ).sort(); - } - - // check for length avoids error when initializing empty list - if ( this.options.active !== false && this.anchors.length ) { - this.active = this._findActive( options.active ); - } else { - this.active = $(); - } - - this._refresh(); - - if ( this.active.length ) { - this.load( options.active ); - } - }, - - _initialActive: function() { - var active = this.options.active, - collapsible = this.options.collapsible, - locationHash = location.hash.substring( 1 ); - - if ( active === null ) { - // check the fragment identifier in the URL - if ( locationHash ) { - this.tabs.each(function( i, tab ) { - if ( $( tab ).attr( "aria-controls" ) === locationHash ) { - active = i; - return false; - } - }); - } - - // check for a tab marked active via a class - if ( active === null ) { - active = this.tabs.index( this.tabs.filter( ".ui-tabs-active" ) ); - } - - // no active tab, set to false - if ( active === null || active === -1 ) { - active = this.tabs.length ? 0 : false; - } - } - - // handle numbers: negative, out of range - if ( active !== false ) { - active = this.tabs.index( this.tabs.eq( active ) ); - if ( active === -1 ) { - active = collapsible ? false : 0; - } - } - - // don't allow collapsible: false and active: false - if ( !collapsible && active === false && this.anchors.length ) { - active = 0; - } - - return active; - }, - - _getCreateEventData: function() { - return { - tab: this.active, - panel: !this.active.length ? $() : this._getPanelForTab( this.active ) - }; - }, - - _tabKeydown: function( event ) { - /*jshint maxcomplexity:15*/ - var focusedTab = $( this.document[0].activeElement ).closest( "li" ), - selectedIndex = this.tabs.index( focusedTab ), - goingForward = true; - - if ( this._handlePageNav( event ) ) { - return; - } - - switch ( event.keyCode ) { - case $.ui.keyCode.RIGHT: - case $.ui.keyCode.DOWN: - selectedIndex++; - break; - case $.ui.keyCode.UP: - case $.ui.keyCode.LEFT: - goingForward = false; - selectedIndex--; - break; - case $.ui.keyCode.END: - selectedIndex = this.anchors.length - 1; - break; - case $.ui.keyCode.HOME: - selectedIndex = 0; - break; - case $.ui.keyCode.SPACE: - // Activate only, no collapsing - event.preventDefault(); - clearTimeout( this.activating ); - this._activate( selectedIndex ); - return; - case $.ui.keyCode.ENTER: - // Toggle (cancel delayed activation, allow collapsing) - event.preventDefault(); - clearTimeout( this.activating ); - // Determine if we should collapse or activate - this._activate( selectedIndex === this.options.active ? false : selectedIndex ); - return; - default: - return; - } - - // Focus the appropriate tab, based on which key was pressed - event.preventDefault(); - clearTimeout( this.activating ); - selectedIndex = this._focusNextTab( selectedIndex, goingForward ); - - // Navigating with control key will prevent automatic activation - if ( !event.ctrlKey ) { - // Update aria-selected immediately so that AT think the tab is already selected. - // Otherwise AT may confuse the user by stating that they need to activate the tab, - // but the tab will already be activated by the time the announcement finishes. - focusedTab.attr( "aria-selected", "false" ); - this.tabs.eq( selectedIndex ).attr( "aria-selected", "true" ); - - this.activating = this._delay(function() { - this.option( "active", selectedIndex ); - }, this.delay ); - } - }, - - _panelKeydown: function( event ) { - if ( this._handlePageNav( event ) ) { - return; - } - - // Ctrl+up moves focus to the current tab - if ( event.ctrlKey && event.keyCode === $.ui.keyCode.UP ) { - event.preventDefault(); - this.active.focus(); - } - }, - - // Alt+page up/down moves focus to the previous/next tab (and activates) - _handlePageNav: function( event ) { - if ( event.altKey && event.keyCode === $.ui.keyCode.PAGE_UP ) { - this._activate( this._focusNextTab( this.options.active - 1, false ) ); - return true; - } - if ( event.altKey && event.keyCode === $.ui.keyCode.PAGE_DOWN ) { - this._activate( this._focusNextTab( this.options.active + 1, true ) ); - return true; - } - }, - - _findNextTab: function( index, goingForward ) { - var lastTabIndex = this.tabs.length - 1; - - function constrain() { - if ( index > lastTabIndex ) { - index = 0; - } - if ( index < 0 ) { - index = lastTabIndex; - } - return index; - } - - while ( $.inArray( constrain(), this.options.disabled ) !== -1 ) { - index = goingForward ? index + 1 : index - 1; - } - - return index; - }, - - _focusNextTab: function( index, goingForward ) { - index = this._findNextTab( index, goingForward ); - this.tabs.eq( index ).focus(); - return index; - }, - - _setOption: function( key, value ) { - if ( key === "active" ) { - // _activate() will handle invalid values and update this.options - this._activate( value ); - return; - } - - if ( key === "disabled" ) { - // don't use the widget factory's disabled handling - this._setupDisabled( value ); - return; - } - - this._super( key, value); - - if ( key === "collapsible" ) { - this.element.toggleClass( "ui-tabs-collapsible", value ); - // Setting collapsible: false while collapsed; open first panel - if ( !value && this.options.active === false ) { - this._activate( 0 ); - } - } - - if ( key === "event" ) { - this._setupEvents( value ); - } - - if ( key === "heightStyle" ) { - this._setupHeightStyle( value ); - } - }, - - _tabId: function( tab ) { - return tab.attr( "aria-controls" ) || "ui-tabs-" + getNextTabId(); - }, - - _sanitizeSelector: function( hash ) { - return hash ? hash.replace( /[!"$%&'()*+,.\/:;<=>?@\[\]\^`{|}~]/g, "\\$&" ) : ""; - }, - - refresh: function() { - var options = this.options, - lis = this.tablist.children( ":has(a[href])" ); - - // get disabled tabs from class attribute from HTML - // this will get converted to a boolean if needed in _refresh() - options.disabled = $.map( lis.filter( ".ui-state-disabled" ), function( tab ) { - return lis.index( tab ); - }); - - this._processTabs(); - - // was collapsed or no tabs - if ( options.active === false || !this.anchors.length ) { - options.active = false; - this.active = $(); - // was active, but active tab is gone - } else if ( this.active.length && !$.contains( this.tablist[ 0 ], this.active[ 0 ] ) ) { - // all remaining tabs are disabled - if ( this.tabs.length === options.disabled.length ) { - options.active = false; - this.active = $(); - // activate previous tab - } else { - this._activate( this._findNextTab( Math.max( 0, options.active - 1 ), false ) ); - } - // was active, active tab still exists - } else { - // make sure active index is correct - options.active = this.tabs.index( this.active ); - } - - this._refresh(); - }, - - _refresh: function() { - this._setupDisabled( this.options.disabled ); - this._setupEvents( this.options.event ); - this._setupHeightStyle( this.options.heightStyle ); - - this.tabs.not( this.active ).attr({ - "aria-selected": "false", - tabIndex: -1 - }); - this.panels.not( this._getPanelForTab( this.active ) ) - .hide() - .attr({ - "aria-expanded": "false", - "aria-hidden": "true" - }); - - // Make sure one tab is in the tab order - if ( !this.active.length ) { - this.tabs.eq( 0 ).attr( "tabIndex", 0 ); - } else { - this.active - .addClass( "ui-tabs-active ui-state-active" ) - .attr({ - "aria-selected": "true", - tabIndex: 0 - }); - this._getPanelForTab( this.active ) - .show() - .attr({ - "aria-expanded": "true", - "aria-hidden": "false" - }); - } - }, - - _processTabs: function() { - var that = this; - - this.tablist = this._getList() - .addClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" ) - .attr( "role", "tablist" ); - - this.tabs = this.tablist.find( "> li:has(a[href])" ) - .addClass( "ui-state-default ui-corner-top" ) - .attr({ - role: "tab", - tabIndex: -1 - }); - - this.anchors = this.tabs.map(function() { - return $( "a", this )[ 0 ]; - }) - .addClass( "ui-tabs-anchor" ) - .attr({ - role: "presentation", - tabIndex: -1 - }); - - this.panels = $(); - - this.anchors.each(function( i, anchor ) { - var selector, panel, panelId, - anchorId = $( anchor ).uniqueId().attr( "id" ), - tab = $( anchor ).closest( "li" ), - originalAriaControls = tab.attr( "aria-controls" ); - - // inline tab - if ( isLocal( anchor ) ) { - selector = anchor.hash; - panel = that.element.find( that._sanitizeSelector( selector ) ); - // remote tab - } else { - panelId = that._tabId( tab ); - selector = "#" + panelId; - panel = that.element.find( selector ); - if ( !panel.length ) { - panel = that._createPanel( panelId ); - panel.insertAfter( that.panels[ i - 1 ] || that.tablist ); - } - panel.attr( "aria-live", "polite" ); - } - - if ( panel.length) { - that.panels = that.panels.add( panel ); - } - if ( originalAriaControls ) { - tab.data( "ui-tabs-aria-controls", originalAriaControls ); - } - tab.attr({ - "aria-controls": selector.substring( 1 ), - "aria-labelledby": anchorId - }); - panel.attr( "aria-labelledby", anchorId ); - }); - - this.panels - .addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" ) - .attr( "role", "tabpanel" ); - }, - - // allow overriding how to find the list for rare usage scenarios (#7715) - _getList: function() { - return this.element.find( "ol,ul" ).eq( 0 ); - }, - - _createPanel: function( id ) { - return $( "<div>" ) - .attr( "id", id ) - .addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" ) - .data( "ui-tabs-destroy", true ); - }, - - _setupDisabled: function( disabled ) { - if ( $.isArray( disabled ) ) { - if ( !disabled.length ) { - disabled = false; - } else if ( disabled.length === this.anchors.length ) { - disabled = true; - } - } - - // disable tabs - for ( var i = 0, li; ( li = this.tabs[ i ] ); i++ ) { - if ( disabled === true || $.inArray( i, disabled ) !== -1 ) { - $( li ) - .addClass( "ui-state-disabled" ) - .attr( "aria-disabled", "true" ); - } else { - $( li ) - .removeClass( "ui-state-disabled" ) - .removeAttr( "aria-disabled" ); - } - } - - this.options.disabled = disabled; - }, - - _setupEvents: function( event ) { - var events = { - click: function( event ) { - event.preventDefault(); - } - }; - if ( event ) { - $.each( event.split(" "), function( index, eventName ) { - events[ eventName ] = "_eventHandler"; - }); - } - - this._off( this.anchors.add( this.tabs ).add( this.panels ) ); - this._on( this.anchors, events ); - this._on( this.tabs, { keydown: "_tabKeydown" } ); - this._on( this.panels, { keydown: "_panelKeydown" } ); - - this._focusable( this.tabs ); - this._hoverable( this.tabs ); - }, - - _setupHeightStyle: function( heightStyle ) { - var maxHeight, - parent = this.element.parent(); - - if ( heightStyle === "fill" ) { - maxHeight = parent.height(); - maxHeight -= this.element.outerHeight() - this.element.height(); - - this.element.siblings( ":visible" ).each(function() { - var elem = $( this ), - position = elem.css( "position" ); - - if ( position === "absolute" || position === "fixed" ) { - return; - } - maxHeight -= elem.outerHeight( true ); - }); - - this.element.children().not( this.panels ).each(function() { - maxHeight -= $( this ).outerHeight( true ); - }); - - this.panels.each(function() { - $( this ).height( Math.max( 0, maxHeight - - $( this ).innerHeight() + $( this ).height() ) ); - }) - .css( "overflow", "auto" ); - } else if ( heightStyle === "auto" ) { - maxHeight = 0; - this.panels.each(function() { - maxHeight = Math.max( maxHeight, $( this ).height( "" ).height() ); - }).height( maxHeight ); - } - }, - - _eventHandler: function( event ) { - var options = this.options, - active = this.active, - anchor = $( event.currentTarget ), - tab = anchor.closest( "li" ), - clickedIsActive = tab[ 0 ] === active[ 0 ], - collapsing = clickedIsActive && options.collapsible, - toShow = collapsing ? $() : this._getPanelForTab( tab ), - toHide = !active.length ? $() : this._getPanelForTab( active ), - eventData = { - oldTab: active, - oldPanel: toHide, - newTab: collapsing ? $() : tab, - newPanel: toShow - }; - - event.preventDefault(); - - if ( tab.hasClass( "ui-state-disabled" ) || - // tab is already loading - tab.hasClass( "ui-tabs-loading" ) || - // can't switch durning an animation - this.running || - // click on active header, but not collapsible - ( clickedIsActive && !options.collapsible ) || - // allow canceling activation - ( this._trigger( "beforeActivate", event, eventData ) === false ) ) { - return; - } - - options.active = collapsing ? false : this.tabs.index( tab ); - - this.active = clickedIsActive ? $() : tab; - if ( this.xhr ) { - this.xhr.abort(); - } - - if ( !toHide.length && !toShow.length ) { - $.error( "jQuery UI Tabs: Mismatching fragment identifier." ); - } - - if ( toShow.length ) { - this.load( this.tabs.index( tab ), event ); - } - this._toggle( event, eventData ); - }, - - // handles show/hide for selecting tabs - _toggle: function( event, eventData ) { - var that = this, - toShow = eventData.newPanel, - toHide = eventData.oldPanel; - - this.running = true; - - function complete() { - that.running = false; - that._trigger( "activate", event, eventData ); - } - - function show() { - eventData.newTab.closest( "li" ).addClass( "ui-tabs-active ui-state-active" ); - - if ( toShow.length && that.options.show ) { - that._show( toShow, that.options.show, complete ); - } else { - toShow.show(); - complete(); - } - } - - // start out by hiding, then showing, then completing - if ( toHide.length && this.options.hide ) { - this._hide( toHide, this.options.hide, function() { - eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" ); - show(); - }); - } else { - eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" ); - toHide.hide(); - show(); - } - - toHide.attr({ - "aria-expanded": "false", - "aria-hidden": "true" - }); - eventData.oldTab.attr( "aria-selected", "false" ); - // If we're switching tabs, remove the old tab from the tab order. - // If we're opening from collapsed state, remove the previous tab from the tab order. - // If we're collapsing, then keep the collapsing tab in the tab order. - if ( toShow.length && toHide.length ) { - eventData.oldTab.attr( "tabIndex", -1 ); - } else if ( toShow.length ) { - this.tabs.filter(function() { - return $( this ).attr( "tabIndex" ) === 0; - }) - .attr( "tabIndex", -1 ); - } - - toShow.attr({ - "aria-expanded": "true", - "aria-hidden": "false" - }); - eventData.newTab.attr({ - "aria-selected": "true", - tabIndex: 0 - }); - }, - - _activate: function( index ) { - var anchor, - active = this._findActive( index ); - - // trying to activate the already active panel - if ( active[ 0 ] === this.active[ 0 ] ) { - return; - } - - // trying to collapse, simulate a click on the current active header - if ( !active.length ) { - active = this.active; - } - - anchor = active.find( ".ui-tabs-anchor" )[ 0 ]; - this._eventHandler({ - target: anchor, - currentTarget: anchor, - preventDefault: $.noop - }); - }, - - _findActive: function( index ) { - return index === false ? $() : this.tabs.eq( index ); - }, - - _getIndex: function( index ) { - // meta-function to give users option to provide a href string instead of a numerical index. - if ( typeof index === "string" ) { - index = this.anchors.index( this.anchors.filter( "[href$='" + index + "']" ) ); - } - - return index; - }, - - _destroy: function() { - if ( this.xhr ) { - this.xhr.abort(); - } - - this.element.removeClass( "ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible" ); - - this.tablist - .removeClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" ) - .removeAttr( "role" ); - - this.anchors - .removeClass( "ui-tabs-anchor" ) - .removeAttr( "role" ) - .removeAttr( "tabIndex" ) - .removeUniqueId(); - - this.tabs.add( this.panels ).each(function() { - if ( $.data( this, "ui-tabs-destroy" ) ) { - $( this ).remove(); - } else { - $( this ) - .removeClass( "ui-state-default ui-state-active ui-state-disabled " + - "ui-corner-top ui-corner-bottom ui-widget-content ui-tabs-active ui-tabs-panel" ) - .removeAttr( "tabIndex" ) - .removeAttr( "aria-live" ) - .removeAttr( "aria-busy" ) - .removeAttr( "aria-selected" ) - .removeAttr( "aria-labelledby" ) - .removeAttr( "aria-hidden" ) - .removeAttr( "aria-expanded" ) - .removeAttr( "role" ); - } - }); - - this.tabs.each(function() { - var li = $( this ), - prev = li.data( "ui-tabs-aria-controls" ); - if ( prev ) { - li - .attr( "aria-controls", prev ) - .removeData( "ui-tabs-aria-controls" ); - } else { - li.removeAttr( "aria-controls" ); - } - }); - - this.panels.show(); - - if ( this.options.heightStyle !== "content" ) { - this.panels.css( "height", "" ); - } - }, - - enable: function( index ) { - var disabled = this.options.disabled; - if ( disabled === false ) { - return; - } - - if ( index === undefined ) { - disabled = false; - } else { - index = this._getIndex( index ); - if ( $.isArray( disabled ) ) { - disabled = $.map( disabled, function( num ) { - return num !== index ? num : null; - }); - } else { - disabled = $.map( this.tabs, function( li, num ) { - return num !== index ? num : null; - }); - } - } - this._setupDisabled( disabled ); - }, - - disable: function( index ) { - var disabled = this.options.disabled; - if ( disabled === true ) { - return; - } - - if ( index === undefined ) { - disabled = true; - } else { - index = this._getIndex( index ); - if ( $.inArray( index, disabled ) !== -1 ) { - return; - } - if ( $.isArray( disabled ) ) { - disabled = $.merge( [ index ], disabled ).sort(); - } else { - disabled = [ index ]; - } - } - this._setupDisabled( disabled ); - }, - - load: function( index, event ) { - index = this._getIndex( index ); - var that = this, - tab = this.tabs.eq( index ), - anchor = tab.find( ".ui-tabs-anchor" ), - panel = this._getPanelForTab( tab ), - eventData = { - tab: tab, - panel: panel - }; - - // not remote - if ( isLocal( anchor[ 0 ] ) ) { - return; - } - - this.xhr = $.ajax( this._ajaxSettings( anchor, event, eventData ) ); - - // support: jQuery <1.8 - // jQuery <1.8 returns false if the request is canceled in beforeSend, - // but as of 1.8, $.ajax() always returns a jqXHR object. - if ( this.xhr && this.xhr.statusText !== "canceled" ) { - tab.addClass( "ui-tabs-loading" ); - panel.attr( "aria-busy", "true" ); - - this.xhr - .success(function( response ) { - // support: jQuery <1.8 - // http://bugs.jquery.com/ticket/11778 - setTimeout(function() { - panel.html( response ); - that._trigger( "load", event, eventData ); - }, 1 ); - }) - .complete(function( jqXHR, status ) { - // support: jQuery <1.8 - // http://bugs.jquery.com/ticket/11778 - setTimeout(function() { - if ( status === "abort" ) { - that.panels.stop( false, true ); - } - - tab.removeClass( "ui-tabs-loading" ); - panel.removeAttr( "aria-busy" ); - - if ( jqXHR === that.xhr ) { - delete that.xhr; - } - }, 1 ); - }); - } - }, - - _ajaxSettings: function( anchor, event, eventData ) { - var that = this; - return { - url: anchor.attr( "href" ), - beforeSend: function( jqXHR, settings ) { - return that._trigger( "beforeLoad", event, - $.extend( { jqXHR : jqXHR, ajaxSettings: settings }, eventData ) ); - } - }; - }, - - _getPanelForTab: function( tab ) { - var id = $( tab ).attr( "aria-controls" ); - return this.element.find( this._sanitizeSelector( "#" + id ) ); - } -}); - -})( jQuery ); - -(function( $ ) { - -var increments = 0; - -function addDescribedBy( elem, id ) { - var describedby = (elem.attr( "aria-describedby" ) || "").split( /\s+/ ); - describedby.push( id ); - elem - .data( "ui-tooltip-id", id ) - .attr( "aria-describedby", $.trim( describedby.join( " " ) ) ); -} - -function removeDescribedBy( elem ) { - var id = elem.data( "ui-tooltip-id" ), - describedby = (elem.attr( "aria-describedby" ) || "").split( /\s+/ ), - index = $.inArray( id, describedby ); - if ( index !== -1 ) { - describedby.splice( index, 1 ); - } - - elem.removeData( "ui-tooltip-id" ); - describedby = $.trim( describedby.join( " " ) ); - if ( describedby ) { - elem.attr( "aria-describedby", describedby ); - } else { - elem.removeAttr( "aria-describedby" ); - } -} - -$.widget( "ui.tooltip", { - version: "1.10.3", - options: { - content: function() { - // support: IE<9, Opera in jQuery <1.7 - // .text() can't accept undefined, so coerce to a string - var title = $( this ).attr( "title" ) || ""; - // Escape title, since we're going from an attribute to raw HTML - return $( "<a>" ).text( title ).html(); - }, - hide: true, - // Disabled elements have inconsistent behavior across browsers (#8661) - items: "[title]:not([disabled])", - position: { - my: "left top+15", - at: "left bottom", - collision: "flipfit flip" - }, - show: true, - tooltipClass: null, - track: false, - - // callbacks - close: null, - open: null - }, - - _create: function() { - this._on({ - mouseover: "open", - focusin: "open" - }); - - // IDs of generated tooltips, needed for destroy - this.tooltips = {}; - // IDs of parent tooltips where we removed the title attribute - this.parents = {}; - - if ( this.options.disabled ) { - this._disable(); - } - }, - - _setOption: function( key, value ) { - var that = this; - - if ( key === "disabled" ) { - this[ value ? "_disable" : "_enable" ](); - this.options[ key ] = value; - // disable element style changes - return; - } - - this._super( key, value ); - - if ( key === "content" ) { - $.each( this.tooltips, function( id, element ) { - that._updateContent( element ); - }); - } - }, - - _disable: function() { - var that = this; - - // close open tooltips - $.each( this.tooltips, function( id, element ) { - var event = $.Event( "blur" ); - event.target = event.currentTarget = element[0]; - that.close( event, true ); - }); - - // remove title attributes to prevent native tooltips - this.element.find( this.options.items ).addBack().each(function() { - var element = $( this ); - if ( element.is( "[title]" ) ) { - element - .data( "ui-tooltip-title", element.attr( "title" ) ) - .attr( "title", "" ); - } - }); - }, - - _enable: function() { - // restore title attributes - this.element.find( this.options.items ).addBack().each(function() { - var element = $( this ); - if ( element.data( "ui-tooltip-title" ) ) { - element.attr( "title", element.data( "ui-tooltip-title" ) ); - } - }); - }, - - open: function( event ) { - var that = this, - target = $( event ? event.target : this.element ) - // we need closest here due to mouseover bubbling, - // but always pointing at the same event target - .closest( this.options.items ); - - // No element to show a tooltip for or the tooltip is already open - if ( !target.length || target.data( "ui-tooltip-id" ) ) { - return; - } - - if ( target.attr( "title" ) ) { - target.data( "ui-tooltip-title", target.attr( "title" ) ); - } - - target.data( "ui-tooltip-open", true ); - - // kill parent tooltips, custom or native, for hover - if ( event && event.type === "mouseover" ) { - target.parents().each(function() { - var parent = $( this ), - blurEvent; - if ( parent.data( "ui-tooltip-open" ) ) { - blurEvent = $.Event( "blur" ); - blurEvent.target = blurEvent.currentTarget = this; - that.close( blurEvent, true ); - } - if ( parent.attr( "title" ) ) { - parent.uniqueId(); - that.parents[ this.id ] = { - element: this, - title: parent.attr( "title" ) - }; - parent.attr( "title", "" ); - } - }); - } - - this._updateContent( target, event ); - }, - - _updateContent: function( target, event ) { - var content, - contentOption = this.options.content, - that = this, - eventType = event ? event.type : null; - - if ( typeof contentOption === "string" ) { - return this._open( event, target, contentOption ); - } - - content = contentOption.call( target[0], function( response ) { - // ignore async response if tooltip was closed already - if ( !target.data( "ui-tooltip-open" ) ) { - return; - } - // IE may instantly serve a cached response for ajax requests - // delay this call to _open so the other call to _open runs first - that._delay(function() { - // jQuery creates a special event for focusin when it doesn't - // exist natively. To improve performance, the native event - // object is reused and the type is changed. Therefore, we can't - // rely on the type being correct after the event finished - // bubbling, so we set it back to the previous value. (#8740) - if ( event ) { - event.type = eventType; - } - this._open( event, target, response ); - }); - }); - if ( content ) { - this._open( event, target, content ); - } - }, - - _open: function( event, target, content ) { - var tooltip, events, delayedShow, - positionOption = $.extend( {}, this.options.position ); - - if ( !content ) { - return; - } - - // Content can be updated multiple times. If the tooltip already - // exists, then just update the content and bail. - tooltip = this._find( target ); - if ( tooltip.length ) { - tooltip.find( ".ui-tooltip-content" ).html( content ); - return; - } - - // if we have a title, clear it to prevent the native tooltip - // we have to check first to avoid defining a title if none exists - // (we don't want to cause an element to start matching [title]) - // - // We use removeAttr only for key events, to allow IE to export the correct - // accessible attributes. For mouse events, set to empty string to avoid - // native tooltip showing up (happens only when removing inside mouseover). - if ( target.is( "[title]" ) ) { - if ( event && event.type === "mouseover" ) { - target.attr( "title", "" ); - } else { - target.removeAttr( "title" ); - } - } - - tooltip = this._tooltip( target ); - addDescribedBy( target, tooltip.attr( "id" ) ); - tooltip.find( ".ui-tooltip-content" ).html( content ); - - function position( event ) { - positionOption.of = event; - if ( tooltip.is( ":hidden" ) ) { - return; - } - tooltip.position( positionOption ); - } - if ( this.options.track && event && /^mouse/.test( event.type ) ) { - this._on( this.document, { - mousemove: position - }); - // trigger once to override element-relative positioning - position( event ); - } else { - tooltip.position( $.extend({ - of: target - }, this.options.position ) ); - } - - tooltip.hide(); - - this._show( tooltip, this.options.show ); - // Handle tracking tooltips that are shown with a delay (#8644). As soon - // as the tooltip is visible, position the tooltip using the most recent - // event. - if ( this.options.show && this.options.show.delay ) { - delayedShow = this.delayedShow = setInterval(function() { - if ( tooltip.is( ":visible" ) ) { - position( positionOption.of ); - clearInterval( delayedShow ); - } - }, $.fx.interval ); - } - - this._trigger( "open", event, { tooltip: tooltip } ); - - events = { - keyup: function( event ) { - if ( event.keyCode === $.ui.keyCode.ESCAPE ) { - var fakeEvent = $.Event(event); - fakeEvent.currentTarget = target[0]; - this.close( fakeEvent, true ); - } - }, - remove: function() { - this._removeTooltip( tooltip ); - } - }; - if ( !event || event.type === "mouseover" ) { - events.mouseleave = "close"; - } - if ( !event || event.type === "focusin" ) { - events.focusout = "close"; - } - this._on( true, target, events ); - }, - - close: function( event ) { - var that = this, - target = $( event ? event.currentTarget : this.element ), - tooltip = this._find( target ); - - // disabling closes the tooltip, so we need to track when we're closing - // to avoid an infinite loop in case the tooltip becomes disabled on close - if ( this.closing ) { - return; - } - - // Clear the interval for delayed tracking tooltips - clearInterval( this.delayedShow ); - - // only set title if we had one before (see comment in _open()) - if ( target.data( "ui-tooltip-title" ) ) { - target.attr( "title", target.data( "ui-tooltip-title" ) ); - } - - removeDescribedBy( target ); - - tooltip.stop( true ); - this._hide( tooltip, this.options.hide, function() { - that._removeTooltip( $( this ) ); - }); - - target.removeData( "ui-tooltip-open" ); - this._off( target, "mouseleave focusout keyup" ); - // Remove 'remove' binding only on delegated targets - if ( target[0] !== this.element[0] ) { - this._off( target, "remove" ); - } - this._off( this.document, "mousemove" ); - - if ( event && event.type === "mouseleave" ) { - $.each( this.parents, function( id, parent ) { - $( parent.element ).attr( "title", parent.title ); - delete that.parents[ id ]; - }); - } - - this.closing = true; - this._trigger( "close", event, { tooltip: tooltip } ); - this.closing = false; - }, - - _tooltip: function( element ) { - var id = "ui-tooltip-" + increments++, - tooltip = $( "<div>" ) - .attr({ - id: id, - role: "tooltip" - }) - .addClass( "ui-tooltip ui-widget ui-corner-all ui-widget-content " + - ( this.options.tooltipClass || "" ) ); - $( "<div>" ) - .addClass( "ui-tooltip-content" ) - .appendTo( tooltip ); - tooltip.appendTo( this.document[0].body ); - this.tooltips[ id ] = element; - return tooltip; - }, - - _find: function( target ) { - var id = target.data( "ui-tooltip-id" ); - return id ? $( "#" + id ) : $(); - }, - - _removeTooltip: function( tooltip ) { - tooltip.remove(); - delete this.tooltips[ tooltip.attr( "id" ) ]; - }, - - _destroy: function() { - var that = this; - - // close open tooltips - $.each( this.tooltips, function( id, element ) { - // Delegate to close method to handle common cleanup - var event = $.Event( "blur" ); - event.target = event.currentTarget = element[0]; - that.close( event, true ); - - // Remove immediately; destroying an open tooltip doesn't use the - // hide animation - $( "#" + id ).remove(); - - // Restore the title - if ( element.data( "ui-tooltip-title" ) ) { - element.attr( "title", element.data( "ui-tooltip-title" ) ); - element.removeData( "ui-tooltip-title" ); - } - }); - } -}); - -}( jQuery ) ); - diff --git a/js/jquery.js b/js/jquery.js deleted file mode 100755 index 0fc98ae..0000000 --- a/js/jquery.js +++ /dev/null @@ -1,6 +0,0 @@ -/*! jQuery v2.0.0 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license -//@ sourceMappingURL=jquery.min.map -*/ -(function(e,undefined){var t,n,r=typeof undefined,i=e.location,o=e.document,s=o.documentElement,a=e.jQuery,u=e.$,l={},c=[],f="2.0.0",p=c.concat,h=c.push,d=c.slice,g=c.indexOf,m=l.toString,y=l.hasOwnProperty,v=f.trim,x=function(e,n){return new x.fn.init(e,n,t)},b=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,w=/\S+/g,T=/^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/,C=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,k=/^-ms-/,N=/-([\da-z])/gi,E=function(e,t){return t.toUpperCase()},S=function(){o.removeEventListener("DOMContentLoaded",S,!1),e.removeEventListener("load",S,!1),x.ready()};x.fn=x.prototype={jquery:f,constructor:x,init:function(e,t,n){var r,i;if(!e)return this;if("string"==typeof e){if(r="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:T.exec(e),!r||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof x?t[0]:t,x.merge(this,x.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:o,!0)),C.test(r[1])&&x.isPlainObject(t))for(r in t)x.isFunction(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return i=o.getElementById(r[2]),i&&i.parentNode&&(this.length=1,this[0]=i),this.context=o,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):x.isFunction(e)?n.ready(e):(e.selector!==undefined&&(this.selector=e.selector,this.context=e.context),x.makeArray(e,this))},selector:"",length:0,toArray:function(){return d.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=x.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return x.each(this,e,t)},ready:function(e){return x.ready.promise().done(e),this},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},map:function(e){return this.pushStack(x.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:h,sort:[].sort,splice:[].splice},x.fn.init.prototype=x.fn,x.extend=x.fn.extend=function(){var e,t,n,r,i,o,s=arguments[0]||{},a=1,u=arguments.length,l=!1;for("boolean"==typeof s&&(l=s,s=arguments[1]||{},a=2),"object"==typeof s||x.isFunction(s)||(s={}),u===a&&(s=this,--a);u>a;a++)if(null!=(e=arguments[a]))for(t in e)n=s[t],r=e[t],s!==r&&(l&&r&&(x.isPlainObject(r)||(i=x.isArray(r)))?(i?(i=!1,o=n&&x.isArray(n)?n:[]):o=n&&x.isPlainObject(n)?n:{},s[t]=x.extend(l,o,r)):r!==undefined&&(s[t]=r));return s},x.extend({expando:"jQuery"+(f+Math.random()).replace(/\D/g,""),noConflict:function(t){return e.$===x&&(e.$=u),t&&e.jQuery===x&&(e.jQuery=a),x},isReady:!1,readyWait:1,holdReady:function(e){e?x.readyWait++:x.ready(!0)},ready:function(e){(e===!0?--x.readyWait:x.isReady)||(x.isReady=!0,e!==!0&&--x.readyWait>0||(n.resolveWith(o,[x]),x.fn.trigger&&x(o).trigger("ready").off("ready")))},isFunction:function(e){return"function"===x.type(e)},isArray:Array.isArray,isWindow:function(e){return null!=e&&e===e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?l[m.call(e)]||"object":typeof e},isPlainObject:function(e){if("object"!==x.type(e)||e.nodeType||x.isWindow(e))return!1;try{if(e.constructor&&!y.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(t){return!1}return!0},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||o;var r=C.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=x.buildFragment([e],t,i),i&&x(i).remove(),x.merge([],r.childNodes))},parseJSON:JSON.parse,parseXML:function(e){var t,n;if(!e||"string"!=typeof e)return null;try{n=new DOMParser,t=n.parseFromString(e,"text/xml")}catch(r){t=undefined}return(!t||t.getElementsByTagName("parsererror").length)&&x.error("Invalid XML: "+e),t},noop:function(){},globalEval:function(e){var t,n=eval;e=x.trim(e),e&&(1===e.indexOf("use strict")?(t=o.createElement("script"),t.text=e,o.head.appendChild(t).parentNode.removeChild(t)):n(e))},camelCase:function(e){return e.replace(k,"ms-").replace(N,E)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,o=e.length,s=j(e);if(n){if(s){for(;o>i;i++)if(r=t.apply(e[i],n),r===!1)break}else for(i in e)if(r=t.apply(e[i],n),r===!1)break}else if(s){for(;o>i;i++)if(r=t.call(e[i],i,e[i]),r===!1)break}else for(i in e)if(r=t.call(e[i],i,e[i]),r===!1)break;return e},trim:function(e){return null==e?"":v.call(e)},makeArray:function(e,t){var n=t||[];return null!=e&&(j(Object(e))?x.merge(n,"string"==typeof e?[e]:e):h.call(n,e)),n},inArray:function(e,t,n){return null==t?-1:g.call(t,e,n)},merge:function(e,t){var n=t.length,r=e.length,i=0;if("number"==typeof n)for(;n>i;i++)e[r++]=t[i];else while(t[i]!==undefined)e[r++]=t[i++];return e.length=r,e},grep:function(e,t,n){var r,i=[],o=0,s=e.length;for(n=!!n;s>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,t,n){var r,i=0,o=e.length,s=j(e),a=[];if(s)for(;o>i;i++)r=t(e[i],i,n),null!=r&&(a[a.length]=r);else for(i in e)r=t(e[i],i,n),null!=r&&(a[a.length]=r);return p.apply([],a)},guid:1,proxy:function(e,t){var n,r,i;return"string"==typeof t&&(n=e[t],t=e,e=n),x.isFunction(e)?(r=d.call(arguments,2),i=function(){return e.apply(t||this,r.concat(d.call(arguments)))},i.guid=e.guid=e.guid||x.guid++,i):undefined},access:function(e,t,n,r,i,o,s){var a=0,u=e.length,l=null==n;if("object"===x.type(n)){i=!0;for(a in n)x.access(e,t,a,n[a],!0,o,s)}else if(r!==undefined&&(i=!0,x.isFunction(r)||(s=!0),l&&(s?(t.call(e,r),t=null):(l=t,t=function(e,t,n){return l.call(x(e),n)})),t))for(;u>a;a++)t(e[a],n,s?r:r.call(e[a],a,t(e[a],n)));return i?e:l?t.call(e):u?t(e[0],n):o},now:Date.now,swap:function(e,t,n,r){var i,o,s={};for(o in t)s[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=s[o];return i}}),x.ready.promise=function(t){return n||(n=x.Deferred(),"complete"===o.readyState?setTimeout(x.ready):(o.addEventListener("DOMContentLoaded",S,!1),e.addEventListener("load",S,!1))),n.promise(t)},x.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){l["[object "+t+"]"]=t.toLowerCase()});function j(e){var t=e.length,n=x.type(e);return x.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}t=x(o),function(e,undefined){var t,n,r,i,o,s,a,u,l,c,f,p,h,d,g,m,y="sizzle"+-new Date,v=e.document,b={},w=0,T=0,C=ot(),k=ot(),N=ot(),E=!1,S=function(){return 0},j=typeof undefined,D=1<<31,A=[],L=A.pop,q=A.push,H=A.push,O=A.slice,F=A.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},P="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",R="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",W=M.replace("w","w#"),$="\\["+R+"*("+M+")"+R+"*(?:([*^$|!~]?=)"+R+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+W+")|)|)"+R+"*\\]",B=":("+M+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+$.replace(3,8)+")*)|.*)\\)|)",I=RegExp("^"+R+"+|((?:^|[^\\\\])(?:\\\\.)*)"+R+"+$","g"),z=RegExp("^"+R+"*,"+R+"*"),_=RegExp("^"+R+"*([>+~]|"+R+")"+R+"*"),X=RegExp(R+"*[+~]"),U=RegExp("="+R+"*([^\\]'\"]*)"+R+"*\\]","g"),Y=RegExp(B),V=RegExp("^"+W+"$"),G={ID:RegExp("^#("+M+")"),CLASS:RegExp("^\\.("+M+")"),TAG:RegExp("^("+M.replace("w","w*")+")"),ATTR:RegExp("^"+$),PSEUDO:RegExp("^"+B),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+R+"*(even|odd|(([+-]|)(\\d*)n|)"+R+"*(?:([+-]|)"+R+"*(\\d+)|))"+R+"*\\)|)","i"),"boolean":RegExp("^(?:"+P+")$","i"),needsContext:RegExp("^"+R+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+R+"*((?:-\\d)?\\d*)"+R+"*\\)|)(?=[^-]|$)","i")},J=/^[^{]+\{\s*\[native \w/,Q=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,K=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,et=/'|\\/g,tt=/\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g,nt=function(e,t){var n="0x"+t-65536;return n!==n?t:0>n?String.fromCharCode(n+65536):String.fromCharCode(55296|n>>10,56320|1023&n)};try{H.apply(A=O.call(v.childNodes),v.childNodes),A[v.childNodes.length].nodeType}catch(rt){H={apply:A.length?function(e,t){q.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function it(e){return J.test(e+"")}function ot(){var e,t=[];return e=function(n,i){return t.push(n+=" ")>r.cacheLength&&delete e[t.shift()],e[n]=i}}function st(e){return e[y]=!0,e}function at(e){var t=c.createElement("div");try{return!!e(t)}catch(n){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function ut(e,t,n,r){var i,o,s,a,u,f,d,g,x,w;if((t?t.ownerDocument||t:v)!==c&&l(t),t=t||c,n=n||[],!e||"string"!=typeof e)return n;if(1!==(a=t.nodeType)&&9!==a)return[];if(p&&!r){if(i=Q.exec(e))if(s=i[1]){if(9===a){if(o=t.getElementById(s),!o||!o.parentNode)return n;if(o.id===s)return n.push(o),n}else if(t.ownerDocument&&(o=t.ownerDocument.getElementById(s))&&m(t,o)&&o.id===s)return n.push(o),n}else{if(i[2])return H.apply(n,t.getElementsByTagName(e)),n;if((s=i[3])&&b.getElementsByClassName&&t.getElementsByClassName)return H.apply(n,t.getElementsByClassName(s)),n}if(b.qsa&&(!h||!h.test(e))){if(g=d=y,x=t,w=9===a&&e,1===a&&"object"!==t.nodeName.toLowerCase()){f=gt(e),(d=t.getAttribute("id"))?g=d.replace(et,"\\$&"):t.setAttribute("id",g),g="[id='"+g+"'] ",u=f.length;while(u--)f[u]=g+mt(f[u]);x=X.test(e)&&t.parentNode||t,w=f.join(",")}if(w)try{return H.apply(n,x.querySelectorAll(w)),n}catch(T){}finally{d||t.removeAttribute("id")}}}return kt(e.replace(I,"$1"),t,n,r)}o=ut.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},l=ut.setDocument=function(e){var t=e?e.ownerDocument||e:v;return t!==c&&9===t.nodeType&&t.documentElement?(c=t,f=t.documentElement,p=!o(t),b.getElementsByTagName=at(function(e){return e.appendChild(t.createComment("")),!e.getElementsByTagName("*").length}),b.attributes=at(function(e){return e.className="i",!e.getAttribute("className")}),b.getElementsByClassName=at(function(e){return e.innerHTML="<div class='a'></div><div class='a i'></div>",e.firstChild.className="i",2===e.getElementsByClassName("i").length}),b.sortDetached=at(function(e){return 1&e.compareDocumentPosition(c.createElement("div"))}),b.getById=at(function(e){return f.appendChild(e).id=y,!t.getElementsByName||!t.getElementsByName(y).length}),b.getById?(r.find.ID=function(e,t){if(typeof t.getElementById!==j&&p){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},r.filter.ID=function(e){var t=e.replace(tt,nt);return function(e){return e.getAttribute("id")===t}}):(r.find.ID=function(e,t){if(typeof t.getElementById!==j&&p){var n=t.getElementById(e);return n?n.id===e||typeof n.getAttributeNode!==j&&n.getAttributeNode("id").value===e?[n]:undefined:[]}},r.filter.ID=function(e){var t=e.replace(tt,nt);return function(e){var n=typeof e.getAttributeNode!==j&&e.getAttributeNode("id");return n&&n.value===t}}),r.find.TAG=b.getElementsByTagName?function(e,t){return typeof t.getElementsByTagName!==j?t.getElementsByTagName(e):undefined}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},r.find.CLASS=b.getElementsByClassName&&function(e,t){return typeof t.getElementsByClassName!==j&&p?t.getElementsByClassName(e):undefined},d=[],h=[],(b.qsa=it(t.querySelectorAll))&&(at(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||h.push("\\["+R+"*(?:value|"+P+")"),e.querySelectorAll(":checked").length||h.push(":checked")}),at(function(e){var t=c.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("t",""),e.querySelectorAll("[t^='']").length&&h.push("[*^$]="+R+"*(?:''|\"\")"),e.querySelectorAll(":enabled").length||h.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),h.push(",.*:")})),(b.matchesSelector=it(g=f.webkitMatchesSelector||f.mozMatchesSelector||f.oMatchesSelector||f.msMatchesSelector))&&at(function(e){b.disconnectedMatch=g.call(e,"div"),g.call(e,"[s!='']:x"),d.push("!=",B)}),h=h.length&&RegExp(h.join("|")),d=d.length&&RegExp(d.join("|")),m=it(f.contains)||f.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},S=f.compareDocumentPosition?function(e,n){if(e===n)return E=!0,0;var r=n.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(n);return r?1&r||!b.sortDetached&&n.compareDocumentPosition(e)===r?e===t||m(v,e)?-1:n===t||m(v,n)?1:u?F.call(u,e)-F.call(u,n):0:4&r?-1:1:e.compareDocumentPosition?-1:1}:function(e,n){var r,i=0,o=e.parentNode,s=n.parentNode,a=[e],l=[n];if(e===n)return E=!0,0;if(!o||!s)return e===t?-1:n===t?1:o?-1:s?1:u?F.call(u,e)-F.call(u,n):0;if(o===s)return lt(e,n);r=e;while(r=r.parentNode)a.unshift(r);r=n;while(r=r.parentNode)l.unshift(r);while(a[i]===l[i])i++;return i?lt(a[i],l[i]):a[i]===v?-1:l[i]===v?1:0},c):c},ut.matches=function(e,t){return ut(e,null,null,t)},ut.matchesSelector=function(e,t){if((e.ownerDocument||e)!==c&&l(e),t=t.replace(U,"='$1']"),!(!b.matchesSelector||!p||d&&d.test(t)||h&&h.test(t)))try{var n=g.call(e,t);if(n||b.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(r){}return ut(t,c,null,[e]).length>0},ut.contains=function(e,t){return(e.ownerDocument||e)!==c&&l(e),m(e,t)},ut.attr=function(e,t){(e.ownerDocument||e)!==c&&l(e);var n=r.attrHandle[t.toLowerCase()],i=n&&n(e,t,!p);return i===undefined?b.attributes||!p?e.getAttribute(t):(i=e.getAttributeNode(t))&&i.specified?i.value:null:i},ut.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},ut.uniqueSort=function(e){var t,n=[],r=0,i=0;if(E=!b.detectDuplicates,u=!b.sortStable&&e.slice(0),e.sort(S),E){while(t=e[i++])t===e[i]&&(r=n.push(i));while(r--)e.splice(n[r],1)}return e};function lt(e,t){var n=t&&e,r=n&&(~t.sourceIndex||D)-(~e.sourceIndex||D);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function ct(e,t,n){var r;return n?undefined:(r=e.getAttributeNode(t))&&r.specified?r.value:e[t]===!0?t.toLowerCase():null}function ft(e,t,n){var r;return n?undefined:r=e.getAttribute(t,"type"===t.toLowerCase()?1:2)}function pt(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function ht(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function dt(e){return st(function(t){return t=+t,st(function(n,r){var i,o=e([],n.length,t),s=o.length;while(s--)n[i=o[s]]&&(n[i]=!(r[i]=n[i]))})})}i=ut.getText=function(e){var t,n="",r=0,o=e.nodeType;if(o){if(1===o||9===o||11===o){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=i(e)}else if(3===o||4===o)return e.nodeValue}else for(;t=e[r];r++)n+=i(t);return n},r=ut.selectors={cacheLength:50,createPseudo:st,match:G,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(tt,nt),e[3]=(e[4]||e[5]||"").replace(tt,nt),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||ut.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&ut.error(e[0]),e},PSEUDO:function(e){var t,n=!e[5]&&e[2];return G.CHILD.test(e[0])?null:(e[4]?e[2]=e[4]:n&&Y.test(n)&&(t=gt(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(tt,nt).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=C[e+" "];return t||(t=RegExp("(^|"+R+")"+e+"("+R+"|$)"))&&C(e,function(e){return t.test("string"==typeof e.className&&e.className||typeof e.getAttribute!==j&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=ut.attr(r,e);return null==i?"!="===t:t?(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i+" ").indexOf(n)>-1:"|="===t?i===n||i.slice(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),s="last"!==e.slice(-4),a="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,u){var l,c,f,p,h,d,g=o!==s?"nextSibling":"previousSibling",m=t.parentNode,v=a&&t.nodeName.toLowerCase(),x=!u&&!a;if(m){if(o){while(g){f=t;while(f=f[g])if(a?f.nodeName.toLowerCase()===v:1===f.nodeType)return!1;d=g="only"===e&&!d&&"nextSibling"}return!0}if(d=[s?m.firstChild:m.lastChild],s&&x){c=m[y]||(m[y]={}),l=c[e]||[],h=l[0]===w&&l[1],p=l[0]===w&&l[2],f=h&&m.childNodes[h];while(f=++h&&f&&f[g]||(p=h=0)||d.pop())if(1===f.nodeType&&++p&&f===t){c[e]=[w,h,p];break}}else if(x&&(l=(t[y]||(t[y]={}))[e])&&l[0]===w)p=l[1];else while(f=++h&&f&&f[g]||(p=h=0)||d.pop())if((a?f.nodeName.toLowerCase()===v:1===f.nodeType)&&++p&&(x&&((f[y]||(f[y]={}))[e]=[w,p]),f===t))break;return p-=i,p===r||0===p%r&&p/r>=0}}},PSEUDO:function(e,t){var n,i=r.pseudos[e]||r.setFilters[e.toLowerCase()]||ut.error("unsupported pseudo: "+e);return i[y]?i(t):i.length>1?(n=[e,e,"",t],r.setFilters.hasOwnProperty(e.toLowerCase())?st(function(e,n){var r,o=i(e,t),s=o.length;while(s--)r=F.call(e,o[s]),e[r]=!(n[r]=o[s])}):function(e){return i(e,0,n)}):i}},pseudos:{not:st(function(e){var t=[],n=[],r=s(e.replace(I,"$1"));return r[y]?st(function(e,t,n,i){var o,s=r(e,null,i,[]),a=e.length;while(a--)(o=s[a])&&(e[a]=!(t[a]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:st(function(e){return function(t){return ut(e,t).length>0}}),contains:st(function(e){return function(t){return(t.textContent||t.innerText||i(t)).indexOf(e)>-1}}),lang:st(function(e){return V.test(e||"")||ut.error("unsupported lang: "+e),e=e.replace(tt,nt).toLowerCase(),function(t){var n;do if(n=p?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===f},focus:function(e){return e===c.activeElement&&(!c.hasFocus||c.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!r.pseudos.empty(e)},header:function(e){return Z.test(e.nodeName)},input:function(e){return K.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||t.toLowerCase()===e.type)},first:dt(function(){return[0]}),last:dt(function(e,t){return[t-1]}),eq:dt(function(e,t,n){return[0>n?n+t:n]}),even:dt(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:dt(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:dt(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:dt(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}};for(t in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})r.pseudos[t]=pt(t);for(t in{submit:!0,reset:!0})r.pseudos[t]=ht(t);function gt(e,t){var n,i,o,s,a,u,l,c=k[e+" "];if(c)return t?0:c.slice(0);a=e,u=[],l=r.preFilter;while(a){(!n||(i=z.exec(a)))&&(i&&(a=a.slice(i[0].length)||a),u.push(o=[])),n=!1,(i=_.exec(a))&&(n=i.shift(),o.push({value:n,type:i[0].replace(I," ")}),a=a.slice(n.length));for(s in r.filter)!(i=G[s].exec(a))||l[s]&&!(i=l[s](i))||(n=i.shift(),o.push({value:n,type:s,matches:i}),a=a.slice(n.length));if(!n)break}return t?a.length:a?ut.error(e):k(e,u).slice(0)}function mt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function yt(e,t,r){var i=t.dir,o=r&&"parentNode"===i,s=T++;return t.first?function(t,n,r){while(t=t[i])if(1===t.nodeType||o)return e(t,n,r)}:function(t,r,a){var u,l,c,f=w+" "+s;if(a){while(t=t[i])if((1===t.nodeType||o)&&e(t,r,a))return!0}else while(t=t[i])if(1===t.nodeType||o)if(c=t[y]||(t[y]={}),(l=c[i])&&l[0]===f){if((u=l[1])===!0||u===n)return u===!0}else if(l=c[i]=[f],l[1]=e(t,r,a)||n,l[1]===!0)return!0}}function vt(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function xt(e,t,n,r,i){var o,s=[],a=0,u=e.length,l=null!=t;for(;u>a;a++)(o=e[a])&&(!n||n(o,r,i))&&(s.push(o),l&&t.push(a));return s}function bt(e,t,n,r,i,o){return r&&!r[y]&&(r=bt(r)),i&&!i[y]&&(i=bt(i,o)),st(function(o,s,a,u){var l,c,f,p=[],h=[],d=s.length,g=o||Ct(t||"*",a.nodeType?[a]:a,[]),m=!e||!o&&t?g:xt(g,p,e,a,u),y=n?i||(o?e:d||r)?[]:s:m;if(n&&n(m,y,a,u),r){l=xt(y,h),r(l,[],a,u),c=l.length;while(c--)(f=l[c])&&(y[h[c]]=!(m[h[c]]=f))}if(o){if(i||e){if(i){l=[],c=y.length;while(c--)(f=y[c])&&l.push(m[c]=f);i(null,y=[],l,u)}c=y.length;while(c--)(f=y[c])&&(l=i?F.call(o,f):p[c])>-1&&(o[l]=!(s[l]=f))}}else y=xt(y===s?y.splice(d,y.length):y),i?i(null,s,y,u):H.apply(s,y)})}function wt(e){var t,n,i,o=e.length,s=r.relative[e[0].type],u=s||r.relative[" "],l=s?1:0,c=yt(function(e){return e===t},u,!0),f=yt(function(e){return F.call(t,e)>-1},u,!0),p=[function(e,n,r){return!s&&(r||n!==a)||((t=n).nodeType?c(e,n,r):f(e,n,r))}];for(;o>l;l++)if(n=r.relative[e[l].type])p=[yt(vt(p),n)];else{if(n=r.filter[e[l].type].apply(null,e[l].matches),n[y]){for(i=++l;o>i;i++)if(r.relative[e[i].type])break;return bt(l>1&&vt(p),l>1&&mt(e.slice(0,l-1)).replace(I,"$1"),n,i>l&&wt(e.slice(l,i)),o>i&&wt(e=e.slice(i)),o>i&&mt(e))}p.push(n)}return vt(p)}function Tt(e,t){var i=0,o=t.length>0,s=e.length>0,u=function(u,l,f,p,h){var d,g,m,y=[],v=0,x="0",b=u&&[],T=null!=h,C=a,k=u||s&&r.find.TAG("*",h&&l.parentNode||l),N=w+=null==C?1:Math.random()||.1;for(T&&(a=l!==c&&l,n=i);null!=(d=k[x]);x++){if(s&&d){g=0;while(m=e[g++])if(m(d,l,f)){p.push(d);break}T&&(w=N,n=++i)}o&&((d=!m&&d)&&v--,u&&b.push(d))}if(v+=x,o&&x!==v){g=0;while(m=t[g++])m(b,y,l,f);if(u){if(v>0)while(x--)b[x]||y[x]||(y[x]=L.call(p));y=xt(y)}H.apply(p,y),T&&!u&&y.length>0&&v+t.length>1&&ut.uniqueSort(p)}return T&&(w=N,a=C),b};return o?st(u):u}s=ut.compile=function(e,t){var n,r=[],i=[],o=N[e+" "];if(!o){t||(t=gt(e)),n=t.length;while(n--)o=wt(t[n]),o[y]?r.push(o):i.push(o);o=N(e,Tt(i,r))}return o};function Ct(e,t,n){var r=0,i=t.length;for(;i>r;r++)ut(e,t[r],n);return n}function kt(e,t,n,i){var o,a,u,l,c,f=gt(e);if(!i&&1===f.length){if(a=f[0]=f[0].slice(0),a.length>2&&"ID"===(u=a[0]).type&&9===t.nodeType&&p&&r.relative[a[1].type]){if(t=(r.find.ID(u.matches[0].replace(tt,nt),t)||[])[0],!t)return n;e=e.slice(a.shift().value.length)}o=G.needsContext.test(e)?0:a.length;while(o--){if(u=a[o],r.relative[l=u.type])break;if((c=r.find[l])&&(i=c(u.matches[0].replace(tt,nt),X.test(a[0].type)&&t.parentNode||t))){if(a.splice(o,1),e=i.length&&mt(a),!e)return H.apply(n,i),n;break}}}return s(e,f)(i,t,!p,n,X.test(e)),n}r.pseudos.nth=r.pseudos.eq;function Nt(){}Nt.prototype=r.filters=r.pseudos,r.setFilters=new Nt,b.sortStable=y.split("").sort(S).join("")===y,l(),[0,0].sort(S),b.detectDuplicates=E,at(function(e){if(e.innerHTML="<a href='#'></a>","#"!==e.firstChild.getAttribute("href")){var t="type|href|height|width".split("|"),n=t.length;while(n--)r.attrHandle[t[n]]=ft}}),at(function(e){if(null!=e.getAttribute("disabled")){var t=P.split("|"),n=t.length;while(n--)r.attrHandle[t[n]]=ct}}),x.find=ut,x.expr=ut.selectors,x.expr[":"]=x.expr.pseudos,x.unique=ut.uniqueSort,x.text=ut.getText,x.isXMLDoc=ut.isXML,x.contains=ut.contains}(e);var D={};function A(e){var t=D[e]={};return x.each(e.match(w)||[],function(e,n){t[n]=!0}),t}x.Callbacks=function(e){e="string"==typeof e?D[e]||A(e):x.extend({},e);var t,n,r,i,o,s,a=[],u=!e.once&&[],l=function(f){for(t=e.memory&&f,n=!0,s=i||0,i=0,o=a.length,r=!0;a&&o>s;s++)if(a[s].apply(f[0],f[1])===!1&&e.stopOnFalse){t=!1;break}r=!1,a&&(u?u.length&&l(u.shift()):t?a=[]:c.disable())},c={add:function(){if(a){var n=a.length;(function s(t){x.each(t,function(t,n){var r=x.type(n);"function"===r?e.unique&&c.has(n)||a.push(n):n&&n.length&&"string"!==r&&s(n)})})(arguments),r?o=a.length:t&&(i=n,l(t))}return this},remove:function(){return a&&x.each(arguments,function(e,t){var n;while((n=x.inArray(t,a,n))>-1)a.splice(n,1),r&&(o>=n&&o--,s>=n&&s--)}),this},has:function(e){return e?x.inArray(e,a)>-1:!(!a||!a.length)},empty:function(){return a=[],o=0,this},disable:function(){return a=u=t=undefined,this},disabled:function(){return!a},lock:function(){return u=undefined,t||c.disable(),this},locked:function(){return!u},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],!a||n&&!u||(r?u.push(t):l(t)),this},fire:function(){return c.fireWith(this,arguments),this},fired:function(){return!!n}};return c},x.extend({Deferred:function(e){var t=[["resolve","done",x.Callbacks("once memory"),"resolved"],["reject","fail",x.Callbacks("once memory"),"rejected"],["notify","progress",x.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return x.Deferred(function(n){x.each(t,function(t,o){var s=o[0],a=x.isFunction(e[t])&&e[t];i[o[1]](function(){var e=a&&a.apply(this,arguments);e&&x.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[s+"With"](this===r?n.promise():this,a?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?x.extend(e,r):r}},i={};return r.pipe=r.then,x.each(t,function(e,o){var s=o[2],a=o[3];r[o[1]]=s.add,a&&s.add(function(){n=a},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=s.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=d.call(arguments),r=n.length,i=1!==r||e&&x.isFunction(e.promise)?r:0,o=1===i?e:x.Deferred(),s=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?d.call(arguments):r,n===a?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},a,u,l;if(r>1)for(a=Array(r),u=Array(r),l=Array(r);r>t;t++)n[t]&&x.isFunction(n[t].promise)?n[t].promise().done(s(t,l,n)).fail(o.reject).progress(s(t,u,a)):--i;return i||o.resolveWith(l,n),o.promise()}}),x.support=function(t){var n=o.createElement("input"),r=o.createDocumentFragment(),i=o.createElement("div"),s=o.createElement("select"),a=s.appendChild(o.createElement("option"));return n.type?(n.type="checkbox",t.checkOn=""!==n.value,t.optSelected=a.selected,t.reliableMarginRight=!0,t.boxSizingReliable=!0,t.pixelPosition=!1,n.checked=!0,t.noCloneChecked=n.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!a.disabled,n=o.createElement("input"),n.value="t",n.type="radio",t.radioValue="t"===n.value,n.setAttribute("checked","t"),n.setAttribute("name","t"),r.appendChild(n),t.checkClone=r.cloneNode(!0).cloneNode(!0).lastChild.checked,t.focusinBubbles="onfocusin"in e,i.style.backgroundClip="content-box",i.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===i.style.backgroundClip,x(function(){var n,r,s="padding:0;margin:0;border:0;display:block;-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box",a=o.getElementsByTagName("body")[0];a&&(n=o.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",a.appendChild(n).appendChild(i),i.innerHTML="",i.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%",x.swap(a,null!=a.style.zoom?{zoom:1}:{},function(){t.boxSizing=4===i.offsetWidth}),e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(i,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(i,null)||{width:"4px"}).width,r=i.appendChild(o.createElement("div")),r.style.cssText=i.style.cssText=s,r.style.marginRight=r.style.width="0",i.style.width="1px",t.reliableMarginRight=!parseFloat((e.getComputedStyle(r,null)||{}).marginRight)),a.removeChild(n))}),t):t}({});var L,q,H=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,O=/([A-Z])/g;function F(){Object.defineProperty(this.cache={},0,{get:function(){return{}}}),this.expando=x.expando+Math.random()}F.uid=1,F.accepts=function(e){return e.nodeType?1===e.nodeType||9===e.nodeType:!0},F.prototype={key:function(e){if(!F.accepts(e))return 0;var t={},n=e[this.expando];if(!n){n=F.uid++;try{t[this.expando]={value:n},Object.defineProperties(e,t)}catch(r){t[this.expando]=n,x.extend(e,t)}}return this.cache[n]||(this.cache[n]={}),n},set:function(e,t,n){var r,i=this.key(e),o=this.cache[i];if("string"==typeof t)o[t]=n;else if(x.isEmptyObject(o))this.cache[i]=t;else for(r in t)o[r]=t[r]},get:function(e,t){var n=this.cache[this.key(e)];return t===undefined?n:n[t]},access:function(e,t,n){return t===undefined||t&&"string"==typeof t&&n===undefined?this.get(e,t):(this.set(e,t,n),n!==undefined?n:t)},remove:function(e,t){var n,r,i=this.key(e),o=this.cache[i];if(t===undefined)this.cache[i]={};else{x.isArray(t)?r=t.concat(t.map(x.camelCase)):t in o?r=[t]:(r=x.camelCase(t),r=r in o?[r]:r.match(w)||[]),n=r.length;while(n--)delete o[r[n]]}},hasData:function(e){return!x.isEmptyObject(this.cache[e[this.expando]]||{})},discard:function(e){delete this.cache[this.key(e)]}},L=new F,q=new F,x.extend({acceptData:F.accepts,hasData:function(e){return L.hasData(e)||q.hasData(e)},data:function(e,t,n){return L.access(e,t,n)},removeData:function(e,t){L.remove(e,t)},_data:function(e,t,n){return q.access(e,t,n)},_removeData:function(e,t){q.remove(e,t)}}),x.fn.extend({data:function(e,t){var n,r,i=this[0],o=0,s=null;if(e===undefined){if(this.length&&(s=L.get(i),1===i.nodeType&&!q.get(i,"hasDataAttrs"))){for(n=i.attributes;n.length>o;o++)r=n[o].name,0===r.indexOf("data-")&&(r=x.camelCase(r.substring(5)),P(i,r,s[r]));q.set(i,"hasDataAttrs",!0)}return s}return"object"==typeof e?this.each(function(){L.set(this,e)}):x.access(this,function(t){var n,r=x.camelCase(e);if(i&&t===undefined){if(n=L.get(i,e),n!==undefined)return n;if(n=L.get(i,r),n!==undefined)return n;if(n=P(i,r,undefined),n!==undefined)return n}else this.each(function(){var n=L.get(this,r);L.set(this,r,t),-1!==e.indexOf("-")&&n!==undefined&&L.set(this,e,t)})},null,t,arguments.length>1,null,!0)},removeData:function(e){return this.each(function(){L.remove(this,e)})}});function P(e,t,n){var r;if(n===undefined&&1===e.nodeType)if(r="data-"+t.replace(O,"-$1").toLowerCase(),n=e.getAttribute(r),"string"==typeof n){try{n="true"===n?!0:"false"===n?!1:"null"===n?null:+n+""===n?+n:H.test(n)?JSON.parse(n):n}catch(i){}L.set(e,t,n)}else n=undefined;return n}x.extend({queue:function(e,t,n){var r;return e?(t=(t||"fx")+"queue",r=q.get(e,t),n&&(!r||x.isArray(n)?r=q.access(e,t,x.makeArray(n)):r.push(n)),r||[]):undefined},dequeue:function(e,t){t=t||"fx";var n=x.queue(e,t),r=n.length,i=n.shift(),o=x._queueHooks(e,t),s=function(){x.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),o.cur=i,i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,s,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return q.get(e,n)||q.access(e,n,{empty:x.Callbacks("once memory").add(function(){q.remove(e,[t+"queue",n])})})}}),x.fn.extend({queue:function(e,t){var n=2;return"string"!=typeof e&&(t=e,e="fx",n--),n>arguments.length?x.queue(this[0],e):t===undefined?this:this.each(function(){var n=x.queue(this,e,t); -x._queueHooks(this,e),"fx"===e&&"inprogress"!==n[0]&&x.dequeue(this,e)})},dequeue:function(e){return this.each(function(){x.dequeue(this,e)})},delay:function(e,t){return e=x.fx?x.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,t){var n,r=1,i=x.Deferred(),o=this,s=this.length,a=function(){--r||i.resolveWith(o,[o])};"string"!=typeof e&&(t=e,e=undefined),e=e||"fx";while(s--)n=q.get(o[s],e+"queueHooks"),n&&n.empty&&(r++,n.empty.add(a));return a(),i.promise(t)}});var R,M,W=/[\t\r\n]/g,$=/\r/g,B=/^(?:input|select|textarea|button)$/i;x.fn.extend({attr:function(e,t){return x.access(this,x.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){x.removeAttr(this,e)})},prop:function(e,t){return x.access(this,x.prop,e,t,arguments.length>1)},removeProp:function(e){return this.each(function(){delete this[x.propFix[e]||e]})},addClass:function(e){var t,n,r,i,o,s=0,a=this.length,u="string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).addClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];a>s;s++)if(n=this[s],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(W," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=x.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,s=0,a=this.length,u=0===arguments.length||"string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).removeClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];a>s;s++)if(n=this[s],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(W," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?x.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e,i="boolean"==typeof t;return x.isFunction(e)?this.each(function(n){x(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var o,s=0,a=x(this),u=t,l=e.match(w)||[];while(o=l[s++])u=i?u:!a.hasClass(o),a[u?"addClass":"removeClass"](o)}else(n===r||"boolean"===n)&&(this.className&&q.set(this,"__className__",this.className),this.className=this.className||e===!1?"":q.get(this,"__className__")||"")})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(W," ").indexOf(t)>=0)return!0;return!1},val:function(e){var t,n,r,i=this[0];{if(arguments.length)return r=x.isFunction(e),this.each(function(n){var i,o=x(this);1===this.nodeType&&(i=r?e.call(this,n,o.val()):e,null==i?i="":"number"==typeof i?i+="":x.isArray(i)&&(i=x.map(i,function(e){return null==e?"":e+""})),t=x.valHooks[this.type]||x.valHooks[this.nodeName.toLowerCase()],t&&"set"in t&&t.set(this,i,"value")!==undefined||(this.value=i))});if(i)return t=x.valHooks[i.type]||x.valHooks[i.nodeName.toLowerCase()],t&&"get"in t&&(n=t.get(i,"value"))!==undefined?n:(n=i.value,"string"==typeof n?n.replace($,""):null==n?"":n)}}}),x.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,s=o?null:[],a=o?i+1:r.length,u=0>i?a:o?i:0;for(;a>u;u++)if(n=r[u],!(!n.selected&&u!==i||(x.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&x.nodeName(n.parentNode,"optgroup"))){if(t=x(n).val(),o)return t;s.push(t)}return s},set:function(e,t){var n,r,i=e.options,o=x.makeArray(t),s=i.length;while(s--)r=i[s],(r.selected=x.inArray(x(r).val(),o)>=0)&&(n=!0);return n||(e.selectedIndex=-1),o}}},attr:function(e,t,n){var i,o,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return typeof e.getAttribute===r?x.prop(e,t,n):(1===s&&x.isXMLDoc(e)||(t=t.toLowerCase(),i=x.attrHooks[t]||(x.expr.match.boolean.test(t)?M:R)),n===undefined?i&&"get"in i&&null!==(o=i.get(e,t))?o:(o=x.find.attr(e,t),null==o?undefined:o):null!==n?i&&"set"in i&&(o=i.set(e,n,t))!==undefined?o:(e.setAttribute(t,n+""),n):(x.removeAttr(e,t),undefined))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(w);if(o&&1===e.nodeType)while(n=o[i++])r=x.propFix[n]||n,x.expr.match.boolean.test(n)&&(e[r]=!1),e.removeAttribute(n)},attrHooks:{type:{set:function(e,t){if(!x.support.radioValue&&"radio"===t&&x.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},propFix:{"for":"htmlFor","class":"className"},prop:function(e,t,n){var r,i,o,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return o=1!==s||!x.isXMLDoc(e),o&&(t=x.propFix[t]||t,i=x.propHooks[t]),n!==undefined?i&&"set"in i&&(r=i.set(e,n,t))!==undefined?r:e[t]=n:i&&"get"in i&&null!==(r=i.get(e,t))?r:e[t]},propHooks:{tabIndex:{get:function(e){return e.hasAttribute("tabindex")||B.test(e.nodeName)||e.href?e.tabIndex:-1}}}}),M={set:function(e,t,n){return t===!1?x.removeAttr(e,n):e.setAttribute(n,n),n}},x.each(x.expr.match.boolean.source.match(/\w+/g),function(e,t){var n=x.expr.attrHandle[t]||x.find.attr;x.expr.attrHandle[t]=function(e,t,r){var i=x.expr.attrHandle[t],o=r?undefined:(x.expr.attrHandle[t]=undefined)!=n(e,t,r)?t.toLowerCase():null;return x.expr.attrHandle[t]=i,o}}),x.support.optSelected||(x.propHooks.selected={get:function(e){var t=e.parentNode;return t&&t.parentNode&&t.parentNode.selectedIndex,null}}),x.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){x.propFix[this.toLowerCase()]=this}),x.each(["radio","checkbox"],function(){x.valHooks[this]={set:function(e,t){return x.isArray(t)?e.checked=x.inArray(x(e).val(),t)>=0:undefined}},x.support.checkOn||(x.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var I=/^key/,z=/^(?:mouse|contextmenu)|click/,_=/^(?:focusinfocus|focusoutblur)$/,X=/^([^.]*)(?:\.(.+)|)$/;function U(){return!0}function Y(){return!1}function V(){try{return o.activeElement}catch(e){}}x.event={global:{},add:function(e,t,n,i,o){var s,a,u,l,c,f,p,h,d,g,m,y=q.get(e);if(y){n.handler&&(s=n,n=s.handler,o=s.selector),n.guid||(n.guid=x.guid++),(l=y.events)||(l=y.events={}),(a=y.handle)||(a=y.handle=function(e){return typeof x===r||e&&x.event.triggered===e.type?undefined:x.event.dispatch.apply(a.elem,arguments)},a.elem=e),t=(t||"").match(w)||[""],c=t.length;while(c--)u=X.exec(t[c])||[],d=m=u[1],g=(u[2]||"").split(".").sort(),d&&(p=x.event.special[d]||{},d=(o?p.delegateType:p.bindType)||d,p=x.event.special[d]||{},f=x.extend({type:d,origType:m,data:i,handler:n,guid:n.guid,selector:o,needsContext:o&&x.expr.match.needsContext.test(o),namespace:g.join(".")},s),(h=l[d])||(h=l[d]=[],h.delegateCount=0,p.setup&&p.setup.call(e,i,g,a)!==!1||e.addEventListener&&e.addEventListener(d,a,!1)),p.add&&(p.add.call(e,f),f.handler.guid||(f.handler.guid=n.guid)),o?h.splice(h.delegateCount++,0,f):h.push(f),x.event.global[d]=!0);e=null}},remove:function(e,t,n,r,i){var o,s,a,u,l,c,f,p,h,d,g,m=q.hasData(e)&&q.get(e);if(m&&(u=m.events)){t=(t||"").match(w)||[""],l=t.length;while(l--)if(a=X.exec(t[l])||[],h=g=a[1],d=(a[2]||"").split(".").sort(),h){f=x.event.special[h]||{},h=(r?f.delegateType:f.bindType)||h,p=u[h]||[],a=a[2]&&RegExp("(^|\\.)"+d.join("\\.(?:.*\\.|)")+"(\\.|$)"),s=o=p.length;while(o--)c=p[o],!i&&g!==c.origType||n&&n.guid!==c.guid||a&&!a.test(c.namespace)||r&&r!==c.selector&&("**"!==r||!c.selector)||(p.splice(o,1),c.selector&&p.delegateCount--,f.remove&&f.remove.call(e,c));s&&!p.length&&(f.teardown&&f.teardown.call(e,d,m.handle)!==!1||x.removeEvent(e,h,m.handle),delete u[h])}else for(h in u)x.event.remove(e,h+t[l],n,r,!0);x.isEmptyObject(u)&&(delete m.handle,q.remove(e,"events"))}},trigger:function(t,n,r,i){var s,a,u,l,c,f,p,h=[r||o],d=y.call(t,"type")?t.type:t,g=y.call(t,"namespace")?t.namespace.split("."):[];if(a=u=r=r||o,3!==r.nodeType&&8!==r.nodeType&&!_.test(d+x.event.triggered)&&(d.indexOf(".")>=0&&(g=d.split("."),d=g.shift(),g.sort()),c=0>d.indexOf(":")&&"on"+d,t=t[x.expando]?t:new x.Event(d,"object"==typeof t&&t),t.isTrigger=i?2:3,t.namespace=g.join("."),t.namespace_re=t.namespace?RegExp("(^|\\.)"+g.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,t.result=undefined,t.target||(t.target=r),n=null==n?[t]:x.makeArray(n,[t]),p=x.event.special[d]||{},i||!p.trigger||p.trigger.apply(r,n)!==!1)){if(!i&&!p.noBubble&&!x.isWindow(r)){for(l=p.delegateType||d,_.test(l+d)||(a=a.parentNode);a;a=a.parentNode)h.push(a),u=a;u===(r.ownerDocument||o)&&h.push(u.defaultView||u.parentWindow||e)}s=0;while((a=h[s++])&&!t.isPropagationStopped())t.type=s>1?l:p.bindType||d,f=(q.get(a,"events")||{})[t.type]&&q.get(a,"handle"),f&&f.apply(a,n),f=c&&a[c],f&&x.acceptData(a)&&f.apply&&f.apply(a,n)===!1&&t.preventDefault();return t.type=d,i||t.isDefaultPrevented()||p._default&&p._default.apply(h.pop(),n)!==!1||!x.acceptData(r)||c&&x.isFunction(r[d])&&!x.isWindow(r)&&(u=r[c],u&&(r[c]=null),x.event.triggered=d,r[d](),x.event.triggered=undefined,u&&(r[c]=u)),t.result}},dispatch:function(e){e=x.event.fix(e);var t,n,r,i,o,s=[],a=d.call(arguments),u=(q.get(this,"events")||{})[e.type]||[],l=x.event.special[e.type]||{};if(a[0]=e,e.delegateTarget=this,!l.preDispatch||l.preDispatch.call(this,e)!==!1){s=x.event.handlers.call(this,e,u),t=0;while((i=s[t++])&&!e.isPropagationStopped()){e.currentTarget=i.elem,n=0;while((o=i.handlers[n++])&&!e.isImmediatePropagationStopped())(!e.namespace_re||e.namespace_re.test(o.namespace))&&(e.handleObj=o,e.data=o.data,r=((x.event.special[o.origType]||{}).handle||o.handler).apply(i.elem,a),r!==undefined&&(e.result=r)===!1&&(e.preventDefault(),e.stopPropagation()))}return l.postDispatch&&l.postDispatch.call(this,e),e.result}},handlers:function(e,t){var n,r,i,o,s=[],a=t.delegateCount,u=e.target;if(a&&u.nodeType&&(!e.button||"click"!==e.type))for(;u!==this;u=u.parentNode||this)if(u.disabled!==!0||"click"!==e.type){for(r=[],n=0;a>n;n++)o=t[n],i=o.selector+" ",r[i]===undefined&&(r[i]=o.needsContext?x(i,this).index(u)>=0:x.find(i,this,null,[u]).length),r[i]&&r.push(o);r.length&&s.push({elem:u,handlers:r})}return t.length>a&&s.push({elem:this,handlers:t.slice(a)}),s},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,t){var n,r,i,s=t.button;return null==e.pageX&&null!=t.clientX&&(n=e.target.ownerDocument||o,r=n.documentElement,i=n.body,e.pageX=t.clientX+(r&&r.scrollLeft||i&&i.scrollLeft||0)-(r&&r.clientLeft||i&&i.clientLeft||0),e.pageY=t.clientY+(r&&r.scrollTop||i&&i.scrollTop||0)-(r&&r.clientTop||i&&i.clientTop||0)),e.which||s===undefined||(e.which=1&s?1:2&s?3:4&s?2:0),e}},fix:function(e){if(e[x.expando])return e;var t,n,r,i=e.type,o=e,s=this.fixHooks[i];s||(this.fixHooks[i]=s=z.test(i)?this.mouseHooks:I.test(i)?this.keyHooks:{}),r=s.props?this.props.concat(s.props):this.props,e=new x.Event(o),t=r.length;while(t--)n=r[t],e[n]=o[n];return 3===e.target.nodeType&&(e.target=e.target.parentNode),s.filter?s.filter(e,o):e},special:{load:{noBubble:!0},focus:{trigger:function(){return this!==V()&&this.focus?(this.focus(),!1):undefined},delegateType:"focusin"},blur:{trigger:function(){return this===V()&&this.blur?(this.blur(),!1):undefined},delegateType:"focusout"},click:{trigger:function(){return"checkbox"===this.type&&this.click&&x.nodeName(this,"input")?(this.click(),!1):undefined},_default:function(e){return x.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){e.result!==undefined&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=x.extend(new x.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?x.event.trigger(i,null,t):x.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},x.removeEvent=function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)},x.Event=function(e,t){return this instanceof x.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.getPreventDefault&&e.getPreventDefault()?U:Y):this.type=e,t&&x.extend(this,t),this.timeStamp=e&&e.timeStamp||x.now(),this[x.expando]=!0,undefined):new x.Event(e,t)},x.Event.prototype={isDefaultPrevented:Y,isPropagationStopped:Y,isImmediatePropagationStopped:Y,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=U,e&&e.preventDefault&&e.preventDefault()},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=U,e&&e.stopPropagation&&e.stopPropagation()},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=U,this.stopPropagation()}},x.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){x.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj;return(!i||i!==r&&!x.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),x.support.focusinBubbles||x.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){x.event.simulate(t,e.target,x.event.fix(e),!0)};x.event.special[t]={setup:function(){0===n++&&o.addEventListener(e,r,!0)},teardown:function(){0===--n&&o.removeEventListener(e,r,!0)}}}),x.fn.extend({on:function(e,t,n,r,i){var o,s;if("object"==typeof e){"string"!=typeof t&&(n=n||t,t=undefined);for(s in e)this.on(s,t,n,e[s],i);return this}if(null==n&&null==r?(r=t,n=t=undefined):null==r&&("string"==typeof t?(r=n,n=undefined):(r=n,n=t,t=undefined)),r===!1)r=Y;else if(!r)return this;return 1===i&&(o=r,r=function(e){return x().off(e),o.apply(this,arguments)},r.guid=o.guid||(o.guid=x.guid++)),this.each(function(){x.event.add(this,e,r,n,t)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,t,n){var r,i;if(e&&e.preventDefault&&e.handleObj)return r=e.handleObj,x(e.delegateTarget).off(r.namespace?r.origType+"."+r.namespace:r.origType,r.selector,r.handler),this;if("object"==typeof e){for(i in e)this.off(i,t,e[i]);return this}return(t===!1||"function"==typeof t)&&(n=t,t=undefined),n===!1&&(n=Y),this.each(function(){x.event.remove(this,e,n,t)})},trigger:function(e,t){return this.each(function(){x.event.trigger(e,t,this)})},triggerHandler:function(e,t){var n=this[0];return n?x.event.trigger(e,t,n,!0):undefined}});var G=/^.[^:#\[\.,]*$/,J=x.expr.match.needsContext,Q={children:!0,contents:!0,next:!0,prev:!0};x.fn.extend({find:function(e){var t,n,r,i=this.length;if("string"!=typeof e)return t=this,this.pushStack(x(e).filter(function(){for(r=0;i>r;r++)if(x.contains(t[r],this))return!0}));for(n=[],r=0;i>r;r++)x.find(e,this[r],n);return n=this.pushStack(i>1?x.unique(n):n),n.selector=(this.selector?this.selector+" ":"")+e,n},has:function(e){var t=x(e,this),n=t.length;return this.filter(function(){var e=0;for(;n>e;e++)if(x.contains(this,t[e]))return!0})},not:function(e){return this.pushStack(Z(this,e||[],!0))},filter:function(e){return this.pushStack(Z(this,e||[],!1))},is:function(e){return!!e&&("string"==typeof e?J.test(e)?x(e,this.context).index(this[0])>=0:x.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,o=[],s=J.test(e)||"string"!=typeof e?x(e,t||this.context):0;for(;i>r;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(11>n.nodeType&&(s?s.index(n)>-1:1===n.nodeType&&x.find.matchesSelector(n,e))){n=o.push(n);break}return this.pushStack(o.length>1?x.unique(o):o)},index:function(e){return e?"string"==typeof e?g.call(x(e),this[0]):g.call(this,e.jquery?e[0]:e):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){var n="string"==typeof e?x(e,t):x.makeArray(e&&e.nodeType?[e]:e),r=x.merge(this.get(),n);return this.pushStack(x.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}});function K(e,t){while((e=e[t])&&1!==e.nodeType);return e}x.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return x.dir(e,"parentNode")},parentsUntil:function(e,t,n){return x.dir(e,"parentNode",n)},next:function(e){return K(e,"nextSibling")},prev:function(e){return K(e,"previousSibling")},nextAll:function(e){return x.dir(e,"nextSibling")},prevAll:function(e){return x.dir(e,"previousSibling")},nextUntil:function(e,t,n){return x.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return x.dir(e,"previousSibling",n)},siblings:function(e){return x.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return x.sibling(e.firstChild)},contents:function(e){return x.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:x.merge([],e.childNodes)}},function(e,t){x.fn[e]=function(n,r){var i=x.map(this,t,n);return"Until"!==e.slice(-5)&&(r=n),r&&"string"==typeof r&&(i=x.filter(r,i)),this.length>1&&(Q[e]||x.unique(i),"p"===e[0]&&i.reverse()),this.pushStack(i)}}),x.extend({filter:function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?x.find.matchesSelector(r,e)?[r]:[]:x.find.matches(e,x.grep(t,function(e){return 1===e.nodeType}))},dir:function(e,t,n){var r=[],i=n!==undefined;while((e=e[t])&&9!==e.nodeType)if(1===e.nodeType){if(i&&x(e).is(n))break;r.push(e)}return r},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});function Z(e,t,n){if(x.isFunction(t))return x.grep(e,function(e,r){return!!t.call(e,r,e)!==n});if(t.nodeType)return x.grep(e,function(e){return e===t!==n});if("string"==typeof t){if(G.test(t))return x.filter(t,e,n);t=x.filter(t,e)}return x.grep(e,function(e){return g.call(t,e)>=0!==n})}var et=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,tt=/<([\w:]+)/,nt=/<|&#?\w+;/,rt=/<(?:script|style|link)/i,it=/^(?:checkbox|radio)$/i,ot=/checked\s*(?:[^=]|=\s*.checked.)/i,st=/^$|\/(?:java|ecma)script/i,at=/^true\/(.*)/,ut=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,lt={option:[1,"<select multiple='multiple'>","</select>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};lt.optgroup=lt.option,lt.tbody=lt.tfoot=lt.colgroup=lt.caption=lt.col=lt.thead,lt.th=lt.td,x.fn.extend({text:function(e){return x.access(this,function(e){return e===undefined?x.text(this):this.empty().append((this[0]&&this[0].ownerDocument||o).createTextNode(e))},null,e,arguments.length)},append:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=ct(this,e);t.appendChild(e)}})},prepend:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=ct(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){var n,r=e?x.filter(e,this):this,i=0;for(;null!=(n=r[i]);i++)t||1!==n.nodeType||x.cleanData(gt(n)),n.parentNode&&(t&&x.contains(n.ownerDocument,n)&&ht(gt(n,"script")),n.parentNode.removeChild(n));return this},empty:function(){var e,t=0;for(;null!=(e=this[t]);t++)1===e.nodeType&&(x.cleanData(gt(e,!1)),e.textContent="");return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return x.clone(this,e,t)})},html:function(e){return x.access(this,function(e){var t=this[0]||{},n=0,r=this.length;if(e===undefined&&1===t.nodeType)return t.innerHTML;if("string"==typeof e&&!rt.test(e)&&!lt[(tt.exec(e)||["",""])[1].toLowerCase()]){e=e.replace(et,"<$1></$2>");try{for(;r>n;n++)t=this[n]||{},1===t.nodeType&&(x.cleanData(gt(t,!1)),t.innerHTML=e);t=0}catch(i){}}t&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=x.map(this,function(e){return[e.nextSibling,e.parentNode]}),t=0;return this.domManip(arguments,function(n){var r=e[t++],i=e[t++];i&&(x(this).remove(),i.insertBefore(n,r))},!0),t?this:this.remove()},detach:function(e){return this.remove(e,!0)},domManip:function(e,t,n){e=p.apply([],e);var r,i,o,s,a,u,l=0,c=this.length,f=this,h=c-1,d=e[0],g=x.isFunction(d);if(g||!(1>=c||"string"!=typeof d||x.support.checkClone)&&ot.test(d))return this.each(function(r){var i=f.eq(r);g&&(e[0]=d.call(this,r,i.html())),i.domManip(e,t,n)});if(c&&(r=x.buildFragment(e,this[0].ownerDocument,!1,!n&&this),i=r.firstChild,1===r.childNodes.length&&(r=i),i)){for(o=x.map(gt(r,"script"),ft),s=o.length;c>l;l++)a=r,l!==h&&(a=x.clone(a,!0,!0),s&&x.merge(o,gt(a,"script"))),t.call(this[l],a,l);if(s)for(u=o[o.length-1].ownerDocument,x.map(o,pt),l=0;s>l;l++)a=o[l],st.test(a.type||"")&&!q.access(a,"globalEval")&&x.contains(u,a)&&(a.src?x._evalUrl(a.src):x.globalEval(a.textContent.replace(ut,"")))}return this}}),x.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){x.fn[e]=function(e){var n,r=[],i=x(e),o=i.length-1,s=0;for(;o>=s;s++)n=s===o?this:this.clone(!0),x(i[s])[t](n),h.apply(r,n.get());return this.pushStack(r)}}),x.extend({clone:function(e,t,n){var r,i,o,s,a=e.cloneNode(!0),u=x.contains(e.ownerDocument,e);if(!(x.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||x.isXMLDoc(e)))for(s=gt(a),o=gt(e),r=0,i=o.length;i>r;r++)mt(o[r],s[r]);if(t)if(n)for(o=o||gt(e),s=s||gt(a),r=0,i=o.length;i>r;r++)dt(o[r],s[r]);else dt(e,a);return s=gt(a,"script"),s.length>0&&ht(s,!u&>(e,"script")),a},buildFragment:function(e,t,n,r){var i,o,s,a,u,l,c=0,f=e.length,p=t.createDocumentFragment(),h=[];for(;f>c;c++)if(i=e[c],i||0===i)if("object"===x.type(i))x.merge(h,i.nodeType?[i]:i);else if(nt.test(i)){o=o||p.appendChild(t.createElement("div")),s=(tt.exec(i)||["",""])[1].toLowerCase(),a=lt[s]||lt._default,o.innerHTML=a[1]+i.replace(et,"<$1></$2>")+a[2],l=a[0];while(l--)o=o.firstChild;x.merge(h,o.childNodes),o=p.firstChild,o.textContent=""}else h.push(t.createTextNode(i));p.textContent="",c=0;while(i=h[c++])if((!r||-1===x.inArray(i,r))&&(u=x.contains(i.ownerDocument,i),o=gt(p.appendChild(i),"script"),u&&ht(o),n)){l=0;while(i=o[l++])st.test(i.type||"")&&n.push(i)}return p},cleanData:function(e){var t,n,r,i=e.length,o=0,s=x.event.special;for(;i>o;o++){if(n=e[o],x.acceptData(n)&&(t=q.access(n)))for(r in t.events)s[r]?x.event.remove(n,r):x.removeEvent(n,r,t.handle);L.discard(n),q.discard(n)}},_evalUrl:function(e){return x.ajax({url:e,type:"GET",dataType:"text",async:!1,global:!1,success:x.globalEval})}});function ct(e,t){return x.nodeName(e,"table")&&x.nodeName(1===t.nodeType?t:t.firstChild,"tr")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function ft(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function pt(e){var t=at.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function ht(e,t){var n=e.length,r=0;for(;n>r;r++)q.set(e[r],"globalEval",!t||q.get(t[r],"globalEval"))}function dt(e,t){var n,r,i,o,s,a,u,l;if(1===t.nodeType){if(q.hasData(e)&&(o=q.access(e),s=x.extend({},o),l=o.events,q.set(t,s),l)){delete s.handle,s.events={};for(i in l)for(n=0,r=l[i].length;r>n;n++)x.event.add(t,i,l[i][n])}L.hasData(e)&&(a=L.access(e),u=x.extend({},a),L.set(t,u))}}function gt(e,t){var n=e.getElementsByTagName?e.getElementsByTagName(t||"*"):e.querySelectorAll?e.querySelectorAll(t||"*"):[];return t===undefined||t&&x.nodeName(e,t)?x.merge([e],n):n}function mt(e,t){var n=t.nodeName.toLowerCase();"input"===n&&it.test(e.type)?t.checked=e.checked:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}x.fn.extend({wrapAll:function(e){var t;return x.isFunction(e)?this.each(function(t){x(this).wrapAll(e.call(this,t))}):(this[0]&&(t=x(e,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstElementChild)e=e.firstElementChild;return e}).append(this)),this)},wrapInner:function(e){return x.isFunction(e)?this.each(function(t){x(this).wrapInner(e.call(this,t))}):this.each(function(){var t=x(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=x.isFunction(e);return this.each(function(n){x(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){x.nodeName(this,"body")||x(this).replaceWith(this.childNodes)}).end()}});var yt,vt,xt=/^(none|table(?!-c[ea]).+)/,bt=/^margin/,wt=RegExp("^("+b+")(.*)$","i"),Tt=RegExp("^("+b+")(?!px)[a-z%]+$","i"),Ct=RegExp("^([+-])=("+b+")","i"),kt={BODY:"block"},Nt={position:"absolute",visibility:"hidden",display:"block"},Et={letterSpacing:0,fontWeight:400},St=["Top","Right","Bottom","Left"],jt=["Webkit","O","Moz","ms"];function Dt(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=jt.length;while(i--)if(t=jt[i]+n,t in e)return t;return r}function At(e,t){return e=t||e,"none"===x.css(e,"display")||!x.contains(e.ownerDocument,e)}function Lt(t){return e.getComputedStyle(t,null)}function qt(e,t){var n,r,i,o=[],s=0,a=e.length;for(;a>s;s++)r=e[s],r.style&&(o[s]=q.get(r,"olddisplay"),n=r.style.display,t?(o[s]||"none"!==n||(r.style.display=""),""===r.style.display&&At(r)&&(o[s]=q.access(r,"olddisplay",Pt(r.nodeName)))):o[s]||(i=At(r),(n&&"none"!==n||!i)&&q.set(r,"olddisplay",i?n:x.css(r,"display"))));for(s=0;a>s;s++)r=e[s],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[s]||"":"none"));return e}x.fn.extend({css:function(e,t){return x.access(this,function(e,t,n){var r,i,o={},s=0;if(x.isArray(t)){for(r=Lt(e),i=t.length;i>s;s++)o[t[s]]=x.css(e,t[s],!1,r);return o}return n!==undefined?x.style(e,t,n):x.css(e,t)},e,t,arguments.length>1)},show:function(){return qt(this,!0)},hide:function(){return qt(this)},toggle:function(e){var t="boolean"==typeof e;return this.each(function(){(t?e:At(this))?x(this).show():x(this).hide()})}}),x.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=yt(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":"cssFloat"},style:function(e,t,n,r){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var i,o,s,a=x.camelCase(t),u=e.style;return t=x.cssProps[a]||(x.cssProps[a]=Dt(u,a)),s=x.cssHooks[t]||x.cssHooks[a],n===undefined?s&&"get"in s&&(i=s.get(e,!1,r))!==undefined?i:u[t]:(o=typeof n,"string"===o&&(i=Ct.exec(n))&&(n=(i[1]+1)*i[2]+parseFloat(x.css(e,t)),o="number"),null==n||"number"===o&&isNaN(n)||("number"!==o||x.cssNumber[a]||(n+="px"),x.support.clearCloneStyle||""!==n||0!==t.indexOf("background")||(u[t]="inherit"),s&&"set"in s&&(n=s.set(e,n,r))===undefined||(u[t]=n)),undefined)}},css:function(e,t,n,r){var i,o,s,a=x.camelCase(t);return t=x.cssProps[a]||(x.cssProps[a]=Dt(e.style,a)),s=x.cssHooks[t]||x.cssHooks[a],s&&"get"in s&&(i=s.get(e,!0,n)),i===undefined&&(i=yt(e,t,r)),"normal"===i&&t in Et&&(i=Et[t]),""===n||n?(o=parseFloat(i),n===!0||x.isNumeric(o)?o||0:i):i}}),yt=function(e,t,n){var r,i,o,s=n||Lt(e),a=s?s.getPropertyValue(t)||s[t]:undefined,u=e.style;return s&&(""!==a||x.contains(e.ownerDocument,e)||(a=x.style(e,t)),Tt.test(a)&&bt.test(t)&&(r=u.width,i=u.minWidth,o=u.maxWidth,u.minWidth=u.maxWidth=u.width=a,a=s.width,u.width=r,u.minWidth=i,u.maxWidth=o)),a};function Ht(e,t,n){var r=wt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function Ot(e,t,n,r,i){var o=n===(r?"border":"content")?4:"width"===t?1:0,s=0;for(;4>o;o+=2)"margin"===n&&(s+=x.css(e,n+St[o],!0,i)),r?("content"===n&&(s-=x.css(e,"padding"+St[o],!0,i)),"margin"!==n&&(s-=x.css(e,"border"+St[o]+"Width",!0,i))):(s+=x.css(e,"padding"+St[o],!0,i),"padding"!==n&&(s+=x.css(e,"border"+St[o]+"Width",!0,i)));return s}function Ft(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=Lt(e),s=x.support.boxSizing&&"border-box"===x.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=yt(e,t,o),(0>i||null==i)&&(i=e.style[t]),Tt.test(i))return i;r=s&&(x.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+Ot(e,t,n||(s?"border":"content"),r,o)+"px"}function Pt(e){var t=o,n=kt[e];return n||(n=Rt(e,t),"none"!==n&&n||(vt=(vt||x("<iframe frameborder='0' width='0' height='0'/>").css("cssText","display:block !important")).appendTo(t.documentElement),t=(vt[0].contentWindow||vt[0].contentDocument).document,t.write("<!doctype html><html><body>"),t.close(),n=Rt(e,t),vt.detach()),kt[e]=n),n}function Rt(e,t){var n=x(t.createElement(e)).appendTo(t.body),r=x.css(n[0],"display");return n.remove(),r}x.each(["height","width"],function(e,t){x.cssHooks[t]={get:function(e,n,r){return n?0===e.offsetWidth&&xt.test(x.css(e,"display"))?x.swap(e,Nt,function(){return Ft(e,t,r)}):Ft(e,t,r):undefined},set:function(e,n,r){var i=r&&Lt(e);return Ht(e,n,r?Ot(e,t,r,x.support.boxSizing&&"border-box"===x.css(e,"boxSizing",!1,i),i):0)}}}),x(function(){x.support.reliableMarginRight||(x.cssHooks.marginRight={get:function(e,t){return t?x.swap(e,{display:"inline-block"},yt,[e,"marginRight"]):undefined}}),!x.support.pixelPosition&&x.fn.position&&x.each(["top","left"],function(e,t){x.cssHooks[t]={get:function(e,n){return n?(n=yt(e,t),Tt.test(n)?x(e).position()[t]+"px":n):undefined}}})}),x.expr&&x.expr.filters&&(x.expr.filters.hidden=function(e){return 0>=e.offsetWidth&&0>=e.offsetHeight},x.expr.filters.visible=function(e){return!x.expr.filters.hidden(e)}),x.each({margin:"",padding:"",border:"Width"},function(e,t){x.cssHooks[e+t]={expand:function(n){var r=0,i={},o="string"==typeof n?n.split(" "):[n];for(;4>r;r++)i[e+St[r]+t]=o[r]||o[r-2]||o[0];return i}},bt.test(e)||(x.cssHooks[e+t].set=Ht)});var Mt=/%20/g,Wt=/\[\]$/,$t=/\r?\n/g,Bt=/^(?:submit|button|image|reset|file)$/i,It=/^(?:input|select|textarea|keygen)/i;x.fn.extend({serialize:function(){return x.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=x.prop(this,"elements");return e?x.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!x(this).is(":disabled")&&It.test(this.nodeName)&&!Bt.test(e)&&(this.checked||!it.test(e))}).map(function(e,t){var n=x(this).val();return null==n?null:x.isArray(n)?x.map(n,function(e){return{name:t.name,value:e.replace($t,"\r\n")}}):{name:t.name,value:n.replace($t,"\r\n")}}).get()}}),x.param=function(e,t){var n,r=[],i=function(e,t){t=x.isFunction(t)?t():null==t?"":t,r[r.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(t===undefined&&(t=x.ajaxSettings&&x.ajaxSettings.traditional),x.isArray(e)||e.jquery&&!x.isPlainObject(e))x.each(e,function(){i(this.name,this.value)});else for(n in e)zt(n,e[n],t,i);return r.join("&").replace(Mt,"+")};function zt(e,t,n,r){var i;if(x.isArray(t))x.each(t,function(t,i){n||Wt.test(e)?r(e,i):zt(e+"["+("object"==typeof i?t:"")+"]",i,n,r)});else if(n||"object"!==x.type(t))r(e,t);else for(i in t)zt(e+"["+i+"]",t[i],n,r)}x.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){x.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),x.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)}});var _t,Xt,Ut=x.now(),Yt=/\?/,Vt=/#.*$/,Gt=/([?&])_=[^&]*/,Jt=/^(.*?):[ \t]*([^\r\n]*)$/gm,Qt=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Kt=/^(?:GET|HEAD)$/,Zt=/^\/\//,en=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,tn=x.fn.load,nn={},rn={},on="*/".concat("*");try{Xt=i.href}catch(sn){Xt=o.createElement("a"),Xt.href="",Xt=Xt.href}_t=en.exec(Xt.toLowerCase())||[];function an(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(w)||[]; -if(x.isFunction(n))while(r=o[i++])"+"===r[0]?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function un(e,t,n,r){var i={},o=e===rn;function s(a){var u;return i[a]=!0,x.each(e[a]||[],function(e,a){var l=a(t,n,r);return"string"!=typeof l||o||i[l]?o?!(u=l):undefined:(t.dataTypes.unshift(l),s(l),!1)}),u}return s(t.dataTypes[0])||!i["*"]&&s("*")}function ln(e,t){var n,r,i=x.ajaxSettings.flatOptions||{};for(n in t)t[n]!==undefined&&((i[n]?e:r||(r={}))[n]=t[n]);return r&&x.extend(!0,e,r),e}x.fn.load=function(e,t,n){if("string"!=typeof e&&tn)return tn.apply(this,arguments);var r,i,o,s=this,a=e.indexOf(" ");return a>=0&&(r=e.slice(a),e=e.slice(0,a)),x.isFunction(t)?(n=t,t=undefined):t&&"object"==typeof t&&(i="POST"),s.length>0&&x.ajax({url:e,type:i,dataType:"html",data:t}).done(function(e){o=arguments,s.html(r?x("<div>").append(x.parseHTML(e)).find(r):e)}).complete(n&&function(e,t){s.each(n,o||[e.responseText,t,e])}),this},x.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){x.fn[t]=function(e){return this.on(t,e)}}),x.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Xt,type:"GET",isLocal:Qt.test(_t[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":on,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":x.parseJSON,"text xml":x.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?ln(ln(e,x.ajaxSettings),t):ln(x.ajaxSettings,e)},ajaxPrefilter:an(nn),ajaxTransport:an(rn),ajax:function(e,t){"object"==typeof e&&(t=e,e=undefined),t=t||{};var n,r,i,o,s,a,u,l,c=x.ajaxSetup({},t),f=c.context||c,p=c.context&&(f.nodeType||f.jquery)?x(f):x.event,h=x.Deferred(),d=x.Callbacks("once memory"),g=c.statusCode||{},m={},y={},v=0,b="canceled",T={readyState:0,getResponseHeader:function(e){var t;if(2===v){if(!o){o={};while(t=Jt.exec(i))o[t[1].toLowerCase()]=t[2]}t=o[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===v?i:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return v||(e=y[n]=y[n]||e,m[e]=t),this},overrideMimeType:function(e){return v||(c.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>v)for(t in e)g[t]=[g[t],e[t]];else T.always(e[T.status]);return this},abort:function(e){var t=e||b;return n&&n.abort(t),k(0,t),this}};if(h.promise(T).complete=d.add,T.success=T.done,T.error=T.fail,c.url=((e||c.url||Xt)+"").replace(Vt,"").replace(Zt,_t[1]+"//"),c.type=t.method||t.type||c.method||c.type,c.dataTypes=x.trim(c.dataType||"*").toLowerCase().match(w)||[""],null==c.crossDomain&&(a=en.exec(c.url.toLowerCase()),c.crossDomain=!(!a||a[1]===_t[1]&&a[2]===_t[2]&&(a[3]||("http:"===a[1]?"80":"443"))===(_t[3]||("http:"===_t[1]?"80":"443")))),c.data&&c.processData&&"string"!=typeof c.data&&(c.data=x.param(c.data,c.traditional)),un(nn,c,t,T),2===v)return T;u=c.global,u&&0===x.active++&&x.event.trigger("ajaxStart"),c.type=c.type.toUpperCase(),c.hasContent=!Kt.test(c.type),r=c.url,c.hasContent||(c.data&&(r=c.url+=(Yt.test(r)?"&":"?")+c.data,delete c.data),c.cache===!1&&(c.url=Gt.test(r)?r.replace(Gt,"$1_="+Ut++):r+(Yt.test(r)?"&":"?")+"_="+Ut++)),c.ifModified&&(x.lastModified[r]&&T.setRequestHeader("If-Modified-Since",x.lastModified[r]),x.etag[r]&&T.setRequestHeader("If-None-Match",x.etag[r])),(c.data&&c.hasContent&&c.contentType!==!1||t.contentType)&&T.setRequestHeader("Content-Type",c.contentType),T.setRequestHeader("Accept",c.dataTypes[0]&&c.accepts[c.dataTypes[0]]?c.accepts[c.dataTypes[0]]+("*"!==c.dataTypes[0]?", "+on+"; q=0.01":""):c.accepts["*"]);for(l in c.headers)T.setRequestHeader(l,c.headers[l]);if(c.beforeSend&&(c.beforeSend.call(f,T,c)===!1||2===v))return T.abort();b="abort";for(l in{success:1,error:1,complete:1})T[l](c[l]);if(n=un(rn,c,t,T)){T.readyState=1,u&&p.trigger("ajaxSend",[T,c]),c.async&&c.timeout>0&&(s=setTimeout(function(){T.abort("timeout")},c.timeout));try{v=1,n.send(m,k)}catch(C){if(!(2>v))throw C;k(-1,C)}}else k(-1,"No Transport");function k(e,t,o,a){var l,m,y,b,w,C=t;2!==v&&(v=2,s&&clearTimeout(s),n=undefined,i=a||"",T.readyState=e>0?4:0,l=e>=200&&300>e||304===e,o&&(b=cn(c,T,o)),b=fn(c,b,T,l),l?(c.ifModified&&(w=T.getResponseHeader("Last-Modified"),w&&(x.lastModified[r]=w),w=T.getResponseHeader("etag"),w&&(x.etag[r]=w)),204===e?C="nocontent":304===e?C="notmodified":(C=b.state,m=b.data,y=b.error,l=!y)):(y=C,(e||!C)&&(C="error",0>e&&(e=0))),T.status=e,T.statusText=(t||C)+"",l?h.resolveWith(f,[m,C,T]):h.rejectWith(f,[T,C,y]),T.statusCode(g),g=undefined,u&&p.trigger(l?"ajaxSuccess":"ajaxError",[T,c,l?m:y]),d.fireWith(f,[T,C]),u&&(p.trigger("ajaxComplete",[T,c]),--x.active||x.event.trigger("ajaxStop")))}return T},getJSON:function(e,t,n){return x.get(e,t,n,"json")},getScript:function(e,t){return x.get(e,undefined,t,"script")}}),x.each(["get","post"],function(e,t){x[t]=function(e,n,r,i){return x.isFunction(n)&&(i=i||r,r=n,n=undefined),x.ajax({url:e,type:t,dataType:i,data:n,success:r})}});function cn(e,t,n){var r,i,o,s,a=e.contents,u=e.dataTypes;while("*"===u[0])u.shift(),r===undefined&&(r=e.mimeType||t.getResponseHeader("Content-Type"));if(r)for(i in a)if(a[i]&&a[i].test(r)){u.unshift(i);break}if(u[0]in n)o=u[0];else{for(i in n){if(!u[0]||e.converters[i+" "+u[0]]){o=i;break}s||(s=i)}o=o||s}return o?(o!==u[0]&&u.unshift(o),n[o]):undefined}function fn(e,t,n,r){var i,o,s,a,u,l={},c=e.dataTypes.slice();if(c[1])for(s in e.converters)l[s.toLowerCase()]=e.converters[s];o=c.shift();while(o)if(e.responseFields[o]&&(n[e.responseFields[o]]=t),!u&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),u=o,o=c.shift())if("*"===o)o=u;else if("*"!==u&&u!==o){if(s=l[u+" "+o]||l["* "+o],!s)for(i in l)if(a=i.split(" "),a[1]===o&&(s=l[u+" "+a[0]]||l["* "+a[0]])){s===!0?s=l[i]:l[i]!==!0&&(o=a[0],c.unshift(a[1]));break}if(s!==!0)if(s&&e["throws"])t=s(t);else try{t=s(t)}catch(f){return{state:"parsererror",error:s?f:"No conversion from "+u+" to "+o}}}return{state:"success",data:t}}x.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return x.globalEval(e),e}}}),x.ajaxPrefilter("script",function(e){e.cache===undefined&&(e.cache=!1),e.crossDomain&&(e.type="GET")}),x.ajaxTransport("script",function(e){if(e.crossDomain){var t,n;return{send:function(r,i){t=x("<script>").prop({async:!0,charset:e.scriptCharset,src:e.url}).on("load error",n=function(e){t.remove(),n=null,e&&i("error"===e.type?404:200,e.type)}),o.head.appendChild(t[0])},abort:function(){n&&n()}}}});var pn=[],hn=/(=)\?(?=&|$)|\?\?/;x.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=pn.pop()||x.expando+"_"+Ut++;return this[e]=!0,e}}),x.ajaxPrefilter("json jsonp",function(t,n,r){var i,o,s,a=t.jsonp!==!1&&(hn.test(t.url)?"url":"string"==typeof t.data&&!(t.contentType||"").indexOf("application/x-www-form-urlencoded")&&hn.test(t.data)&&"data");return a||"jsonp"===t.dataTypes[0]?(i=t.jsonpCallback=x.isFunction(t.jsonpCallback)?t.jsonpCallback():t.jsonpCallback,a?t[a]=t[a].replace(hn,"$1"+i):t.jsonp!==!1&&(t.url+=(Yt.test(t.url)?"&":"?")+t.jsonp+"="+i),t.converters["script json"]=function(){return s||x.error(i+" was not called"),s[0]},t.dataTypes[0]="json",o=e[i],e[i]=function(){s=arguments},r.always(function(){e[i]=o,t[i]&&(t.jsonpCallback=n.jsonpCallback,pn.push(i)),s&&x.isFunction(o)&&o(s[0]),s=o=undefined}),"script"):undefined}),x.ajaxSettings.xhr=function(){try{return new XMLHttpRequest}catch(e){}};var dn=x.ajaxSettings.xhr(),gn={0:200,1223:204},mn=0,yn={};e.ActiveXObject&&x(e).on("unload",function(){for(var e in yn)yn[e]();yn=undefined}),x.support.cors=!!dn&&"withCredentials"in dn,x.support.ajax=dn=!!dn,x.ajaxTransport(function(e){var t;return x.support.cors||dn&&!e.crossDomain?{send:function(n,r){var i,o,s=e.xhr();if(s.open(e.type,e.url,e.async,e.username,e.password),e.xhrFields)for(i in e.xhrFields)s[i]=e.xhrFields[i];e.mimeType&&s.overrideMimeType&&s.overrideMimeType(e.mimeType),e.crossDomain||n["X-Requested-With"]||(n["X-Requested-With"]="XMLHttpRequest");for(i in n)s.setRequestHeader(i,n[i]);t=function(e){return function(){t&&(delete yn[o],t=s.onload=s.onerror=null,"abort"===e?s.abort():"error"===e?r(s.status||404,s.statusText):r(gn[s.status]||s.status,s.statusText,"string"==typeof s.responseText?{text:s.responseText}:undefined,s.getAllResponseHeaders()))}},s.onload=t(),s.onerror=t("error"),t=yn[o=mn++]=t("abort"),s.send(e.hasContent&&e.data||null)},abort:function(){t&&t()}}:undefined});var vn,xn,bn=/^(?:toggle|show|hide)$/,wn=RegExp("^(?:([+-])=|)("+b+")([a-z%]*)$","i"),Tn=/queueHooks$/,Cn=[Dn],kn={"*":[function(e,t){var n,r,i=this.createTween(e,t),o=wn.exec(t),s=i.cur(),a=+s||0,u=1,l=20;if(o){if(n=+o[2],r=o[3]||(x.cssNumber[e]?"":"px"),"px"!==r&&a){a=x.css(i.elem,e,!0)||n||1;do u=u||".5",a/=u,x.style(i.elem,e,a+r);while(u!==(u=i.cur()/s)&&1!==u&&--l)}i.unit=r,i.start=a,i.end=o[1]?a+(o[1]+1)*n:n}return i}]};function Nn(){return setTimeout(function(){vn=undefined}),vn=x.now()}function En(e,t){x.each(t,function(t,n){var r=(kn[t]||[]).concat(kn["*"]),i=0,o=r.length;for(;o>i;i++)if(r[i].call(e,t,n))return})}function Sn(e,t,n){var r,i,o=0,s=Cn.length,a=x.Deferred().always(function(){delete u.elem}),u=function(){if(i)return!1;var t=vn||Nn(),n=Math.max(0,l.startTime+l.duration-t),r=n/l.duration||0,o=1-r,s=0,u=l.tweens.length;for(;u>s;s++)l.tweens[s].run(o);return a.notifyWith(e,[l,o,n]),1>o&&u?n:(a.resolveWith(e,[l]),!1)},l=a.promise({elem:e,props:x.extend({},t),opts:x.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:vn||Nn(),duration:n.duration,tweens:[],createTween:function(t,n){var r=x.Tween(e,l.opts,t,n,l.opts.specialEasing[t]||l.opts.easing);return l.tweens.push(r),r},stop:function(t){var n=0,r=t?l.tweens.length:0;if(i)return this;for(i=!0;r>n;n++)l.tweens[n].run(1);return t?a.resolveWith(e,[l,t]):a.rejectWith(e,[l,t]),this}}),c=l.props;for(jn(c,l.opts.specialEasing);s>o;o++)if(r=Cn[o].call(l,e,c,l.opts))return r;return En(l,c),x.isFunction(l.opts.start)&&l.opts.start.call(e,l),x.fx.timer(x.extend(u,{elem:e,anim:l,queue:l.opts.queue})),l.progress(l.opts.progress).done(l.opts.done,l.opts.complete).fail(l.opts.fail).always(l.opts.always)}function jn(e,t){var n,r,i,o,s;for(n in e)if(r=x.camelCase(n),i=t[r],o=e[n],x.isArray(o)&&(i=o[1],o=e[n]=o[0]),n!==r&&(e[r]=o,delete e[n]),s=x.cssHooks[r],s&&"expand"in s){o=s.expand(o),delete e[r];for(n in o)n in e||(e[n]=o[n],t[n]=i)}else t[r]=i}x.Animation=x.extend(Sn,{tweener:function(e,t){x.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;i>r;r++)n=e[r],kn[n]=kn[n]||[],kn[n].unshift(t)},prefilter:function(e,t){t?Cn.unshift(e):Cn.push(e)}});function Dn(e,t,n){var r,i,o,s,a,u,l,c,f,p=this,h=e.style,d={},g=[],m=e.nodeType&&At(e);n.queue||(c=x._queueHooks(e,"fx"),null==c.unqueued&&(c.unqueued=0,f=c.empty.fire,c.empty.fire=function(){c.unqueued||f()}),c.unqueued++,p.always(function(){p.always(function(){c.unqueued--,x.queue(e,"fx").length||c.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[h.overflow,h.overflowX,h.overflowY],"inline"===x.css(e,"display")&&"none"===x.css(e,"float")&&(h.display="inline-block")),n.overflow&&(h.overflow="hidden",p.always(function(){h.overflow=n.overflow[0],h.overflowX=n.overflow[1],h.overflowY=n.overflow[2]})),a=q.get(e,"fxshow");for(r in t)if(o=t[r],bn.exec(o)){if(delete t[r],u=u||"toggle"===o,o===(m?"hide":"show")){if("show"!==o||a===undefined||a[r]===undefined)continue;m=!0}g.push(r)}if(s=g.length){a=q.get(e,"fxshow")||q.access(e,"fxshow",{}),"hidden"in a&&(m=a.hidden),u&&(a.hidden=!m),m?x(e).show():p.done(function(){x(e).hide()}),p.done(function(){var t;q.remove(e,"fxshow");for(t in d)x.style(e,t,d[t])});for(r=0;s>r;r++)i=g[r],l=p.createTween(i,m?a[i]:0),d[i]=a[i]||x.style(e,i),i in a||(a[i]=l.start,m&&(l.end=l.start,l.start="width"===i||"height"===i?1:0))}}function An(e,t,n,r,i){return new An.prototype.init(e,t,n,r,i)}x.Tween=An,An.prototype={constructor:An,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(x.cssNumber[n]?"":"px")},cur:function(){var e=An.propHooks[this.prop];return e&&e.get?e.get(this):An.propHooks._default.get(this)},run:function(e){var t,n=An.propHooks[this.prop];return this.pos=t=this.options.duration?x.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):An.propHooks._default.set(this),this}},An.prototype.init.prototype=An.prototype,An.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=x.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){x.fx.step[e.prop]?x.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[x.cssProps[e.prop]]||x.cssHooks[e.prop])?x.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},An.propHooks.scrollTop=An.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},x.each(["toggle","show","hide"],function(e,t){var n=x.fn[t];x.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(Ln(t,!0),e,r,i)}}),x.fn.extend({fadeTo:function(e,t,n,r){return this.filter(At).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=x.isEmptyObject(e),o=x.speed(t,n,r),s=function(){var t=Sn(this,x.extend({},e),o);s.finish=function(){t.stop(!0)},(i||q.get(this,"finish"))&&t.stop(!0)};return s.finish=s,i||o.queue===!1?this.each(s):this.queue(o.queue,s)},stop:function(e,t,n){var r=function(e){var t=e.stop;delete e.stop,t(n)};return"string"!=typeof e&&(n=t,t=e,e=undefined),t&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,i=null!=e&&e+"queueHooks",o=x.timers,s=q.get(this);if(i)s[i]&&s[i].stop&&r(s[i]);else for(i in s)s[i]&&s[i].stop&&Tn.test(i)&&r(s[i]);for(i=o.length;i--;)o[i].elem!==this||null!=e&&o[i].queue!==e||(o[i].anim.stop(n),t=!1,o.splice(i,1));(t||!n)&&x.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=q.get(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=x.timers,s=r?r.length:0;for(n.finish=!0,x.queue(this,e,[]),i&&i.cur&&i.cur.finish&&i.cur.finish.call(this),t=o.length;t--;)o[t].elem===this&&o[t].queue===e&&(o[t].anim.stop(!0),o.splice(t,1));for(t=0;s>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete n.finish})}});function Ln(e,t){var n,r={height:e},i=0;for(t=t?1:0;4>i;i+=2-t)n=St[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}x.each({slideDown:Ln("show"),slideUp:Ln("hide"),slideToggle:Ln("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){x.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),x.speed=function(e,t,n){var r=e&&"object"==typeof e?x.extend({},e):{complete:n||!n&&t||x.isFunction(e)&&e,duration:e,easing:n&&t||t&&!x.isFunction(t)&&t};return r.duration=x.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in x.fx.speeds?x.fx.speeds[r.duration]:x.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){x.isFunction(r.old)&&r.old.call(this),r.queue&&x.dequeue(this,r.queue)},r},x.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},x.timers=[],x.fx=An.prototype.init,x.fx.tick=function(){var e,t=x.timers,n=0;for(vn=x.now();t.length>n;n++)e=t[n],e()||t[n]!==e||t.splice(n--,1);t.length||x.fx.stop(),vn=undefined},x.fx.timer=function(e){e()&&x.timers.push(e)&&x.fx.start()},x.fx.interval=13,x.fx.start=function(){xn||(xn=setInterval(x.fx.tick,x.fx.interval))},x.fx.stop=function(){clearInterval(xn),xn=null},x.fx.speeds={slow:600,fast:200,_default:400},x.fx.step={},x.expr&&x.expr.filters&&(x.expr.filters.animated=function(e){return x.grep(x.timers,function(t){return e===t.elem}).length}),x.fn.offset=function(e){if(arguments.length)return e===undefined?this:this.each(function(t){x.offset.setOffset(this,e,t)});var t,n,i=this[0],o={top:0,left:0},s=i&&i.ownerDocument;if(s)return t=s.documentElement,x.contains(t,i)?(typeof i.getBoundingClientRect!==r&&(o=i.getBoundingClientRect()),n=qn(s),{top:o.top+n.pageYOffset-t.clientTop,left:o.left+n.pageXOffset-t.clientLeft}):o},x.offset={setOffset:function(e,t,n){var r,i,o,s,a,u,l,c=x.css(e,"position"),f=x(e),p={};"static"===c&&(e.style.position="relative"),a=f.offset(),o=x.css(e,"top"),u=x.css(e,"left"),l=("absolute"===c||"fixed"===c)&&(o+u).indexOf("auto")>-1,l?(r=f.position(),s=r.top,i=r.left):(s=parseFloat(o)||0,i=parseFloat(u)||0),x.isFunction(t)&&(t=t.call(e,n,a)),null!=t.top&&(p.top=t.top-a.top+s),null!=t.left&&(p.left=t.left-a.left+i),"using"in t?t.using.call(e,p):f.css(p)}},x.fn.extend({position:function(){if(this[0]){var e,t,n=this[0],r={top:0,left:0};return"fixed"===x.css(n,"position")?t=n.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),x.nodeName(e[0],"html")||(r=e.offset()),r.top+=x.css(e[0],"borderTopWidth",!0),r.left+=x.css(e[0],"borderLeftWidth",!0)),{top:t.top-r.top-x.css(n,"marginTop",!0),left:t.left-r.left-x.css(n,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||s;while(e&&!x.nodeName(e,"html")&&"static"===x.css(e,"position"))e=e.offsetParent;return e||s})}}),x.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,n){var r="pageYOffset"===n;x.fn[t]=function(i){return x.access(this,function(t,i,o){var s=qn(t);return o===undefined?s?s[n]:t[i]:(s?s.scrollTo(r?e.pageXOffset:o,r?o:e.pageYOffset):t[i]=o,undefined)},t,i,arguments.length,null)}});function qn(e){return x.isWindow(e)?e:9===e.nodeType&&e.defaultView}x.each({Height:"height",Width:"width"},function(e,t){x.each({padding:"inner"+e,content:t,"":"outer"+e},function(n,r){x.fn[r]=function(r,i){var o=arguments.length&&(n||"boolean"!=typeof r),s=n||(r===!0||i===!0?"margin":"border");return x.access(this,function(t,n,r){var i;return x.isWindow(t)?t.document.documentElement["client"+e]:9===t.nodeType?(i=t.documentElement,Math.max(t.body["scroll"+e],i["scroll"+e],t.body["offset"+e],i["offset"+e],i["client"+e])):r===undefined?x.css(t,n,s):x.style(t,n,r,s)},t,o?r:undefined,o,null)}})}),x.fn.size=function(){return this.length},x.fn.andSelf=x.fn.addBack,"object"==typeof module&&"object"==typeof module.exports?module.exports=x:"function"==typeof define&&define.amd&&define("jquery",[],function(){return x}),"object"==typeof e&&"object"==typeof e.document&&(e.jQuery=e.$=x)})(window); diff --git a/js/textbook_companion.js b/js/textbook_companion.js deleted file mode 100755 index bbbb851..0000000 --- a/js/textbook_companion.js +++ /dev/null @@ -1,210 +0,0 @@ -$( document ).ready(function() { -//to search - $('#searchtext').keyup(function(event) { - var search_text = $('#searchtext').val(); - var rg = new RegExp(search_text,'i'); - $('#aicte-list-wrapper .title , .form-item' ).each(function(){ - if($.trim($(this).html()).search(rg) == -1) { - //alert("one"); - $(this).parent('div').css('background-color', '#ffffff'); - $(this).css('display', 'none'); - $(this).next().css('display', 'none'); - $(this).next().next().css('display', 'none'); - } - else { - //alert("two"); - $(this).parent('div').css('background-color', '#ffffff'); - $(this).css('display', ''); - $(this).next().css('display', ''); - $(this).next().next().css('display', ''); - } - }); - }); - - //to clear the searched text - $('#search_clear').click(function() { - $('#searchtext').val(''); - $('#aicte-list-wrapper .title , .form-item' ).each(function(){ - $(this).parent().css('display', ''); - $(this).css('display', ''); - $(this).next().css('display', ''); - $(this).next().next().css('display', ''); - }); -}); - - -$('#edit-same-address').click(function() { - var temp = $('#edit-chq-address').val(); - $('#edit-temp-chq-address').val(temp); - var temp1 = $('#edit-perm-city').val(); - $('#edit-temp-city').val(temp1); - var temp1 = $('#edit-perm-pincode').val(); - $('#edit-temp-pincode').val(temp1); - var temp1 = $('#edit-perm-state').val(); - $('#edit-temp-state').val(temp1); - - $("#edit-cheque-sent").datepicker(); - - - $("#edit-cheque-cleared").datepicker(); - -}); - -$("#edit-perm-pincode").blur(function() - { - var string_length,string_val; - string_val = $("#edit-perm-pincode").val(); - string_length = $("#edit-perm-pincode").text().length; - //$("#username_warning").empty(); - - if ((isNaN(string_val))&&(string_length < 6)) - alert("Not A Valid Zip Code!!"); - - // $("#username_warning").append("Username is too short"); - }); -$("#edit-temp-pincode").blur(function() - { - var string_length1,string_val1; - string_val = $("#edit-temp-pincode").val(); - string_length = $("#edit-temp-pincode").text().length; - //$("#username_warning").empty(); - - if ((isNaN(string_val))&&(string_length1 < 6)) - alert("Not A Valid Zip Code!!"); - - // $("#username_warning").append("Username is too short"); - }); - -$("#edit-mobileno1").blur(function() - { - var string_length3,string_val3; - string_val3 = $("#edit-mobileno1").val(); - string_length3 = $("#edit-mobileno1").text().length; - //$("#username_warning").empty(); - - if (isNaN(string_val3)) - { - alert("Mobile No should be a number!!"); - // $("#username_warning").append("Username is too short"); - } - if((string_length3 > 0)&&(string_length3 < 11)) - { - alert("Not A Valid Mobile No!!"); - } - }); - -$("#edit-mobileno2").blur(function() - { - var string_length4,string_val4; - string_val4 = $("#edit-mobileno2").val(); - string_length4 = $("#edit-mobileno2").text().length; - //$("#username_warning").empty(); - - if (isNaN(string_val4)) - { - alert("Mobile No should be a number!!"); - // $("#username_warning").append("Username is too short"); - } - if((string_length4 > 0)&&(string_length4 < 11)) - { - alert("Not A Valid Mobile No!!"); - } - }); -$('#edit-older-wrapper').hide(); -$('#edit-version').change(function() { - var selected = $(this).val(); - //$('#edit-older-wrapper').hide(); - if(selected == 'olderversion'){ - $('#edit-older-wrapper').show(); - } - else - { - $('#edit-older-wrapper').hide(); - } -}); - -/* hide nonaicte_proposal form textbox of other reason */ -$('#edit-other-reason-wrapper').hide(); -$(function() { - enable_cb(); - $("#edit-reason-Other-reason").click(enable_cb); -}); -function enable_cb() { - if (this.checked) { - $('#edit-other-reason-wrapper').show(); - } else { - $('#edit-other-reason-wrapper').hide(); - } -} - - - - -/* highlighting current filter [A-Z] of book search pages */ -var pathname = window.location.pathname; -var filter = pathname.charAt(pathname.length-1); -$filters = $("#filter-links a"); -$filters.each(function() { - - var current = $(this).attr("href"); - var current = current.charAt(current.length-1); - if(current == filter) { - $(this).css({ - "padding": "0 2px", - "color": "#000000", - "font-weight": "bolder", - "background-color": "#f5f5f5" - }); - } -}); - -$report_form = $("#textbook-companion-aicte-report-form"); -$("#aicte-report").click(function() { - $("#textbook-companion-aicte-report-form").lightbox_me( { - centered: true - }); -}); - -/* validate report_form and submit */ -function danger(obj) { - obj.css("border", "2px solid red"); -} -function safe(obj) { - obj.css("border", "2px solid #cccccc"); -} -function validateEmail(email) { - var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; - return re.test(email); -} -$report_form.submit(function(e) { - var $name = $("#edit-name"); - var $email = $("#edit-email"); - var $number = $("#edit-number"); - var $book = $("#edit-book"); - - var errors = 0; - /* reset errors */ - safe($name); safe($email); safe($number); safe($book); - if(!$name.val()) { - danger($name); - errors = 1; - } - if(!validateEmail($email.val())) { - danger($email); - errors = 1; - } - if(!$number.val()) { - danger($number); - errors = 1; - } - if($book.val() == "0") { - danger($book); - errors = 1; - } - if(!errors) { - $(this).submit(); - } - e.preventDefault(); -}); - -}); @@ -1,213 +1,236 @@ <?php - function textbook_companion_download_book() -{ - $preference_id = arg(2); - _latex_copy_script_file(); - $full_book = arg(3); - if ($full_book == "1") - _latex_generate_files($preference_id, TRUE); - else - _latex_generate_files($preference_id, FALSE); -} - -function _latex_generate_files($preference_id, $full_book = FALSE) -{ - $root_path = textbook_companion_path(); - $dir_path = $root_path . "latex/"; - - $book_filedata = ""; - $contributor_filedata = ""; - $latex_filedata = ""; - $latex_dep_filedata = ""; - - $depedency_list = array(); - - $eol = "\n"; - $sep = "#"; - - $preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d", $preference_id); - $preference_data = db_fetch_object($preference_q); - if (!$preference_data) - { - drupal_set_message('Invalid book specified.', 'error'); - drupal_goto(''); - } - if ($preference_data->approval_status == 0) - { - drupal_set_message('Book proposal is still in pending review.', 'error'); - drupal_goto(''); - } - $book_filedata = $preference_data->book . $sep . $preference_data->author . $sep . $preference_data->isbn . $sep . $preference_data->publisher . $sep . $preference_data->edition . $sep . $preference_data->year . $eol; - - /* regenerate book if full book selected */ - if ($full_book) - del_book_pdf($preference_data->id); - - /* check if book already generated */ - if (file_exists($dir_path . "book_" . $preference_data->id . ".pdf")) - { - /* download zip file */ - header('Content-Type: application/pdf'); - header('Content-disposition: attachment; filename="' . $preference_data->book . '_' . $preference_data->author . '.pdf"'); - header('Content-Length: ' . filesize($dir_path . "book_" . $preference_data->id . ".pdf")); - header("Content-Transfer-Encoding: binary"); - header('Expires: 0'); - header('Pragma: no-cache'); - ob_end_flush(); - ob_clean(); - flush(); - - readfile($dir_path . "book_" . $preference_data->id . ".pdf"); - return; - } - - $proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d", $preference_data->proposal_id); - $proposal_data = db_fetch_object($proposal_q); - if (!$proposal_data) { - drupal_set_message('Could not fetch contributors information for the book specified.', 'error'); + $preference_id = arg(2); + _latex_copy_script_file(); + $full_book = arg(3); + if ($full_book == "1") + _latex_generate_files($preference_id, TRUE); + else + _latex_generate_files($preference_id, FALSE); } - $contributor_filedata .= $proposal_data->full_name . $sep . $proposal_data->course . $sep . $proposal_data->branch . $sep . $proposal_data->university . $sep . $proposal_data->faculty . $sep . $proposal_data->reviewer . $eol; - - $chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE preference_id = %d ORDER BY number DESC", $preference_data->id); - while ($chapter_data = db_fetch_object($chapter_q)) +function _latex_generate_files($preference_id, $full_book = FALSE) { - if ($full_book) - $example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE chapter_id = %d ORDER BY number DESC", $chapter_data->id); - else - $example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE chapter_id = %d AND approval_status = 1 ORDER BY number DESC", $chapter_data->id); - while ($example_data = db_fetch_object($example_q)) - { - $example_files_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE example_id = %d", $example_data->id); - while ($example_files_data = db_fetch_object($example_files_q)) + $root_path = textbook_companion_path(); + $dir_path = $root_path . "latex/"; + $book_filedata = ""; + $contributor_filedata = ""; + $latex_filedata = ""; + $latex_dep_filedata = ""; + $depedency_list = array(); + $eol = "\n"; + $sep = "#"; + /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d", $preference_id); + $preference_data = db_fetch_object($preference_q);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('id', $preference_id); + $preference_q = $query->execute(); + $preference_data = $preference_q->fetchObject(); + if (!$preference_data) { - $latex_filedata .= $chapter_data->number . $sep; - $latex_filedata .= $chapter_data->name . $sep; - $latex_filedata .= $example_data->number . $sep; - $latex_filedata .= $example_data->caption . $sep; - $latex_filedata .= $example_files_data->filename . $sep; - $latex_filedata .= $example_files_data->filepath . $sep; - $latex_filedata .= $example_files_data->filetype . $sep; - $latex_filedata .= $sep; - $latex_filedata .= $example_files_data->id; - $latex_filedata .= $eol; + drupal_set_message('Invalid book specified.', 'error'); + drupal_goto(''); } - $dependency_files_q = db_query("SELECT * FROM {textbook_companion_example_dependency} WHERE example_id = %d", $example_data->id); - while ($dependency_files_data = db_fetch_object($dependency_files_q)) + if ($preference_data->approval_status == 0) { - $dependency_q = db_query("SELECT * FROM {textbook_companion_dependency_files} WHERE id = %d LIMIT 1", $dependency_files_data->dependency_id); - if ($dependency_data = db_fetch_object($dependency_q)) - { - $latex_filedata .= $chapter_data->number . $sep; - $latex_filedata .= $chapter_data->name . $sep; - $latex_filedata .= $example_data->number . $sep; - $latex_filedata .= $example_data->caption . $sep; - $latex_filedata .= $dependency_data->filename . $sep; - $latex_filedata .= $dependency_data->filepath . $sep; - $latex_filedata .= 'D' . $sep; - $latex_filedata .= $dependency_data->caption . $sep; - $latex_filedata .= $dependency_data->id; - $latex_filedata .= $eol; - - $depedency_list[$dependency_data->id] = "D"; - } + drupal_set_message('Book proposal is still in pending review.', 'error'); + drupal_goto(''); } - } - } - - foreach ($depedency_list as $row => $data) { - $dependency_q = db_query("SELECT * FROM {textbook_companion_dependency_files} WHERE id = %d LIMIT 1", $row); - if ($dependency_data = db_fetch_object($dependency_q)) - { - $latex_dep_filedata .= $dependency_data->filename . $sep; - $latex_dep_filedata .= $dependency_data->filepath . $sep; - $latex_dep_filedata .= $dependency_data->caption . $sep; - $latex_dep_filedata .= $dependency_data->id; - $latex_dep_filedata .= $eol; - } + $book_filedata = $preference_data->book . $sep . $preference_data->author . $sep . $preference_data->isbn . $sep . $preference_data->publisher . $sep . $preference_data->edition . $sep . $preference_data->year . $eol; + /* regenerate book if full book selected */ + if ($full_book) + del_book_pdf($preference_data->id); + /* check if book already generated */ + if (file_exists($dir_path . "book_" . $preference_data->id . ".pdf")) + { + /* download zip file */ + header('Content-Type: application/pdf'); + header('Content-disposition: attachment; filename="' . $preference_data->book . '_' . $preference_data->author . '.pdf"'); + header('Content-Length: ' . filesize($dir_path . "book_" . $preference_data->id . ".pdf")); + header("Content-Transfer-Encoding: binary"); + header('Expires: 0'); + header('Pragma: no-cache'); + ob_end_flush(); + ob_clean(); + flush(); + readfile($dir_path . "book_" . $preference_data->id . ".pdf"); + return; + } + /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d", $preference_data->proposal_id); + $proposal_data = db_fetch_object($proposal_q);*/ + $query = db_select('textbook_companion_proposal'); + $query->fields('textbook_companion_proposal'); + $query->condition('id', $preference_data->proposal_id); + $proposal_q = $query->execute(); + $proposal_data = $proposal_q->fetchObject(); + if (!$proposal_data) + { + drupal_set_message('Could not fetch contributors information for the book specified.', 'error'); + } + $contributor_filedata .= $proposal_data->full_name . $sep . $proposal_data->course . $sep . $proposal_data->branch . $sep . $proposal_data->university . $sep . $proposal_data->faculty . $sep . $proposal_data->reviewer . $eol; + /*$chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE preference_id = %d ORDER BY number DESC", $preference_data->id);*/ + $query = db_select('textbook_companion_chapter'); + $query->fields('textbook_companion_chapter'); + $query->condition('preference_id', $preference_data->id); + $query->orderBy('number', 'DESC'); + $chapter_q = $query->execute(); + while ($chapter_data = $chapter_q->fetchObject()) + { + if ($full_book) + { + /*$example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE chapter_id = %d ORDER BY number DESC", $chapter_data->id);*/ + $query = db_select('textbook_companion_example'); + $query->fields('textbook_companion_example'); + $query->condition('chapter_id', $chapter_data->id); + $query->orderBy('number', 'DESC'); + $example_q = $query->execute(); + } + else + { + /*$example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE chapter_id = %d AND approval_status = 1 ORDER BY number DESC", $chapter_data->id);*/ + $query = db_select('textbook_companion_example'); + $query->fields('textbook_companion_example'); + $query->condition('chapter_id', $chapter_data->id); + $query->condition('approval_status', 1); + $query->orderBy('number', 'DESC'); + $example_q = $query->execute(); + } + while ($example_data = $example_q->fetchObject()) + { + /*$example_files_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE example_id = %d", $example_data->id);*/ + $query = db_select('textbook_companion_example_files'); + $query->fields('textbook_companion_example_files'); + $query->condition('example_id', $example_data->id); + $example_files_q = $query->execute(); + while ($example_files_data = $example_files_q->fetchObject()) + { + $latex_filedata .= $chapter_data->number . $sep; + $latex_filedata .= $chapter_data->name . $sep; + $latex_filedata .= $example_data->number . $sep; + $latex_filedata .= $example_data->caption . $sep; + $latex_filedata .= $example_files_data->filename . $sep; + $latex_filedata .= $example_files_data->filepath . $sep; + $latex_filedata .= $example_files_data->filetype . $sep; + $latex_filedata .= $sep; + $latex_filedata .= $example_files_data->id; + $latex_filedata .= $eol; + } + /*$dependency_files_q = db_query("SELECT * FROM {textbook_companion_example_dependency} WHERE example_id = %d", $example_data->id);*/ + $query = db_select('textbook_companion_example_dependency'); + $query->fields('textbook_companion_example_dependency'); + $query->condition('example_id', $example_data->id); + $dependency_files_q = $query->execute(); + while ($dependency_files_data = $dependency_files_q->fetchObject()) + { + /*$dependency_q = db_query("SELECT * FROM {textbook_companion_dependency_files} WHERE id = %d LIMIT 1", $dependency_files_data->dependency_id);*/ + $query = db_select('textbook_companion_dependency_files'); + $query->fields('textbook_companion_dependency_files'); + $query->condition('id', $dependency_files_data->dependency_id); + $query->range(0, 1); + $dependency_q = $query->execute(); + if ($dependency_data = $dependency_q->fetchObject()) + { + $latex_filedata .= $chapter_data->number . $sep; + $latex_filedata .= $chapter_data->name . $sep; + $latex_filedata .= $example_data->number . $sep; + $latex_filedata .= $example_data->caption . $sep; + $latex_filedata .= $dependency_data->filename . $sep; + $latex_filedata .= $dependency_data->filepath . $sep; + $latex_filedata .= 'D' . $sep; + $latex_filedata .= $dependency_data->caption . $sep; + $latex_filedata .= $dependency_data->id; + $latex_filedata .= $eol; + $depedency_list[$dependency_data->id] = "D"; + } + } + } + } + foreach ($depedency_list as $row => $data) + { + /*$dependency_q = db_query("SELECT * FROM {textbook_companion_dependency_files} WHERE id = %d LIMIT 1", $row);*/ + $query = db_select('textbook_companion_dependency_files'); + $query->fields('textbook_companion_dependency_files'); + $query->condition('id', $row); + $query->range(0, 1); + $dependency_q = $query->execute(); + if ($dependency_data = $dependency_q->fetchObject()) + { + $latex_dep_filedata .= $dependency_data->filename . $sep; + $latex_dep_filedata .= $dependency_data->filepath . $sep; + $latex_dep_filedata .= $dependency_data->caption . $sep; + $latex_dep_filedata .= $dependency_data->id; + $latex_dep_filedata .= $eol; + } + } + /**************************** WRITE TO FILES ********************************/ + $download_filename = $preference_data->book . "_" . $preference_data->author; + $book_filename = "tmp_" . $preference_data->id . "_book.txt"; + $contributor_filename = "tmp_" . $preference_data->id . "_contributor.txt"; + $latex_filename = "tmp_" . $preference_data->id . "_data.txt"; + $latex_dep_filename = "tmp_" . $preference_data->id . "_dep_data.txt"; + $pdf_filename = "book_" . $preference_data->id . ".pdf"; + // $book_filedata = str_replace("&", "\&", $book_filedata); + $fb = fopen($dir_path . $book_filename, 'w'); + fwrite($fb, $book_filedata); + fclose($fb); + // $contributor_filedata = str_replace("&", "\&", $contributor_filedata); + $fc = fopen($dir_path . $contributor_filename, 'w'); + fwrite($fc, $contributor_filedata); + fclose($fc); + $fl = fopen($dir_path . $latex_filename, 'w'); + fwrite($fl, $latex_filedata); + fclose($fl); + $fd = fopen($dir_path . $latex_dep_filename, 'w'); + fwrite($fd, $latex_dep_filedata); + fclose($fd); + if (_latex_run_script($book_filename, $contributor_filename, $latex_filename, $latex_dep_filename, $pdf_filename)) + { + /* download zip file */ + header('Content-Type: application/pdf'); + header('Content-disposition: attachment; filename="' . $preference_data->book . '_' . $preference_data->author . '.pdf"'); + header('Content-Length: ' . filesize($dir_path . $pdf_filename)); + header("Content-Transfer-Encoding: binary"); + header('Expires: 0'); + header('Pragma: no-cache'); + ob_end_flush(); + ob_clean(); + flush(); + readfile($dir_path . $pdf_filename); + } + else + { + drupal_set_message("Error occurred when generating the PDF version of the Book.", 'error'); + } + /*********************** DELETING TEMPORARY FILES ***************************/ + /* regenerate book if full book selected */ + if ($full_book) + del_book_pdf($preference_data->id); } - - /**************************** WRITE TO FILES ********************************/ - $download_filename = $preference_data->book . "_" . $preference_data->author; - $book_filename = "tmp_" . $preference_data->id . "_book.txt"; - $contributor_filename = "tmp_" . $preference_data->id . "_contributor.txt"; - $latex_filename = "tmp_" . $preference_data->id . "_data.txt"; - $latex_dep_filename = "tmp_" . $preference_data->id . "_dep_data.txt"; - $pdf_filename = "book_" . $preference_data->id . ".pdf"; - - // $book_filedata = str_replace("&", "\&", $book_filedata); - $fb = fopen($dir_path . $book_filename, 'w'); - fwrite($fb, $book_filedata); - fclose($fb); - - // $contributor_filedata = str_replace("&", "\&", $contributor_filedata); - $fc = fopen($dir_path . $contributor_filename, 'w'); - fwrite($fc, $contributor_filedata); - fclose($fc); - - $fl = fopen($dir_path . $latex_filename, 'w'); - fwrite($fl, $latex_filedata); - fclose($fl); - - $fd = fopen($dir_path . $latex_dep_filename, 'w'); - fwrite($fd, $latex_dep_filedata); - fclose($fd); - - if (_latex_run_script($book_filename, $contributor_filename, $latex_filename, $latex_dep_filename, $pdf_filename)) - { - /* download zip file */ - header('Content-Type: application/pdf'); - header('Content-disposition: attachment; filename="' . $preference_data->book . '_' . $preference_data->author . '.pdf"'); - header('Content-Length: ' . filesize($dir_path . $pdf_filename)); - header("Content-Transfer-Encoding: binary"); - header('Expires: 0'); - header('Pragma: no-cache'); - ob_end_flush(); - ob_clean(); - flush(); - - readfile($dir_path . $pdf_filename); - } else { - drupal_set_message("Error occurred when generating the PDF version of the Book.", 'error'); - } - - /*********************** DELETING TEMPORARY FILES ***************************/ - /* regenerate book if full book selected */ - if ($full_book) - del_book_pdf($preference_data->id); -} - function _latex_copy_script_file() -{ - exec("cp ./" . drupal_get_path('module', 'textbook_companion') . "/latex/* ./uploads/latex"); - exec("chmod u+x ./uploads/latex/*.sh"); -} - + { + exec("cp ./" . drupal_get_path('module', 'textbook_companion') . "/latex/* ./uploads/latex"); + exec("chmod u+x ./uploads/latex/*.sh"); + } function _latex_run_script($book_filename, $contributor_filename, $latex_filename, $latex_dep_filename, $pdf_filename) -{ - $root_path = textbook_companion_path(); - $ret = 0; - - chdir("uploads"); - chdir("latex"); - - $sh_command = "./latex_test.sh " . $book_filename . " " . $contributor_filename . " " . $latex_filename . " " . $latex_dep_filename; - exec($sh_command); - exec("mv TEX_final.pdf " . $pdf_filename); - - if ($ret == 0) - return TRUE; - else - return FALSE; -} - + { + $root_path = textbook_companion_path(); + $ret = 0; + chdir("uploads"); + chdir("latex"); + $sh_command = "./pdf_creator.sh " . $book_filename . " " . $contributor_filename . " " . $latex_filename . " " . $latex_dep_filename; + exec($sh_command); + exec("mv TEX_final.pdf " . $pdf_filename); + if ($ret == 0) + return TRUE; + else + return FALSE; + } function textbook_companion_delete_book() -{ - $book_id = arg(2); - del_book_pdf($book_id); - drupal_set_message(t('Book schedule for regeneration.'), 'status'); - drupal_goto('code_approval/bulk'); - return; -} - + { + $book_id = arg(2); + del_book_pdf($book_id); + drupal_set_message(t('Book schedule for regeneration.'), 'status'); + drupal_goto('code_approval/bulk'); + return; + } diff --git a/latex/Initial_body b/latex/Initial_body index b032dbd..c8d3576 100755 --- a/latex/Initial_body +++ b/latex/Initial_body @@ -1,58 +1,58 @@ \nonstopmode -\documentclass[12pt]{report} -\usepackage{hyperref} -\hypersetup{colorlinks=true,linkcolor=blue} -\usepackage{theorem,graphicx} -\usepackage{listings,alltt} -\bibliographystyle{plain} - - -\lstset{ %configuring the display of Dwsim codes - tabsize=4, - language=dwsim, - basicstyle=\ttfamily, - aboveskip={1\baselineskip}, - showstringspaces=false, - breaklines=true, - showspaces=false, - numbers=left, - numberstyle=\small, - stringstyle=\normalfont, - keywordstyle=\color{red}, - emph={clc, all, gca}, - emphstyle=\color{red}, - commentstyle=\color{blue}\normalfont} - - -% code environment -{\theorembodyfont{\rmfamily} \newtheorem{codemass}{Dwsim code}[chapter]} -\newenvironment{code}% -{\begin{codemass}}{\hrule \end{codemass}} - -{\theorembodyfont{\rmfamily} \newtheorem{accmass}{Acc}[chapter]} -\newenvironment{acc-code}% -{\begin{accmass}}{\end{accmass}} - - -% create listing for code - -\newcommand\tcaption[1] - {\addcontentsline{cod}{section}{\protect\numberline {\thecodemass}#1}} -\makeatletter \newcommand\listofcode - {\chapter*{List of Dwsim Codes\markboth% - {\bf List of Dwsim Codes}{}}% -\renewcommand*\l@section{\@dottedtocline{1}{1.5em}{5em}}% -\addcontentsline{toc}{chapter}{\protect\numberline{List of Dwsim Codes}} -\@starttoc{cod}} -\newcommand\l@matlab[3] - {#1 \par\noindent#2, #3 \par} -\renewcommand\@pnumwidth{2.1em} -%\makeatother - -\makeatletter -\def\curlable#1{\def\thecodemass{#1}\def\@currentlabel{#1}} -\makeatother - -\newcommand{\coderef}[1]{Exa~\ref{#1}} -\newcommand{\figref}[1]{Fig.~\ref{#1}} +\documentclass[12pt]{report}
+\usepackage{hyperref}
+\hypersetup{colorlinks=true,linkcolor=blue}
+\usepackage{theorem,graphicx}
+\usepackage{listings,alltt}
+\bibliographystyle{plain}
+
+
+\lstset{ %configuring the display of scilab codes
+ tabsize=4,
+ language=scilab,
+ basicstyle=\ttfamily,
+ aboveskip={1\baselineskip},
+ showstringspaces=false,
+ breaklines=true,
+ showspaces=false,
+ numbers=left,
+ numberstyle=\small,
+ stringstyle=\normalfont,
+ keywordstyle=\color{red},
+ emph={clc, all, gca},
+ emphstyle=\color{red},
+ commentstyle=\color{blue}\normalfont}
+
+
+% code environment
+{\theorembodyfont{\rmfamily} \newtheorem{codemass}{Scilab code}[chapter]}
+\newenvironment{code}%
+{\begin{codemass}}{\hrule \end{codemass}}
+
+{\theorembodyfont{\rmfamily} \newtheorem{accmass}{Acc}[chapter]}
+\newenvironment{acc-code}%
+{\begin{accmass}}{\end{accmass}}
+
+
+% create listing for code
+
+\newcommand\tcaption[1]
+ {\addcontentsline{cod}{section}{\protect\numberline {\thecodemass}#1}}
+\makeatletter \newcommand\listofcode
+ {\chapter*{List of Scilab Codes\markboth%
+ {\bf List of Scilab Codes}{}}%
+\renewcommand*\l@section{\@dottedtocline{1}{1.5em}{5em}}%
+\addcontentsline{toc}{chapter}{\protect\numberline{List of Scilab Codes}}
+\@starttoc{cod}}
+\newcommand\l@matlab[3]
+ {#1 \par\noindent#2, #3 \par}
+\renewcommand\@pnumwidth{2.1em}
+%\makeatother
+
+\makeatletter
+\def\curlable#1{\def\thecodemass{#1}\def\@currentlabel{#1}}
+\makeatother
+
+\newcommand{\coderef}[1]{Exa~\ref{#1}}
+\newcommand{\figref}[1]{Fig.~\ref{#1}}
diff --git a/manage_proposal.inc b/manage_proposal.inc index 3840c73..b99bf8c 100755 --- a/manage_proposal.inc +++ b/manage_proposal.inc @@ -1,1283 +1,1726 @@ <?php -// $Id$ - function _proposal_pending() { - /* get pending proposals to be approved */ - $pending_rows = array(); - $pending_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE proposal_status = 0 ORDER BY id DESC"); - while ($pending_data = db_fetch_object($pending_q)) - { - list($y, $m, $d) = explode('-', $pending_data->creation_date); - $cre_date = $d.'-'.$m.'-'.$y; - $dates = new DateTime($cre_date); - $creation_date = $dates->format('d-m-Y'); - list($y, $m, $d) = explode('-', $pending_data->expected_completion_date); - $exe_date = $d.'-'.$m.'-'.$y; - $exe_date = new DateTime($exe_date); - $expected_completion_date = $exe_date->format('d-m-Y'); - $pending_rows[$pending_data->id] = array($creation_date, l($pending_data->full_name, 'user/' . $pending_data->uid), $expected_completion_date, l('Approve', 'manage_proposal/approve/' . $pending_data->id) . ' | ' . l('Edit', 'manage_proposal/edit/' . $pending_data->id)); - } - - /* check if there are any pending proposals */ - if (!$pending_rows) - { - drupal_set_message(t('There are no pending proposals.'), 'status'); - return ''; - } - - $pending_header = array('Date of Submission', 'Contributor Name', 'Date of Completion', 'Action'); - $output = theme_table($pending_header, $pending_rows); - return $output; + /* get pending proposals to be approved */ + $pending_rows = array(); + /*$pending_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE proposal_status = 0 ORDER BY id DESC");*/ + $query = db_select('textbook_companion_proposal'); + $query->fields('textbook_companion_proposal'); + $query->condition('proposal_status', 0); + $query->orderBy('id', 'DESC'); + $pending_q = $query->execute(); + while ($pending_data = $pending_q->fetchObject()) { + $pending_rows[$pending_data->id] = array( + date('d-m-Y', $pending_data->creation_date), + l($pending_data->full_name, 'user/' . $pending_data->uid), + date('d-m-Y', $pending_data->completion_date), + l('Approve', 'textbook-companion/manage-proposal/approve/' . $pending_data->id) . ' | ' . l('Edit', 'textbook-companion/manage-proposal/edit/' . $pending_data->id) + ); + } + /* check if there are any pending proposals */ + if (!$pending_rows) { + drupal_set_message(t('There are no pending proposals.'), 'status'); + return ''; + } + $pending_header = array( + 'Date of Submission', + 'Contributor Name', + 'Date of Completion', + 'Action' + ); + $output = theme('table', array( + 'header' => $pending_header, + 'rows' => $pending_rows + )); + return $output; } - function _proposal_all() { - function _tbc_ext($status, $preference_id) { - if($status == "Approved") { - return " | " . l("ER", "tbc_external_review/add_book/" . $preference_id); - } - else { - return ""; - } - } - /* get pending proposals to be approved */ - $proposal_rows = array(); - $proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} ORDER BY id DESC"); - while ($proposal_data = db_fetch_object($proposal_q)) - { - /* get preference */ - $preference_q = db_query("SELECT * FROM textbook_companion_preference WHERE proposal_id = %d AND approval_status = 1 LIMIT 1", $proposal_data->id); - $preference_data = db_fetch_object($preference_q); - if(!$preference_data){ - $preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND pref_number = 1 LIMIT 1", $proposal_data->id); - $preference_data = db_fetch_object($preference_q); - } - - $proposal_status = ''; - switch ($proposal_data->proposal_status) + function _tbc_ext($status, $preference_id) { - case 0: $proposal_status = 'Pending'; break; - case 1: $proposal_status = 'Approved'; break; - case 2: $proposal_status = 'Dis-approved'; break; - case 3: $proposal_status = 'Completed'; break; - case 4: $proposal_status = 'External'; break; - default: $proposal_status = 'Unknown'; break; + if ($status == "Approved") { + //return " | " . l("ER", "tbc_external_review/add_book/" . $preference_id); + return ""; + } else { + return ""; + } } - list($y, $m, $d) = explode('-', $proposal_data->creation_date); - $cre_date = $d.'-'.$m.'-'.$y; - $dates = new DateTime($cre_date); - $creation_date = $dates->format('d-m-Y'); - list($y, $m, $d) = explode('-', $proposal_data->expected_completion_date); - $exe_date = $d.'-'.$m.'-'.$y; - $exe_date = new DateTime($exe_date); - $expected_completion_date = $exe_date->format('d-m-Y'); - - $proposal_rows[] = array( - $creation_date, - "{$preference_data->book} <br> <em>by {$preference_data->author}</em>", - l($proposal_data->full_name, 'user/' . $proposal_data->uid), - $expected_completion_date, - $proposal_status, - l('Status', 'manage_proposal/status/' . $proposal_data->id) . ' | ' . l('Edit', 'manage_proposal/edit/' . $proposal_data->id) . _tbc_ext($proposal_status, $preference_data->id) - ); - } - - /* check if there are any pending proposals */ - if (!$proposal_rows) - { - drupal_set_message(t('There are no proposals.'), 'status'); - return ''; - } - - $proposal_header = array('Date of Submission', 'Title of the Book', 'Contributor Name', 'Expected Date of Completion', 'Status', 'Action'); - $output = theme_table($proposal_header, $proposal_rows); - return $output; + /* get pending proposals to be approved */ + $proposal_rows = array(); + /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} ORDER BY id DESC");*/ + $query = db_select('textbook_companion_proposal'); + $query->fields('textbook_companion_proposal'); + $query->orderBy('id', 'DESC'); + $proposal_q = $query->execute(); + while ($proposal_data = $proposal_q->fetchObject()) { + /* get preference */ + /*$preference_q = db_query("SELECT * FROM textbook_companion_preference WHERE proposal_id = %d AND approval_status = 1 LIMIT 1", $proposal_data->id); + $preference_data = db_fetch_object($preference_q);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('proposal_id', $proposal_data->id); + $query->condition('approval_status', 1); + $query->range(0, 1); + $preference_q = $query->execute(); + $preference_data = $preference_q->fetchObject(); + if (!$preference_data) { + /* $preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND pref_number = 1 LIMIT 1", $proposal_data->id); + $preference_data = db_fetch_object($preference_q);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('proposal_id', $proposal_data->id); + $query->condition('pref_number', 1); + //$query->condition('approval_status', 0); + $query->range(0, 1); + $preference_q = $query->execute(); + $preference_data = $preference_q->fetchObject(); + } + $proposal_status = ''; + switch ($proposal_data->proposal_status) { + case 0: + $proposal_status = 'Pending'; + break; + case 1: + $proposal_status = 'Approved'; + break; + case 2: + $proposal_status = 'Dis-approved'; + break; + case 3: + $proposal_status = 'Completed'; + break; + case 4: + $proposal_status = 'External'; + break; + case 5: + $proposal_status = 'Submitted all codes'; + break; + default: + $proposal_status = 'Unknown'; + break; + } + $proposal_rows[] = array( + date('d-m-Y', $proposal_data->creation_date), + "{$preference_data->book} <br> +<em>by {$preference_data->author}</em>", + l($proposal_data->full_name, 'user/' . $proposal_data->uid), + date('d-m-Y', $proposal_data->completion_date), + $proposal_status, + l('Status', 'textbook-companion/manage-proposal/status/' . $proposal_data->id) . ' | ' . l('Edit', 'textbook-companion/manage-proposal/edit/' . $proposal_data->id) . _tbc_ext($proposal_status, $preference_data->id) + ); + } + /* check if there are any pending proposals */ + if (!$proposal_rows) { + drupal_set_message(t('There are no proposals.'), 'status'); + return ''; + } + $proposal_header = array( + 'Date of Submission', + 'Title of the Book', + 'Contributor Name', + 'Expected Date of Completion', + 'Status', + 'Action' + ); + $output = theme('table', array( + 'header' => $proposal_header, + 'rows' => $proposal_rows + )); + return $output; } - function _category_all() { - /* get pending proposals to be approved */ - $preference_rows = array(); - $preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE approval_status = 1 ORDER BY id DESC"); - while ($preference_data = db_fetch_object($preference_q)) - { - switch ($preference_data->category) - { - case 0: $category_data = 'Not Selected'; break; - case 1: $category_data = 'Fluid Mechanics'; break; - case 2: $category_data = 'Control Theory & Control Systems'; break; - case 3: $category_data = 'Chemical Engineering'; break; - case 4: $category_data = 'Thermodynamics'; break; - case 5: $category_data = 'Mechanical Engineering'; break; - case 6: $category_data = 'Signal Processing'; break; - case 7: $category_data = 'Digital Communications'; break; - case 8: $category_data = 'Electrical Technology'; break; - case 9: $category_data = 'Mathematics & Pure Science'; break; - case 10: $category_data = 'Analog Electronics'; break; - case 11: $category_data = 'Digital Electronics'; break; - case 12: $category_data = 'Computer Programming'; break; - case 13: $category_data = 'Others'; break; - default: $category_data = 'Unknown'; break; - } - $preference_rows[] = array($preference_data->book ."<br> <i>by " .$preference_data->author."</i>", $preference_data->isbn, $preference_data->publisher, $preference_data->edition, $preference_data->year, $category_data, l('Edit', 'manage_proposal/category/edit/' . $preference_data->id)); - } - - $preference_header = array('Book', 'ISBN', 'Publisher', 'Edition', 'Year', 'Category', 'Status'); - $output = theme_table($preference_header, $preference_rows); - return $output; + /* get pending proposals to be approved */ + $preference_rows = array(); + /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE approval_status = 1 ORDER BY id DESC");*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('approval_status', 1); + $query->orderBy('id', 'DESC'); + $preference_q = $query->execute(); + while ($preference_data = $preference_q->fetchObject()) { + switch ($preference_data->category) { + case 0: + $category_data = 'Not Selected'; + break; + case 1: + $category_data = 'Fluid Mechanics'; + break; + case 2: + $category_data = 'Control Theory & Control Systems'; + break; + case 3: + $category_data = 'Chemical Engineering'; + break; + case 4: + $category_data = 'Thermodynamics'; + break; + case 5: + $category_data = 'Mechanical Engineering'; + break; + case 6: + $category_data = 'Signal Processing'; + break; + case 7: + $category_data = 'Digital Communications'; + break; + case 8: + $category_data = 'Electrical Technology'; + break; + case 9: + $category_data = 'Mathematics & Pure Science'; + break; + case 10: + $category_data = 'Analog Electronics'; + break; + case 11: + $category_data = 'Digital Electronics'; + break; + case 12: + $category_data = 'Computer Programming'; + break; + case 13: + $category_data = 'Others'; + break; + default: + $category_data = 'Unknown'; + break; + } + $preference_rows[] = array( + $preference_data->book . "<br> <i>by " . $preference_data->author . "</i>", + $preference_data->isbn, + $preference_data->publisher, + $preference_data->edition, + $preference_data->year, + $category_data, + l('Edit', 'textbook-companion/manage-proposal/category/edit/' . $preference_data->id) + ); + } + $preference_header = array( + 'Book', + 'ISBN', + 'Publisher', + 'Edition', + 'Year', + 'Category', + 'Status' + ); + $output = theme('table', array( + 'header' => $preference_header, + 'rows' => $preference_rows + )); + return $output; } - /******************************************************************************/ /************************** PROPOSAL APPROVAL FORM ****************************/ /******************************************************************************/ - -function proposal_approval_form($form_state) +function proposal_approval_form($form, $form_state) { - global $user; - - /* get current proposal */ - $proposal_id = arg(2); - $result = db_query("SELECT * FROM {textbook_companion_proposal} WHERE proposal_status = 0 and id = %d", $proposal_id); - if ($result) - { - if ($row = db_fetch_object($result)) - { - /* everything ok */ + global $user; + /* get current proposal */ + $proposal_id = arg(3); + /*$result = db_query("SELECT * FROM {textbook_companion_proposal} WHERE proposal_status = 0 and id = %d", $proposal_id);*/ + $query = db_select('textbook_companion_proposal'); + $query->fields('textbook_companion_proposal'); + $query->condition('proposal_status', 0); + $query->condition('id', $proposal_id); + $result = $query->execute(); + if ($result) { + if ($row = $result->fetchObject()) { + /* everything ok */ + } else { + drupal_set_message(t('Invalid proposal selected. Please try again.'), 'error'); + drupal_goto('textbook-companion/manage-proposal'); + return; + } } else { - drupal_set_message(t('Invalid proposal selected. Please try again.'), 'error'); - drupal_goto('manage_proposal'); - return; + drupal_set_message(t('Invalid proposal selected. Please try again.'), 'error'); + drupal_goto('textbook-companion/manage-proposal'); + return; + } + $form['full_name'] = array( + '#type' => 'item', + '#markup' => l($row->full_name, 'user/' . $row->uid), + '#title' => t('Contributor Name') + ); + $form['email'] = array( + '#type' => 'item', + '#markup' => user_load($row->uid)->mail, + '#title' => t('Email') + ); + $form['mobile'] = array( + '#type' => 'item', + '#markup' => $row->mobile, + '#title' => t('Mobile') + ); + $form['how_project'] = array( + '#type' => 'item', + '#markup' => $row->how_project, + '#title' => t('How did you come to know about this project') + ); + $form['course'] = array( + '#type' => 'item', + '#markup' => $row->course, + '#title' => t('Course') + ); + $form['branch'] = array( + '#type' => 'item', + '#markup' => $row->branch, + '#title' => t('Department/Branch') + ); + $form['university'] = array( + '#type' => 'item', + '#markup' => $row->university, + '#title' => t('University/Institute') + ); + $form['city'] = array( + '#type' => 'item', + '#markup' => $row->city, + '#title' => t('City/Village') + ); + $form['pincode'] = array( + '#type' => 'item', + '#markup' => $row->pincode, + '#title' => t('Pincode') + ); + $form['state'] = array( + '#type' => 'item', + '#markup' => $row->state, + '#title' => t('State') + ); + $form['faculty'] = array( + '#type' => 'hidden', + '#markup' => $row->faculty, + '#title' => t('College Teacher/Professor') + ); + $form['reviewer'] = array( + '#type' => 'hidden', + '#markup' => $row->reviewer, + '#title' => t('Reviewer') + ); + $form['completion_date'] = array( + '#type' => 'item', + '#markup' => date('d-m-Y', $row->completion_date), + '#title' => t('Expected Date of Completion') + ); + $form['operating_system'] = array( + '#type' => 'item', + '#markup' => $row->operating_system, + '#title' => t('Operating System') + ); + $form['version'] = array( + '#type' => 'item', + '#markup' => $row->dwsim_version, + '#title' => t('DWSIM Version') + ); + $form['reference'] = array( + '#type' => 'item', + '#markup' => $row->reference, + '#title' => t('References') + ); + $form['reason'] = array( + '#type' => 'item', + '#markup' => $row->reason, + '#title' => t('Reasons') + ); + /* get book preference */ + $preference_rows = array(); + /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d ORDER BY pref_number ASC", $proposal_id);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('proposal_id', $proposal_id); + $query->orderBy('pref_number', 'ASC'); + $preference_q = $query->execute(); + while ($preference_data = $preference_q->fetchObject()) { + $preference_rows[$preference_data->id] = $preference_data->book . ' (Written by ' . $preference_data->author . ')'; + } + if ($row->proposal_type == 1) { + $form['book_preference'] = array( + '#type' => 'radios', + '#options' => $preference_rows, + '#title' => t('Book Preferences'), + '#required' => TRUE + ); + } else { + $form['book_preference'] = array( + '#type' => 'radios', + '#title' => t('Book Preferences'), + '#options' => $preference_rows, + '#required' => TRUE + ); + } + if ($row->samplefilepath != "Not available") { + $form['samplecode'] = array( + '#type' => 'markup', + '#markup' => l('Download Sample Code', 'textbook-companion/download/samplecode/' . $proposal_id) . "<br><br>" + ); + } + $form['disapprove'] = array( + '#type' => 'checkbox', + '#title' => t('Disapprove all the above book preferences') + ); + $form['message'] = array( + '#type' => 'textarea', + '#title' => t('Reason for disapproval'), + '#states' => array( + 'visible' => array( + ':input[name="disapprove"]' => array( + 'checked' => TRUE + ) + ), + 'required' => array( + ':input[name="disapprove"]' => array( + 'checked' => TRUE + ) + ) + ) + ); + $form['proposal_id'] = array( + '#type' => 'hidden', + '#value' => $proposal_id + ); + $form['submit'] = array( + '#type' => 'submit', + '#value' => t('Submit') + ); + $form['cancel'] = array( + '#type' => 'markup', + '#value' => l(t('Cancel'), 'textbook-companion/manage-proposal') + ); + return $form; +} +function proposal_approval_form_validate($form, &$form_state) +{ + if ($form_state['values']['disapprove']) { + if (strlen(trim($form_state['values']['message'])) <= 30) { + form_set_error('message', t('Please mention the reason for disapproval in minimum 30 characters.')); + } } - } else { - drupal_set_message(t('Invalid proposal selected. Please try again.'), 'error'); - drupal_goto('manage_proposal'); return; - } - - $form['full_name'] = array( - '#type' => 'item', - '#value' => l($row->full_name, 'user/' . $row->uid), - '#title' => t('Contributor Name'), - ); - $form['email'] = array( - '#type' => 'item', - '#value' => user_load($row->uid)->mail, - '#title' => t('Email'), - ); - $form['mobile'] = array( - '#type' => 'item', - '#value' => $row->mobile, - '#title' => t('Mobile'), - ); - $form['how_project'] = array( - '#type' => 'item', - '#value' => $row->how_project, - '#title' => t('How did you come to know about this project'), - ); - $form['course'] = array( - '#type' => 'item', - '#value' => $row->course, - '#title' => t('Course'), - ); - $form['branch'] = array( - '#type' => 'item', - '#value' => $row->branch, - '#title' => t('Department/Branch'), - ); - $form['university'] = array( - '#type' => 'item', - '#value' => $row->university, - '#title' => t('University/Institute'), - ); - $form['faculty'] = array( - '#type' => 'item', - '#value' => $row->faculty, - '#title' => t('College Teacher/Professor'), - ); - $form['reviewer'] = array( - '#type' => 'item', - '#value' => $row->reviewer, - '#title' => t('Reviewer'), - ); - - list($y, $m, $d) = explode('-', $row->expected_completion_date); - $con_date = $d.'-'.$m.'-'.$y; - $date = new DateTime($con_date); - $expected_completion_date = $date->format('d-m-Y'); - $form['completion_date'] = array( - '#type' => 'item', - '#value' => $expected_completion_date, - '#title' => t('Expected Date of Completion'), - ); - $form['operating_system'] = array( - '#type' => 'item', - '#value' => $row->operating_system, - '#title' => t('Operating System'), - ); - $form['dwsim_version'] = array( - '#type' => 'item', - '#value' => $row->dwsim_version, - '#title' => t('DWSIM Version'), - ); - $form['reference'] = array( - '#type' => 'item', - '#value' => $row->reference, - '#title' => t('References'), - ); - $form['reason'] = array( - '#type' => 'item', - '#value' => $row->reason, - '#title' => t('Reasons'), - ); - - /* get book preference */ - $preference_rows = array(); - $preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d ORDER BY pref_number ASC", $proposal_id); - while ($preference_data = db_fetch_object($preference_q)) - { - $preference_rows[$preference_data->id] = $preference_data->book . ' (Written by ' . $preference_data->author . ')'; - } - if($row->proposal_type == 1){ - $form['book_preference'] = array( - '#type' => 'radios', - '#options' => $preference_rows, - '#title' => t('Book Preferences'), - '#required' => TRUE, - - ); - } - else{ - $form['book_preference'] = array( - '#type' => 'radios', - '#title' => t('Book Preferences'), - '#options' => $preference_rows, - '#required' => TRUE, - );} - - $form['disapprove'] = array( - '#type' => 'checkbox', - '#title' => t('Disapprove all the above book preferences'), - - ); - - $form['message'] = array( - '#type' => 'textarea', - '#title' => t('Reason for disapproval'), - ); - - $form['proposal_id'] = array( - '#type' => 'hidden', - '#value' => $proposal_id, - ); - - $form['submit'] = array( - '#type' => 'submit', - '#value' => t('Submit') - ); - - $form['cancel'] = array( - '#type' => 'markup', - '#value' => l(t('Cancel'), 'manage_proposal'), - ); - return $form; } - function proposal_approval_form_submit($form, &$form_state) { - global $user; - - /* get current proposal */ - $proposal_id = $form_state['values']['proposal_id']; - $result = db_query("SELECT * FROM {textbook_companion_proposal} WHERE proposal_status = 0 and id = %d", $proposal_id); - if ($result) - { - if ($row = db_fetch_object($result)) - { - /* everything ok */ + global $user; + /* get current proposal */ + $proposal_id = $form_state['values']['proposal_id']; + /*$result = db_query("SELECT * FROM {textbook_companion_proposal} WHERE proposal_status = 0 and id = %d", $proposal_id);*/ + $query = db_select('textbook_companion_proposal'); + $query->fields('textbook_companion_proposal'); + $query->condition('proposal_status', 0); + $query->condition('id', $proposal_id); + $result = $query->execute(); + if ($result) { + if ($row = $result->fetchObject()) { + /* everything ok */ + } else { + drupal_set_message(t('Invalid proposal selected. Please try again.'), 'error'); + drupal_goto('textbook-companion/manage-proposal'); + return; + } } else { - drupal_set_message(t('Invalid proposal selected. Please try again.'), 'error'); - drupal_goto('manage_proposal'); - return; + drupal_set_message(t('Invalid proposal selected. Please try again.'), 'error'); + drupal_goto('textbook-companion/manage-proposal'); + return; } - } else { - drupal_set_message(t('Invalid proposal selected. Please try again.'), 'error'); - drupal_goto('manage_proposal'); - return; - } - - /* disapprove */ - if ($form_state['values']['disapprove']) - { $dt = new DateTime(); - $current_date = $dt->format("Y-m-d"); - db_query("UPDATE {textbook_companion_proposal} SET approver_uid = %d, approval_date = %d, proposal_status = 2, message = '%s' WHERE id = %d", $user->uid, $current_date, $form_state['values']['message'], $proposal_id); - db_query("UPDATE {textbook_companion_preference} SET approval_status = 2 WHERE proposal_id = %d", $proposal_id); - - /* unlock all the aicte books */ - $query = " - UPDATE textbook_companion_aicte - SET status = 0, uid = 0, proposal_id = 0, preference_id = 0 - WHERE proposal_id = {$proposal_id} + /* disapprove */ + if ($form_state['values']['disapprove']) { + /*db_query("UPDATE {textbook_companion_proposal} SET approver_uid = %d, approval_date = %d, proposal_status = 2, message = '%s' WHERE id = %d", $user->uid, time(), $form_state['values']['message'], $proposal_id);*/ + $query = db_update('textbook_companion_proposal'); + $query->fields(array( + 'approver_uid' => $user->uid, + 'approval_date' => time(), + 'proposal_status' => 2, + 'message' => $form_state['values']['message'] + )); + $query->condition('id', $proposal_id); + $num_updated = $query->execute(); + /*db_query("UPDATE {textbook_companion_preference} SET approval_status = 2 WHERE proposal_id = %d", $proposal_id);*/ + $query = db_update('textbook_companion_preference'); + $query->fields(array( + 'approval_status' => 2 + )); + $query->condition('proposal_id', $proposal_id); + $num_updated = $query->execute(); + /* unlock all the aicte books */ + /*$query = " + UPDATE textbook_companion_aicte + SET status = 0, uid = 0, proposal_id = 0, preference_id = 0 + WHERE proposal_id = {$proposal_id} + "; + db_query($query);*/ + /*$query = db_update('textbook_companion_aicte'); + $query->fields(array( + 'status' => 0, + 'uid' => 0, + 'proposal_id' => 0, + 'preference_id' => 0, + )); + $query->condition('proposal_id', $proposal_id); + $num_updated = $query->execute();*/ + /* sending email */ + $book_user = user_load($row->uid); + $email_to = $book_user->mail; + $from = variable_get('textbook_companion_from_email', ''); + $bcc = variable_get('textbook_companion_emails', ''); + $cc = variable_get('textbook_companion_cc_emails', ''); + $param['proposal_disapproved']['proposal_id'] = $proposal_id; + $param['proposal_disapproved']['user_id'] = $row->uid; + $param['proposal_disapproved']['headers'] = array( + 'From' => $from, + 'MIME-Version' => '1.0', + 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes', + 'Content-Transfer-Encoding' => '8Bit', + 'X-Mailer' => 'Drupal', + 'Cc' => $cc, + 'Bcc' => $bcc + ); + if (!drupal_mail('textbook_companion', 'proposal_disapproved', $email_to, language_default(), $param, $from, TRUE)) + drupal_set_message('Error sending email message.', 'error'); + drupal_set_message('Book proposal dis-approved. User has been notified of the dis-approval.', 'error'); + drupal_goto('textbook-companion/manage-proposal'); + return; + } + /* get book preference and set the status */ + $preference_id = $form_state['values']['book_preference']; + /*db_query("UPDATE {textbook_companion_proposal} SET approver_uid = %d, approval_date = %d, proposal_status = 1 WHERE id = %d", $user->uid, time(), $proposal_id);*/ + $query = db_update('textbook_companion_proposal'); + $query->fields(array( + 'approver_uid' => $user->uid, + 'approval_date' => time(), + 'proposal_status' => 1 + )); + $query->condition('id', $proposal_id); + $num_updated = $query->execute(); + /*db_query("UPDATE {textbook_companion_preference} SET approval_status = 1 WHERE id = %d", $preference_id);*/ + $query = db_update('textbook_companion_preference'); + $query->fields(array( + 'approval_status' => 1 + )); + $query->condition('id', $preference_id); + $num_updated = $query->execute(); + /* unlock aicte books except the one which was approved out of 3 nos */ + /* $query = " + UPDATE textbook_companion_aicte + SET status = 0, uid = 0, proposal_id = 0, preference_id = 0 + WHERE proposal_id = {$proposal_id} AND preference_id != {$preference_id} "; - db_query($query); + db_query($query);*/ + /*$query = db_update('textbook_companion_aicte'); + $query->fields(array( + 'status' => 0, + 'uid' => 0, + 'proposal_id' => 0, + 'preference_id' => 0, + )); + $query->condition('proposal_id', '$proposal_id'); + $query->condition('preference_id', '$preference_id', '<>'); + $num_updated = $query->execute();*/ /* sending email */ $book_user = user_load($row->uid); - $param['proposal_disapproved']['proposal_id'] = $proposal_id; - $param['proposal_disapproved']['user_id'] = $row->uid; $email_to = $book_user->mail; - if (!drupal_mail('textbook_companion', 'proposal_disapproved', $email_to , language_default(), $param, variable_get('textbook_companion_from_email', NULL), TRUE)) - drupal_set_message('Error sending email message.', 'error'); - - drupal_set_message('Book proposal dis-approved. User has been notified of the dis-approval.', 'error'); - drupal_goto('manage_proposal'); + $from = variable_get('textbook_companion_from_email', ''); + $bcc = variable_get('textbook_companion_emails', ''); + $cc = variable_get('textbook_companion_cc_emails', ''); + $param['proposal_approved']['proposal_id'] = $proposal_id; + $param['proposal_approved']['user_id'] = $row->uid; + $param['proposal_approved']['headers'] = array( + 'From' => $from, + 'MIME-Version' => '1.0', + 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes', + 'Content-Transfer-Encoding' => '8Bit', + 'X-Mailer' => 'Drupal', + 'Cc' => $cc, + 'Bcc' => $bcc + ); + if (!drupal_mail('textbook_companion', 'proposal_approved', $email_to, language_default(), $param, $from, TRUE)) + drupal_set_message('Error sending email message.', 'error'); + drupal_set_message('Book proposal approved. User has been notified of the approval', 'status'); + drupal_goto('textbook-companion/manage-proposal'); return; - } - $dt = new DateTime(); - $current_date = $dt->format("Y-m-d"); - /* get book preference and set the status */ - $preference_id = $form_state['values']['book_preference']; - db_query("UPDATE {textbook_companion_proposal} SET approver_uid = %d, approval_date = %d, proposal_status = 1 WHERE id = %d", $user->uid, $current_date, $proposal_id); - db_query("UPDATE {textbook_companion_preference} SET approval_status = 1 WHERE id = %d", $preference_id); - - /* unlock aicte books except the one which was approved out of 3 nos */ - $query = " - UPDATE textbook_companion_aicte - SET status = 0, uid = 0, proposal_id = 0, preference_id = 0 - WHERE proposal_id = {$proposal_id} AND preference_id != {$preference_id} - "; - db_query($query); - - /* sending email */ - $book_user = user_load($row->uid); - $param['proposal_approved']['proposal_id'] = $proposal_id; - $param['proposal_approved']['user_id'] = $row->uid; - $email_to = $book_user->mail; - if (!drupal_mail('textbook_companion', 'proposal_approved', $email_to , language_default(), $param, variable_get('textbook_companion_from_email', NULL), TRUE)) - drupal_set_message('Error sending email message.', 'error'); - - drupal_set_message('Book proposal approved. User has been notified of the approval', 'status'); - drupal_goto('manage_proposal'); - return; } - - /******************************************************************************/ /*************************** PROPOSAL STATUS FORM *****************************/ /******************************************************************************/ - -function proposal_status_form($form_state) +function proposal_status_form($from, $form_state) { - global $user; - - /* get current proposal */ - $proposal_id = arg(2); - $proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d", $proposal_id); - if (!$proposal_data = db_fetch_object($proposal_q)) - { - drupal_set_message(t('Invalid proposal selected. Please try again.'), 'error'); - drupal_goto('manage_proposal'); - return; - } - - $form['full_name'] = array( - '#type' => 'item', - '#value' => $proposal_data->full_name, - '#title' => t('Contributor Name'), - ); - $form['email'] = array( - '#type' => 'item', - '#value' => user_load($proposal_data->uid)->mail, - '#title' => t('Email'), - ); - $form['mobile'] = array( - '#type' => 'item', - '#value' => $proposal_data->mobile, - '#title' => t('Mobile'), - ); - $form['how_project'] = array( - '#type' => 'item', - '#value' => $proposal_data->how_project, - '#title' => t('How did you come to know about this project'), - ); - $form['course'] = array( - '#type' => 'item', - '#value' => $proposal_data->course, - '#title' => t('Course'), - ); - $form['branch'] = array( - '#type' => 'item', - '#value' => $proposal_data->branch, - '#title' => t('Department/Branch'), - ); - $form['university'] = array( - '#type' => 'item', - '#value' => $proposal_data->university, - '#title' => t('University/Institute'), - ); - $form['faculty'] = array( - '#type' => 'item', - '#value' => $proposal_data->faculty, - '#title' => t('College Teacher/Professor'), - ); - $form['reviewer'] = array( - '#type' => 'item', - '#value' => $proposal_data->reviewer, - '#title' => t('Reviewer'), - ); - list($y, $m, $d) = explode('-', $proposal_data->expected_completion_date); - $con_date = $d.'-'.$m.'-'.$y; - $date = new DateTime($con_date); - $expected_completion_date = $date->format('d-m-Y'); - $form['completion_date'] = array( - '#type' => 'item', - '#value' => $expected_completion_date, - '#title' => t('Expected Date of Completion'), - ); - $form['operating_system'] = array( - '#type' => 'item', - '#value' => $proposal_data->operating_system, - '#title' => t('Operating System'), - ); - $form['dwsim_version'] = array( - '#type' => 'item', - '#value' => $proposal_data->dwsim_version, - '#title' => t('DWSIM Version'), - ); - if($proposal_data->proposal_type == 1) - { - $form['reason'] = array( - '#type' => 'item', - '#value' => $proposal_data->reason, - '#title' => t('Reason'), - ); - $form['reference'] = array( - '#type' => 'item', - '#value' => $proposal_data->reference, - '#title' => t('References'), - ); - } - - - /* get book preference */ - $preference_html = '<ul>'; - $preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d ORDER BY pref_number ASC", $proposal_id); - while ($preference_data = db_fetch_object($preference_q)) - { - if ($preference_data->approval_status == 1) - $preference_html .= '<li><strong>' . $preference_data->book . ' (Written by ' . $preference_data->author . ') - Approved Book</strong></li>'; - else - $preference_html .= '<li>' . $preference_data->book . ' (Written by ' . $preference_data->author . ')</li>'; - } - $preference_html .= '</ul>'; - - $form['book_preference'] = array( - '#type' => 'item', - '#value' => $preference_html, - '#title' => t('Book Preferences'), - ); - - $proposal_status = ''; - switch ($proposal_data->proposal_status) - { - case 0: $proposal_status = t('Pending'); break; - case 1: $proposal_status = t('Approved'); break; - case 2: $proposal_status = t('Dis-approved'); break; - case 3: $proposal_status = t('Completed'); break; - case 4: $proposal_status = t('External'); break; - default: $proposal_status = t('Unkown'); break; - } - $form['proposal_status'] = array( - '#type' => 'item', - '#value' => $proposal_status, - '#title' => t('Proposal Status'), - ); - - if ($proposal_data->proposal_status == 2) { - $form['message'] = array( - '#type' => 'item', - '#value' => $proposal_data->message, - '#title' => t('Reason for disapproval'), - ); - } - - if ($proposal_data->proposal_status == 1 || $proposal_data->proposal_status == 4) - { - $form['completed'] = array( - '#type' => 'checkbox', - '#title' => t('Completed'), - '#description' => t('Check if user has completed all the book examples.'), - ); - } - - if ($proposal_data->proposal_status == 0) - { - $form['approve'] = array( - '#type' => 'item', - '#value' => l('Click here', 'manage_proposal/approve/' . $proposal_id), - '#title' => t('Approve'), - ); - } - - $form['proposal_id'] = array( - '#type' => 'hidden', - '#value' => $proposal_id, - ); - - $form['submit'] = array( - '#type' => 'submit', - '#value' => t('Submit') - ); - - $form['cancel'] = array( - '#type' => 'markup', - '#value' => l(t('Cancel'), 'manage_proposal/all'), - ); - return $form; + global $user; + /* get current proposal */ + $proposal_id = arg(3); + /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d", $proposal_id);*/ + $query = db_select('textbook_companion_proposal'); + $query->fields('textbook_companion_proposal'); + $query->condition('id', $proposal_id); + $proposal_q = $query->execute(); + if (!$proposal_data = $proposal_q->fetchObject()) { + drupal_set_message(t('Invalid proposal selected. Please try again.'), 'error'); + drupal_goto('textbook-companion/manage-proposal'); + return; + } + $form['full_name'] = array( + '#type' => 'item', + '#markup' => $proposal_data->full_name, + '#title' => t('Contributor Name') + ); + $form['email'] = array( + '#type' => 'item', + '#markup' => user_load($proposal_data->uid)->mail, + '#title' => t('Email') + ); + $form['mobile'] = array( + '#type' => 'item', + '#markup' => $proposal_data->mobile, + '#title' => t('Mobile') + ); + $form['how_project'] = array( + '#type' => 'item', + '#markup' => $proposal_data->how_project, + '#title' => t('How did you come to know about this project') + ); + $form['course'] = array( + '#type' => 'item', + '#markup' => $proposal_data->course, + '#title' => t('Course') + ); + $form['branch'] = array( + '#type' => 'item', + '#markup' => $proposal_data->branch, + '#title' => t('Department/Branch') + ); + $form['university'] = array( + '#type' => 'item', + '#markup' => $proposal_data->university, + '#title' => t('University/Institute') + ); + $form['city'] = array( + '#type' => 'item', + '#markup' => $proposal_data->city, + '#title' => t('City/Village') + ); + $form['pincode'] = array( + '#type' => 'item', + '#markup' => $proposal_data->pincode, + '#title' => t('Pincode') + ); + $form['state'] = array( + '#type' => 'item', + '#markup' => $proposal_data->state, + '#title' => t('State') + ); + $form['faculty'] = array( + '#type' => 'hidden', + '#markup' => $proposal_data->faculty, + '#title' => t('College Teacher/Professor') + ); + $form['reviewer'] = array( + '#type' => 'hidden', + '#markup' => $proposal_data->reviewer, + '#title' => t('Reviewer') + ); + $form['completion_date'] = array( + '#type' => 'item', + '#markup' => date('d-m-Y', $proposal_data->completion_date), + '#title' => t('Expected Date of Completion') + ); + $form['operating_system'] = array( + '#type' => 'item', + '#markup' => $proposal_data->operating_system, + '#title' => t('Operating System') + ); + $form['version'] = array( + '#type' => 'item', + '#markup' => $proposal_data->dwsim_version, + '#title' => t('DWSIM Version') + ); + if ($proposal_data->proposal_type == 1) { + $form['reason'] = array( + '#type' => 'hidden', + '#markup' => $proposal_data->reason, + '#title' => t('Reason') + ); + $form['reference'] = array( + '#type' => 'hidden', + '#markup' => $proposal_data->reference, + '#title' => t('References') + ); + } + /* get book preference */ + $preference_html = '<ul>'; + /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d ORDER BY pref_number ASC", $proposal_id);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('proposal_id', $proposal_id); + $query->orderBy('pref_number', 'ASC'); + $preference_q = $query->execute(); + while ($preference_data = $preference_q->fetchObject()) { + if ($preference_data->approval_status == 1) + $preference_html .= '<li><strong>' . $preference_data->book . ' (Written by ' . $preference_data->author . ') - Approved Book</strong></li>'; + else + $preference_html .= '<li>' . $preference_data->book . ' (Written by ' . $preference_data->author . ')</li>'; + } + $preference_html .= '</ul>'; + $form['book_preference'] = array( + '#type' => 'item', + '#markup' => $preference_html, + '#title' => t('Book Preferences') + ); + $proposal_status = ''; + switch ($proposal_data->proposal_status) { + case 0: + $proposal_status = t('Pending'); + break; + case 1: + $proposal_status = t('Approved'); + break; + case 2: + $proposal_status = t('Dis-approved'); + break; + case 3: + $proposal_status = t('Completed'); + break; + case 4: + $proposal_status = t('External'); + break; + case 5: + $proposal_status = t('Submitted all codes'); + break; + default: + $proposal_status = t('Unkown'); + break; + } + $form['proposal_status'] = array( + '#type' => 'item', + '#markup' => $proposal_status, + '#title' => t('Proposal Status') + ); + if ($proposal_data->proposal_status == 2) { + $form['message'] = array( + '#type' => 'item', + '#markup' => $proposal_data->message, + '#title' => t('Reason for disapproval') + ); + } + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('proposal_id', $proposal_id); + $query->orderBy('pref_number', 'ASC'); + $preference_q_status = $query->execute()->fetchObject(); + if ($preference_q_status->submited_all_examples_code < 1 && $proposal_data->proposal_status == 5) { + $form['submit_all_code'] = array( + '#type' => 'checkbox', + '#title' => t('<strong>Enable Code Submission for user</strong>'), + '#description' => t('Check if user has not submitted all the book examples.') + ); + $form['completed'] = array( + '#type' => 'hidden', + '#value' => 0 + ); + } + if ($proposal_data->proposal_status == 1 || $proposal_data->proposal_status == 4 || $preference_q_status->submited_all_examples_code == 1 && $proposal_data->proposal_status == 5) { + $form['completed'] = array( + '#type' => 'checkbox', + '#title' => t('<strong>Completed</strong>'), + '#description' => t('Check if user has completed all the book examples.') + ); + $form['submit_all_code'] = array( + '#type' => 'hidden', + '#value' => 0 + ); + } + if ($proposal_data->proposal_status == 0) { + $form['approve'] = array( + '#type' => 'item', + '#markup' => l('Click here', 'textbook-companion/manage-proposal/approve/' . $proposal_id), + '#title' => t('Approve') + ); + $form['completed'] = array( + '#type' => 'hidden', + '#value' => 0 + ); + $form['submit_all_code'] = array( + '#type' => 'hidden', + '#value' => 0 + ); + } + $form['proposal_id'] = array( + '#type' => 'hidden', + '#value' => $proposal_id + ); + $form['submit'] = array( + '#type' => 'submit', + '#value' => t('Submit') + ); + $form['cancel'] = array( + '#type' => 'item', + '#markup' => l(t('Cancel'), 'textbook-companion/manage-proposal/all') + ); + return $form; } - function proposal_status_form_submit($form, &$form_state) { - global $user; - - /* get current proposal */ - $proposal_id = $form_state['values']['proposal_id']; - $proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d", $proposal_id); - if (!$proposal_data = db_fetch_object($proposal_q)) - { - drupal_set_message(t('Invalid proposal selected. Please try again.'), 'error'); - drupal_goto('manage_proposal'); + global $user; + /* get current proposal */ + $proposal_id = $form_state['values']['proposal_id']; + /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d", $proposal_id);*/ + $query = db_select('textbook_companion_proposal'); + $query->fields('textbook_companion_proposal'); + $query->condition('id', $proposal_id); + $proposal_q = $query->execute(); + if (!$proposal_data = $proposal_q->fetchObject()) { + drupal_set_message(t('Invalid proposal selected. Please try again.'), 'error'); + drupal_goto('textbook-companion/manage-proposal'); + return; + } + if ($form_state['values']['submit_all_code'] == 1) { + /*db_query("UPDATE {textbook_companion_proposal} SET proposal_status = 3 WHERE id = %d", $proposal_id);*/ + $query = db_update('textbook_companion_proposal'); + $query->fields(array( + 'proposal_status' => 1 + )); + $query->condition('id', $proposal_id); + $num_updated = $query->execute(); + /* sending email */ + $book_user = user_load($proposal_data->uid); + $params['all_code_submitted_status_changed']['proposal_id'] = $proposal_id; + $params['all_code_submitted_status_changed']['user_id'] = $proposal_data->uid; + $email_to = $book_user->mail; + if (!drupal_mail('textbook_companion', 'all_code_submitted_status_changed', $email_to, language_default(), $params, variable_get('textbook_companion_from_email', NULL), TRUE)) + drupal_set_message('Error sending email message.', 'error'); + drupal_set_message('User has been notified of that code submission interface is now available .', 'status'); + drupal_goto('textbook-companion/manage-proposal'); + return; + } else /* set the book status to completed */ if ($form_state['values']['completed'] == 1) { + /*db_query("UPDATE {textbook_companion_proposal} SET proposal_status = 3 WHERE id = %d", $proposal_id);*/ + $query = db_update('textbook_companion_proposal'); + $query->fields(array( + 'proposal_status' => 3, + 'completion_date' => time() + )); + $query->condition('id', $proposal_id); + $num_updated = $query->execute(); + CreateReadmeFileTextbookCompanion($proposal_id); + /* sending email */ + $book_user = user_load($proposal_data->uid); + $email_to = $book_user->mail; + $from = variable_get('textbook_companion_from_email', ''); + $bcc = variable_get('textbook_companion_emails', ''); + $cc = variable_get('textbook_companion_cc_emails', ''); + $param['proposal_completed']['proposal_id'] = $proposal_id; + $param['proposal_completed']['user_id'] = $proposal_data->uid; + $param['proposal_completed']['headers'] = array( + 'From' => $from, + 'MIME-Version' => '1.0', + 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes', + 'Content-Transfer-Encoding' => '8Bit', + 'X-Mailer' => 'Drupal', + 'Cc' => $cc, + 'Bcc' => $bcc + ); + if (!drupal_mail('textbook_companion', 'proposal_completed', $email_to, language_default(), $param, $from, TRUE)) + drupal_set_message('Error sending email message.', 'error'); + drupal_set_message('Congratulations! Book proposal has been marked as completed. User has been notified of the completion.', 'status'); + } else { + drupal_set_message('Please select any one action.', 'error'); + drupal_goto('textbook-companion/manage-proposal/status/' . $proposal_id); + return; + } + drupal_goto('textbook-companion/manage-proposal'); return; - } - - /* set the book status to completed */ - - - if ($form_state['values']['completed'] == 1) - {$dt = new DateTime(); - $current_date = $dt->format("Y-m-d"); - db_query("UPDATE {textbook_companion_proposal} SET proposal_status = 3 , actual_completion_date = '".$current_date."' WHERE id = %d", $proposal_id); - - /* sending email */ - $book_user = user_load($proposal_data->uid); - $param['proposal_completed']['proposal_id'] = $proposal_id; - $param['proposal_completed']['user_id'] = $proposal_data->uid; - $email_to = $book_user->mail; - if (!drupal_mail('textbook_companion', 'proposal_completed', $email_to , language_default(), $param, variable_get('textbook_companion_from_email', NULL), TRUE)) - drupal_set_message('Error sending email message.', 'error'); - - drupal_set_message('Congratulations! Book proposal has been marked as completed. User has been notified of the completion.', 'status'); - } - drupal_goto('manage_proposal'); - return; } - - /******************************************************************************/ /**************************** PROPOSAL EDIT FORM ******************************/ /******************************************************************************/ - -function proposal_edit_form($form_state,$nonaicte_book) +function proposal_edit_form($fom, $form_state, $nonaicte_book) { - global $user; - - /* get current proposal */ - $proposal_id = arg(2); - $proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d", $proposal_id); - if ($proposal_q) - { - $proposal_data = db_fetch_object($proposal_q); - if (!$proposal_data) - { - drupal_set_message(t('Invalid proposal selected. Please try again.'), 'error'); - drupal_goto('manage_proposal'); - return; + global $user; + /* get current proposal */ + $proposal_id = arg(3); + /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d", $proposal_id);*/ + $query = db_select('textbook_companion_proposal'); + $query->fields('textbook_companion_proposal'); + $query->condition('id', $proposal_id); + $proposal_q = $query->execute(); + if ($proposal_q) { + $proposal_data = $proposal_q->fetchObject(); + if (!$proposal_data) { + drupal_set_message(t('Invalid proposal selected. Please try again.'), 'error'); + drupal_goto('textbook-companion/manage-proposal'); + return; + } + } else { + drupal_set_message(t('Invalid proposal selected. Please try again.'), 'error'); + drupal_goto('textbook-companion/manage-proposal'); + return; } - } else { - drupal_set_message(t('Invalid proposal selected. Please try again.'), 'error'); - drupal_goto('manage_proposal'); - return; - } - - $user_data = user_load($proposal_data->uid); - - $preference1_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND pref_number = %d LIMIT 1", $proposal_id, 1); - $preference1_data = db_fetch_object($preference1_q); - $preference2_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND pref_number = %d LIMIT 1", $proposal_id, 2); - $preference2_data = db_fetch_object($preference2_q); - $preference3_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND pref_number = %d LIMIT 1", $proposal_id, 3); - $preference3_data = db_fetch_object($preference3_q); - - $form['full_name'] = array( - '#type' => 'textfield', - '#title' => t('Full Name'), - '#size' => 30, - '#maxlength' => 50, - '#required' => TRUE, - '#default_value' => $proposal_data->full_name, - ); - $form['email_id'] = array( - '#type' => 'textfield', - '#title' => t('Email'), - '#size' => 30, - '#value' => $user_data->mail, - '#disabled' => TRUE, - ); - $form['mobile'] = array( - '#type' => 'textfield', - '#title' => t('Mobile No.'), - '#size' => 30, - '#maxlength' => 15, - '#required' => TRUE, - '#default_value' => $proposal_data->mobile, - ); - $form['how_project'] = array( - '#type' => 'select', - '#title' => t('How did you come to know about this project'), - '#options' => array('DWSIM Website' => 'DWSIM Website', - 'Friend' => 'Friend', - 'Professor/Teacher' => 'Professor/Teacher', - 'Mailing List' => 'Mailing List', - 'Poster in my/other college' => 'Poster in my/other college', - 'Others' => 'Others'), - '#required' => TRUE, - '#default_value' => $proposal_data->how_project, - ); - $form['course'] = array( - '#type' => 'textfield', - '#title' => t('Course'), - '#size' => 30, - '#maxlength' => 50, - '#required' => TRUE, - '#default_value' => $proposal_data->course, - ); - $form['branch'] = array( - '#type' => 'select', - '#title' => t('Department/Branch'), - '#options' => array('Electrical Engineering' => 'Electrical Engineering', - 'Electronics Engineering' => 'Electronics Engineering', - 'Computer Engineering' => 'Computer Engineering', - 'Chemical Engineering' => 'Chemical Engineering', - 'Instrumentation Engineering' => 'Instrumentation Engineering', - 'Mechanical Engineering' => 'Mechanical Engineering', - 'Civil Engineering' => 'Civil Engineering', - 'Physics' => 'Physics', - 'Mathematics' => 'Mathematics', - 'Others' => 'Others'), - '#required' => TRUE, - '#default_value' => $proposal_data->branch, - ); - $form['university'] = array( - '#type' => 'textfield', - '#title' => t('University/Institute'), - '#size' => 30, - '#maxlength' => 100, - '#required' => TRUE, - '#default_value' => $proposal_data->university, - ); - $form['faculty'] = array( - '#type' => 'textfield', - '#title' => t('College Teacher/Professor'), - '#size' => 30, - '#maxlength' => 100, - '#required' => TRUE, - '#default_value' => $proposal_data->faculty, - ); - $form['reviewer'] = array( - '#type' => 'textfield', - '#title' => t('Reviewer'), - '#size' => 30, - '#maxlength' => 100, - '#default_value' => $proposal_data->reviewer, - ); - list($y, $m, $d) = explode('-', $proposal_data->expected_completion_date); - $con_date = $d.'-'.$m.'-'.$y; - $date = new DateTime($con_date); - $expected_completion_date = $date->format('d-m-Y'); - $form['completion_date'] = array( - '#type' => 'textfield', - '#title' => t('Expected Date of Completion'), - '#description' => t('Input date format should be DD-MM-YYYY. Eg: 23-03-2011'), - '#size' => 10, - '#maxlength' => 10, - '#default_value' => $expected_completion_date, - ); - $form['dwsim_version'] = array( - '#type' => 'textfield', - '#title' => t('DWSIM Version'), - '#size' => 10, - '#maxlength' => 20, - '#default_value' => $proposal_data->dwsim_version, - ); - $form['operating_system'] = array( - '#type' => 'textfield', - '#title' => t('Operating System'), - '#size' => 30, - '#maxlength' => 50, - '#default_value' => $proposal_data->operating_system, - ); - $form['preference1'] = array( - '#type' => 'fieldset', - '#title' => t('Book Preference'), - '#collapsible' => TRUE, - '#collapsed' => FALSE, - ); - $form['preference1']['book1'] = array( - '#type' => 'textfield', - '#title' => t('Title of the book'), - '#size' => 30, - '#maxlength' => 100, - '#required' => TRUE, - '#default_value' => $preference1_data->book, - ); - $form['preference1']['author1'] = array( - '#type' => 'textfield', - '#title' => t('Author Name'), - '#size' => 30, - '#maxlength' => 100, - '#required' => TRUE, - '#default_value' => $preference1_data->author, - ); - $form['preference1']['isbn1'] = array( - '#type' => 'textfield', - '#title' => t('ISBN No'), - '#size' => 30, - '#maxlength' => 25, - '#required' => TRUE, - '#default_value' => $preference1_data->isbn, - ); - $form['preference1']['publisher1'] = array( - '#type' => 'textfield', - '#title' => t('Publisher & Place'), - '#size' => 30, - '#maxlength' => 50, - '#required' => TRUE, - '#default_value' => $preference1_data->publisher, - ); - $form['preference1']['edition1'] = array( - '#type' => 'textfield', - '#title' => t('Edition'), - '#size' => 4, - '#maxlength' => 2, - '#required' => TRUE, - '#default_value' => $preference1_data->edition, - ); - $form['preference1']['year1'] = array( - '#type' => 'textfield', - '#title' => t('Year of pulication'), - '#size' => 4, - '#maxlength' => 4, - '#required' => TRUE, - '#default_value' => $preference1_data->year, - ); - /*if($preference2_data){ - $form['preference2'] = array( - '#type' => 'fieldset', - '#title' => t('Book Preference 2'), - '#collapsible' => TRUE, - '#collapsed' => FALSE, - ); - $form['preference2']['book2'] = array( - '#type' => 'textfield', - '#title' => t('Title of the book'), - '#size' => 30, - '#maxlength' => 100, - '#required' => TRUE, - '#default_value' => $preference2_data->book, - ); - $form['preference2']['author2'] = array( - '#type' => 'textfield', - '#title' => t('Author Name'), - '#size' => 30, - '#maxlength' => 100, - '#required' => TRUE, - '#default_value' => $preference2_data->author, - ); - $form['preference2']['isbn2'] = array( - '#type' => 'textfield', - '#title' => t('ISBN No'), - '#size' => 30, - '#maxlength' => 25, - '#required' => TRUE, - '#default_value' => $preference2_data->isbn, - ); - $form['preference2']['publisher2'] = array( - '#type' => 'textfield', - '#title' => t('Publisher & Place'), - '#size' => 30, - '#maxlength' => 50, - '#required' => TRUE, - '#default_value' => $preference2_data->publisher, - ); - $form['preference2']['edition2'] = array( - '#type' => 'textfield', - '#title' => t('Edition'), - '#size' => 4, - '#maxlength' => 2, - '#required' => TRUE, - '#default_value' => $preference2_data->edition, - ); - $form['preference2']['year2'] = array( - '#type' => 'textfield', - '#title' => t('Year of pulication'), - '#size' => 4, - '#maxlength' => 4, - '#required' => TRUE, - '#default_value' => $preference2_data->year, - ); -} -if($preference3_data){ - $form['preference3'] = array( - '#type' => 'fieldset', - '#title' => t('Book Preference 3'), - '#collapsible' => TRUE, - '#collapsed' => FALSE, - ); - $form['preference3']['book3'] = array( - '#type' => 'textfield', - '#title' => t('Title of the book'), - '#size' => 30, - '#maxlength' => 100, - '#required' => TRUE, - '#default_value' => $preference3_data->book, - ); - $form['preference3']['author3'] = array( - '#type' => 'textfield', - '#title' => t('Author Name'), - '#size' => 30, - '#maxlength' => 100, - '#required' => TRUE, - '#default_value' => $preference3_data->author, - ); - $form['preference3']['isbn3'] = array( - '#type' => 'textfield', - '#title' => t('ISBN No'), - '#size' => 30, - '#maxlength' => 25, - '#required' => TRUE, - '#default_value' => $preference3_data->isbn, - ); - $form['preference3']['publisher3'] = array( - '#type' => 'textfield', - '#title' => t('Publisher & Place'), - '#size' => 30, - '#maxlength' => 50, - '#required' => TRUE, - '#default_value' => $preference3_data->publisher, - ); - $form['preference3']['edition3'] = array( - '#type' => 'textfield', - '#title' => t('Edition'), - '#size' => 4, - '#maxlength' => 2, - '#required' => TRUE, - '#default_value' => $preference3_data->edition, - ); - $form['preference3']['year3'] = array( - '#type' => 'textfield', - '#title' => t('Year of pulication'), - '#size' => 4, - '#maxlength' => 4, - '#required' => TRUE, - '#default_value' => $preference3_data->year, - ); -}*/ - - /* hidden fields */ - $form['hidden_proposal_id'] = array( + $user_data = user_load($proposal_data->uid); + /* $preference1_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND pref_number = %d LIMIT 1", $proposal_id, 1); + $preference1_data = db_fetch_object($preference1_q);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('proposal_id', $proposal_id); + $query->condition('pref_number', 1); + $query->range(0, 1); + $preference1_q = $query->execute(); + $preference1_data = $preference1_q->fetchObject(); + /********************************************************************/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('proposal_id', $proposal_id); + $query->condition('pref_number', 2); + $query->range(0, 1); + $preference2_q = $query->execute(); + $preference2_data = $preference2_q->fetchObject(); + /**************************************************************************/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('proposal_id', $proposal_id); + $query->condition('pref_number', 3); + $query->range(0, 1); + $preference3_q = $query->execute(); + $preference3_data = $preference3_q->fetchObject(); + /*************************************************************************/ + $form['full_name'] = array( + '#type' => 'textfield', + '#title' => t('Full Name'), + '#size' => 30, + '#maxlength' => 50, + '#required' => TRUE, + '#default_value' => $proposal_data->full_name + ); + $form['email_id'] = array( + '#type' => 'textfield', + '#title' => t('Email'), + '#size' => 30, + '#value' => $user_data->mail, + '#disabled' => TRUE + ); + $form['mobile'] = array( + '#type' => 'textfield', + '#title' => t('Mobile No.'), + '#size' => 30, + '#maxlength' => 15, + '#required' => TRUE, + '#default_value' => $proposal_data->mobile + ); + $form['how_project'] = array( + '#type' => 'select', + '#title' => t('How did you come to know about this project'), + '#options' => array( + 'DWSIM Website' => 'DWSIM Website', + 'Friend' => 'Friend', + 'Professor/Teacher' => 'Professor/Teacher', + 'Mailing List' => 'Mailing List', + 'Poster in my/other college' => 'Poster in my/other college', + 'Others' => 'Others' + ), + '#required' => TRUE, + '#default_value' => $proposal_data->how_project + ); + $form['course'] = array( + '#type' => 'textfield', + '#title' => t('Course'), + '#size' => 30, + '#maxlength' => 50, + '#required' => TRUE, + '#default_value' => $proposal_data->course + ); + $form['branch'] = array( + '#type' => 'select', + '#title' => t('Department/Branch'), + '#options' => _list_of_departments(), + '#required' => TRUE, + '#default_value' => $proposal_data->branch + ); + $form['university'] = array( + '#type' => 'textfield', + '#title' => t('University/ Institute'), + '#size' => 80, + '#maxlength' => 200, + '#required' => TRUE, + '#attributes' => array( + 'placeholder' => 'Insert full name of your institute/ university.... ' + ), + '#default_value' => $proposal_data->university + ); + $form['country'] = array( + '#type' => 'select', + '#title' => t('Country'), + '#options' => array( + 'India' => 'India', + 'Others' => 'Others' + ), + '#required' => TRUE, + '#tree' => TRUE, + '#validated' => TRUE, + '#default_value' => $proposal_data->country + ); + $form['other_country'] = array( + '#type' => 'textfield', + '#title' => t('Other than India'), + '#size' => 100, + '#attributes' => array( + 'placeholder' => t('Enter your country name') + ), + '#default_value' => $proposal_data->country, + '#states' => array( + 'visible' => array( + ':input[name="country"]' => array( + 'value' => 'Others' + ) + ) + ) + ); + $form['other_state'] = array( + '#type' => 'textfield', + '#title' => t('State other than India'), + '#size' => 100, + '#default_value' => $proposal_data->state, + '#attributes' => array( + 'placeholder' => t('Enter your state/region name') + ), + '#states' => array( + 'visible' => array( + ':input[name="country"]' => array( + 'value' => 'Others' + ) + ) + ) + ); + $form['other_city'] = array( + '#type' => 'textfield', + '#title' => t('City other than India'), + '#size' => 100, + '#default_value' => $proposal_data->city, + '#attributes' => array( + 'placeholder' => t('Enter your city name') + ), + '#states' => array( + 'visible' => array( + ':input[name="country"]' => array( + 'value' => 'Others' + ) + ) + ) + ); + $form['all_state'] = array( + '#type' => 'select', + '#title' => t('State'), + '#selected' => array( + '' => '-select-' + ), + '#options' => _list_of_states(), + '#default_value' => $proposal_data->state, + '#validated' => TRUE, + '#states' => array( + 'visible' => array( + ':input[name="country"]' => array( + 'value' => 'India' + ) + ) + ) + ); + $form['city'] = array( + '#type' => 'select', + '#title' => t('City'), + '#default_value' => $proposal_data->city, + '#options' => _list_of_cities(), + '#states' => array( + 'visible' => array( + ':input[name="country"]' => array( + 'value' => 'India' + ) + ) + ) + ); + $form['pincode'] = array( + '#type' => 'textfield', + '#title' => t('Pincode'), + '#size' => 30, + '#maxlength' => 6, + '#required' => False, + '#default_value' => $proposal_data->pincode, + '#attributes' => array( + 'placeholder' => 'Enter pincode....' + ) + ); + /***************************************************************************/ + $form['hr'] = array( + '#type' => 'item', + '#markup' => '<hr>' + ); + $form['faculty'] = array( + '#type' => 'hidden', + '#title' => t('College Teacher/Professor'), + '#size' => 30, + '#maxlength' => 100, + '#required' => TRUE, + '#default_value' => $proposal_data->faculty + ); + $form['reviewer'] = array( + '#type' => 'hidden', + '#title' => t('Reviewer'), + '#size' => 30, + '#maxlength' => 100, + '#default_value' => $proposal_data->reviewer + ); + $form['completion_date'] = array( + '#type' => 'textfield', + '#title' => t('Expected Date of Completion'), + '#description' => t('Input date format should be DD-MM-YYYY. Eg: 23-03-2011'), + '#size' => 10, + '#maxlength' => 10, + '#default_value' => date('d-m-Y', $proposal_data->completion_date) + ); + $form['version'] = array( + '#type' => 'textfield', + '#title' => t('DWSIM Version'), + '#size' => 10, + '#maxlength' => 20, + '#default_value' => $proposal_data->dwsim_version + ); + $form['operating_system'] = array( + '#type' => 'textfield', + '#title' => t('Operating System'), + '#size' => 30, + '#maxlength' => 50, + '#default_value' => $proposal_data->operating_system + ); + $form['preference1'] = array( + '#type' => 'fieldset', + '#title' => t('Book Preference 1'), + '#collapsible' => TRUE, + '#collapsed' => FALSE + ); + $form['preference1']['book1'] = array( + '#type' => 'textfield', + '#title' => t('Title of the book'), + '#size' => 30, + '#maxlength' => 100, + '#required' => TRUE, + '#default_value' => $preference1_data->book + ); + $form['preference1']['author1'] = array( + '#type' => 'textfield', + '#title' => t('Author Name'), + '#size' => 30, + '#maxlength' => 100, + '#required' => TRUE, + '#default_value' => $preference1_data->author + ); + $form['preference1']['isbn1'] = array( + '#type' => 'textfield', + '#title' => t('ISBN No'), + '#size' => 30, + '#maxlength' => 25, + '#required' => TRUE, + '#default_value' => $preference1_data->isbn + ); + $form['preference1']['publisher1'] = array( + '#type' => 'textfield', + '#title' => t('Publisher & Place'), + '#size' => 30, + '#maxlength' => 50, + '#required' => TRUE, + '#default_value' => $preference1_data->publisher + ); + $form['preference1']['edition1'] = array( + '#type' => 'textfield', + '#title' => t('Edition'), + '#size' => 4, + '#maxlength' => 2, + '#required' => TRUE, + '#default_value' => $preference1_data->edition + ); + $form['preference1']['year1'] = array( + '#type' => 'textfield', + '#title' => t('Year of pulication'), + '#size' => 4, + '#maxlength' => 4, + '#required' => TRUE, + '#default_value' => $preference1_data->year + ); + if ($preference2_data) { + $form['preference2'] = array( + '#type' => 'fieldset', + '#title' => t('Book Preference 2'), + '#collapsible' => TRUE, + '#collapsed' => FALSE + ); + $form['preference2']['book2'] = array( + '#type' => 'textfield', + '#title' => t('Title of the book'), + '#size' => 30, + '#maxlength' => 100, + '#required' => TRUE, + '#default_value' => $preference2_data->book + ); + $form['preference2']['author2'] = array( + '#type' => 'textfield', + '#title' => t('Author Name'), + '#size' => 30, + '#maxlength' => 100, + '#required' => TRUE, + '#default_value' => $preference2_data->author + ); + $form['preference2']['isbn2'] = array( + '#type' => 'textfield', + '#title' => t('ISBN No'), + '#size' => 30, + '#maxlength' => 25, + '#required' => TRUE, + '#default_value' => $preference2_data->isbn + ); + $form['preference2']['publisher2'] = array( + '#type' => 'textfield', + '#title' => t('Publisher & Place'), + '#size' => 30, + '#maxlength' => 50, + '#required' => TRUE, + '#default_value' => $preference2_data->publisher + ); + $form['preference2']['edition2'] = array( + '#type' => 'textfield', + '#title' => t('Edition'), + '#size' => 4, + '#maxlength' => 2, + '#required' => TRUE, + '#default_value' => $preference2_data->edition + ); + $form['preference2']['year2'] = array( + '#type' => 'textfield', + '#title' => t('Year of pulication'), + '#size' => 4, + '#maxlength' => 4, + '#required' => TRUE, + '#default_value' => $preference2_data->year + ); + } + if ($preference3_data) { + $form['preference3'] = array( + '#type' => 'fieldset', + '#title' => t('Book Preference 3'), + '#collapsible' => TRUE, + '#collapsed' => FALSE + ); + $form['preference3']['book3'] = array( + '#type' => 'textfield', + '#title' => t('Title of the book'), + '#size' => 30, + '#maxlength' => 100, + '#required' => TRUE, + '#default_value' => $preference3_data->book + ); + $form['preference3']['author3'] = array( + '#type' => 'textfield', + '#title' => t('Author Name'), + '#size' => 30, + '#maxlength' => 100, + '#required' => TRUE, + '#default_value' => $preference3_data->author + ); + $form['preference3']['isbn3'] = array( + '#type' => 'textfield', + '#title' => t('ISBN No'), + '#size' => 30, + '#maxlength' => 25, + '#required' => TRUE, + '#default_value' => $preference3_data->isbn + ); + $form['preference3']['publisher3'] = array( + '#type' => 'textfield', + '#title' => t('Publisher & Place'), + '#size' => 30, + '#maxlength' => 50, + '#required' => TRUE, + '#default_value' => $preference3_data->publisher + ); + $form['preference3']['edition3'] = array( + '#type' => 'textfield', + '#title' => t('Edition'), + '#size' => 4, + '#maxlength' => 2, + '#required' => TRUE, + '#default_value' => $preference3_data->edition + ); + $form['preference3']['year3'] = array( + '#type' => 'textfield', + '#title' => t('Year of pulication'), + '#size' => 4, + '#maxlength' => 4, + '#required' => TRUE, + '#default_value' => $preference3_data->year + ); + } + /* hidden fields */ + $form['hidden_preference_id1'] = array( + '#type' => 'hidden', + '#value' => $preference1_data->id + ); + /* $form['hidden_preference_id2'] = array( + '#type' => 'hidden', + '#value' => $preference2_data->id + ); + $form['hidden_preference_id3'] = array( '#type' => 'hidden', - '#value' => $proposal_id, - ); - - $form['submit'] = array( - '#type' => 'submit', - '#value' => t('Submit') - ); - $form['cancel'] = array( - '#type' => 'markup', - '#value' => l(t('Cancel'), 'manage_proposal'), - ); - return $form; + '#value' => $preference3_data->id + );*/ + $form['hidden_proposal_id'] = array( + '#type' => 'hidden', + '#value' => $proposal_id + ); + $form['submit'] = array( + '#type' => 'submit', + '#value' => t('Submit') + ); + $form['cancel'] = array( + '#type' => 'item', + '#markup' => l(t('Cancel'), 'textbook-companion/manage-proposal') + ); + return $form; } - function proposal_edit_form_validate($form, &$form_state) - { - - /* mobile */ - if (!preg_match('/^[0-9\ \+]{0,15}$/', $form_state['values']['mobile'])) - form_set_error('mobile', t('Invalid mobile number')); - - /* date of completion */ - if (!preg_match('/^[0-9]{1,2}-[0-9]{1,2}-[0-9]{4}$/', $form_state['values']['completion_date'])) - form_set_error('completion_date', t('Invalid expected date of completion')); - - list($d, $m, $y) = explode('-', $form_state['values']['completion_date']); - $d = (int)$d; $m = (int)$m; $y = (int)$y; - if (!checkdate($m, $d, $y)) - form_set_error('completion_date', t('Invalid expected date of completion')); - //if (mktime(0, 0, 0, $m, $d, $y) <= time()) + if ($form_state['values']['book1'] && $form_state['values']['author1']) { + $bk1 = trim($form_state['values']['book1']); + $auth1 = trim($form_state['values']['author1']); + if (_dir_name($bk1, $auth1, $form_state['values']['hidden_preference_id1']) != NULL) { + $form_state['values']['dir_name1'] = _dir_name($bk1, $auth1, $form_state['values']['hidden_preference_id1']); + } + } + /*if ($form_state['values']['book2'] && $form_state['values']['author2']) + { + $bk2 = trim($form_state['values']['book2']); + $auth2 = trim($form_state['values']['author2']); + + if (_dir_name($bk2, $auth2, $form_state['values']['hidden_preference_id2']) != NULL) + { + $form_state['values']['dir_name2'] = _dir_name($bk2, $auth2, $form_state['values']['hidden_preference_id2']); + } + } + if ($form_state['values']['book3'] && $form_state['values']['author3']) + { + $bk3 = trim($form_state['values']['book3']); + $auth3 = trim($form_state['values']['author3']); + + if (_dir_name($bk3, $auth3, $form_state['values']['hidden_preference_id3']) != NULL) + { + $form_state['values']['dir_name3'] = _dir_name($bk3, $auth3, $form_state['values']['hidden_preference_id3']); + } + } + /* mobile */ + if (!preg_match('/^[0-9\ \+]{0,15}$/', $form_state['values']['mobile'])) + form_set_error('mobile', t('Invalid mobile number')); + /* date of completion */ + if (!preg_match('/^[0-9]{1,2}-[0-9]{1,2}-[0-9]{4}$/', $form_state['values']['completion_date'])) + form_set_error('completion_date', t('Invalid expected date of completion')); + list($d, $m, $y) = explode('-', $form_state['values']['completion_date']); + $d = (int) $d; + $m = (int) $m; + $y = (int) $y; + if (!checkdate($m, $d, $y)) + form_set_error('completion_date', t('Invalid expected date of completion')); + //if (mktime(0, 0, 0, $m, $d, $y) <= time()) //form_set_error('completion_date', t('Expected date of completion should be in future')); - - /* edition */ - if (!preg_match('/^[1-9][0-9]{0,1}$/', $form_state['values']['edition1'])) - form_set_error('edition1', t('Invalid edition for Book Preference 1')); - if($form_state['values']['edition2']){ - if (!preg_match('/^[1-9][0-9]{0,1}$/', $form_state['values']['edition2'])) - form_set_error('edition2', t('Invalid edition for Book Preference 2')); - if (!preg_match('/^[1-9][0-9]{0,1}$/', $form_state['values']['edition3'])) - form_set_error('edition3', t('Invalid edition for Book Preference 3')); -} - - - /* year of publication */ - if (!preg_match('/^[1-3][0-9][0-9][0-9]$/', $form_state['values']['year1'])) - form_set_error('year1', t('Invalid year of pulication for Book Preference 1')); - if($form_state['values']['edition2']){ - if (!preg_match('/^[1-3][0-9][0-9][0-9]$/', $form_state['values']['year2'])) - form_set_error('year2', t('Invalid year of pulication for Book Preference 2')); - if (!preg_match('/^[1-3][0-9][0-9][0-9]$/', $form_state['values']['year3'])) - form_set_error('year3', t('Invalid year of pulication for Book Preference 3')); -} - - /* year of publication */ - $cur_year = date('Y'); - if ((int)$form_state['values']['year1'] > $cur_year) - form_set_error('year1', t('Year of pulication should be not in the future for Book Preference 1')); - if ((int)$form_state['values']['year2'] > $cur_year) - form_set_error('year2', t('Year of pulication should be not in the future for Book Preference 2')); - if ((int)$form_state['values']['year3'] > $cur_year) - form_set_error('year3', t('Year of pulication should be not in the future for Book Preference 3')); - - /* isbn */ - if (!preg_match('/^[0-9\-xX]+$/', $form_state['values']['isbn1'])) - form_set_error('isbn1', t('Invalid ISBN for Book Preference 1')); - if($form_state['values']['edition2']){ - if (!preg_match('/^[0-9\-xX]+$/', $form_state['values']['isbn2'])) - form_set_error('isbn2', t('Invalid ISBN for Book Preference 2')); - if (!preg_match('/^[0-9\-xX]+$/', $form_state['values']['isbn3'])) - form_set_error('isbn3', t('Invalid ISBN for Book Preference 3')); -} - return; + /* edition */ + if (!preg_match('/^[1-9][0-9]{0,1}$/', $form_state['values']['edition1'])) + form_set_error('edition1', t('Invalid edition for Book Preference 1')); + /* year of publication */ + if (!preg_match('/^[1-3][0-9][0-9][0-9]$/', $form_state['values']['year1'])) + form_set_error('year1', t('Invalid year of pulication for Book Preference 1')); + /* year of publication */ + $cur_year = date('Y'); + if ((int) $form_state['values']['year1'] > $cur_year) + form_set_error('year1', t('Year of pulication should be not in the future for Book Preference 1')); + /* isbn */ + if (!preg_match('/^[0-9\-xX]+$/', $form_state['values']['isbn1'])) + form_set_error('isbn1', t('Invalid ISBN for Book Preference 1')); + if ($form_state['values']['version'] == 'olderversion') { + if ($form_state['values']['older'] == '') { + form_set_error('older', t('Please provide valid version')); + } + } + return; } - function proposal_edit_form_submit($form, &$form_state) { - /* completion date to timestamp */ - list($d, $m, $y) = explode('-', $form_state['values']['completion_date']); - $con_date = $y.'-'.$m.'-'.$d; - $date = new DateTime($con_date); - $expected_completion_date = $date->format('Y-m-d'); - $proposal_id = $form_state['values']['hidden_proposal_id']; - - - $query = "UPDATE {textbook_companion_proposal} SET full_name = '".$form_state['values']['full_name']."', mobile = '".$form_state['values']['mobile']."', how_project = '".$form_state['values']['how_project']."', course = '".$form_state['values']['course']."', branch = '".$form_state['values']['branch']."', university = '".$form_state['values']['university']."', faculty = '".$form_state['values']['faculty']."', reviewer = '".$form_state['values']['reviewer']."', expected_completion_date = '$expected_completion_date', operating_system= '".$form_state['values']['operating_system']."', dwsim_version= '".$form_state['values']['dwsim_version']."' WHERE id =".$proposal_id; - - - db_query($query); - - -/*db_query("UPDATE {textbook_companion_proposal} SET full_name = '%s', mobile = '%s', how_project = '%s', course = '%s', branch = '%s', university = '%s', faculty = '%s', reviewer = '%s', completion_date = %d, operating_system= '%s', scilab_version= '%s' WHERE id = %d", - $form_state['values']['full_name'], - $form_state['values']['mobile'], - $form_state['values']['how_project'], - $form_state['values']['course'], - $form_state['values']['branch'], - $form_state['values']['university'], - $form_state['values']['faculty'], - $form_state['values']['reviewer'], - $completion_date_timestamp, - $form_state['values']['operating_system'], - $form_state['values']['scilab_version'], - $proposal_id); */ - - $preference1_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND pref_number = %d LIMIT 1", $proposal_id, 1); - $preference1_data = db_fetch_object($preference1_q); - if ($preference1_data) - $preference1_id = $preference1_data->id; - $preference2_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND pref_number = %d LIMIT 1", $proposal_id, 2); - $preference2_data = db_fetch_object($preference2_q); - if ($preference2_data) - $preference2_id = $preference2_data->id; - $preference3_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND pref_number = %d LIMIT 1", $proposal_id, 3); - $preference3_data = db_fetch_object($preference3_q); - if ($preference3_data) - $preference3_id = $preference3_data->id; - - if ($preference1_data) - { - del_book_pdf($preference1_data->id); - db_query("UPDATE {textbook_companion_preference} SET book = '%s', author = '%s', isbn = '%s', publisher = '%s', edition = %d, year = %d WHERE id = %d", - $form_state['values']['book1'], - $form_state['values']['author1'], - $form_state['values']['isbn1'], - $form_state['values']['publisher1'], - $form_state['values']['edition1'], - $form_state['values']['year1'], - $preference1_id); - } - if ($preference2_data) - { - del_book_pdf($preference2_data->id); - db_query("UPDATE {textbook_companion_preference} SET book = '%s', author = '%s', isbn = '%s', publisher = '%s', edition = %d, year = %d WHERE id = %d", - $form_state['values']['book2'], - $form_state['values']['author2'], - $form_state['values']['isbn2'], - $form_state['values']['publisher2'], - $form_state['values']['edition2'], - $form_state['values']['year2'], - $preference2_id); - } - if ($preference3_data) - { - del_book_pdf($preference3_data->id); - db_query("UPDATE {textbook_companion_preference} SET book = '%s', author = '%s', isbn = '%s', publisher = '%s', edition = %d, year = %d WHERE id = %d", - $form_state['values']['book3'], - $form_state['values']['author3'], - $form_state['values']['isbn3'], - $form_state['values']['publisher3'], - $form_state['values']['edition3'], - $form_state['values']['year3'], - $preference3_id); - } - drupal_set_message(t('Proposal Updated'), 'status'); + /* completion date to timestamp */ + list($d, $m, $y) = explode('-', $form_state['values']['completion_date']); + $completion_date_timestamp = mktime(0, 0, 0, $m, $d, $y); + $proposal_id = $form_state['values']['hidden_proposal_id']; + if ($form_state['values']['version'] == 'olderversion') { + $form_state['values']['version'] = $form_state['values']['older']; + } + if ($form_state['values']['country'] == 'other') { + $form_state['values']['country'] = $form_state['values']['other_country']; + $form_state['values']['all_state'] = $form_state['values']['other_state']; + } + $query = db_update('textbook_companion_proposal'); + $query->fields(array( + 'full_name' => $form_state['values']['full_name'], + 'mobile' => $form_state['values']['mobile'], + 'how_project' => $form_state['values']['how_project'], + 'course' => $form_state['values']['course'], + 'branch' => $form_state['values']['branch'], + 'university' => $form_state['values']['university'], + 'city' => $form_state['values']['city'], + 'pincode' => $form_state['values']['pincode'], + 'state' => $form_state['values']['all_state'], + 'country' => $form_state['values']['country'], + 'faculty' => $form_state['values']['faculty'], + 'reviewer' => $form_state['values']['reviewer'], + 'completion_date' => $completion_date_timestamp, + 'operating_system' => $form_state['values']['operating_system'], + 'dwsim_version' => $form_state['values']['version'] + )); + $query->condition('id', $proposal_id); + $num_updated = $query->execute(); + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('proposal_id', $proposal_id); + $query->condition('pref_number', 1); + $query->range(0, 1); + $preference1_q = $query->execute(); + $preference1_data = $preference1_q->fetchObject(); + $preference1_id = $preference1_data->id; + if ($preference1_data) { + del_book_pdf($preference1_data->id); + RenameDir($preference1_id, $form_state['values']['dir_name1']); + $query = db_update('textbook_companion_preference'); + $query->fields(array( + 'book' => $form_state['values']['book1'], + 'author' => $form_state['values']['author1'], + 'isbn' => $form_state['values']['isbn1'], + 'publisher' => $form_state['values']['publisher1'], + 'edition' => $form_state['values']['edition1'], + 'year' => $form_state['values']['year1'], + 'directory_name' => $form_state['values']['dir_name1'] + )); + $query->condition('id', $preference1_id); + $num_updated = $query->execute(); + } + /**************************************************************/ + /**$query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('proposal_id', $proposal_id); + $query->condition('pref_number', 2); + $query->range(0, 1); + $preference2_q = $query->execute(); + $preference2_data = $preference2_q->fetchObject(); + $preference2_id = $preference2_data->id; + if ($preference2_data) + { + del_book_pdf($preference2_data->id); + RenameDir($preference2_id, $form_state['values']['dir_name2']); + $query = db_update('textbook_companion_preference'); + $query->fields(array( + 'book' => $form_state['values']['book2'], + 'author' => $form_state['values']['author2'], + 'isbn' => $form_state['values']['isbn2'], + 'publisher' => $form_state['values']['publisher2'], + 'edition' => $form_state['values']['edition2'], + 'year' => $form_state['values']['year2'], + 'directory_name' => $form_state['values']['dir_name2'] + )); + $query->condition('id', $preference2_id); + $num_updated = $query->execute(); + } + /*****************************************************************/ + /**$query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('proposal_id', $proposal_id); + $query->condition('pref_number', 3); + $query->range(0, 1); + $preference3_q = $query->execute(); + $preference3_data = $preference3_q->fetchObject(); + $preference3_id = $preference3_data->id; + if ($preference3_data) + { + del_book_pdf($preference3_data->id); + RenameDir($preference3_id, $form_state['values']['dir_name3']); + $query = db_update('textbook_companion_preference'); + $query->fields(array( + 'book' => $form_state['values']['book3'], + 'author' => $form_state['values']['author3'], + 'isbn' => $form_state['values']['isbn3'], + 'publisher' => $form_state['values']['publisher3'], + 'edition' => $form_state['values']['edition3'], + 'year' => $form_state['values']['year3'], + 'directory_name' => $form_state['values']['dir_name3'] + )); + $query->condition('id', $preference3_id); + $num_updated = $query->execute(); + }**/ + drupal_set_message(t('Proposal Updated'), 'status'); } - - - /******************************************************************************/ /**************************** CATEGORY EDIT FORM ******************************/ /******************************************************************************/ - -function category_edit_form($form_state) +function category_edit_form($from, $form_state) { - /* get current proposal */ - $preference_id = arg(3); - $preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d", $preference_id); - $preference_data = db_fetch_object($preference_q); - if (!$preference_data) - { - drupal_set_message(t('Invalid book selected. Please try again.'), 'error'); - drupal_goto('manage_proposal/category'); - return; - } - - $form['book'] = array( - '#type' => 'item', - '#title' => t('Title of the book'), - '#value' => $preference_data->book, - ); - $form['author'] = array( - '#type' => 'item', - '#title' => t('Author Name'), - '#value' => $preference_data->author, - ); - $form['isbn'] = array( - '#type' => 'item', - '#title' => t('ISBN No'), - '#value' => $preference_data->isbn, - ); - $form['publisher'] = array( - '#type' => 'item', - '#title' => t('Publisher & Place'), - '#value' => $preference_data->publisher, - ); - $form['edition'] = array( - '#type' => 'item', - '#title' => t('Edition'), - '#value' => $preference_data->edition, - ); - $form['year'] = array( - '#type' => 'item', - '#title' => t('Year of pulication'), - '#value' => $preference_data->year, - ); - $form['category'] = array( - '#type' => 'select', - '#title' => t('Category'), - '#options' => array(0 => 'Please select', - 1 => 'Fluid Mechanics', - 2 => 'Control Theory & Control Systems', - 3 => 'Chemical Engineering', - 4 => 'Thermodynamics', - 5 => 'Mechanical Engineering', - 6 => 'Signal Processing', - 7 => 'Digital Communications', - 8 => 'Electrical Technology', - 9 => 'Mathematics & Pure Science', - 10 => 'Analog Electronics', - 11 => 'Digital Electronics', - 12 => 'Computer Programming', - 13 => 'Others'), - '#required' => TRUE, - '#default_value' => $preference_data->category, - ); - - $form['submit'] = array( - '#type' => 'submit', - '#value' => t('Submit') - ); - $form['cancel'] = array( - '#type' => 'markup', - '#value' => l(t('Cancel'), 'manage_proposal/category'), - ); - return $form; + /* get current proposal */ + $preference_id = arg(3); + /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d", $preference_id); + $preference_data = db_fetch_object($preference_q);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('id', $preference_id); + $result = $query->execute(); + if (!$preference_data) { + drupal_set_message(t('Invalid book selected. Please try again.'), 'error'); + drupal_goto('textbook-companion/manage-proposal/category'); + return; + } + $form['book'] = array( + '#type' => 'item', + '#title' => t('Title of the book'), + '#markup' => $preference_data->book + ); + $form['author'] = array( + '#type' => 'item', + '#title' => t('Author Name'), + '#markup' => $preference_data->author + ); + $form['isbn'] = array( + '#type' => 'item', + '#title' => t('ISBN No'), + '#markup' => $preference_data->isbn + ); + $form['publisher'] = array( + '#type' => 'item', + '#title' => t('Publisher & Place'), + '#markup' => $preference_data->publisher + ); + $form['edition'] = array( + '#type' => 'item', + '#title' => t('Edition'), + '#markup' => $preference_data->edition + ); + $form['year'] = array( + '#type' => 'item', + '#title' => t('Year of pulication'), + '#markup' => $preference_data->year + ); + $form['category'] = array( + '#type' => 'select', + '#title' => t('Category'), + '#options' => _tbc_list_of_categories(), + '#required' => TRUE, + '#default_value' => $preference_data->category + ); + $form['submit'] = array( + '#type' => 'submit', + '#value' => t('Submit') + ); + $form['cancel'] = array( + '#type' => 'markup', + '#value' => l(t('Cancel'), 'textbook-companion/manage-proposal/category') + ); + return $form; } - function category_edit_form_submit($form, &$form_state) { - /* get current proposal */ - $preference_id = (int)arg(3); - $preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d", $preference_id); - $preference_data = db_fetch_object($preference_q); - if (!$preference_data) - { - drupal_set_message(t('Invalid book selected. Please try again.'), 'error'); - drupal_goto('manage_proposal/category'); - return; - } - - db_query("UPDATE {textbook_companion_preference} SET category = %d WHERE id = %d", $form_state['values']['category'], $preference_data->id); - - drupal_set_message(t('Book Category Updated'), 'status'); - drupal_goto('manage_proposal/category'); + /* get current proposal */ + $preference_id = (int) arg(3); + /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d", $preference_id); + $preference_data = db_fetch_object($preference_q);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('id', $preference_id); + $preference_q = $query->execute(); + $preference_data = $preference_q->fetchObject(); + if (!$preference_data) { + drupal_set_message(t('Invalid book selected. Please try again.'), 'error'); + drupal_goto('textbook-companion/manage-proposal/category'); + return; + } + /*db_query("UPDATE {textbook_companion_preference} SET category = %d WHERE id = %d", $form_state['values']['category'], $preference_data->id);*/ + $query = db_update('textbook_companion_preference'); + $query->fields(array( + 'category' => $form_state['values']['category'] + )); + $query->condition('id', $preference_data->id); + $num_updated = $query->execute(); + drupal_set_message(t('Book Category Updated'), 'status'); + drupal_goto('textbook-companion/manage-proposal/category'); } - /****************************************************************/ /* Data entry forms */ /****************************************************************/ - function _data_entry_proposal_all() { - /* get pending proposals to be approved */ - $proposal_rows = array(); - $preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE approval_status = 1 ORDER BY book ASC"); - $sno = 1; - while ($preference_data = db_fetch_object($preference_q)) - { - $proposal_rows[] = array($sno++, $preference_data->book, $preference_data->author, $preference_data->isbn, l('Edit', 'dataentry_edit/' . $preference_data->id)); - } - - /* check if there are any pending proposals */ - if (!$proposal_rows) - { - drupal_set_message(t('There are no proposals.'), 'status'); - return ''; - } - - $proposal_header = array('SNO', 'Title of the Book', 'Author', 'ISBN', ''); - $output = theme_table($proposal_header, $proposal_rows); - return $output; + /* get pending proposals to be approved */ + $proposal_rows = array(); + /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE approval_status = 1 ORDER BY book ASC");*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('approval_status', 1); + $query->orderBy('book', 'ASC'); + $preference_q = $query->execute(); + $sno = 1; + while ($preference_data = $preference_q->fetchObject()) { + $proposal_rows[] = array( + $sno++, + $preference_data->book, + $preference_data->author, + $preference_data->isbn, + l('Edit', 'textbook-companion/dataentry-edit/' . $preference_data->id) + ); + } + /* check if there are any pending proposals */ + if (!$proposal_rows) { + drupal_set_message(t('There are no proposals.'), 'status'); + return ''; + } + $proposal_header = array( + 'SNO', + 'Title of the Book', + 'Author', + 'ISBN', + '' + ); + $output = theme('table', array( + 'headers' => $proposal_header, + 'rows' => $proposal_rows + )); + return $output; } - -function dataentry_edit($id = NULL) { - if($id) { - return drupal_get_form('dataentry_edit_form', $id); - }else { - return 'Access denied'; - } +function dataentry_edit($id = NULL) +{ + if ($id) { + return drupal_get_form('dataentry_edit_form', $id); + } else { + return 'Access denied'; + } } - function dataentry_edit_form($form_state, $id) { - global $user; - - $preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d", $id); - $preference_data = db_fetch_object($preference_q); - - $form['id'] = array( - '#type' => 'hidden', - '#required' => TRUE, - '#value' => $id, - ); - $form['book'] = array( - '#type' => 'textfield', - '#title' => t('Title of the book'), - '#size' => 30, - '#maxlength' => 100, - '#required' => TRUE, - '#default_value' => $preference_data->book, - ); - $form['author'] = array( - '#type' => 'textfield', - '#title' => t('Author Name'), - '#size' => 30, - '#maxlength' => 100, - '#required' => TRUE, - '#default_value' => $preference_data->author, - ); - $form['isbn'] = array( - '#type' => 'textfield', - '#title' => t('ISBN No'), - '#size' => 30, - '#maxlength' => 25, - '#required' => TRUE, - '#attribute' => array('readonly' => 'readonly'), - '#default_value' => $preference_data->isbn, - ); - $form['publisher'] = array( - '#type' => 'textfield', - '#title' => t('Publisher & Place'), - '#size' => 30, - '#maxlength' => 50, - '#required' => TRUE, - '#default_value' => $preference_data->publisher, - ); - $form['edition'] = array( - '#type' => 'textfield', - '#title' => t('Edition'), - '#size' => 4, - '#maxlength' => 2, - '#required' => TRUE, - '#default_value' => $preference_data->edition, - ); - $form['year'] = array( - '#type' => 'textfield', - '#title' => t('Year of pulication'), - '#size' => 4, - '#maxlength' => 4, - '#required' => TRUE, - '#default_value' => $preference_data->year, - ); - $form['submit'] = array( - '#type' => 'submit', - '#value' => t('Submit') - ); - - return $form; + global $user; + /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d", $id); + $preference_data = db_fetch_object($preference_q);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('id', $id); + $preference_q = $query->execute(); + $preference_data = $preference_q->fetchObject(); + $form['id'] = array( + '#type' => 'hidden', + '#required' => TRUE, + '#value' => $id + ); + $form['book'] = array( + '#type' => 'textfield', + '#title' => t('Title of the book'), + '#size' => 30, + '#maxlength' => 100, + '#required' => TRUE, + '#default_value' => $preference_data->book + ); + $form['author'] = array( + '#type' => 'textfield', + '#title' => t('Author Name'), + '#size' => 30, + '#maxlength' => 100, + '#required' => TRUE, + '#default_value' => $preference_data->author + ); + $form['isbn'] = array( + '#type' => 'textfield', + '#title' => t('ISBN No'), + '#size' => 30, + '#maxlength' => 25, + '#required' => TRUE, + '#attribute' => array( + 'readonly' => 'readonly' + ), + '#default_value' => $preference_data->isbn + ); + $form['publisher'] = array( + '#type' => 'textfield', + '#title' => t('Publisher & Place'), + '#size' => 30, + '#maxlength' => 50, + '#required' => TRUE, + '#default_value' => $preference_data->publisher + ); + $form['edition'] = array( + '#type' => 'textfield', + '#title' => t('Edition'), + '#size' => 4, + '#maxlength' => 2, + '#required' => TRUE, + '#default_value' => $preference_data->edition + ); + $form['year'] = array( + '#type' => 'textfield', + '#title' => t('Year of pulication'), + '#size' => 4, + '#maxlength' => 4, + '#required' => TRUE, + '#default_value' => $preference_data->year + ); + $form['submit'] = array( + '#type' => 'submit', + '#value' => t('Submit') + ); + return $form; } - function dataentry_edit_form_submit($form, &$form_state) { - db_query("UPDATE {textbook_companion_preference} SET book = '%s', author = '%s', isbn = '%s', publisher = '%s', edition = '%s', year = %d WHERE id = %d", $_POST['book'], $_POST['author'], $_POST['isbn'], $_POST['publisher'], $_POST['edition'], $_POST['year'], $_POST['id']); - drupal_set_message('Book details updated successfully'); - drupal_goto('dataentry_book'); + /*db_query("UPDATE {textbook_companion_preference} SET book = '%s', author = '%s', isbn = '%s', publisher = '%s', edition = '%s', year = %d WHERE id = %d", $_POST['book'], $_POST['author'], $_POST['isbn'], $_POST['publisher'], $_POST['edition'], $_POST['year'], $_POST['id']);*/ + $query = db_update('textbook_companion_preference'); + $query->fields(array( + 'book' => $_POST['book'], + 'author' => $_POST['author'], + 'isbn' => $_POST['isbn'], + 'publisher' => $_POST['publisher'], + 'edition' => $_POST['edition'], + 'year' => $_POST['year'] + )); + $query->condition('id', $_POST['id']); + $num_updated = $query->execute(); + drupal_set_message('Book details updated successfully'); + drupal_goto('dataentry_book'); } - - -function _failed_all($preference_id=0, $confirm="") { - $page_content = ""; - if($preference_id && $confirm == "yes"){ - $query = " - SELECT *, pro.id as proposal_id FROM textbook_companion_proposal pro - LEFT JOIN textbook_companion_preference pre ON pre.proposal_id = pro.id - LEFT JOIN users usr ON usr.uid = pro.uid - WHERE pre.id = {$preference_id} - "; - $result = db_query($query); - $row = db_fetch_object($result); - - /* increment failed_reminder */ - $query = " - UPDATE textbook_companion_proposal - SET failed_reminder = failed_reminder + 1 - WHERE id = {$row->proposal_id} - "; - db_query($query); - - /* sending mail */ - $to = $row->mail; - $subject = "Failed to upload the TBC codes on time"; - $body = " +function _failed_all($preference_id = 0, $confirm = "") +{ + $page_content = ""; + if ($preference_id && $confirm == "yes") { + /*$query = " + SELECT *, pro.id as proposal_id FROM textbook_companion_proposal pro + LEFT JOIN textbook_companion_preference pre ON pre.proposal_id = pro.id + LEFT JOIN users usr ON usr.uid = pro.uid + WHERE pre.id = {$preference_id} + "; + $result = db_query($query); + $row = db_fetch_object($result);*/ + $query = db_select('textbook_companion_proposal', 'pro'); + $query->fields('*', array( + '' + )); + $query->fields('pro', array( + 'id' + )); + $query->leftJoin('textbook_companion_preference', 'pre', 'pre.proposal_id = pro.id'); + $query->leftJoin('users', 'usr', 'usr.uid = pro.uid'); + $query->condition('pre.id', '$preference_id'); + $result = $query->execute(); + $row = $result->fetchObject(); + /* increment failed_reminder */ + /*$query = " + UPDATE textbook_companion_proposal + SET failed_reminder = failed_reminder + 1 + WHERE id = {$row->proposal_id} + "; + db_query($query);*/ + $query = db_update('textbook_companion_proposal'); + $query->fields(array( + 'failed_reminder' => 'failed_reminder + 1' + )); + $query->condition('id', '$row->proposal_id'); + $num_updated = $query->execute(); + /* sending mail */ + $to = $row->mail; + $subject = "Failed to upload the TBC codes on time"; + $body = " <p> Dear {$row->name},<br><br> This is to inform you that you have failed to upload the TBC codes on time.<br> @@ -1285,67 +1728,147 @@ function _failed_all($preference_id=0, $confirm="") { Kindly upload the TBC codes on the interface within 5 days from now.<br> Failure to submit the same will result in disapproval of your work and cancellation of your internship.<br><br> Regards,<br> - DWSIM Team + DWSIM TBC Team </p> "; - - $message = array( - "to" => $to, - "subject" => $subject, - "body" => $body, - "headers" => array( - "From" => "textbook@dwsim.fossee.in", - "Bcc" => "textbook@dwsim.fossee.in, prashantsinalkar@gmail.com", - "Content-Type" => "text/html; charset=UTF-8; format=flowed" - ) - ); - drupal_mail_send($message); - drupal_set_message("Reminder sent successfully."); - drupal_goto("manage_proposal/failed"); - } else if($preference_id) { - $query = " - SELECT * FROM textbook_companion_preference pre - LEFT JOIN textbook_companion_proposal pro ON pro.id = pre.proposal_id - WHERE pre.id = {$preference_id} - "; - $result = db_query($query); - $row = db_fetch_object($result); - $page_content .= "Are you sure you want to notify?<br><br>"; - $page_content .= "Book: <b>{$row->book}</b><br>"; - $page_content .= "Author: <b>{$row->author}</b><br>"; - $page_content .= "Contributor: <b>{$row->full_name}</b><br>"; - $page_content .= "Expected Completion Date: <b>" . date("d-m-Y", $row->completion_date) . "</b><br><br>"; - $page_content .= l("Yes", "manage_proposal/failed/{$preference_id}/yes") . " | "; - $page_content .= l("Cancel", "manage_proposal/failed"); - } else { - $query = " - SELECT * FROM textbook_companion_proposal pro - LEFT JOIN textbook_companion_preference pre ON pre.proposal_id = pro.id - LEFT JOIN users usr ON usr.uid = pro.uid - WHERE pro.proposal_status = 1 AND pre.approval_status = 1 AND pro.expected_completion_date < %d - ORDER BY failed_reminder - "; - $result = db_query($query, time()); - - $headers = array( - "Date of Submission", "Book", "Contributor Name", - "Expected Completion Date", "Remainders", "Action" - ); - $rows = array(); - - while ($row = db_fetch_object($result)) { - $item =array( - date("d-m-Y", $row->creation_date), - "{$row->book}<br><i>by</i> {$row->author}", - $row->name, - date("d-m-Y", $row->completion_date), - $row->failed_reminder, - l("Remind", "manage_proposal/failed/{$row->id}") - ); - array_push($rows, $item); + $message = array( + "to" => $to, + "subject" => $subject, + "body" => $body, + "headers" => array( + "From" => "contact-dwsim@fossee.in", + "Bcc" => "contact-dwsim@fossee.in", + "Content-Type" => "text/html; charset=UTF-8; format=flowed" + ) + ); + drupal_mail_send($message); + drupal_set_message("Reminder sent successfully."); + drupal_goto("textbook-companion/manage-proposal/failed"); + } else if ($preference_id) { + /*$query = " + SELECT * FROM textbook_companion_preference pre + LEFT JOIN textbook_companion_proposal pro ON pro.id = pre.proposal_id + WHERE pre.id = {$preference_id} + "; + $result = db_query($query); + $row = db_fetch_object($result);*/ + $query = db_select('textbook_companion_preference', 'pre'); + $query->fields('pre'); + $query->leftJoin('textbook_companion_proposal', 'pro', 'pro.id = pre.proposal_id'); + $query->condition('pre.id', $preference_id); + $result = $query->execute(); + $row = $result->fetchObject(); + $page_content .= "Are you sure you want to notify?<br><br>"; + $page_content .= "Book: <b>{$row->book}</b><br>"; + $page_content .= "Author: <b>{$row->author}</b><br>"; + $page_content .= "Contributor: <b>{$row->full_name}</b><br>"; + $page_content .= "Expected Completion Date: <b>" . date("d-m-Y", $row->completion_date) . "</b><br><br>"; + $page_content .= l("Yes", "textbook-companion/manage-proposal/failed/{$preference_id}/yes") . " | "; + $page_content .= l("Cancel", "textbook-companion/manage-proposal/failed"); + } else { + /*$query = " + SELECT * FROM textbook_companion_proposal pro + LEFT JOIN textbook_companion_preference pre ON pre.proposal_id = pro.id + LEFT JOIN users usr ON usr.uid = pro.uid + WHERE pro.proposal_status = 1 AND pre.approval_status = 1 AND pro.completion_date < %d + ORDER BY failed_reminder + "; + $result = db_query($query, time());*/ + $query = db_select('textbook_companion_proposal', 'pro'); + $query->fields('pro'); + $query->leftJoin('textbook_companion_preference', 'pre', 'pre.proposal_id = pro.id'); + $query->leftJoin('users', 'usr', 'usr.uid = pro.uid'); + $query->condition('pro.proposal_status', 1); + $query->condition('pre.approval_status', 1); + $query->condition('pro.completion_date', '%time()', '<'); + $query->orderBy('failed_reminder', 'ASC'); + $result = $query->execute(); + $headers = array( + "Date of Submission", + "Book", + "Contributor Name", + "Expected Completion Date", + "Remainders", + "Action" + ); + $rows = array(); + while ($row = $result->fetchObject()) { + $item = array( + date("d-m-Y", $row->creation_date), + "{$row->book}<br><i>by</i> {$row->author}", + $row->name, + date("d-m-Y", $row->completion_date), + $row->failed_reminder, + l("Remind", "textbook-companion/manage-proposal/failed/{$row->id}") + ); + array_push($rows, $item); + } + $page_content .= theme('table', array( + 'header' => $headers, + 'rows' => $rows + )); + } + return $page_content; +} +/***************************************************************************/ +/*******Function to create readme file after book marked as completed*******/ +/***************************************************************************/ +function CreateReadmeFileTextbookCompanion($proposal_id) +{ + $result = db_query(" + SELECT tcc.id AS proposal_id,tcc.full_name, tcc.course, tcc.branch, tcc.university, tcp.id as pref_id, tcp.directory_name, tcp.* FROM textbook_companion_preference tcp JOIN textbook_companion_proposal tcc ON tcp.proposal_id= tcc.id WHERE tcc.proposal_status = 3 AND tcp.approval_status = 1 AND tcc.id = :proposal_id + ", array( + ":proposal_id" => $proposal_id + )); + $proposal_data = $result->fetchObject(); + $root_path = textbook_companion_path(); + $readme_file = fopen($root_path . $proposal_data->directory_name . "/README.txt", "w") or die('unable to open file'); + $txt = ""; + $txt .= "About The Contributor" . "\n\n"; + $txt .= "Contributed By: " . ucwords(strtolower($proposal_data->full_name)) . "\n"; + $txt .= "Course: " . ucwords(strtolower($proposal_data->course)) . "\n"; + $txt .= "Branch: " . ucwords(strtolower($proposal_data->branch)) . "\n"; + $txt .= "College/Institute/Organization: " . ucwords(strtolower($proposal_data->university)) . "\n\n"; + $txt .= "About The Book" . "\n\n"; + $txt .= "Book: " . ucwords(strtolower($proposal_data->book)) . "\n"; + $txt .= "Author: " . ucwords(strtolower($proposal_data->author)) . "\n"; + $txt .= "Publisher: " . ucwords(strtolower($proposal_data->publisher)) . "\n"; + $txt .= "Year Of Publication: " . $proposal_data->year . "\n"; + $txt .= "ISBN: " . $proposal_data->isbn . "\n"; + $txt .= "Edition: " . ucwords(strtolower($proposal_data->edition)) . "\n"; + $txt .= "\n" . "\n"; + $txt .= "Textbook Companion Project By FOSSEE, IIT Bombay" . "\n"; + fwrite($readme_file, $txt); + fclose($readme_file); + return; +} +function RenameDir($preference_id, $dir_name) +{ + $preference_id = $preference_id; + $dir_name = $dir_name; + $query = db_query("SELECT directory_name, proposal_id, id FROM textbook_companion_preference WHERE id = :preference_id", array( + ':preference_id' => $preference_id + )); + $result = $query->fetchObject(); + if ($result != NULL) { + $files = scandir(textbook_companion_path()); + $files_id_dir = textbook_companion_path() . $result->id; + $file_dir = textbook_companion_path() . $result->directory_name; + if (is_dir($file_dir)) { + $new_directory_name = rename(textbook_companion_path() . $result->directory_name, textbook_companion_path() . $dir_name); + CreateReadmeFileTextbookCompanion($result->proposal_id); + return $new_directory_name; + } else if (is_dir($files_id_dir)) { + $new_directory_name = rename(textbook_companion_path() . $result->id, textbook_companion_path() . $dir_name); + CreateReadmeFileTextbookCompanion($result->proposal_id); + return $new_directory_name; + } else { + drupal_set_message('Can not rename the directory. If you are editing proposal before approving the proposal directory is not present because the code has been not uploaded yet. For more information please contact to administrator'); + return; + } + } else { + drupal_set_message('Book names directory not present in databse'); + return; } - $page_content .= theme("table", $headers, $rows); - } - - return $page_content; + return; } @@ -1,120 +1,165 @@ <?php // $Id$ - /******************************************************************************/ /***************************** BOOK NOTES *************************************/ /******************************************************************************/ - function book_notes_form($form_state) -{ - global $user; - - /* get current proposal */ - $preference_id = arg(2); - $preference_id = (int)$preference_id; - $result = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d", $preference_id); - if ($result) { - if ($row = db_fetch_object($result)) - { - /* everything ok */ - } else { - drupal_set_message(t('Invalid book selected. Please try again.'), 'error'); - drupal_goto('code_approval/bulk'); - return; - } - } else { - drupal_set_message(t('Invalid book selected. Please try again.'), 'error'); - drupal_goto('code_approval/bulk'); - return; + global $user; + /* get current proposal */ + $preference_id = arg(2); + $preference_id = (int) $preference_id; + /*$result = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d", $preference_id);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('id', $preference_id); + $result = $query->execute(); + if ($result) + { + if ($row = $result->fetchObject()) + { + /* everything ok */ + } + else + { + drupal_set_message(t('Invalid book selected. Please try again.'), 'error'); + drupal_goto('code_approval/bulk'); + return; + } + } + else + { + drupal_set_message(t('Invalid book selected. Please try again.'), 'error'); + drupal_goto('code_approval/bulk'); + return; + } + /* get current notes */ + $notes = ''; + /*$notes_q = db_query("SELECT * FROM {textbook_companion_notes} WHERE preference_id = %d LIMIT 1", $preference_id);*/ + $query = db_select('textbook_companion_notes'); + $query->fields('textbook_companion_notes'); + $query->condition('preference_id', $preference_id); + $query->range(0, 1); + $notes_q = $query->execute(); + if ($notes_q) + { + $notes_data = $notes_q->fetchObject(); + $notes = $notes_data->notes; + } + $book_details = _book_information($preference_id); + $form['book_details'] = array( + '#type' => 'item', + '#markup' => '<span style="color: rgb(128, 0, 0);"><strong>About the Book</strong></span><br />' . '<strong>Author:</strong> ' . $book_details->author . '<br />' . '<strong>Title of the Book:</strong> ' . $book_details->book . '<br />' . '<strong>Publisher:</strong> ' . $book_details->publisher . '<br />' . '<strong>Year:</strong> ' . $book_details->year . '<br />' . '<strong>Edition:</strong> ' . $book_details->edition . '<br /><br />' . '<span style="color: rgb(128, 0, 0);"><strong>About the Contributor</strong></span><br />' . '<strong>Contributor Name:</strong> ' . $book_details->full_name . ', ' . $book_details->course . ', ' . $book_details->branch . ', ' . $book_details->university . '<br />' + ); + $form['notes'] = array( + '#type' => 'textarea', + '#rows' => 20, + '#title' => t('Notes for Reviewers'), + '#default_value' => $notes + ); + $form['submit'] = array( + '#type' => 'submit', + '#value' => t('Submit') + ); + $form['cancel'] = array( + '#type' => 'markup', + '#value' => l(t('Back'), 'code_approval/bulk') + ); + return $form; } - - /* get current notes */ - $notes = ''; - $notes_q = db_query("SELECT * FROM {textbook_companion_notes} WHERE preference_id = %d LIMIT 1", $preference_id); - if ($notes_q) - { - $notes_data = db_fetch_object($notes_q); - $notes = $notes_data->notes; - } - - $book_details = _book_information($preference_id); - $form['book_details'] = array( - '#type' => 'item', - '#value' => '<span style="color: rgb(128, 0, 0);"><strong>About the Book</strong></span><br />' . - '<strong>Author:</strong> ' . $book_details->preference_author . '<br />' . - '<strong>Title of the Book:</strong> ' . $book_details->preference_book . '<br />' . - '<strong>Publisher:</strong> ' . $book_details->preference_publisher . '<br />' . - '<strong>Year:</strong> ' . $book_details->preference_year . '<br />' . - '<strong>Edition:</strong> ' . $book_details->preference_edition . '<br /><br />' . - '<span style="color: rgb(128, 0, 0);"><strong>About the Contributor</strong></span><br />' . - '<strong>Contributor Name:</strong> ' . $book_details->proposal_full_name . ', ' . $book_details->proposal_course . ', ' . $book_details->proposal_branch . ', ' . $book_details->proposal_university . '<br />', - ); - - $form['notes'] = array( - '#type' => 'textarea', - '#rows' => 20, - '#title' => t('Notes for Reviewers'), - '#default_value' => $notes, - ); - - $form['submit'] = array( - '#type' => 'submit', - '#value' => t('Submit') - ); - - $form['cancel'] = array( - '#type' => 'markup', - '#value' => l(t('Back'), 'code_approval/bulk'), - ); - return $form; -} - function book_notes_form_submit($form, &$form_state) -{ - global $user; - - /* get current proposal */ - $preference_id = arg(2); - $preference_id = (int)$preference_id; - $result = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d", $preference_id); - if ($result) { - if ($row = db_fetch_object($result)) - { - /* everything ok */ - } else { - drupal_set_message(t('Invalid book selected. Please try again.'), 'error'); - drupal_goto('code_approval/bulk'); - return; - } - } else { - drupal_set_message(t('Invalid book selected. Please try again.'), 'error'); - drupal_goto('code_approval/bulk'); - return; - } - - /* find existing notes */ - $notes_q = db_query("SELECT * FROM {textbook_companion_notes} WHERE preference_id = %d LIMIT 1", $preference_id); - $notes_data = db_fetch_object($notes_q); - - /* add or update notes in database */ - if ($notes_data) { - db_query("UPDATE {textbook_companion_notes} SET notes = '%s' WHERE id = %d", $form_state['values']['notes'], $notes_data->id); - drupal_set_message('Notes updated successfully.', 'status'); - } else { - db_query("INSERT INTO {textbook_companion_notes} (preference_id, notes) VALUES (%d, '%s')", $preference_id, $form_state['values']['notes']); - drupal_set_message('Notes added successfully.', 'status'); + global $user; + /* get current proposal */ + $preference_id = arg(2); + $preference_id = (int) $preference_id; + /*$result = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d", $preference_id);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('id', $preference_id); + $result = $query->execute(); + if ($result) + { + if ($row = $result->fetchObject()) + { + /* everything ok */ + } + else + { + drupal_set_message(t('Invalid book selected. Please try again.'), 'error'); + drupal_goto('code_approval/bulk'); + return; + } + } + else + { + drupal_set_message(t('Invalid book selected. Please try again.'), 'error'); + drupal_goto('code_approval/bulk'); + return; + } + /* find existing notes */ + /*$notes_q = db_query("SELECT * FROM {textbook_companion_notes} WHERE preference_id = %d LIMIT 1", $preference_id); + $notes_data = db_fetch_object($notes_q);*/ + $query = db_select('textbook_companion_notes'); + $query->fields('textbook_companion_notes'); + $query->condition('preference_id', $preference_id); + $query->range(0, 1); + $notes_q = $query->execute(); + $notes_data = $notes_q->fetchObject(); + /* add or update notes in database */ + if ($notes_data) + { + /*db_query("UPDATE {textbook_companion_notes} SET notes = '%s' WHERE id = %d", $form_state['values']['notes'], $notes_data->id);*/ + $query = db_update('textbook_companion_notes'); + $query->fields(array( + 'notes' => $form_state['values']['notes'] + )); + $query->condition('id', $notes_data->id); + $num_updated = $query->execute(); + drupal_set_message('Notes updated successfully.', 'status'); + } + else + { + /*db_query("INSERT INTO {textbook_companion_notes} (preference_id, notes) VALUES (%d, '%s')", $preference_id, $form_state['values']['notes']);*/ + $query = "INSERT INTO {textbook_companion_notes} (preference_id, notes) VALUES + (:preference_id, :notes)"; + $args = array( + ":preference_id" => $preference_id, + ":notes" => $form_state['values']['notes'] + ); + $result = db_query($query, $args, array( + 'return' => Database::RETURN_INSERT_ID + )); + drupal_set_message('Notes added successfully.', 'status'); + } } -} - -/* return proposal and author information */ +/* return proposal and author information */ function _book_information($preference_id) -{ - $book_data = db_fetch_object(db_query("SELECT + { + /*$book_data = db_fetch_object(db_query("SELECT preference.book as preference_book, preference.author as preference_author, preference.isbn as preference_isbn, preference.publisher as preference_publisher, preference.edition as preference_edition, preference.year as preference_year, proposal.full_name as proposal_full_name, proposal.faculty as proposal_faculty, proposal.reviewer as proposal_reviewer, proposal.course as proposal_course, proposal.branch as proposal_branch, proposal.university as proposal_university - FROM {textbook_companion_proposal} proposal LEFT JOIN {textbook_companion_preference} preference ON proposal.id = preference.proposal_id WHERE preference.id = %d", $preference_id)); - return $book_data; -} - + FROM {textbook_companion_proposal} proposal LEFT JOIN {textbook_companion_preference} preference ON proposal.id = preference.proposal_id WHERE preference.id = %d", $preference_id));*/ + $query = db_select('textbook_companion_proposal', 'proposal'); + $query->fields('preference', array( + 'book', + 'author', + 'isbn', + 'publisher', + 'edition', + 'year' + )); + $query->fields('proposal', array( + 'full_name', + 'faculty', + 'reviewer', + 'course', + 'branch', + 'university' + )); + $query->leftJoin('textbook_companion_preference', 'preference', 'proposal.id=preference.proposal_id'); + $query->condition('preference.id', $preference_id); + $result = $query->execute(); + $book_data = $result->fetchObject(); + return $book_data; + } diff --git a/pdf/generate_pdf.inc b/pdf/generate_pdf.inc index 4f2cee7..db76a88 100755 --- a/pdf/generate_pdf.inc +++ b/pdf/generate_pdf.inc @@ -1,117 +1,127 @@ <?php - function generate_pdf() - { - require('fpdf/fpdf.php'); - global $user; - $x = $user->uid; - $proposal_id = arg(2); - $query2 = db_query("SELECT * FROM {textbook_companion_preference} WHERE approval_status=1 AND proposal_id=".$proposal_id); - $data2 = db_fetch_object($query2); - $query3 = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id=".$proposal_id); - $data3 = db_fetch_object($query3); - //var_dump($data3->gender); - $gender = array('salutation' => 'Mr. /Ms.', 'gender' => 'He/She'); - if($data3->gender){ - if($data3->gender == 'M'){ - $gender = array('salutation' => 'Mr.', 'gender' => 'He'); - - }else{ - $gender = array('salutation' => 'Ms.', 'gender' => 'She'); - } - } - //die; - /*if($data3->proposal_status == 3) - {*/ - $pdf=new FPDF('L', 'mm', 'Letter'); - if (!$pdf) - { - echo "Error!"; - } - $pdf->AddPage(); - - $pdf->SetMargins(18,1,18); - - $pdf->Line(7.0,7.0,270.0,7.0); - $pdf->Line(7.0,7.0,7.0,210.0); - $pdf->Line(270.0,210.0,270.0,7.0); - $pdf->Line(7.0,210.0,270.0,210.0); - - $pdf->Image("/Sites/scilab_in/sites/default/files/scilab_logo.png", 10, 9, 0, 15); - $path = drupal_get_path('module', 'textbook_companion'); - $pdf->Image($path."/pdf/images/fossee.png", 228, 9, 0, 15); - - $pdf->SetFont('Arial','B',25); - $pdf->Ln(30); - $pdf->Cell(240,8,'Certificate', 0,1,'C'); - $pdf->Ln(5); - $pdf->SetFont('Arial','B',12); - $pdf->Cell(240,8,'Textbook Companion', '0','1','C'); - - $pdf->Ln(20); - //$pdf->Cell(240,8,'IIT Bombay', '0','1','C'); - - $pdf->SetFont('Arial','',12); - if(strtolower($data3->branch)!="others") - { - $pdf->MultiCell(240,8,'This is to certify that '.$gender['salutation']." ".$data3->full_name.' from the Department of '.$data3->branch.', '.$data3->university.' has successfully completed Internship under Scilab Textbook Companion for a duration equivalent to six weeks. '.$gender['gender'].' has coded, in Scilab, all the solved examples of the allotted textbook: '.$data2->book.' by '.$data2->author.'.', 0); - } - else - { - $pdf->MultiCell(240,8,'This is to certify that '.$gender['salutation']." ".$data3->full_name.' from '.$data3->university.' has successfully completed training under Scilab Textbook Companion for a duration equivalent to six weeks. '.$gender['gender'].' has coded, in Scilab, all the solved examples of the allotted textbook: '.$data2->book.' by '.$data2->author.'.', 0); - } $pdf->Cell(10,10,'The work done is available at ', '0','0','L'); - - $pdf->SetX(75); - $pdf->SetFont('','U'); - $pdf->SetTextColor(0,0,255); - $pdf->write(10,'http://scilab.in','http://scilab.in'); - $pdf->SetFont('',''); - $pdf->SetTextColor(0,0,0); - $pdf->write(10,'.','.'); - - $pdf->Ln(10); - - $pdf->SetFont('Arial','',12); - $pdf->SetTextColor(0,0,0); - $pdf->Cell(10,10,'This work was funded by the FOSSEE project, IIT Bombay (for more details visit', '0','0','L'); - - $pdf->SetX(170); - $pdf->SetFont('','U'); - $pdf->SetTextColor(0,0,255); - $pdf->write(10,'http://fossee.in','http://fossee.in'); - - $pdf->SetX(198); - $pdf->SetFont('',''); - $pdf->SetTextColor(0,0,0); - $pdf->write(10,').'); - - $pdf->SetY(-50); - - $pdf->SetX(209); - $pdf->SetTextColor(0,0,0); - $pdf->SetFont('','B'); - $pdf->Image($path."/pdf/images/sign.png", 212, 151, 0, 15); - //$pdf->SetX(206); - $pdf->Cell(0,7,'Prof. Madhu Belur', 0,1,'L'); - $pdf->SetX(195); - $pdf->Cell(0,7,'Principal Investigator - FOSSEE',0,1,'L'); - $pdf->SetX(195); - $pdf->Cell(0,7,' Dept. of Electrical Engineering', 0,1,'L'); - - $pdf->SetX(216); - $pdf->Cell(0,7,'IIT Bombay', 0,1,'L'); - - $cur_date=date('jS F, Y'); - $pdf->SetY(180); - $pdf->SetFont('',''); - $pdf->Cell(200,0,' Date: '.$cur_date.'',0,1,'L'); - //$pdf->Cell(200,0,' Date: 28th August, 2013',0,1,'L'); - $pdf->Cell(200,15,'Email: textbook@scilab.in', 0,1,'L'); - $pdf->Output(); - /*} - else - { - drupal_set_message('Your Book Is Still Under Review.', 'status'); - }*/ -} +function generate_pdf() + { + require('fpdf/fpdf.php'); + global $user; + $x = $user->uid; + $proposal_id = arg(3); + /*$query2 = db_query("SELECT * FROM {textbook_companion_preference} WHERE approval_status=1 AND proposal_id=". $proposal_id); + $data2 = db_fetch_object($query2);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('approval_status', 1); + $query->condition('proposal_id', $proposal_id); + $result = $query->execute(); + $data2 = $result->fetchObject(); + /*$query3 = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id=".$proposal_id); + $data3 = db_fetch_object($query3);*/ + $query = db_select('textbook_companion_proposal'); + $query->fields('textbook_companion_proposal'); + $query->condition('id', $proposal_id); + $result = $query->execute(); + $data3 = $result->fetchObject(); + //var_dump($data3->gender); + $gender = array( + 'salutation' => 'Mr. /Ms.', + 'gender' => 'He/She' + ); + if ($data3->gender) + { + if ($data3->gender == 'M') + { + $gender = array( + 'salutation' => 'Mr.', + 'gender' => 'He' + ); + } + else + { + $gender = array( + 'salutation' => 'Ms.', + 'gender' => 'She' + ); + } + } + //die; + /*if($data3->proposal_status == 3) + {*/ + $pdf = new FPDF('L', 'mm', 'Letter'); + if (!$pdf) + { + echo "Error!"; + } + $pdf->AddPage(); + $pdf->SetMargins(18, 1, 18); + $pdf->Line(7.0, 7.0, 270.0, 7.0); + $pdf->Line(7.0, 7.0, 7.0, 210.0); + $pdf->Line(270.0, 210.0, 270.0, 7.0); + $pdf->Line(7.0, 210.0, 270.0, 210.0); + $path = drupal_get_path('module', 'textbook_companion'); + $pdf->Image($path . "/pdf/images/dwsim_logo.png", 10, 9, 0, 15); + $pdf->Image($path . "/pdf/images/fossee.png", 228, 9, 0, 15); + $pdf->SetFont('Arial', 'B', 25); + $pdf->Ln(30); + $pdf->Cell(240, 8, 'Certificate', 0, 1, 'C'); + $pdf->Ln(5); + $pdf->SetFont('Arial', 'B', 12); + $pdf->Cell(240, 8, 'Textbook Companion', '0', '1', 'C'); + $pdf->Ln(20); + //$pdf->Cell(240,8,'IIT Bombay', '0','1','C'); + $pdf->SetFont('Arial', '', 12); + /* if(strtolower($data3->branch)!="others") + { + $pdf->MultiCell(240,8,'This is to certify that '.$gender['salutation']." ".$data3->full_name.' from the Department of '.$data3->branch.', '.$data3->university.' has successfully completed Internship under Scilab Textbook Companion for a duration equivalent to six weeks. '.$gender['gender'].' has coded, in DWSIM, all the solved examples of the allotted textbook: '.$data2->book.' by '.$data2->author.'.', 0); + } + else + {*/ + $pdf->MultiCell(240, 8, 'This is to certify that ' . $gender['salutation'] . " " . $data3->full_name . ' from ' . $data3->university . ' has successfully completed training under DWSIM Textbook Companion for a duration equivalent to six weeks. ' . $gender['gender'] . ' has coded, in DWSIM, all the solved examples of the allotted textbook: ' . $data2->book . ' by ' . $data2->author . '.', 0); + //} + $pdf->Cell(10, 10, 'The work done is available at ', '0', '0', 'L'); + $pdf->SetX(75); + $pdf->SetFont('', 'U'); + $pdf->SetTextColor(0, 0, 255); + $pdf->write(10, 'http://dwsim.fossee.in', 'http://dwsim.fossee.in'); + $pdf->SetFont('', ''); + $pdf->SetTextColor(0, 0, 0); + $pdf->write(10, '.', '.'); + $pdf->Ln(10); + $pdf->SetFont('Arial', '', 12); + $pdf->SetTextColor(0, 0, 0); + $pdf->Cell(10, 10, 'This work was funded by the FOSSEE project, IIT Bombay (for more details visit', '0', '0', 'L'); + $pdf->SetX(170); + $pdf->SetFont('', 'U'); + $pdf->SetTextColor(0, 0, 255); + $pdf->write(10, 'http://fossee.in', 'http://fossee.in'); + $pdf->SetX(198); + $pdf->SetFont('', ''); + $pdf->SetTextColor(0, 0, 0); + $pdf->write(10, ').'); + $pdf->SetY(-50); + $pdf->SetX(209); + $pdf->SetTextColor(0, 0, 0); + $pdf->SetFont('', 'B'); + $pdf->Image($path . "/pdf/images/sign.png", 212, 151, 0, 15); + //$pdf->SetX(206); + $pdf->Cell(0, 7, 'Prof. Kannan M Moudgalya', 0, 1, 'L'); + $pdf->SetX(195); + $pdf->Cell(0, 7, 'Principal Investigator - FOSSEE', 0, 1, 'L'); + $pdf->SetX(195); + $pdf->Cell(0, 7, ' Dept. of Chemical Engineering', 0, 1, 'L'); + $pdf->SetX(216); + $pdf->Cell(0, 7, 'IIT Bombay', 0, 1, 'L'); + $cur_date = date('jS F, Y'); + $pdf->SetY(180); + $pdf->SetFont('', ''); + $pdf->Cell(200, 0, ' Date: ' . $cur_date . '', 0, 1, 'L'); + //$pdf->Cell(200,0,' Date: 28th August, 2013',0,1,'L'); + $pdf->Cell(200, 15, 'Email: contact-dwsim@sfossee.in', 0, 1, 'L'); + $name = $data3->full_name; + $certificate_name = str_replace(' ', '_', $name); + $pdf->Output($certificate_name . '_DWSIM_TBC_Certificate.pdf', 'D'); + /*} + else + { + drupal_set_message('Your Book Is Still Under Review.', 'status'); + }*/ + } ?> - diff --git a/pdf/images/dwsim_logo.png b/pdf/images/dwsim_logo.png Binary files differnew file mode 100755 index 0000000..48647f7 --- /dev/null +++ b/pdf/images/dwsim_logo.png diff --git a/pdf/list_all_certificates.inc b/pdf/list_all_certificates.inc index 766c1f1..19dede5 100755 --- a/pdf/list_all_certificates.inc +++ b/pdf/list_all_certificates.inc @@ -1,97 +1,119 @@ <?php /* function _list_all_certificates() - { - global $user; - $uid1 = $user->uid; +{ +global $user; +$uid1 = $user->uid; - $query2 = db_query("SELECT * FROM {textbook_companion_proposal} WHERE proposal_status=3 AND uid=".$user->uid); - $data2 = db_fetch_object($query2); - if($data2->id) - /*while($data2 = db_fetch_object($query2)) - {*/ - /* if($data2->id) - { - $search_rows = array(); - global $output; - $output = ''; - $query3 = db_query("SELECT * FROM textbook_companion_preference WHERE approval_status=1 AND proposal_id=".$data2->id); +$query2 = db_query("SELECT * FROM {textbook_companion_proposal} WHERE proposal_status=3 AND uid=".$user->uid); +$data2 = db_fetch_object($query2); +if($data2->id) +/*while($data2 = db_fetch_object($query2)) +{*/ +/* if($data2->id) +{ +$search_rows = array(); +global $output; +$output = ''; +$query3 = db_query("SELECT * FROM textbook_companion_preference WHERE approval_status=1 AND proposal_id=".$data2->id); - while ($search_data3 = db_fetch_object($query3)) - { - $search_rows[] = array($search_data3->isbn,$search_data3->book,$search_data3->author,l('Download Certificate', 'certificate/generate_pdf/'.$search_data3->id)); - } - if ($search_rows) - { - $search_header = array('ISBN', 'Book Name', 'Author', 'Download Certificates'); - $output = theme_table($search_header, $search_rows); - return $output; - } - else - { - echo("Error"); - return ''; - } - } - else - { - $query3 = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid=".$user->uid); - $data3 = db_fetch_object($query3); - if($data3) - { - drupal_set_message('<strong>Your book is still under Review!</strong>', 'status'); - return ''; - } - else - { - drupal_set_message('<strong>You need to propose a book <a href="/proposal">Book Proposal</a></strong>', 'status'); - return ''; - } - } +while ($search_data3 = db_fetch_object($query3)) +{ +$search_rows[] = array($search_data3->isbn,$search_data3->book,$search_data3->author,l('Download Certificate', 'certificate/generate_pdf/'.$search_data3->id)); +} +if ($search_rows) +{ +$search_header = array('ISBN', 'Book Name', 'Author', 'Download Certificates'); +$output = theme_table($search_header, $search_rows); +return $output; +} +else +{ +echo("Error"); +return ''; +} +} +else +{ +$query3 = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid=".$user->uid); +$data3 = db_fetch_object($query3); +if($data3) +{ +drupal_set_message('<strong>Your book is still under Review!</strong>', 'status'); +return ''; +} +else +{ +drupal_set_message('<strong>You need to propose a book <a href="/proposal">Book Proposal</a></strong>', 'status'); +return ''; +} +} //} -} */ - +} */ function _list_all_certificates() - { - global $user; - $query_id =db_query("SELECT id FROM textbook_companion_proposal WHERE proposal_status=3 AND uid=".$user->uid); - $exist_id = db_fetch_object($query_id); - if($exist_id->id) - { - if($exist_id->id<3) - { - drupal_set_message('<strong>You need to propose a book <a href="/proposal">Book Proposal</a></strong>', 'status'); - return ''; - } - else - { - $search_rows = array(); - global $output; - $output = ''; - $query3 = db_query("SELECT prop.id,pref.isbn,pref.book,pref.author FROM textbook_companion_proposal as prop,textbook_companion_preference as pref WHERE prop.proposal_status=3 AND pref.approval_status=1 AND pref.proposal_id=prop.id AND prop.uid=".$user->uid); - while ($search_data3 = db_fetch_object($query3)) - { - if($search_data3->id) - { - $search_rows[] = array($search_data3->isbn,$search_data3->book,$search_data3->author,l('Download Certificate', 'certificate/generate_pdf/'.$search_data3->id)); - } - } - if($search_rows) - { - $search_header = array('ISBN', 'Book Name', 'Author', 'Download Certificates'); - $output = theme_table($search_header, $search_rows); - return $output; - } - else - { - echo("Error"); - return ''; - } - } - } - else - { - drupal_set_message('<strong>You need to propose a book <a href="/proposal">Book Proposal</a></strong>', 'status'); - return ''; - } -} + { + global $user; + /*$query_id =db_query("SELECT id FROM textbook_companion_proposal WHERE proposal_status=3 AND uid=".$user->uid); + $exist_id = db_fetch_object($query_id);*/ + $query = db_select('textbook_companion_proposal'); + $query->fields('textbook_companion_proposal', array( + 'id' + )); + $query->condition('proposal_status', 3); + $query->condition('uid', $user->uid); + $result = $query->execute(); + $exist_id = $result->fetchObject(); + if ($exist_id->id) + { + if ($exist_id->id < 3) + { + drupal_set_message('<strong>You need to propose a book <a href="/proposal">Book Proposal</a></strong>', 'status'); + return ''; + } + else + { + $search_rows = array(); + global $output; + $output = ''; + $query3 = db_query("SELECT prop.id,pref.isbn,pref.book,pref.author FROM textbook_companion_proposal as prop,textbook_companion_preference as pref WHERE prop.proposal_status=3 AND pref.approval_status=1 AND pref.proposal_id=prop.id AND prop.uid=:uid", array( + ":uid" => $user->uid + )); + while ($search_data3 = $query3->fetchObject()) + { + if ($search_data3->id) + { + $search_rows[] = array( + $search_data3->isbn, + $search_data3->book, + $search_data3->author, + l('Download Certificate', 'textbook-companion/certificate/generate-pdf/' . $search_data3->id) + ); + } + } + if ($search_rows) + { + $search_header = array( + 'ISBN', + 'Book Name', + 'Author', + 'Download Certificates' + ); + $output = theme('table', array( + 'header' => $search_header, + 'rows' => $search_rows + )); + return $output; + } + else + { + echo ("Error"); + return ''; + } + } + } + else + { + drupal_set_message('<strong>You need to propose a book <a href="/proposal">Book Proposal</a></strong>', 'status'); + return ''; + } + } ?> @@ -1,372 +1,550 @@ <?php -// $Id$ - -function textbook_companion_run_form($form_state, $pref_id = NULL) +function textbook_companion_run_form($form, &$form_state) { - - $form['#redirect'] = FALSE; - $book_default_value = 0; - - ahah_helper_register($form, $form_state); - if (!isset($form_state['storage']['run']['category'])) - { - $category_default_value = 0; - if($pref_id){ - $query = "select category from textbook_companion_preference where id=".$pref_id; - $result = db_query($query); - $row = db_fetch_object($result); - $category_default_value = $row->category; - $book_default_value = $pref_id; - } - } else { - $category_default_value = $form_state['storage']['run']['category']; - } - /* default value for ahah fields */ - if (!isset($form_state['storage']['run']['book'])) - { - /* get the book id from url */ - $url_book_id = (int)arg(1); - if ($url_book_id) - { - /* add javascript for book selected */ - $chapter_name_js = " $(document).ready(function() { - $('#edit-run-book').val(" . $url_book_id . "); - $('#edit-run-book').change(); - });"; - drupal_add_js($chapter_name_js, 'inline', 'footer'); - } - } else { - $book_default_value = $form_state['storage']['run']['book']; - } - - if (!isset($form_state['storage']['run']['chapter'])) - { - $chapter_default_value = 0; - } else { - if ($form_state['values']['run']['book_hidden'] != $form_state['values']['run']['book']) - $chapter_default_value = 0; - else - $chapter_default_value = $form_state['storage']['run']['chapter']; - } - - if (!isset($form_state['storage']['run']['example'])) - { - $example_default_value = 0; - } else { - if ($form_state['values']['run']['book_hidden'] != $form_state['values']['run']['book']) - $example_default_value = 0; - else if ($form_state['values']['run']['chapter_hidden'] != $form_state['values']['run']['chapter']) - $example_default_value = 0; - else - $example_default_value = $form_state['storage']['run']['example']; - } - - $form['run'] = array( - '#type' => 'fieldset', - '#title' => t('Run Book Example'), - '#collapsible' => FALSE, - '#collapsed' => FALSE, - '#prefix' => '<div id="run-wrapper">', - '#suffix' => '</div>', - '#tree' => TRUE, - ); - $form['run']['category'] = array( - '#type' => 'select', - '#title' => t('Category'), - '#options' => array(0 => 'Please select', - 1 => 'Fluid Mechanics', - 2 => 'Control Theory & Control Systems', - 3 => 'Chemical Engineering', - 4 => 'Thermodynamics', - 5 => 'Mechanical Engineering', - 6 => 'Signal Processing', - 7 => 'Digital Communications', - 8 => 'Electrical Technology', - 9 => 'Mathematics & Pure Science', - 10 => 'Analog Electronics', - 11 => 'Digital Electronics', - 12 => 'Computer Programming', - 13 => 'Others'), - '#default_value' => $category_default_value, - '#tree' => TRUE, - '#ahah' => array( - 'event' => 'change', - 'effect' => 'none', - 'path' => ahah_helper_path(array('run')), - 'wrapper' => 'run-wrapper', - 'progress' => array( - 'type' => 'throbber', - 'message' => t(''), - ), - ), - ); - if($category_default_value > 0) { - $form['run']['book'] = array( - '#type' => 'select', - '#title' => t('Title of the Book'), - '#options' => _list_of_books($category_default_value), - '#default_value' => $book_default_value, - '#tree' => TRUE, - '#ahah' => array( - 'event' => 'change', - 'effect' => 'none', - 'path' => ahah_helper_path(array('run')), - 'wrapper' => 'run-wrapper', - 'progress' => array( - 'type' => 'throbber', - 'message' => t(''), - ), - ), - ); - }else { - $book_default_value = 0; + $url_book_pref_id = (int) arg(2); + // var_dump($url_book_pref_id);die; + if ($url_book_pref_id) { + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference', array( + 'category' + )); + $query->condition('id', $url_book_pref_id); + $result = $query->execute()->fetchObject(); + $category_default_value = $result->category; + } else { + $category_default_value = 0; } - /* hidden form elements */ - $form['run']['book_hidden'] = array( - '#type' => 'hidden', - '#value' => $form_state['values']['run']['book'], - ); - - /* hidden form elements */ - $form['run']['chapter_hidden'] = array( - '#type' => 'hidden', - '#value' => $form_state['values']['run']['chapter'], - ); - - if ($book_default_value > 0) - { - $book_details = _book_information($book_default_value); - $form['run']['book_details'] = array( - '#type' => 'item', - '#value' => '<table cellspacing="1" cellpadding="1" border="0" style="width: 100%;" valign="top">' . - '<tr><td style="width: 35%;"><span style="color: rgb(128, 0, 0);"><strong>About the Book</strong></span></td><td style="width: 35%;"><span style="color: rgb(128, 0, 0);"><strong>About the Contributor</strong></span></td>' . - '<tr><td valign="top"><ul>' . - '<li><strong>Author:</strong> ' . $book_details->preference_author . '</li>' . - '<li><strong>Title of the Book:</strong> ' . $book_details->preference_book . '</li>' . - '<li><strong>Publisher:</strong> ' . $book_details->preference_publisher . '</li>' . - '<li><strong>Year:</strong> ' . $book_details->preference_year . '</li>' . - '<li><strong>Edition:</strong> ' . $book_details->preference_edition . '</li>' . - '</ul></td><td valign="top"><ul>' . - '<li><strong>Contributor Name: </strong>' . $book_details->proposal_full_name . ', ' . $book_details->proposal_course . ', ' . $book_details->proposal_branch . ', ' . $book_details->proposal_university . '</li>' . - '<li><strong>College Teacher: </strong>' . $book_details->proposal_faculty . '</li>' . - '<li><strong>Reviewer: </strong>' . $book_details->proposal_reviewer . '</li>' . - '</ul></td></tr>' . - '</table>', - ); - - $form['run']['download_book'] = array( - '#type' => 'item', - '#value' => l('Download', 'download/book/' . $book_default_value) . ' ' . t('(Download the DWSIM codes for all the solved examples)'), - ); - // $form['run']['chapter'] = array( - // '#type' => 'select', - // '#title' => t('Title of the Chapter'), - // '#options' => _list_of_chapters($book_default_value), - // '#default_value' => $chapter_default_value, - // '#tree' => TRUE, - // '#ahah' => array( - // 'event' => 'change', - // 'effect' => 'none', - // 'path' => ahah_helper_path(array('run')), - // 'wrapper' => 'run-wrapper', - // 'progress' => array( - // 'type' => 'throbber', - // 'message' => t(''), - // ), - // ), - // ); - if ($chapter_default_value > 0) - { - $form['run']['download_chapter'] = array( + if ($url_book_pref_id) { + $form['category'] = array( + '#type' => 'hidden', + '#title' => t('Category'), + '#options' => _list_of_category(), + '#default_value' => $category_default_value, + '#ajax' => array( + 'callback' => 'ajax_book_list_callback' + ), + '#validated' => TRUE + ); + $book_default_value = $url_book_pref_id; + $form['book'] = array( + '#type' => 'select', + '#title' => t('Title of the book'), + '#options' => _list_of_books($book_default_value), + '#default_value' => $book_default_value, + '#prefix' => '<div id="ajax-book-list-replace">', + '#suffix' => '</div>', + '#ajax' => array( + 'callback' => 'ajax_chapter_list_callback' + ), + '#validated' => TRUE + ); + /*$form['book_details'] = array( + '#prefix' => '<div id="ajax-book-details-replace"></div>', + '#suffix' => '</div>', + '#markup' => '', + );*/ + $form['book_details'] = array( + '#type' => 'item', + '#markup' => '<div id="ajax-book-details-replace">' . _html_book_info($book_default_value) . '</div>' + ); + $form['download_book'] = array( + '#type' => 'item', + '#markup' => '<div id="ajax-download-book-replace">' . l('Download', 'textbook-companion/download/book/' . $book_default_value) . ' ' . t('(Download the DWSIM codes for all the solved examples)') . '</div>' + ); + /*$book_pref_id_array = array("19"); + if(in_array($book_default_value, $book_pref_id_array)){ + $form['freeeda_download_book'] = array( '#type' => 'item', - '#value' => l('Download', 'download/chapter/' . $chapter_default_value) . ' ' . t('(Download the DWSIM codes for all the solved examples from the Chapter)'), - ); - $form['run']['example'] = array( - '#type' => 'select', - '#title' => t('Example No. (Caption)'), - '#options' => _list_of_examples($chapter_default_value), - '#default_value' => $example_default_value, - '#tree' => TRUE, - '#ahah' => array( - 'event' => 'change', - 'effect' => 'none', - 'path' => ahah_helper_path(array('run')), - 'wrapper' => 'run-wrapper', - 'progress' => array( - 'type' => 'throbber', - 'message' => t(''), - ), - ), - ); - } - } - - /* hidden form elements */ - $form['run']['update_book'] = array( - '#type' => 'submit', - '#value' => t('Update'), - '#submit' => array('ahah_helper_generic_submit'), - '#attributes' => array('class' => 'no-js'), - ); - - $form['run']['update_chapter'] = array( - '#type' => 'submit', - '#value' => t('Update'), - '#submit' => array('ahah_helper_generic_submit'), - '#attributes' => array('class' => 'no-js'), - ); - - /************ START OF $_POST **************/ - if ($_POST) - { - if (($book_default_value > 0) && ($chapter_default_value > 0) && ($example_default_value > 0)) - { - $example_list_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE example_id = %d", $form_state['values']['run']['example']); - if ($example_list_q) - { - $example_files_rows = array(); - while ($example_list_data = db_fetch_object($example_list_q)) - { - $example_file_type = 'Source or Main file'; - $example_files_rows[] = array(l($example_list_data->filename, 'download/file/' . $example_list_data->id), $example_file_type); - } - - /* creating list of files table */ - $example_files_header = array('Filename', 'Type'); - $example_files = theme_table($example_files_header, $example_files_rows); - } - $form['run']['download_example'] = array( + '#markup' => '<div id="ajax-download-freeeda-book-replace">'.l('Download (FreeEDA Version)', 'textbook-companion/uploads/Microelectronic_Circuits___Theory_And_Applications_FreeEDA_Version.zip') . ' ' . t('(Download the FreeEDA codes for all the solved examples)').'</div>', + ); + }*/ + /* $form['download_pdf'] = array( + '#type' => 'item', + '#markup' => '<div id="ajax-download-book-pdf-replace">'.l('Download PDF', 'textbook_companion/generate_book/' . $book_default_value) . ' ' . t('(Download the PDF file containing eSim codes for all the solved examples)').'</div>', + );*/ + $form['chapter'] = array( + '#type' => 'select', + '#title' => t('Title of the chapter'), + '#options' => _list_of_chapters($book_default_value), + //'#default_value' => isset($form_state['values']['chapter']) ? $form_state['values']['chapter'] : '', + '#prefix' => '<div id="ajax-chapter-list-replace">', + '#suffix' => '</div>', + '#ajax' => array( + 'callback' => 'ajax_example_list_callback' + ), + '#validated' => TRUE, + '#states' => array( + 'invisible' => array( + ':input[name="category"]' => array( + 'value' => 0 + ) + ) + ) + ); + $form['download_chapter'] = array( + '#type' => 'item', + '#markup' => '<div id="ajax-download-chapter-replace"></div>' + ); + $example_default_value = isset($form_state['values']['chapter']) ? $form_state['values']['chapter'] : ''; + $form['examples'] = array( + '#type' => 'select', + '#title' => t('Example No. (Caption): '), + '#options' => _list_of_examples($example_default_value), + '#default_value' => isset($form_state['values']['examples']) ? $form_state['values']['examples'] : '', + '#prefix' => '<div id="ajax-example-list-replace">', + '#suffix' => '</div>', + '#ajax' => array( + 'callback' => 'ajax_example_files_callback' + ), + '#states' => array( + 'invisible' => array( + ':input[name="chapter"]' => array( + 'value' => 0 + ) + ) + ) + ); + $form['download_example_code'] = array( + '#type' => 'item', + '#markup' => '<div id="ajax-download-example-code-replace"></div>' + ); + $form['example_files'] = array( + '#type' => 'item', + '#markup' => '<div id="ajax-download-example-files-replace"></div>' + ); + } else { + $form['category'] = array( + '#type' => 'hidden', + '#title' => t('Category'), + '#options' => _list_of_category(), + '#default_value' => $category_default_value, + '#ajax' => array( + 'callback' => 'ajax_book_list_callback' + ), + '#validated' => TRUE + ); + $form['book'] = array( + '#type' => 'select', + '#title' => t('Title of the book'), + '#options' => _list_of_books(), + //'#default_value' => isset($form_state['values']['book']) ? $form_state['values']['book'] : 0, + '#prefix' => '<div id="ajax-book-list-replace">', + '#suffix' => '</div>', + '#ajax' => array( + 'callback' => 'ajax_chapter_list_callback' + ), + '#validated' => TRUE + //'#states' => array('invisible' => array(':input[name="category"]' => array('value' => 0),),), + ); + $form['book_details'] = array( + '#type' => 'item', + '#markup' => '<div id="ajax-book-details-replace"></div>' + ); + $form['download_book'] = array( + '#type' => 'item', + '#markup' => '<div id="ajax-download-book-replace"></div>' + ); + $form['freeeda_download_book'] = array( + '#type' => 'item', + '#markup' => '<div id="ajax-download-freeeda-book-replace"></div>' + ); + /* $form['download_pdf'] = array( '#type' => 'item', - '#value' => l('Download Example', 'download/example/' . $example_default_value), - ); - $form['run']['example_files'] = array( - '#type' => 'item', - '#title' => 'List of example files', - '#value' => $example_files, - ); - //$form['run']['submit'] = array( - // '#type' => 'submit', - // '#value' => t('Run') - //); - if (user_access('create feedback')) - { - $form['run']['feedback'] = array( - '#type' => 'textarea', - '#title' => t('Feedback on the above example') + '#markup' => '<div id="ajax-download-book-pdf-replace"></div>', + );*/ + $book_default_value = isset($form_state['values']['book']) ? $form_state['values']['book'] : ''; + $form['chapter'] = array( + '#type' => 'select', + '#title' => t('Title of the chapter'), + '#options' => _list_of_chapters($book_default_value), + //'#default_value' => isset($form_state['values']['chapter']) ? $form_state['values']['chapter'] : '', + '#prefix' => '<div id="ajax-chapter-list-replace">', + '#suffix' => '</div>', + '#ajax' => array( + 'callback' => 'ajax_example_list_callback' + ), + '#validated' => TRUE, + '#states' => array( + 'invisible' => array( + ':input[name="book"]' => array( + 'value' => 0 + ) + ) + ) + ); + $form['download_chapter'] = array( + '#type' => 'item', + '#markup' => '<div id="ajax-download-chapter-replace"></div>' + ); + $example_default_value = isset($form_state['values']['chapter']) ? $form_state['values']['chapter'] : ''; + $form['examples'] = array( + '#type' => 'select', + '#title' => t('Example No. (Caption): '), + '#options' => _list_of_examples($example_default_value), + '#default_value' => isset($form_state['values']['examples']) ? $form_state['values']['examples'] : '', + '#prefix' => '<div id="ajax-example-list-replace">', + '#suffix' => '</div>', + '#ajax' => array( + 'callback' => 'ajax_example_files_callback' + ), + '#states' => array( + 'invisible' => array( + ':input[name="book"]' => array( + 'value' => 0 + ) + ) + ) + ); + $form['download_example_code'] = array( + '#type' => 'item', + '#markup' => '<div id="ajax-download-example-code-replace"></div>' ); - $form['run']['feedback_submit'] = array( - '#type' => 'submit', - '#value' => t('Submit') + $form['example_files'] = array( + '#type' => 'item', + '#markup' => '<div id="ajax-download-example-files-replace"></div>' + ); + } + return $form; +} +/********************* Ajax callback ***************************/ +function ajax_book_list_callback($form, $form_state) +{ + $category_default_value = $form_state['values']['category']; + if ($category_default_value == 0) { + $form['book']['#options'] = _list_of_books($category_default_value); + $commands[] = ajax_command_replace("#ajax-book-list-replace", drupal_render($form['book'])); + $commands[] = ajax_command_html("#ajax-chapter-list-replace", ''); + $commands[] = ajax_command_html("#ajax-example-list-replace", ''); + } else { + $form['book']['#options'] = _list_of_books(); + $commands[] = ajax_command_replace("#ajax-book-list-replace", drupal_render($form['book'])); + $commands[] = ajax_command_html("#ajax-book-list-replace", ''); + $commands[] = ajax_command_html("#ajax-chapter-list-replace", ''); + $commands[] = ajax_command_html("#ajax-example-list-replace", ''); + $commands[] = ajax_command_html("#ajax-book-details-replace", ''); + $commands[] = ajax_command_html("#ajax-download-book-replace", ''); + $commands[] = ajax_command_html("#ajax-download-freeeda-book-replace", ''); + $commands[] = ajax_command_html("#ajax-download-chapter-replace", ''); + $commands[] = ajax_command_html("#ajax-download-example-code-replace", ''); + $commands[] = ajax_command_html("#ajax-download-example-files-replace", ''); + } + return array( + '#type' => 'ajax', + '#commands' => $commands + ); +} +/*************************************************************************/ +function ajax_chapter_list_callback($form, $form_state) +{ + $book_list_default_value = $form_state['values']['book']; + if ($book_list_default_value > 0) { + $commands[] = ajax_command_html("#ajax-book-details-replace", _html_book_info($book_list_default_value)); + $form['chapter']['#options'] = _list_of_chapters($book_list_default_value); + $commands[] = ajax_command_html("#ajax-download-book-replace", l('Download', 'textbook-companion/download/book/' . $book_list_default_value) . ' ' . t('(Download the DWSIM codes for all the solved examples)')); + $book_pref_id_array = array( + "19" ); - } + if (in_array($book_list_default_value, $book_pref_id_array)) { + $commands[] = ajax_command_html("#ajax-download-freeeda-book-replace", l('Download FreeEDA Version', 'textbook-companion/uploads/Microelectronic_Circuits___Theory_And_Applications_FreeEDA_Version.zip') . ' ' . t('(Download the FreeEDA codes for all the solved examples)')); + } else { + $commands[] = ajax_command_html("#ajax-download-freeeda-book-replace", ''); + } + $commands[] = ajax_command_replace("#ajax-chapter-list-replace", drupal_render($form['chapter'])); + $commands[] = ajax_command_html("#ajax-example-list-replace", ''); + $commands[] = ajax_command_html("#ajax-download-example-code-replace", ''); + $commands[] = ajax_command_html("#ajax-download-example-files-replace", ''); + $commands[] = ajax_command_html("#ajax-download-chapter-replace", ''); + } else { + $commands[] = ajax_command_html("#ajax-book-details-replace", ''); + $form['chapter']['#options'] = _list_of_chapters(); + $commands[] = ajax_command_replace("#ajax-chapter-list-replace", drupal_render($form['chapter'])); + $commands[] = ajax_command_html("#ajax-chapter-list-replace", ''); + $commands[] = ajax_command_html("#ajax-download-book-replace", ''); + $commands[] = ajax_command_html("#ajax-download-chapter-replace", ''); + $commands[] = ajax_command_html("#ajax-download-freeeda-book-replace", ''); + $commands[] = ajax_command_html("#ajax-example-list-replace", ''); + $commands[] = ajax_command_html("#ajax-download-example-code-replace", ''); + $commands[] = ajax_command_html("#ajax-download-example-files-replace", ''); } - } - /************ END OF $_POST **************/ - - return $form; + return array( + '#type' => 'ajax', + '#commands' => $commands + ); } - -function textbook_companion_run_form_submit($form, &$form_state) +function ajax_example_list_callback($form, $form_state) { - global $user; - - if ($form_state['clicked_button']['#value'] == 'Submit') - { - if (user_access('create feedback')) - { - $example_data = db_fetch_object(db_query("SELECT * FROM {textbook_companion_example} WHERE id = %d", $form_state['values']['run']['example'])); - if (!$example_data) - { - drupal_set_message(t('Invalid example selected'), 'error'); - return; - } - $chapter_data = db_fetch_object(db_query("SELECT * FROM {textbook_companion_chapter} WHERE id = %d", $example_data->chapter_id)); - if (!$chapter_data) - { - drupal_set_message(t('Invalid chapter selected'), 'error'); - return; - } - $book_data = db_fetch_object(db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d", $chapter_data->preference_id)); - if (!$book_data) - { - drupal_set_message(t('Invalid book selected'), 'error'); - return; - } - $proposal_data = db_fetch_object(db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d", $book_data->proposal_id)); - if (!$proposal_data) - { - drupal_set_message(t('Invalid proposal selected'), 'error'); - return; - } - db_query("INSERT INTO {textbook_companion_feedback} (example_id, uid, feedback, ip_address, timestamp) VALUES (%d, %d, '%s', '%s', %d)", - $example_data->id, - $user->uid, - $form_state['values']['run']['feedback'], - $_SERVER['REMOTE_ADDR'], - time()); - - /* sending email */ - $param['feedback_received']['user_id'] = $user->uid; - $param['feedback_received']['book_title'] = $book_data->book; - $param['feedback_received']['chapter_number'] = $chapter_data->number; - $param['feedback_received']['chapter_title'] = $chapter_data->name; - $param['feedback_received']['example_no'] = $example_data->number; - $param['feedback_received']['feedback'] = $form_state['values']['run']['feedback']; - - $email_to = $user->mail; - // . ', ' . user_load($proposal_data->uid)->mail. ', ' . user_load($example_data->approver_uid)->mail; - if (!drupal_mail('textbook_companion', 'feedback_received', $email_to, language_default(), $param, variable_get('textbook_companion_from_email', NULL), TRUE)) - drupal_set_message('Error sending email message.', 'error'); - - drupal_set_message(t('Thank you for your feedback.'), 'status'); + $chapter_list_default_value = $form_state['values']['chapter']; + if ($chapter_list_default_value > 0) { + $form['examples']['#options'] = _list_of_examples($chapter_list_default_value); + $commands[] = ajax_command_replace("#ajax-example-list-replace", drupal_render($form['examples'])); + $commands[] = ajax_command_html("#ajax-download-chapter-replace", l('Download', 'textbook-companion/download/chapter/' . $chapter_list_default_value) . ' ' . t('(Download the DWSIM codes for all the solved examples from the Chapter)')); + $commands[] = ajax_command_html("#ajax-download-example-code-replace", ''); + $commands[] = ajax_command_html("#ajax-download-example-files-replace", ''); } else { - drupal_set_message(t('You do not have permission to submit feeback.'), 'error'); + $form['examples']['#options'] = _list_of_examples(); + $commands[] = ajax_command_replace("#ajax-example-list-replace", drupal_render($form['examples'])); + $commands[] = ajax_command_html("#ajax-example-list-replace", ''); + $commands[] = ajax_command_html("#ajax-download-chapter-replace", ''); + $commands[] = ajax_command_html("#ajax-download-example-code-replace", ''); + $commands[] = ajax_command_html("#ajax-download-example-files-replace", ''); } - } + return array( + '#type' => 'ajax', + '#commands' => $commands + ); +} +/*****************************************************/ +function ajax_example_files_callback($form, $form_state) +{ + $example_list_default_value = $form_state['values']['examples']; + if ($example_list_default_value != 0) { + // $example_list_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE example_id = %d", $form_state['values']['run']['example']); + $query = db_select('textbook_companion_example_files'); + $query->fields('textbook_companion_example_files'); + $query->condition('example_id', $example_list_default_value); + $example_list_q = $query->execute(); + if ($example_list_q) { + $example_files_rows = array(); + while ($example_list_data = $example_list_q->fetchObject()) { + $example_file_type = ''; + switch ($example_list_data->filetype) { + case 'S': + $example_file_type = 'Source or Main file'; + break; + case 'R': + $example_file_type = 'Result file'; + break; + case 'X': + $example_file_type = 'xcos file'; + break; + default: + $example_file_type = 'Unknown'; + break; + } + $example_files_rows[] = array( + l($example_list_data->filename, 'textbook-companion/download/file/' . $example_list_data->id), + $example_file_type + ); + } + /* creating list of files table */ + $example_files_header = array( + 'Filename', + 'Type' + ); + $example_files = theme('table', array( + 'header' => $example_files_header, + 'rows' => $example_files_rows + )); + } + $commands[] = ajax_command_html("#ajax-download-example-code-replace", l('Download DWSIM code for the example', 'textbook-companion/download/example/' . $example_list_default_value)); + $commands[] = ajax_command_html("#ajax-download-example-files-replace", $example_files); + } else { + $commands[] = ajax_command_html("#ajax-download-example-code-replace", ''); + $commands[] = ajax_command_html("#ajax-download-example-files-replace", ''); + } + return array( + '#type' => 'ajax', + '#commands' => $commands + ); +} +/*******************************************************************/ +function bootstrap_table_format($headers, $rows) +{ + $thead = ""; + $tbody = ""; + foreach ($headers as $header) { + $thead .= "<th>{$header}</th>"; + } + foreach ($rows as $row) { + $tbody .= "<tr>"; + foreach ($row as $data) { + $tbody .= "<td>{$data}</td>"; + } + $tbody .= "</tr>"; + } + $table = " + <table class='table table-bordered table-hover' style='margin-left:-140px'> + <thead>{$thead}</thead> + <tbody>{$tbody}</tbody> + </table> + "; + return $table; +} +/***********************************************************************************/ +function _list_of_category() +{ + $category_titles = array( + 0 => 'Please select category ...', + 1 => 'Fluid Mechanics', + 2 => 'Control Theory & Control Systems', + 3 => 'Chemical Engineering', + 4 => 'Thermodynamics', + 5 => 'Mechanical Engineering', + 6 => 'Signal Processing', + 7 => 'Digital Communications', + 8 => 'Electrical Technology', + 9 => 'Mathematics & Pure Science', + 10 => 'Analog Electronics', + 11 => 'Digital Electronics', + 12 => 'Computer Programming', + 13 => 'Others' + ); + return $category_titles; } - -function _list_of_books($category_default_value) +function _list_of_books($preference_id = NULL) { - $book_titles = array('0' => 'Please select...'); - // $book_titles_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE category=".$category_default_value." AND approval_status = 1 OR approval_status = 3 ORDER BY book ASC"); - $book_titles_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE category=".$category_default_value." AND approval_status = 1 AND proposal_id IN (SELECT id FROM textbook_companion_proposal WHERE proposal_status=3) ORDER BY book ASC"); - while ($book_titles_data = db_fetch_object($book_titles_q)) - { - $book_titles[$book_titles_data->id] = $book_titles_data->book . ' (Written by ' . $book_titles_data->author . ')'; - } - return $book_titles; + if ($preference_id != NULL) { + $book_titles = array( + 0 => 'Please select ...' + ); + // $book_titles_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE category=".$category_default_value." AND approval_status = 1 OR approval_status = 3 ORDER BY book ASC"); + // $book_titles_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE category=".$category_default_value." AND approval_status = 1 AND proposal_id IN (SELECT id FROM textbook_companion_proposal WHERE proposal_status=3) ORDER BY book ASC"); + // var_dump('ok= '. $category_default_value); + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('id', $preference_id); + $query->condition('approval_status', 1); + $subquery = db_select('textbook_companion_proposal'); + $subquery->fields('textbook_companion_proposal', array( + 'id' + )); + $subquery->condition('proposal_status', 3); + $query->condition('proposal_id', $subquery, 'IN'); + $query->orderBy('book', 'ASC'); + $book_titles_q = $query->execute(); + while ($book_titles_data = $book_titles_q->fetchObject()) { + $book_titles[$book_titles_data->id] = $book_titles_data->book . ' (Written by ' . $book_titles_data->author . ')'; + } + } else { + $book_titles = array( + 0 => 'Please select ...' + ); + // $book_titles_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE category=".$category_default_value." AND approval_status = 1 OR approval_status = 3 ORDER BY book ASC"); + // $book_titles_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE category=".$category_default_value." AND approval_status = 1 AND proposal_id IN (SELECT id FROM textbook_companion_proposal WHERE proposal_status=3) ORDER BY book ASC"); + // var_dump('ok= '. $category_default_value); + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + //$query->condition('id', $preference_id); + $query->condition('approval_status', 1); + $subquery = db_select('textbook_companion_proposal'); + $subquery->fields('textbook_companion_proposal', array( + 'id' + )); + $subquery->condition('proposal_status', 3); + $query->condition('proposal_id', $subquery, 'IN'); + $query->orderBy('book', 'ASC'); + $book_titles_q = $query->execute(); + while ($book_titles_data = $book_titles_q->fetchObject()) { + $book_titles[$book_titles_data->id] = $book_titles_data->book . ' (Written by ' . $book_titles_data->author . ')'; + } + } + return $book_titles; } - function _list_of_chapters($preference_id = 0) { - $book_chapters = array('0' => 'Please select...'); - $book_chapters_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE preference_id = %d ORDER BY number ASC", $preference_id); - while ($book_chapters_data = db_fetch_object($book_chapters_q)) - { - $book_chapters[$book_chapters_data->id] = $book_chapters_data->number . '. ' . $book_chapters_data->name; - } - return $book_chapters; + $book_chapters = array( + 0 => 'Please select...' + ); + //$book_chapters_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE preference_id = %d ORDER BY number ASC", $preference_id); + $query = db_select('textbook_companion_chapter'); + $query->fields('textbook_companion_chapter'); + $query->condition('preference_id', $preference_id); + $query->orderBy('number', 'ASC'); + $book_chapters_q = $query->execute(); + while ($book_chapters_data = $book_chapters_q->fetchObject()) { + $book_chapters[$book_chapters_data->id] = $book_chapters_data->number . '. ' . $book_chapters_data->name; + } + return $book_chapters; } - function _list_of_examples($chapter_id = 0) { - $book_examples = array('0' => 'Please select...'); - $book_examples_q = db_query("SELECT * FROM {textbook_companion_example} WHERE chapter_id = %d AND approval_status = 1 ORDER BY - CAST(SUBSTRING_INDEX(number, '.', 1) AS BINARY) ASC, - CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(number , '.', 2), '.', -1) AS UNSIGNED) ASC, - CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(number , '.', -1), '.', 1) AS UNSIGNED) ASC", $chapter_id); - while ($book_examples_data = db_fetch_object($book_examples_q)) - { - $book_examples[$book_examples_data->id] = $book_examples_data->number . ' (' . $book_examples_data->caption . ')'; - } - return $book_examples; + $book_examples = array( + 0 => 'Please select...' + ); + //$book_examples_q = db_query("SELECT * FROM {textbook_companion_example} WHERE chapter_id = %d AND approval_status = 1 ORDER BY + // CAST(SUBSTRING_INDEX(number, '.', 1) AS BINARY) ASC, + // CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(number , '.', 2), '.', -1) AS UNSIGNED) ASC, + // CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(number , '.', -1), '.', 1) AS UNSIGNED) ASC", $chapter_id); + $query = db_select('textbook_companion_example'); + $query->fields('textbook_companion_example'); + $query->condition('chapter_id', $chapter_id); + $query->condition('approval_status', 1); + //$query->orderBy('', ''); + $book_examples_q = $query->execute(); + while ($book_examples_data = $book_examples_q->fetchObject()) { + $book_examples[$book_examples_data->id] = $book_examples_data->number . ' (' . $book_examples_data->caption . ')'; + } + return $book_examples; } - function _book_information($preference_id) { - $book_data = db_fetch_object(db_query("SELECT + /*$book_data = db_fetch_object(db_query("SELECT + preference.book as preference_book, preference.author as preference_author, preference.isbn as preference_isbn, preference.publisher as preference_publisher, preference.edition as preference_edition, preference.year as preference_year, + proposal.full_name as proposal_full_name, proposal.faculty as proposal_faculty, proposal.reviewer as proposal_reviewer, proposal.course as proposal_course, proposal.branch as proposal_branch, proposal.university as proposal_university + FROM {textbook_companion_proposal} proposal LEFT JOIN {textbook_companion_preference} preference ON proposal.id = preference.proposal_id WHERE preference.id = %d", $preference_id));*/ + $query = db_select('textbook_companion_proposal', 'proposal'); + $query->fields('preference', array( + 'book', + 'author', + 'isbn', + 'publisher', + 'edition', + 'year' + )); + $query->fields('proposal', array( + 'full_name', + 'faculty', + 'reviewer', + 'course', + 'branch', + 'university' + )); + $query->leftJoin('textbook_companion_preference', 'preference', 'proposal.id = preference.proposal_id'); + $query->condition('preference.id', $preference_id); + $book_data = $query->execute()->fetchObject(); + return $book_data; +} +function _html_book_info($preference_id) +{ + /*$book_details = db_fetch_object(db_query("SELECT preference.book as preference_book, preference.author as preference_author, preference.isbn as preference_isbn, preference.publisher as preference_publisher, preference.edition as preference_edition, preference.year as preference_year, proposal.full_name as proposal_full_name, proposal.faculty as proposal_faculty, proposal.reviewer as proposal_reviewer, proposal.course as proposal_course, proposal.branch as proposal_branch, proposal.university as proposal_university - FROM {textbook_companion_proposal} proposal LEFT JOIN {textbook_companion_preference} preference ON proposal.id = preference.proposal_id WHERE preference.id = %d", $preference_id)); - return $book_data; + FROM {textbook_companion_proposal} proposal LEFT JOIN {textbook_companion_preference} preference ON proposal.id = preference.proposal_id WHERE preference.id=".$preference_id));*/ + $query = db_select('textbook_companion_proposal', 'proposal'); + $query->addField('preference', 'book', 'preference_book'); + $query->addField('preference', 'author', 'preference_author'); + $query->addField('preference', 'isbn', 'preference_isbn'); + $query->addField('preference', 'publisher', 'preference_publisher'); + $query->addField('preference', 'edition', 'preference_edition'); + $query->addField('preference', 'year', 'preference_year'); + $query->addField('proposal', 'full_name', 'proposal_full_name'); + $query->addField('proposal', 'faculty', 'proposal_faculty'); + $query->addField('proposal', 'reviewer', 'proposal_reviewer'); + $query->addField('proposal', 'course', 'proposal_course'); + $query->addField('proposal', 'branch', 'proposal_branch'); + $query->addField('proposal', 'university', 'proposal_university'); + $query->fields('proposal', array( + 'full_name', + 'faculty', + 'reviewer', + 'course', + 'branch', + 'university' + )); + $query->leftJoin('textbook_companion_preference', 'preference', 'proposal.id = preference.proposal_id'); + $query->fields('preference', array( + 'book', + 'author', + 'isbn', + 'publisher', + 'edition', + 'year' + )); + $query->condition('preference.id', $preference_id); + $book_details = $query->execute()->fetchObject(); + $html_data = ''; + if ($book_details) { + $html_data = '<table cellspacing="1" cellpadding="1" border="0" style="width: 100%;" valign="top">' . '<tr><td style="width: 35%;"><span style="color: rgb(128, 0, 0);"><strong>About the Book</strong></span></td><td style="width: 35%;"><span style="color: rgb(128, 0, 0);"><strong>About the Contributor</strong></span></td>' . '<tr><td valign="top"><ul>' . '<li><strong>Author:</strong> ' . $book_details->preference_author . '</li>' . '<li><strong>Title of the Book:</strong> ' . $book_details->preference_book . '</li>' . '<li><strong>Publisher:</strong> ' . $book_details->preference_publisher . '</li>' . '<li><strong>Year:</strong> ' . $book_details->preference_year . '</li>' . '<li><strong>Edition:</strong> ' . $book_details->preference_edition . '</li>' . '</ul></td><td valign="top"><ul>' . '<li><strong>Contributor Name: </strong>' . $book_details->proposal_full_name . ', ' . $book_details->proposal_course . ', ' . $book_details->proposal_branch . ', ' . $book_details->proposal_university . '</li>' . '<li><strong>College Teacher: </strong>' . $book_details->proposal_faculty . '</li>' . '<li><strong>Reviewer: </strong>' . $book_details->proposal_reviewer . '</li>' . '</ul></td></tr>' . '</table>'; + } + return $html_data; } @@ -1,274 +1,426 @@ <?php // $Id$ - -function textbook_companion_search_form() -{ - $form['#redirect'] = FALSE; - $form['search'] = array( - '#type' => 'textfield', - '#title' => t('Search'), - '#size' => 48, - ); - - $form['search_by_title'] = array( - '#type' => 'checkbox', - '#default_value' => TRUE, - '#title' => t('Search by Title of the Book'), - ); - - $form['search_by_author'] = array( - '#type' => 'checkbox', - '#default_value' => TRUE, - '#title' => t('Search by Author of the Book'), - ); - - $form['submit'] = array( - '#type' => 'submit', - '#value' => t('Search') - ); - - $form['cancel'] = array( - '#type' => 'markup', - '#value' => l(t('Cancel'), ''), - ); - - if ($_POST) +function textbook_companion_search_form($form, $form_state) { - $output = ''; - $search_rows = array(); - $search_query = ''; - if ($_POST['search_by_title'] && $_POST['search_by_author']) - $search_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE approval_status = 1 AND (book LIKE '%%%s%%' OR author LIKE '%%%s%%')", $_POST['search'], $_POST['search']); - else if ($_POST['search_by_title']) - $search_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE approval_status = 1 AND book LIKE '%%%s%%'", $_POST['search']); - else if ($_POST['search_by_author']) - $search_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE approval_status = 1 AND author LIKE '%%%s%%'", $_POST['search']); - else - drupal_set_message('Please select whether to search by Title and/or Author of the Book.', 'error'); - while ($search_data = db_fetch_object($search_q)) - { - $search_rows[] = array(l($search_data->book, 'textbook_run/' . $search_data->id), $search_data->author); - } - if ($search_rows) - { - $search_header = array('Title of the Book', 'Author Name'); - $output .= theme_table($search_header, $search_rows); - $form['search_results'] = array( - '#type' => 'item', - '#title' => t('Search results for "') . $_POST['search'] . '"', - '#value' => $output, - ); - } else { - $form['search_results'] = array( - '#type' => 'item', - '#title' => t('Search results for "') . $_POST['search'] . '"', - '#value' => 'No results found', - ); - } + $form['#redirect'] = FALSE; + $form['search'] = array( + '#type' => 'textfield', + '#title' => t('Search'), + '#size' => 48 + ); + $form['search_by_title'] = array( + '#type' => 'checkbox', + '#default_value' => TRUE, + '#title' => t('Search by Title of the Book') + ); + $form['search_by_author'] = array( + '#type' => 'checkbox', + '#default_value' => TRUE, + '#title' => t('Search by Author of the Book') + ); + $form['submit'] = array( + '#type' => 'submit', + '#value' => t('Search') + ); + $form['cancel'] = array( + '#type' => 'item', + '#markup' => l(t('Cancel'), '') + ); + if ($_POST) + { + $output = ''; + $search_rows = array(); + $search_query = ''; + if ($_POST['search_by_title'] && $_POST['search_by_author']) + { + /*$search_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE approval_status = 1 AND (book LIKE '%%%s%%' OR author LIKE '%%%s%%')", $_POST['search'], $_POST['search']);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('approval_status', 1); + $or = db_or(); + $or->condition('book', '%%' . $_POST['search'] . '%%', 'LIKE'); + $or->condition('author', '%%' . $_POST['search'] . '%%', 'LIKE'); + $query->condition($or); + $search_q = $query->execute(); + } + else if ($_POST['search_by_title']) + { + /*$search_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE approval_status = 1 AND book LIKE '%%%s%%'", $_POST['search']);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('approval_status', 1); + $query->condition('book', '%%' . $_POST['search'] . '%%', 'LIKE'); + $search_q = $query->execute(); + } + else if ($_POST['search_by_author']) + { + /*$search_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE approval_status = 1 AND author LIKE '%%%s%%'", $_POST['search']);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('approval_status', 1); + $query->condition('author', '%%' . $_POST['search'] . '%%', 'LIKE'); + $search_q = $query->execute(); + } + else + { + drupal_set_message('Please select whether to search by Title and/or Author of the Book.', 'error'); + } + while ($search_data = $search_q->fetchObject()) + { + $search_rows[] = array( + l($search_data->book, 'textbook_run/' . $search_data->id), + $search_data->author + ); + } + if ($search_rows) + { + $search_header = array( + 'Title of the Book', + 'Author Name' + ); + $output .= theme('table', array( + 'headers' => $search_header, + 'rows' => $search_rows + )); + $form['search_results'] = array( + '#type' => 'item', + '#title' => t('Search results for "') . $_POST['search'] . '"', + '#markup' => $output + ); + } + else + { + $form['search_results'] = array( + '#type' => 'item', + '#title' => t('Search results for "') . $_POST['search'] . '"', + '#markup' => 'No results found' + ); + } + } + return $form; } - return $form; -} - /******************************************************************************/ /**************************** BROWSE BY FORMS *********************************/ /******************************************************************************/ - function textbook_companion_browse_book() -{ - $return_html = _browse_list('book'); - $return_html .= '<br /><br />'; - $query_character = arg(2); - if (!$query_character) { - /* all books */ - $return_html .= "Please select the starting character of the title of the book"; + { + $return_html = _browse_list('book'); + $return_html .= '<br /><br />'; + $query_character = arg(2); + if (!$query_character) + { + /* all books */ + $return_html .= "Please select the starting character of the title of the book"; + return $return_html; + } + $book_rows = array(); + /*$book_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE book like '%s%%' AND approval_status = 1", $query_character);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('book', '' . $query_character . '%%', 'like'); + $query->condition('approval_status', 1); + $book_q = $query->execute(); + while ($book_data = $book_q->fetchObject()) + { + $book_rows[] = array( + l($book_data->book, 'textbook_run/' . $book_data->id), + $book_data->author + ); + } + if (!$book_rows) + { + $return_html .= "Sorry no books are available with that title"; + } + else + { + $book_header = array( + 'Title of the Book', + 'Author Name' + ); + $return_html .= theme('table', array( + 'headers' => $book_header, + 'rows' => $book_rows + )); + } return $return_html; } - $book_rows = array(); - $book_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE book like '%s%%' AND approval_status = 1", $query_character); - while ($book_data = db_fetch_object($book_q)) +function textbook_companion_browse_author() { - $book_rows[] = array(l($book_data->book, 'textbook_run/' . $book_data->id), $book_data->author); + $return_html = _browse_list('author'); + $return_html .= '<br /><br />'; + $query_character = arg(2); + if (!$query_character) + { + /* all books */ + $return_html .= "Please select the starting character of the author's name"; + return $return_html; + } + $book_rows = array(); + /*$book_q = db_query("SELECT pe.book as book, pe.author as author, pe.publisher as publisher, pe.year as year, pe.id as id FROM {textbook_companion_preference} pe RIGHT JOIN {textbook_companion_proposal} po on pe.proposal_id=po.id WHERE po.proposal_status=3 and pe.approval_status = 1", $query_character);*/ + $query = db_select('textbook_companion_preference', 'pe'); + $query->fields('pe', array( + 'book', + 'author', + 'publisher', + 'year', + 'id' + )); + $query->rightJoin('textbook_companion_proposal', 'po', 'pe.proposal_id = po.id'); + $query->condition('po.proposal_status', 3); + $query->condition('pe.approval_status', 1); + $book_q = $query->execute(); + while ($book_data = $book_q->fetchObject()) + { + /* Initial's fix algorithm */ + preg_match_all("/{$query_character}[a-z]+/", $book_data->author, $matches); + if (count($matches) > 0) + { + /* Remove the word "And"/i from the match array and make match bold */ + if (count($matches[0]) > 0) + { + foreach ($matches[0] as $key => $value) + { + if (strtolower($value) == "and") + { + unset($matches[$key]); + } + else + { + $matches[0][$key] = "<b>" . $value . "</b>"; + $book_data->author = str_replace($value, $matches[0][$key], $book_data->author); + } + } + } + /* Check count of matches after removing And */ + if (count($matches[0]) > 0) + { + $book_rows[] = array( + l($book_data->book, 'textbook_run/' . $book_data->id), + $book_data->author + ); + } + } + } + if (!$book_rows) + { + $return_html .= "Sorry no books are available with that author's name"; + } + else + { + $book_header = array( + 'Title of the Book', + 'Author Name' + ); + $return_html .= theme('table', array( + 'headers' => $book_header, + 'rows' => $book_rows + )); + } + return $return_html; } - if (!$book_rows) +function textbook_companion_browse_student() { - $return_html .= "Sorry no books are available with that title"; - } else { - $book_header = array('Title of the Book', 'Author Name'); - $return_html .= theme_table($book_header, $book_rows); - } - return $return_html; -} - -function textbook_companion_browse_author() -{ - $return_html = _browse_list('author'); - $return_html .= '<br /><br />'; - $query_character = arg(2); - if (!$query_character) { - /* all books */ - $return_html .= "Please select the starting character of the author's name"; + $return_html = _browse_list('student'); + $return_html .= '<br /><br />'; + $query_character = arg(2); + //print $query_character; + //die(); + if (!$query_character) + { + /* all books */ + $return_html .= "Please select the starting character of the student's name"; + return $return_html; + } + $book_rows = array(); + /*$student_q = db_query(" + SELECT po.full_name, pe.book as book, pe.author as author, pe.publisher as publisher, pe.year as year, pe.id as pe_id, po.approval_date as approval_date + FROM textbook_companion_preference pe LEFT JOIN textbook_companion_proposal po ON pe.proposal_id = po.id + WHERE po.proposal_status = 3 AND pe.approval_status = 1 AND full_name LIKE '%s%%' + ", $query_character);*/ + $query = db_select('textbook_companion_preference', 'pe'); + $query->fields('po', array( + 'full_name', + 'approval_date' + )); + $query->fields('pe', array( + 'book', + 'author', + 'publisher', + 'year', + 'id' + )); + $query->leftJoin('textbook_companion_proposal', 'po', 'pe.proposal_id = po.id'); + $query->condition('po.proposal_status', 3); + $query->condition('pe.approval_status', 1); + $query->condition('full_name', '' . $query_character . '%%', 'LIKE'); + $student_q = $query->execute(); + while ($student_data = $student_q->fetchObject()) + { + $book_rows[] = array( + l($student_data->book, 'textbook_run/' . $student_data->pe_id), + $student_data->full_name + ); + } + if (!$book_rows) + { + $return_html .= "Sorry no books are available with that student's name"; + } + else + { + $book_header = array( + 'Title of the Book', + 'Student Name' + ); + $return_html .= theme('table', array( + 'headers' => $book_header, + 'rows' => $book_rows + )); + } return $return_html; } - $book_rows = array(); - $book_q = db_query("SELECT pe.book as book, pe.author as author, pe.publisher as publisher, pe.year as year, pe.id as id FROM {textbook_companion_preference} pe RIGHT JOIN {textbook_companion_proposal} po on pe.proposal_id=po.id WHERE po.proposal_status=3 and pe.approval_status = 1", $query_character); - while ($book_data = db_fetch_object($book_q)) +function _browse_list($type) { - /* Initial's fix algorithm */ - preg_match_all("/{$query_character}[a-z]+/", $book_data->author, $matches); - - if (count($matches) > 0) { - /* Remove the word "And"/i from the match array and make match bold */ - if (count($matches[0]) > 0) { - - foreach ($matches[0] as $key => $value) { - - if (strtolower($value) == "and") { - unset($matches[$key]); - } - else { - $matches[0][$key] = "<b>" . $value . "</b>"; - $book_data->author = str_replace($value, $matches[0][$key], $book_data->author); - } - } - } - - /* Check count of matches after removing And */ - if (count($matches[0]) > 0) { - $book_rows[] = array(l($book_data->book, 'textbook_run/' . $book_data->id), $book_data->author); - } - } + $return_html = ''; + $char_list = array( + 'A', + 'B', + 'C', + 'D', + 'E', + 'F', + 'G', + 'H', + 'I', + 'J', + 'K', + 'L', + 'M', + 'N', + 'O', + 'P', + 'Q', + 'R', + 'S', + 'T', + 'U', + 'V', + 'W', + 'X', + 'Y', + 'Z' + ); + foreach ($char_list as $char_name) + { + $return_html .= l($char_name, 'textbook_search/' . $type . '/' . $char_name); + if ($char_name != 'Z') + $return_html .= ' | '; + } + return '<div id="filter-links">' . $return_html . "</div>"; } - - - if (!$book_rows) +function _list_of_colleges() { - $return_html .= "Sorry no books are available with that author's name"; - } else { - $book_header = array('Title of the Book', 'Author Name'); - $return_html .= theme_table($book_header, $book_rows); - } - return $return_html; -} - -function textbook_companion_browse_student() -{ - $return_html = _browse_list('student'); - $return_html .= '<br /><br />'; - $query_character = arg(2); - //print $query_character; - //die(); - if (!$query_character) { - /* all books */ - $return_html .= "Please select the starting character of the student's name"; - return $return_html; - } - $book_rows = array(); - $student_q = db_query(" - SELECT po.full_name, pe.book as book, pe.author as author, pe.publisher as publisher, pe.year as year, pe.id as pe_id, po.approval_date as approval_date - FROM textbook_companion_preference pe LEFT JOIN textbook_companion_proposal po ON pe.proposal_id = po.id - WHERE po.proposal_status = 3 AND pe.approval_status = 1 AND full_name LIKE '%s%%' - ", $query_character); - while ($student_data = db_fetch_object($student_q)) - { - $book_rows[] = array(l($student_data->book, 'textbook_run/' . $student_data->pe_id), $student_data->full_name); + $college_names = array( + '0' => '--- select ---' + ); + /*$college_names_q = db_query("SELECT DISTINCT university FROM {textbook_companion_proposal} WHERE proposal_status=1 OR proposal_status=3 ORDER BY university ASC");*/ + $query = db_select('textbook_companion_proposal'); + $query = distinct(); + $query->fields('university', array( + '' + )); + $or = db_or(); + $or->condition('proposal_status', 1); + $or->condition('proposal_status', 3); + $query->condition($or); + $query->orderBy('university', 'ASC'); + $college_names_q = $query->execute(); + while ($college_names_data = $college_names_q->fetchObject()) + { + $college_names[$college_names_data->university] = $college_names_data->university; + } + return $college_names; } - if (!$book_rows) +function _list_books_by_college($college) { - $return_html .= "Sorry no books are available with that student's name"; - } else { - $book_header = array('Title of the Book', 'Student Name'); - $return_html .= theme_table($book_header, $book_rows); + /*$query = "SELECT pro.full_name, pro.proposal_status, pre.id as preid, pre.book, pre.isbn FROM textbook_companion_proposal pro, textbook_companion_preference pre WHERE pro.university='".$college."' AND (pro.proposal_status=1 OR pro.proposal_status=3) AND pre.proposal_id=pro.id AND pre.approval_status=1"; + $result = db_query($query);*/ + $query = db_select('textbook_companion_proposal', 'pro'); + $query->fields('pro', array( + 'full_name', + 'proposal_status' + )); + $query->fields('pre', array( + 'id', + 'book', + 'isbn' + )); + $query->condition('pro.university', $college); + $or = db_or(); + $or->condition('pro.proposal_status', 1); + $or->condition('pro.proposal_status', 3); + $query->condition($or); + $query->condition('pre.proposal_id', 'pro.id'); + $query->condition('pre.approval_status', 1); + $result = $query->execute(); + $output = '<table><tr><th>SNO</th><th>Name</th><th>Book</th><th>ISBN</th><th>Status</th></tr>'; + $sno = 1; + while ($row = $result->fetchObject()) + { + if ($row->proposal_status == 1) + { + $output .= '<tr><td>' . $sno++ . '</td><td>' . $row->full_name . '</td><td>' . $row->book . '</td><td>' . str_replace("-", "", $row->isbn) . '</td><td style="color: orange;">Approved</td>'; + } + else + { + $output .= '<tr><td>' . $sno++ . '</td><td>' . $row->full_name . '</td><td><a target="_blank" href="' . base_path() . 'textbook_run/' . $row->preid . '">' . $row->book . '</a></td><td>' . str_replace("-", "", $row->isbn) . '</td><td style="color: green;">Completed</td>'; + } + $output .= '</tr>'; + } + return $output; } - return $return_html; -} - -function _browse_list($type) -{ - $return_html = ''; - $char_list = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'); - foreach ($char_list as $char_name) +function textbook_companion_browse_college_form($form_state) { - $return_html .= l($char_name, 'textbook_search/' . $type . '/' . $char_name); - if ($char_name != 'Z') - $return_html .= ' | '; + $form = array(); + ahah_helper_register($form, $form_state); + if (!isset($form_state['storage']['college_info']['college'])) + { + $usage_default_value = '0'; + } + else + { + $usage_default_value = $form_state['storage']['college_info']['college']; + } + $form['college_info'] = array( + '#type' => 'fieldset', + '#prefix' => '<div id="college-info-wrapper">', + '#suffix' => '</div>', + '#tree' => TRUE + ); + $form['college_info']['college'] = array( + '#type' => 'select', + '#title' => t('College Name'), + '#options' => _list_of_colleges(), + '#default_value' => $usage_default_value, + '#ahah' => array( + 'event' => 'change', + 'path' => ahah_helper_path(array( + 'college_info' + )), + 'wrapper' => 'college-info-wrapper' + ) + ); + if ($usage_default_value != '0') + { + $form['college_info']['book_details'] = array( + '#type' => 'item', + '#value' => _list_books_by_college($usage_default_value) + ); + } + return $form; } - return '<div id="filter-links">' . $return_html . "</div>"; -} -function _list_of_colleges() -{ - $college_names = array('0' => '--- select ---'); - $college_names_q = db_query("SELECT DISTINCT university FROM {textbook_companion_proposal} WHERE proposal_status=1 OR proposal_status=3 ORDER BY university ASC"); - while ($college_names_data = db_fetch_object($college_names_q)) +function textbook_companion_browse_college_form_validate($form, &$form_state) { - $college_names[$college_names_data->university] = $college_names_data->university; - } - return $college_names; -} - -function _list_books_by_college($college) { - $query = "SELECT pro.full_name, pro.proposal_status, pre.id as preid, pre.book, pre.isbn FROM textbook_companion_proposal pro, textbook_companion_preference pre WHERE pro.university='".$college."' AND (pro.proposal_status=1 OR pro.proposal_status=3) AND pre.proposal_id=pro.id AND pre.approval_status=1"; - $result = db_query($query); - $output = '<table><tr><th>SNO</th><th>Name</th><th>Book</th><th>ISBN</th><th>Status</th></tr>'; - $sno = 1; - while($row = db_fetch_object($result)) { - - if($row->proposal_status == 1) { - $output .= '<tr><td>'.$sno++.'</td><td>'.$row->full_name.'</td><td>'.$row->book.'</td><td>'.str_replace("-", "", $row->isbn).'</td><td style="color: orange;">Approved</td>'; - }else { - $output .= '<tr><td>'.$sno++.'</td><td>'.$row->full_name.'</td><td><a target="_blank" href="'.base_path().'textbook_run/'.$row->preid.'">'.$row->book.'</a></td><td>'.str_replace("-", "", $row->isbn).'</td><td style="color: green;">Completed</td>'; - } - $output .= '</tr>'; - } - - return $output; -} - -function textbook_companion_browse_college_form($form_state) { - $form = array(); - - ahah_helper_register($form, $form_state); - - - if (!isset($form_state['storage']['college_info']['college'])) { - $usage_default_value = '0'; } - else { - $usage_default_value = $form_state['storage']['college_info']['college']; - } - - $form['college_info'] = array( - '#type' => 'fieldset', - '#prefix' => '<div id="college-info-wrapper">', - '#suffix' => '</div>', - '#tree' => TRUE, - ); - $form['college_info']['college'] = array( - '#type' => 'select', - '#title' => t('College Name'), - '#options' => _list_of_colleges(), - '#default_value' => $usage_default_value, - '#ahah' => array( - 'event' => 'change', - 'path' => ahah_helper_path(array('college_info')), - 'wrapper' => 'college-info-wrapper', - ), - ); - - - if ($usage_default_value != '0') { - $form['college_info']['book_details'] = array( - '#type' => 'item', - '#value' => _list_books_by_college($usage_default_value) - ); +function textbook_companion_browse_college_form_submit($form, &$form_state) + { } - - return $form; -} - -function textbook_companion_browse_college_form_validate($form, &$form_state) { - -} - -function textbook_companion_browse_college_form_submit($form, &$form_state) { - -} diff --git a/settings.inc b/settings.inc index aa80453..cdacb28 100755 --- a/settings.inc +++ b/settings.inc @@ -1,94 +1,72 @@ <?php // $Id$ - -function textbook_companion_settings_form($form_state) -{ - $form['emails'] = array( - '#type' => 'textfield', - '#title' => t('Notification emails'), - '#description' => t('A comma separated list of email addresses to receive notifications emails'), - '#size' => 50, - '#maxlength' => 255, - '#required' => TRUE, - '#default_value' => variable_get('textbook_companion_emails', ''), - ); - $form['to_emails'] = array( - '#type' => 'textfield', - '#title' => t('Notification emails to all other'), - '#description' => t('A comma separated list of email addresses to receive notifications emails'), - '#size' => 50, - '#maxlength' => 255, - '#required' => TRUE, - '#default_value' => variable_get('textbook_companion_emails_all', ''), - ); - - $form['from_email'] = array( - '#type' => 'textfield', - '#title' => t('Outgoing from email address'), - '#description' => t('Email address to be display in the from field of all outgoing messages'), - '#size' => 50, - '#maxlength' => 255, - '#required' => TRUE, - '#default_value' => variable_get('textbook_companion_from_email', ''), - ); - - $form['extensions']['source'] = array( - '#type' => 'textfield', - '#title' => t('Allowed source file extensions'), - '#description' => t('A comma separated list WITHOUT SPACE of source file extensions that are permitted to be uploaded on the server'), - '#size' => 50, - '#maxlength' => 255, - '#required' => TRUE, - '#default_value' => variable_get('textbook_companion_source_extensions', ''), - ); - $form['extensions']['dependency'] = array( - '#type' => 'textfield', - '#title' => t('Allowed dependency file extensions'), - '#description' => t('A comma separated list WITHOUT SPACE of dependency file extensions that are permitted to be uploaded on the server'), - '#size' => 50, - '#maxlength' => 255, - '#required' => TRUE, - '#default_value' => variable_get('textbook_companion_dependency_extensions', ''), - ); - $form['extensions']['result'] = array( - '#type' => 'textfield', - '#title' => t('Allowed result file extensions'), - '#description' => t('A comma separated list WITHOUT SPACE of result file extensions that are permitted to be uploaded on the server'), - '#size' => 50, - '#maxlength' => 255, - '#required' => TRUE, - '#default_value' => variable_get('textbook_companion_result_extensions', ''), - ); - $form['extensions']['xcos'] = array( - '#type' => 'textfield', - '#title' => t('Allowed xcos file extensions'), - '#description' => t('A comma separated list WITHOUT SPACE of xcos file extensions that are permitted to be uploaded on the server'), - '#size' => 50, - '#maxlength' => 255, - '#required' => TRUE, - '#default_value' => variable_get('textbook_companion_xcos_extensions', ''), - ); - - $form['submit'] = array( - '#type' => 'submit', - '#value' => t('Submit') - ); - return $form; -} - +function textbook_companion_settings_form($form, $form_state) + { + $form['emails'] = array( + '#type' => 'textfield', + '#title' => t('(Bcc) Notification emails'), + '#description' => t('Specify emails id for Bcc option of mail system with comma separated'), + '#size' => 50, + '#maxlength' => 255, + '#required' => TRUE, + '#default_value' => variable_get('textbook_companion_emails', '') + ); + $form['cc_emails'] = array( + '#type' => 'textfield', + '#title' => t('(Cc) Notification emails'), + '#description' => t('Specify emails id for Cc option of mail system with comma separated'), + '#size' => 50, + '#maxlength' => 255, + '#required' => TRUE, + '#default_value' => variable_get('textbook_companion_cc_emails', '') + ); + $form['from_email'] = array( + '#type' => 'textfield', + '#title' => t('Outgoing from email address'), + '#description' => t('Email address to be display in the from field of all outgoing messages'), + '#size' => 50, + '#maxlength' => 255, + '#required' => TRUE, + '#default_value' => variable_get('textbook_companion_from_email', '') + ); + $form['extensions']['source'] = array( + '#type' => 'textfield', + '#title' => t('Allowed source file extensions'), + '#description' => t('A comma separated list WITHOUT SPACE of source file extensions that are permitted to be uploaded on the server'), + '#size' => 50, + '#maxlength' => 255, + '#required' => TRUE, + '#default_value' => variable_get('textbook_companion_source_extensions', '') + ); + $options = array( + '1' => t('1'), + '2' => t('2'), + '3' => t('3') + ); + $form['book_preference_options'] = array( + '#type' => 'radios', + '#title' => t('Book Preferences'), + '#options' => $options, + '#required' => TRUE, + '#description' => t('Set number book preference to be allowed'), + '#default_value' => variable_get('textbook_companion_book_preferences', '') + ); + $form['submit'] = array( + '#type' => 'submit', + '#value' => t('Submit') + ); + return $form; + } function textbook_companion_settings_form_validate($form, &$form_state) -{ - return; -} - + { + return; + } function textbook_companion_settings_form_submit($form, &$form_state) -{ - variable_set('textbook_companion_emails', $form_state['values']['emails']); - variable_set('textbook_companion_emails_all', $form_state['values']['to_emails']); - variable_set('textbook_companion_from_email', $form_state['values']['from_email']); - variable_set('textbook_companion_source_extensions', $form_state['values']['source']); - variable_set('textbook_companion_dependency_extensions', $form_state['values']['dependency']); - variable_set('textbook_companion_result_extensions', $form_state['values']['result']); - variable_set('textbook_companion_xcos_extensions', $form_state['values']['xcos']); - drupal_set_message(t('Settings updated'), 'status'); -} + { + variable_set('textbook_companion_emails', $form_state['values']['emails']); + variable_set('textbook_companion_cc_emails', $form_state['values']['cc_emails']); + variable_set('textbook_companion_from_email', $form_state['values']['from_email']); + variable_set('textbook_companion_source_extensions', $form_state['values']['source']); + variable_set('textbook_companion_book_preferences', $form_state['values']['book_preference_options']); + drupal_set_message(t('Settings updated'), 'status'); + } diff --git a/textbook_companion.info b/textbook_companion.info index 3294d2d..cdc1948 100755 --- a/textbook_companion.info +++ b/textbook_companion.info @@ -1,6 +1,6 @@ name = Textbook Companion description = IIT Bombay Textbook Companion project package = IITB -version = VERSION -core = 6.x -dependencies[] = ahah_helper +version = 7.1 +core = 7.x + diff --git a/textbook_companion.install b/textbook_companion.install index dad05a8..374bd12 100755 --- a/textbook_companion.install +++ b/textbook_companion.install @@ -1,501 +1,512 @@ <?php // $Id$ - /** * Implementation of hook_install(). */ -function textbook_companion_install() { - // Create tables. - drupal_install_schema('textbook_companion'); - variable_set('textbook_companion_emails', ''); - variable_set('textbook_companion_from_email', ''); - variable_set('textbook_companion_source_extensions', ''); - variable_set('textbook_companion_dependency_extensions', ''); - variable_set('textbook_companion_result_extensions', ''); - variable_set('textbook_companion_xcos_extensions', ''); -} - +function textbook_companion_install() + { + // Create tables. + drupal_install_schema('textbook_companion'); + variable_set('textbook_companion_emails', ''); + variable_set('textbook_companion_from_email', ''); + variable_set('textbook_companion_source_extensions', ''); + variable_set('textbook_companion_dependency_extensions', ''); + variable_set('textbook_companion_result_extensions', ''); + variable_set('textbook_companion_xcos_extensions', ''); + } /** * Implementation of hook_uninstall(). */ -function textbook_companion_uninstall() { - // Remove tables. - drupal_uninstall_schema('textbook_companion'); - // Remove variables - variable_del('textbook_companion_emails'); - variable_del('textbook_companion_from_email'); - variable_del('textbook_companion_source_extensions'); - variable_del('textbook_companion_dependency_extensions'); - variable_del('textbook_companion_result_extensions'); - variable_del('textbook_companion_xcos_extensions'); -} - +function textbook_companion_uninstall() + { + // Remove tables. + drupal_uninstall_schema('textbook_companion'); + // Remove variables + variable_del('textbook_companion_emails'); + variable_del('textbook_companion_from_email'); + variable_del('textbook_companion_source_extensions'); + variable_del('textbook_companion_dependency_extensions'); + variable_del('textbook_companion_result_extensions'); + variable_del('textbook_companion_xcos_extensions'); + } /** * Implementation of hook_schema(). */ -function textbook_companion_schema() { - - /* proposal */ - $schema['textbook_companion_proposal'] = array( - 'description' => t('TODO: please describe this table!'), - 'fields' => array( - 'id' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'serial', - 'not null' => TRUE, - ), - 'uid' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'int', - 'not null' => TRUE, - ), - 'approver_uid' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'int', - 'not null' => TRUE, - ), - 'full_name' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'varchar', - 'length' => '50', - 'not null' => TRUE, - ), - 'mobile' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'varchar', - 'length' => '15', - 'not null' => TRUE, - ), - 'how_project' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'varchar', - 'length' => '50', - 'not null' => TRUE, - ), - 'course' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'varchar', - 'length' => '50', - 'not null' => TRUE, - ), - 'branch' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'varchar', - 'length' => '50', - 'not null' => TRUE, - ), - 'university' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'varchar', - 'length' => '100', - 'not null' => TRUE, - ), - 'faculty' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'varchar', - 'length' => '100', - 'not null' => TRUE, - ), - 'reviewer' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'varchar', - 'length' => '100', - 'not null' => TRUE, - ), - 'completion_date' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'int', - 'not null' => TRUE, - ), - 'creation_date' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'int', - 'not null' => TRUE, - ), - 'approval_date' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'int', - 'not null' => TRUE, - ), - 'proposal_status' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'int', - 'not null' => TRUE, - ), - 'message' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'text', - 'size' => 'medium', - 'not null' => TRUE, - ), - ), - 'primary key' => array('id'), - 'unique keys' => array( - 'id' => array('id') - ), - ); - - /* book preference */ - $schema['textbook_companion_preference'] = array( - 'description' => t('TODO: please describe this table!'), - 'fields' => array( - 'id' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'serial', - 'not null' => TRUE, - ), - 'proposal_id' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'int', - 'not null' => TRUE, - ), - 'pref_number' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'int', - 'not null' => TRUE, - ), - 'book' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'varchar', - 'length' => '100', - 'not null' => TRUE, - ), - 'author' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'varchar', - 'length' => '100', - 'not null' => TRUE, - ), - 'isbn' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'varchar', - 'length' => '25', - 'not null' => TRUE, - ), - 'publisher' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'varchar', - 'length' => '50', - 'not null' => TRUE, - ), - 'edition' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'varchar', - 'length' => '2', - 'not null' => TRUE, - ), - 'year' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'int', - 'not null' => TRUE, - ), - 'category' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'int', - 'not null' => TRUE, - ), - 'approval_status' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'int', - 'not null' => TRUE, - ), - ), - 'primary key' => array('id'), - 'unique keys' => array( - 'id' => array('id') - ), - ); - - /* chapter */ - $schema['textbook_companion_chapter'] = array( - 'description' => t('TODO: please describe this table!'), - 'fields' => array( - 'id' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'serial', - 'not null' => TRUE, - ), - 'preference_id' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'int', - 'not null' => TRUE, - ), - 'number' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'int', - 'not null' => TRUE, - ), - 'name' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'varchar', - 'length' => '255', - 'not null' => TRUE, - ), - ), - 'primary key' => array('id'), - ); - - /* examples */ - $schema['textbook_companion_example'] = array( - 'description' => t('TODO: please describe this table!'), - 'fields' => array( - 'id' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'serial', - 'not null' => TRUE, - ), - 'chapter_id' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'int', - 'not null' => TRUE, - ), - 'approver_uid' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'int', - 'not null' => TRUE, - ), - 'number' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'varchar', - 'length' => '10', - 'not null' => TRUE, - ), - 'caption' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'varchar', - 'length' => '255', - 'not null' => TRUE, - ), - 'approval_date' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'int', - 'not null' => TRUE, - ), - 'approval_status' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'int', - 'not null' => TRUE, - ), - 'timestamp' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'int', - 'not null' => TRUE, - ), - ), - 'primary key' => array('id'), - ); - - /* example files */ - $schema['textbook_companion_example_files'] = array( - 'description' => t('TODO: please describe this table!'), - 'fields' => array( - 'id' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'serial', - 'not null' => TRUE, - ), - 'example_id' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'int', - 'not null' => TRUE, - ), - 'filename' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'varchar', - 'length' => '255', - 'not null' => TRUE, - ), - 'filepath' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'varchar', - 'length' => '500', - 'not null' => TRUE, - ), - 'filemime' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'varchar', - 'length' => '255', - 'not null' => TRUE, - ), - 'filesize' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'int', - 'not null' => TRUE, - ), - 'filetype' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'varchar', - 'length' => '1', - 'not null' => TRUE, - ), - 'caption' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'varchar', - 'length' => '100', - 'not null' => TRUE, - ), - 'timestamp' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'int', - 'not null' => TRUE, - ), - ), - 'primary key' => array('id'), - ); - - /* dependency files */ - $schema['textbook_companion_dependency_files'] = array( - 'description' => t('TODO: please describe this table!'), - 'fields' => array( - 'id' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'serial', - 'not null' => TRUE, - ), - 'preference_id' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'int', - 'not null' => TRUE, - ), - 'filename' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'varchar', - 'length' => '255', - 'not null' => TRUE, - ), - 'filepath' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'varchar', - 'length' => '500', - 'not null' => TRUE, - ), - 'filemime' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'varchar', - 'length' => '255', - 'not null' => TRUE, - ), - 'filesize' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'int', - 'not null' => TRUE, - ), - 'caption' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'varchar', - 'length' => '100', - 'not null' => TRUE, - ), - 'description' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'text', - 'size' => 'medium', - 'not null' => TRUE, - ), - 'timestamp' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'int', - 'not null' => TRUE, - ), - ), - 'primary key' => array('id'), - ); - - /* example - dependency files links */ - $schema['textbook_companion_example_dependency'] = array( - 'description' => t('TODO: please describe this table!'), - 'fields' => array( - 'id' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'serial', - 'not null' => TRUE, - ), - 'example_id' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'int', - 'not null' => TRUE, - ), - 'dependency_id' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'int', - 'not null' => TRUE, - ), - 'approval_status' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'int', - 'not null' => TRUE, - ), - 'timestamp' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'int', - 'not null' => TRUE, - ), - ), - 'primary key' => array('id'), - ); - - $schema['textbook_companion_notes'] = array( - 'description' => t('TODO: please describe this table!'), - 'fields' => array( - 'id' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'serial', - 'not null' => TRUE, - ), - 'preference_id' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'int', - 'not null' => TRUE, - ), - 'notes' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'text', - 'size' => 'medium', - 'not null' => TRUE, - ), - ), - 'primary key' => array('id'), - ); - - $schema['textbook_companion_feedback'] = array( - 'description' => t('TODO: please describe this table!'), - 'fields' => array( - 'id' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'serial', - 'not null' => TRUE, - ), - 'example_id' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'int', - 'not null' => TRUE, - ), - 'uid' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'int', - 'not null' => TRUE, - ), - 'feedback' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'text', - 'size' => 'medium', - 'not null' => TRUE, - ), - 'ip_address' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'varchar', - 'length' => '16', - 'not null' => TRUE, - ), - 'timestamp' => array( - 'description' => t('TODO: please describe this field!'), - 'type' => 'int', - 'not null' => TRUE, - ), - ), - 'primary key' => array('id'), - ); - - return $schema; -} - +function textbook_companion_schema() + { + /* proposal */ + $schema['textbook_companion_proposal'] = array( + 'description' => t('TODO: please describe this table!'), + 'fields' => array( + 'id' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'serial', + 'not null' => TRUE + ), + 'uid' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'int', + 'not null' => TRUE + ), + 'approver_uid' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'int', + 'not null' => TRUE + ), + 'full_name' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'varchar', + 'length' => '50', + 'not null' => TRUE + ), + 'mobile' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'varchar', + 'length' => '15', + 'not null' => TRUE + ), + 'how_project' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'varchar', + 'length' => '50', + 'not null' => TRUE + ), + 'course' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'varchar', + 'length' => '50', + 'not null' => TRUE + ), + 'branch' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'varchar', + 'length' => '50', + 'not null' => TRUE + ), + 'university' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'varchar', + 'length' => '100', + 'not null' => TRUE + ), + 'faculty' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'varchar', + 'length' => '100', + 'not null' => TRUE + ), + 'reviewer' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'varchar', + 'length' => '100', + 'not null' => TRUE + ), + 'completion_date' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'int', + 'not null' => TRUE + ), + 'creation_date' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'int', + 'not null' => TRUE + ), + 'approval_date' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'int', + 'not null' => TRUE + ), + 'proposal_status' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'int', + 'not null' => TRUE + ), + 'message' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'text', + 'size' => 'medium', + 'not null' => TRUE + ) + ), + 'primary key' => array( + 'id' + ), + 'unique keys' => array( + 'id' => array( + 'id' + ) + ) + ); + /* book preference */ + $schema['textbook_companion_preference'] = array( + 'description' => t('TODO: please describe this table!'), + 'fields' => array( + 'id' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'serial', + 'not null' => TRUE + ), + 'proposal_id' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'int', + 'not null' => TRUE + ), + 'pref_number' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'int', + 'not null' => TRUE + ), + 'book' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'varchar', + 'length' => '100', + 'not null' => TRUE + ), + 'author' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'varchar', + 'length' => '100', + 'not null' => TRUE + ), + 'isbn' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'varchar', + 'length' => '25', + 'not null' => TRUE + ), + 'publisher' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'varchar', + 'length' => '50', + 'not null' => TRUE + ), + 'edition' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'varchar', + 'length' => '2', + 'not null' => TRUE + ), + 'year' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'int', + 'not null' => TRUE + ), + 'category' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'int', + 'not null' => TRUE + ), + 'approval_status' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'int', + 'not null' => TRUE + ) + ), + 'primary key' => array( + 'id' + ), + 'unique keys' => array( + 'id' => array( + 'id' + ) + ) + ); + /* chapter */ + $schema['textbook_companion_chapter'] = array( + 'description' => t('TODO: please describe this table!'), + 'fields' => array( + 'id' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'serial', + 'not null' => TRUE + ), + 'preference_id' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'int', + 'not null' => TRUE + ), + 'number' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'int', + 'not null' => TRUE + ), + 'name' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'varchar', + 'length' => '255', + 'not null' => TRUE + ) + ), + 'primary key' => array( + 'id' + ) + ); + /* examples */ + $schema['textbook_companion_example'] = array( + 'description' => t('TODO: please describe this table!'), + 'fields' => array( + 'id' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'serial', + 'not null' => TRUE + ), + 'chapter_id' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'int', + 'not null' => TRUE + ), + 'approver_uid' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'int', + 'not null' => TRUE + ), + 'number' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'varchar', + 'length' => '10', + 'not null' => TRUE + ), + 'caption' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'varchar', + 'length' => '255', + 'not null' => TRUE + ), + 'approval_date' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'int', + 'not null' => TRUE + ), + 'approval_status' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'int', + 'not null' => TRUE + ), + 'timestamp' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'int', + 'not null' => TRUE + ) + ), + 'primary key' => array( + 'id' + ) + ); + /* example files */ + $schema['textbook_companion_example_files'] = array( + 'description' => t('TODO: please describe this table!'), + 'fields' => array( + 'id' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'serial', + 'not null' => TRUE + ), + 'example_id' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'int', + 'not null' => TRUE + ), + 'filename' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'varchar', + 'length' => '255', + 'not null' => TRUE + ), + 'filepath' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'varchar', + 'length' => '500', + 'not null' => TRUE + ), + 'filemime' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'varchar', + 'length' => '255', + 'not null' => TRUE + ), + 'filesize' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'int', + 'not null' => TRUE + ), + 'filetype' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'varchar', + 'length' => '1', + 'not null' => TRUE + ), + 'caption' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'varchar', + 'length' => '100', + 'not null' => TRUE + ), + 'timestamp' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'int', + 'not null' => TRUE + ) + ), + 'primary key' => array( + 'id' + ) + ); + /* dependency files */ + $schema['textbook_companion_dependency_files'] = array( + 'description' => t('TODO: please describe this table!'), + 'fields' => array( + 'id' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'serial', + 'not null' => TRUE + ), + 'preference_id' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'int', + 'not null' => TRUE + ), + 'filename' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'varchar', + 'length' => '255', + 'not null' => TRUE + ), + 'filepath' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'varchar', + 'length' => '500', + 'not null' => TRUE + ), + 'filemime' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'varchar', + 'length' => '255', + 'not null' => TRUE + ), + 'filesize' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'int', + 'not null' => TRUE + ), + 'caption' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'varchar', + 'length' => '100', + 'not null' => TRUE + ), + 'description' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'text', + 'size' => 'medium', + 'not null' => TRUE + ), + 'timestamp' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'int', + 'not null' => TRUE + ) + ), + 'primary key' => array( + 'id' + ) + ); + /* example - dependency files links */ + $schema['textbook_companion_example_dependency'] = array( + 'description' => t('TODO: please describe this table!'), + 'fields' => array( + 'id' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'serial', + 'not null' => TRUE + ), + 'example_id' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'int', + 'not null' => TRUE + ), + 'dependency_id' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'int', + 'not null' => TRUE + ), + 'approval_status' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'int', + 'not null' => TRUE + ), + 'timestamp' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'int', + 'not null' => TRUE + ) + ), + 'primary key' => array( + 'id' + ) + ); + $schema['textbook_companion_notes'] = array( + 'description' => t('TODO: please describe this table!'), + 'fields' => array( + 'id' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'serial', + 'not null' => TRUE + ), + 'preference_id' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'int', + 'not null' => TRUE + ), + 'notes' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'text', + 'size' => 'medium', + 'not null' => TRUE + ) + ), + 'primary key' => array( + 'id' + ) + ); + $schema['textbook_companion_feedback'] = array( + 'description' => t('TODO: please describe this table!'), + 'fields' => array( + 'id' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'serial', + 'not null' => TRUE + ), + 'example_id' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'int', + 'not null' => TRUE + ), + 'uid' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'int', + 'not null' => TRUE + ), + 'feedback' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'text', + 'size' => 'medium', + 'not null' => TRUE + ), + 'ip_address' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'varchar', + 'length' => '16', + 'not null' => TRUE + ), + 'timestamp' => array( + 'description' => t('TODO: please describe this field!'), + 'type' => 'int', + 'not null' => TRUE + ) + ), + 'primary key' => array( + 'id' + ) + ); + return $schema; + } diff --git a/textbook_companion.module b/textbook_companion.module index 0a6b051..5a3685c 100755 --- a/textbook_companion.module +++ b/textbook_companion.module @@ -1,67 +1,73 @@ <?php -// $Id$ - /* -* Implementation of hook_menu(). +implementation of hook_menu(). */ - function textbook_companion_menu() { - $items = array(); - - /* users */ - $items['proposal'] = array( - 'title' => 'Book Proposal Form', - 'description' => 'Book Proposal Form.', - 'page callback' => 'textbook_companion_nonaicte_proposal_all', - 'access callback' => 'user_access', - 'access arguments' => array('create book proposal'), - 'type' => MENU_CALLBACK, - ); - /* $items["aicte_proposal"] = array( + $items = array(); + /* users */ + $items['textbook-companion/proposal'] = array( + 'title' => 'Book Proposal Form', + 'description' => 'Book Proposal Form.', + 'page callback' => 'textbook_companion_proposal_all', + 'access callback' => 'user_access', + 'access arguments' => array( + 'create book proposal' + ), + 'type' => MENU_CALLBACK + ); + /*$items["aicte_proposal"] = array( "title" => "AICTE Book Proposal", "description" => "AICTE Book Proposal Form", "page callback" => "textbook_companion_aicte_proposal_all", 'access arguments' => array('create book proposal'), - 'type' => MENU_NORMAL_ITEM, - );*/ - // $items["all_proposal"] = array( - // "title" => "Book Proposal", - // "description" => "Book Proposal Form", - // "page callback" => "textbook_companion_aicte_proposal_all", - // 'access arguments' => array('create book proposal'), - // 'type' => MENU_NORMAL_ITEM, - // ); - /* for reviewers */ - $items['manage_proposal'] = array( - 'title' => 'Manage Book Proposals', - 'description' => 'Manage Book Proposals', - 'page callback' => '_proposal_pending', - 'access callback' => 'user_access', - 'access arguments' => array('approve book proposal'), - 'file' => 'manage_proposal.inc', - ); - $items['manage_proposal/pending'] = array( - 'title' => 'Pending Proposals', - 'description' => 'Pending Proposals Queue', - 'page callback' => '_proposal_pending', - 'access callback' => 'user_access', - 'access arguments' => array('approve book proposal'), - 'type' => MENU_DEFAULT_LOCAL_TASK, - 'weight' => 1, - 'file' => 'manage_proposal.inc', - ); - $items['manage_proposal/all'] = array( - 'title' => 'All Proposals', - 'description' => 'All Proposals', - 'page callback' => '_proposal_all', - 'access callback' => 'user_access', - 'access arguments' => array('approve book proposal'), - 'type' => MENU_LOCAL_TASK, - 'weight' => 2, - 'file' => 'manage_proposal.inc', - ); - $items['manage_proposal/category'] = array( + 'type' => MENU_CALLBACK, + );*/ + $items["textbook-companion/all_proposal"] = array( + "title" => "Book Proposal", + "description" => "Book Proposal Form", + "page callback" => "textbook_companion_aicte_proposal_all", + 'access arguments' => array( + 'create book proposal' + ), + 'type' => MENU_CALLBACK + ); + /* for reviewers */ + $items['textbook-companion/manage-proposal'] = array( + 'title' => 'Manage Book Proposals', + 'description' => 'Manage Book Proposals', + 'page callback' => '_proposal_pending', + 'access callback' => 'user_access', + 'access arguments' => array( + 'approve book proposal' + ), + 'file' => 'manage_proposal.inc' + ); + $items['textbook-companion/manage-proposal/pending'] = array( + 'title' => 'Pending Proposals', + 'description' => 'Pending Proposals Queue', + 'page callback' => '_proposal_pending', + 'access callback' => 'user_access', + 'access arguments' => array( + 'approve book proposal' + ), + 'type' => MENU_DEFAULT_LOCAL_TASK, + 'weight' => 1, + 'file' => 'manage_proposal.inc' + ); + $items['textbook-companion/manage-proposal/all'] = array( + 'title' => 'All Proposals', + 'description' => 'All Proposals', + 'page callback' => '_proposal_all', + 'access callback' => 'user_access', + 'access arguments' => array( + 'approve book proposal' + ), + 'type' => MENU_LOCAL_TASK, + 'weight' => 2, + 'file' => 'manage_proposal.inc' + ); + /*$items['manage_proposal/category'] = array( 'title' => 'Categorize', 'description' => 'Categorize Books', 'page callback' => '_category_all', @@ -70,45 +76,59 @@ function textbook_companion_menu() 'type' => MENU_LOCAL_TASK, 'weight' => 2, 'file' => 'manage_proposal.inc', - ); - $items['manage_proposal/failed'] = array( - 'title' => 'Failed Proposals', - 'description' => 'Failed to submit code', - 'page callback' => '_failed_all', - 'access callback' => 'user_access', - 'access arguments' => array('approve book proposal'), - 'type' => MENU_LOCAL_TASK, - 'weight' => 3, - 'file' => 'manage_proposal.inc', - ); - $items['manage_proposal/approve'] = array( - 'title' => 'Proposal Approval', - 'description' => 'Proposal Approval', - 'page callback' => 'drupal_get_form', - 'page arguments' => array('proposal_approval_form'), - 'access arguments' => array('approve book proposal'), - 'type' => MENU_CALLBACK, - 'file' => 'manage_proposal.inc', - ); - $items['manage_proposal/status'] = array( - 'title' => 'Proposal Status', - 'description' => 'Proposal Status', - 'page callback' => 'drupal_get_form', - 'page arguments' => array('proposal_status_form'), - 'access arguments' => array('approve book proposal'), - 'type' => MENU_CALLBACK, - 'file' => 'manage_proposal.inc', - ); - $items['manage_proposal/edit'] = array( - 'title' => 'Edit Proposal', - 'description' => 'Edit Proposal', - 'page callback' => 'drupal_get_form', - 'page arguments' => array('proposal_edit_form'), - 'access arguments' => array('edit book proposal'), - 'type' => MENU_CALLBACK, - 'file' => 'manage_proposal.inc', - ); - $items['manage_proposal/category/edit'] = array( + );*/ + $items['textbook-companion/manage-proposal/failed'] = array( + 'title' => 'Failed Proposals', + 'description' => 'Failed to submit code', + 'page callback' => '_failed_all', + 'access callback' => 'user_access', + 'access arguments' => array( + 'approve book proposal' + ), + 'type' => MENU_LOCAL_TASK, + 'weight' => 3, + 'file' => 'manage_proposal.inc' + ); + $items['textbook-companion/manage-proposal/approve'] = array( + 'title' => 'Proposal Approval', + 'description' => 'Proposal Approval', + 'page callback' => 'drupal_get_form', + 'page arguments' => array( + 'proposal_approval_form' + ), + 'access arguments' => array( + 'approve book proposal' + ), + 'type' => MENU_CALLBACK, + 'file' => 'manage_proposal.inc' + ); + $items['textbook-companion/manage-proposal/status'] = array( + 'title' => 'Proposal Status', + 'description' => 'Proposal Status', + 'page callback' => 'drupal_get_form', + 'page arguments' => array( + 'proposal_status_form' + ), + 'access arguments' => array( + 'approve book proposal' + ), + 'type' => MENU_CALLBACK, + 'file' => 'manage_proposal.inc' + ); + $items['textbook-companion/manage-proposal/edit'] = array( + 'title' => 'Edit Proposal', + 'description' => 'Edit Proposal', + 'page callback' => 'drupal_get_form', + 'page arguments' => array( + 'proposal_edit_form' + ), + 'access arguments' => array( + 'edit book proposal' + ), + 'type' => MENU_CALLBACK, + 'file' => 'manage_proposal.inc' + ); + /*$items['manage_proposal/category/edit'] = array( 'title' => 'Edit Category', 'description' => 'Edit category', 'page callback' => 'drupal_get_form', @@ -116,543 +136,893 @@ function textbook_companion_menu() 'access arguments' => array('edit book proposal'), 'type' => MENU_CALLBACK, 'file' => 'manage_proposal.inc', - ); - - $items['code_approval'] = array( - 'title' => 'Manage Code Approval', - 'description' => 'Manage Code Approval', - 'page callback' => 'code_approval', - 'access arguments' => array('approve code'), - 'type' => MENU_NORMAL_ITEM, - 'file' => 'code_approval.inc', - ); - $items['code_approval/approve'] = array( - 'title' => 'Code Approval', - 'description' => 'Code Approval', + );*/ + $items['textbook-companion/code-approval'] = array( + 'title' => 'Manage Code Approval', + 'description' => 'Manage Code Approval', + 'page callback' => 'code_approval', + 'access arguments' => array( + 'approve code' + ), + 'type' => MENU_NORMAL_ITEM, + 'file' => 'code_approval.inc' + ); + $items['textbook-companion/code-approval/approve'] = array( + 'title' => 'Code Approval', + 'description' => 'Code Approval', + 'page callback' => 'drupal_get_form', + 'page arguments' => array( + 'code_approval_form' + ), + 'access arguments' => array( + 'approve code' + ), + 'type' => MENU_DEFAULT_LOCAL_TASK, + 'weight' => 1, + 'file' => 'code_approval.inc' + ); + $items['textbook-companion/code-approval/bulk'] = array( + 'title' => 'Bulk Manage', + 'description' => 'Bulk Mangage', + 'page callback' => 'drupal_get_form', + 'page arguments' => array( + 'bulk_approval_form' + ), + 'access arguments' => array( + 'bulk manage code' + ), + 'type' => MENU_LOCAL_TASK, + 'weight' => 2, + 'file' => 'code_approval.inc' + ); + /* $items['textbook-companion/code-approval/edit-code-submission'] = array( + 'title' => 'Edit Code Submission', + 'description' => 'Enable users code submission interface', + // 'page callback' => 'drupal_get_form', + 'page callback' => 'edit_code_submission', + // 'page arguments' => array( + // 'edit_code_submission_form' + // ), + 'access arguments' => array( + 'bulk manage code' + ), + 'type' => MENU_LOCAL_TASK, + 'weight' => 3, + 'file' => 'code_approval.inc' + );*/ + $items['textbook-companion/code-approval/edit-code-submission/edit'] = array( + 'title' => 'Edit Code Submission', + 'description' => 'Enable users code submission interface', + 'page callback' => 'drupal_get_form', + 'page arguments' => array( + 'edit_code_submission_form' + ), + 'access arguments' => array( + 'bulk manage code' + ), + 'file' => 'code_approval.inc' + ); + $items['textbook-companion/code-approval/editcode'] = array( + 'title' => 'Admin Edit Example', + 'description' => 'Admin Edit Example', + 'page callback' => 'drupal_get_form', + 'page arguments' => array( + 'upload_examples_admin_edit_form' + ), + 'access arguments' => array( + 'approve code' + ), + 'type' => MENU_CALLBACK, + 'weight' => 3, + 'file' => 'editcodeadmin.inc' + ); + $items['textbook-companion/code-approval/notes'] = array( + 'title' => 'Notes for Reviewers', + 'description' => 'Notes for Reviewers', + 'page callback' => 'drupal_get_form', + 'page arguments' => array( + 'book_notes_form' + ), + 'access arguments' => array( + 'bulk manage code' + ), + 'type' => MENU_CALLBACK, + 'weight' => 4, + 'file' => 'notes.inc' + ); + /* $items['code_approval/dependency'] = array( + 'title' => 'Dependency', + 'description' => 'Dependency', 'page callback' => 'drupal_get_form', - 'page arguments' => array('code_approval_form'), - 'access arguments' => array('approve code'), + 'page arguments' => array('textbook_companion_dependency_approval_form'), + 'access arguments' => array('bulk manage code'), 'type' => MENU_LOCAL_TASK, - 'weight' => 1, - 'file' => 'code_approval.inc', - ); - // $items['code_approval/bulk'] = array( - // 'title' => 'Bulk Manage', - // 'description' => 'Bulk Mangage', - // 'page callback' => 'drupal_get_form', - // 'page arguments' => array('bulk_approval_form'), - // 'access arguments' => array('bulk manage code'), - // 'type' => MENU_LOCAL_TASK, - // 'weight' => 2, - // 'file' => 'code_approval.inc', - // ); - - $items['code_approval/ajax'] = array( - 'title' => 'Ajax', - 'description' => 'Ajax', - 'page callback' => 'textbook_companion_bulk_manage_ajax', - 'access arguments' => array('access content'), - 'type' => MENU_CALLBACK, - 'file' => 'code_approval.inc', - ); - $items['code_approval/editcode'] = array( - 'title' => 'Admin Edit Example', - 'description' => 'Admin Edit Example', - 'page callback' => 'drupal_get_form', - 'page arguments' => array('upload_examples_admin_edit_form'), - 'access arguments' => array('approve code'), - 'type' => MENU_CALLBACK, 'weight' => 3, - 'file' => 'editcodeadmin.inc', - ); - $items['code_approval/notes'] = array( - 'title' => 'Notes for Reviewers', - 'description' => 'Notes for Reviewers', + 'file' => 'dependency_approval.inc', + );*/ + $items['textbook-companion/code'] = array( + 'title' => 'Code Submission', + 'description' => 'Code Submission', + 'page callback' => 'list_chapters', + 'access callback' => 'user_access', + 'access arguments' => array( + 'upload code' + ), + 'file' => 'general.inc' + ); + $items['textbook-companion/code/list_chapters'] = array( + 'title' => 'List Chapters', + 'description' => 'List Chapters', + 'page callback' => 'list_chapters', + 'access arguments' => array( + 'upload code' + ), + 'type' => MENU_DEFAULT_LOCAL_TASK, + 'file' => 'general.inc', + 'weight' => 1 + ); + $items['textbook-companion/code/upload'] = array( + 'title' => 'Code Submission', + 'description' => 'Code Submission', + 'page callback' => 'upload_examples', + 'access arguments' => array( + 'upload code' + ), + 'type' => MENU_LOCAL_TASK, + 'file' => 'code.inc', + 'weight' => 2 + ); + /* $items['textbook_companion/code/upload_dep'] = array( + 'title' => 'Upload Dependency', + 'description' => 'Upload Dependency Files', 'page callback' => 'drupal_get_form', - 'page arguments' => array('book_notes_form'), - 'access arguments' => array('bulk manage code'), - 'type' => MENU_CALLBACK, - 'weight' => 4, - 'file' => 'notes.inc', - ); - // $items['code_approval/dependency'] = array( - // 'title' => 'Dependency', - // 'description' => 'Dependency', - // 'page callback' => 'drupal_get_form', - // 'page arguments' => array('textbook_companion_dependency_approval_form'), - // 'access arguments' => array('bulk manage code'), - // 'type' => MENU_LOCAL_TASK, - // 'weight' => 2, - // 'file' => 'dependency_approval.inc', - // ); - $items['textbook_companion/code'] = array( - 'title' => 'Code Submission', - 'description' => 'Code Submission', - 'page callback' => 'list_chapters', - 'access callback' => 'user_access', - 'access arguments' => array('upload code'), - 'file' => 'general.inc', - ); - $items['textbook_companion/code/list_chapters'] = array( - 'title' => 'List Chapters', - 'description' => 'List Chapters', - 'page callback' => 'list_chapters', - 'access arguments' => array('upload code'), - 'type' => MENU_DEFAULT_LOCAL_TASK, - 'file' => 'general.inc', - 'weight' => 1, - ); - $items['textbook_companion/code/upload'] = array( - 'title' => 'Code Submission', - 'description' => 'Code Submission', - 'page callback' => 'upload_examples', + 'page arguments' => array('upload_dependency_form'), 'access arguments' => array('upload code'), 'type' => MENU_LOCAL_TASK, - 'file' => 'code.inc', - 'weight' => 2, - ); - // $items['textbook_companion/code/upload_dep'] = array( - // 'title' => 'Upload Dependency', - // 'description' => 'Upload Dependency Files', - // 'page callback' => 'drupal_get_form', - // 'page arguments' => array('upload_dependency_form'), - // 'access arguments' => array('upload code'), - // 'type' => MENU_LOCAL_TASK, - // 'file' => 'dependency.inc', - // 'weight' => 3, - // ); - $items['textbook_companion/code/edit_dep'] = array( + 'file' => 'dependency.inc', + 'weight' => 3, + ); + $items['textbook_companion/code/edit_dep'] = array( 'title' => 'Edit Dependency', 'description' => 'Edit Dependency File', 'page callback' => 'edit_dependency', 'access arguments' => array('upload code'), 'type' => MENU_CALLBACK, 'file' => 'dependency.inc', - ); - $items['textbook_companion/code/delete_dep'] = array( + ); + $items['textbook_companion/code/delete_dep'] = array( 'title' => 'Delete Dependency', 'description' => 'Delete Dependency File', 'page callback' => 'delete_dependency', 'access arguments' => array('upload code'), 'type' => MENU_CALLBACK, 'file' => 'dependency.inc', - ); - $items['textbook_companion/code/edit'] = array( - 'title' => 'Edit Example', - 'description' => 'Edit Example', - 'page callback' => 'drupal_get_form', - 'page arguments' => array('upload_examples_edit_form'), - 'access arguments' => array('edit uploaded code'), - 'type' => MENU_CALLBACK, - 'file' => 'editcode.inc', - ); - $items['textbook_companion/code/delete'] = array( - 'title' => 'Delete Example', - 'description' => 'Delete Example', - 'page callback' => '_upload_examples_delete', - 'access arguments' => array('upload code'), - 'type' => MENU_CALLBACK, - 'file' => 'code.inc', - ); - $items['textbook_companion/code/chapter/edit'] = array( - 'title' => 'Edit Chapter Title', - 'description' => 'Edit Chapter Title', - 'page callback' => 'drupal_get_form', - 'page arguments' => array('edit_chapter_title_form'), - 'access arguments' => array('upload code'), - 'type' => MENU_CALLBACK, - 'file' => 'editcode.inc', - ); - $items['textbook_companion/code/list_examples'] = array( - 'title' => 'List Examples', - 'description' => 'List Examples', - 'page callback' => 'list_examples', - 'access arguments' => array('upload code'), - 'type' => MENU_CALLBACK, - 'file' => 'general.inc', - 'weight' => 3, - ); - $items['textbook_search'] = array( - 'title' => 'Book Search', - 'description' => '', - 'page callback' => 'drupal_get_form', - 'page arguments' => array('textbook_companion_search_form'), - 'access arguments' => array('access content'), - 'type' => MENU_NORMAL_ITEM, - 'file' => 'search.inc', - ); - $items['textbook_search/search'] = array( - 'title' => 'Book Search', - 'description' => '', - 'page callback' => 'drupal_get_form', - 'page arguments' => array('textbook_companion_search_form'), - 'access arguments' => array('access content'), - 'type' => MENU_DEFAULT_LOCAL_TASK, - 'file' => 'search.inc', - 'weight' => 1, - ); - $items['textbook_search/book'] = array( - 'title' => 'By Book Title', - 'description' => '', - 'page callback' => 'textbook_companion_browse_book', - 'access arguments' => array('access content'), - 'type' => MENU_LOCAL_TASK, - 'file' => 'search.inc', - 'weight' => 2, - ); - $items['textbook_search/author'] = array( - 'title' => 'By Author', - 'description' => '', - 'page callback' => 'textbook_companion_browse_author', - 'access arguments' => array('access content'), - 'type' => MENU_LOCAL_TASK, - 'file' => 'search.inc', - 'weight' => 3, - ); - $items['textbook_search/college'] = array( - 'title' => 'By College', - 'description' => '', - 'page callback' => 'textbook_companion_browse_college', - 'page callback' => 'drupal_get_form', - 'page arguments' => array('textbook_companion_browse_college_form'), - 'access arguments' => array('access content'), - 'type' => MENU_LOCAL_TASK, - 'file' => 'search.inc', - 'weight' => 4, - ); - $items['textbook_search/student'] = array( - 'title' => 'By Student', - 'description' => '', - 'page callback' => 'textbook_companion_browse_student', - 'access arguments' => array('access content'), - 'type' => MENU_LOCAL_TASK, - 'file' => 'search.inc', - 'weight' => 5, - ); - $items['textbook_run'] = array( + );*/ + $items['textbook-companion/code/edit'] = array( + 'title' => 'Edit Example', + 'description' => 'Edit Example', + 'page callback' => 'drupal_get_form', + 'page arguments' => array( + 'upload_examples_edit_form' + ), + 'access arguments' => array( + 'edit uploaded code' + ), + 'type' => MENU_CALLBACK, + 'file' => 'editcode.inc' + ); + $items['textbook-companion/code/delete'] = array( + 'title' => 'Delete Example', + 'description' => 'Delete Example', + 'page callback' => '_upload_examples_delete', + 'access arguments' => array( + 'upload code' + ), + 'type' => MENU_CALLBACK, + 'file' => 'code.inc' + ); + $items['textbook-companion/code/chapter/edit'] = array( + 'title' => 'Edit Chapter Title', + 'description' => 'Edit Chapter Title', + 'page callback' => 'drupal_get_form', + 'page arguments' => array( + 'edit_chapter_title_form' + ), + 'access arguments' => array( + 'upload code' + ), + 'type' => MENU_CALLBACK, + 'file' => 'editcode.inc' + ); + $items['textbook-companion/code/list-examples'] = array( + 'title' => 'List Examples', + 'description' => 'List Examples', + 'page callback' => 'list_examples', + 'access arguments' => array( + 'upload code' + ), + 'type' => MENU_CALLBACK, + 'file' => 'general.inc', + 'weight' => 3 + ); + $items['textbook-companion/textbook-search'] = array( + 'title' => 'Book Search', + 'description' => '', + 'page callback' => 'drupal_get_form', + 'page arguments' => array( + 'textbook_companion_search_form' + ), + 'access arguments' => array( + 'access content' + ), + 'type' => MENU_NORMAL_ITEM, + 'file' => 'search.inc' + ); + $items['textbook-companion/textbook-search/search'] = array( + 'title' => 'Book Search', + 'description' => '', + 'page callback' => 'drupal_get_form', + 'page arguments' => array( + 'textbook_companion_search_form' + ), + 'access arguments' => array( + 'access content' + ), + 'type' => MENU_DEFAULT_LOCAL_TASK, + 'file' => 'search.inc', + 'weight' => 1 + ); + $items['textbook-companion/textbook-search/book'] = array( + 'title' => 'By Book Title', + 'description' => '', + 'page callback' => 'textbook_companion_browse_book', + 'access arguments' => array( + 'access content' + ), + 'type' => MENU_LOCAL_TASK, + 'file' => 'search.inc', + 'weight' => 2 + ); + $items['textbook-companion/textbook-search/author'] = array( + 'title' => 'By Author', + 'description' => '', + 'page callback' => 'textbook_companion_browse_author', + 'access arguments' => array( + 'access content' + ), + 'type' => MENU_LOCAL_TASK, + 'file' => 'search.inc', + 'weight' => 3 + ); + $items['textbook-companion/textbook-search/college'] = array( + 'title' => 'By College', + 'description' => '', + 'page callback' => 'textbook_companion_browse_college', + 'page callback' => 'drupal_get_form', + 'page arguments' => array( + 'textbook_companion_browse_college_form' + ), + 'access arguments' => array( + 'access content' + ), + 'type' => MENU_LOCAL_TASK, + 'file' => 'search.inc', + 'weight' => 4 + ); + $items['textbook-companion/textbook-search/student'] = array( + 'title' => 'By Student', + 'description' => '', + 'page callback' => 'textbook_companion_browse_student', + 'access arguments' => array( + 'access content' + ), + 'type' => MENU_LOCAL_TASK, + 'file' => 'search.inc', + 'weight' => 5 + ); + /* $items['textbook_run'] = array( 'title' => 'Download Codes', 'page callback' => 'drupal_get_form', - 'page arguments' => array('textbook_companion_run_form'), + 'page arguments' => array('textbook_companion_run_form_ajax'), 'access arguments' => array('access content'), 'type' => MENU_NORMAL_ITEM, 'file' => 'run.inc', - ); - $items['download_codes'] = array( + );*/ + $items['textbook-companion/textbook-run'] = array( + 'title' => 'Download Codes', + 'page callback' => 'drupal_get_form', + 'page arguments' => array( + 'textbook_companion_run_form' + ), + 'access arguments' => array( + 'access content' + ), + 'type' => MENU_NORMAL_ITEM, + 'file' => 'run.inc' + ); + /*$items['textbook_run_ajax'] = array( + 'page callback' => 'textbook_run_ajax', + 'access callback' => TRUE, + 'file' => 'run.inc', + );*/ + /*$items['download_codes'] = array( 'title' => 'Download Codes', 'page callback' => 'drupal_get_form', - 'page arguments' => array('textbook_companion_run_form'), + 'page arguments' => array('textbook_companion_run_form_ajax'), 'access arguments' => array('access content'), 'type' => MENU_NORMAL_ITEM, 'file' => 'run.inc', - ); - /* download callbacks */ - $items['download/file'] = array( - 'title' => 'Code Download', - 'description' => 'Code Download', - 'page callback' => 'textbook_companion_download_example_file', - 'access arguments' => array('download code'), - 'type' => MENU_CALLBACK, - 'file' => 'download.inc', - ); - $items['download/dependency'] = array( + );*/ + $items['textbook-companion/download-codes'] = array( + 'title' => 'Download Codes', + 'page callback' => 'drupal_get_form', + 'page arguments' => array( + 'textbook_companion_run_form' + ), + 'access arguments' => array( + 'access content' + ), + 'type' => MENU_NORMAL_ITEM, + 'file' => 'run.inc' + ); + /* download callbacks */ + $items['textbook-companion/download/file'] = array( + 'title' => 'Code Download', + 'description' => 'Code Download', + 'page callback' => 'textbook_companion_download_example_file', + 'access arguments' => array( + 'download code' + ), + 'type' => MENU_CALLBACK, + 'file' => 'download.inc' + ); + $items['textbook-companion/download/samplecode'] = array( + 'title' => 'Sample Code Download', + 'description' => 'Sample Code Download', + 'page callback' => 'textbook_companion_download_sample_code', + 'access arguments' => array( + 'download code' + ), + 'type' => MENU_CALLBACK, + 'file' => 'download.inc' + ); + /* $items['download/dependency'] = array( 'title' => 'Code Download', 'description' => 'Code Download', 'page callback' => 'textbook_companion_download_dependency_file', 'access arguments' => array('download code'), 'type' => MENU_CALLBACK, 'file' => 'download.inc', - ); - $items['download/example'] = array( - 'title' => 'Code Download', - 'description' => 'Code Download', - 'page callback' => 'textbook_companion_download_example', - 'access arguments' => array('download code'), - 'type' => MENU_CALLBACK, - 'file' => 'download.inc', - ); - $items['download/chapter'] = array( - 'title' => 'Code Download', - 'description' => 'Code Download', - 'page callback' => 'textbook_companion_download_chapter', - 'access arguments' => array('download code'), - 'type' => MENU_CALLBACK, - 'file' => 'download.inc', - ); - $items['download/book'] = array( - 'title' => 'Code Download', - 'description' => 'Code Download', - 'page callback' => 'textbook_companion_download_book', - 'access arguments' => array('download code'), - 'type' => MENU_CALLBACK, - 'file' => 'download.inc', - ); - /* reviewer download */ - $items['full_download/chapter'] = array( - 'title' => 'Code Download', - 'description' => 'Code Download', - 'page callback' => 'textbook_companion_download_full_chapter', - 'access arguments' => array('download code'), - 'type' => MENU_CALLBACK, - 'file' => 'full_download.inc', - ); - $items['full_download/book'] = array( - 'title' => 'Code Download', - 'description' => 'Code Download', - 'page callback' => 'textbook_companion_download_full_book', - 'access arguments' => array('download code'), - 'type' => MENU_CALLBACK, - 'file' => 'full_download.inc', - ); - - /* external reviewer download */ - $items['full_download_external/chapter'] = array( - 'title' => 'Code Download', - 'description' => 'Code Download', - 'page callback' => 'textbook_companion_download_full_chapter', - 'access arguments' => array('download books to review'), - 'type' => MENU_CALLBACK, - 'file' => 'full_download.inc', - ); - $items['full_download_external/book'] = array( - 'title' => 'Code Download', - 'description' => 'Code Download', - 'page callback' => 'textbook_companion_download_full_book', - 'access arguments' => array('download books to review'), - 'type' => MENU_CALLBACK, - 'file' => 'full_download.inc', - ); - - /* latex script for book generation */ - $items['textbook_companion/generate_book'] = array( - 'title' => 'Generate Book', - 'description' => 'Generate Book From Latex Script', - 'page callback' => 'textbook_companion_download_book', - 'access arguments' => array('generate book'), - 'type' => MENU_CALLBACK, - 'file' => 'latex.inc', - ); - $items['textbook_companion/delete_book'] = array( - 'title' => 'Delete Book PDF', - 'description' => 'Delete Book PDF', - 'page callback' => 'textbook_companion_delete_book', - 'access arguments' => array('approve code'), - 'type' => MENU_CALLBACK, - 'file' => 'latex.inc', - ); - - /* general purpose callbacks */ - $items['textbook_companion/ajax'] = array( - 'title' => 'Ajax', - 'description' => 'Ajax', - 'page callback' => 'textbook_companion_ajax', - 'access arguments' => array('access content'), - 'type' => MENU_CALLBACK, - ); - - /* for admin */ - $items['admin/settings/book_companion'] = array( - 'title' => 'Book Companion Settings', - 'description' => 'Book Companion Settings', - 'page callback' => 'drupal_get_form', - 'page arguments' => array('textbook_companion_settings_form'), - 'access arguments' => array('administer book companion'), - 'type' => MENU_NORMAL_ITEM, - 'file' => 'settings.inc', - ); - /* for data entry */ - $items['dataentry_book'] = array( - 'title' => 'Approved books list', - 'page callback' => '_data_entry_proposal_all', - 'access callback' => 'user_access', - 'access arguments' => array('dataentry book proposal'), - 'file' => 'manage_proposal.inc', - ); - $items['dataentry_edit'] = array( - 'title' => 'Edit book details', - 'page callback' => 'dataentry_edit', - 'access callback' => 'user_access', - 'access arguments' => array('dataentry book proposal'), - 'type' => MENU_NORMAL_ITEM, - 'file' => 'manage_proposal.inc', - ); - /*Cheque Details and Contact Form */ - $items['cheque_manage/all'] = array( - 'title' => 'Cheque Proposals', - 'description' => 'Cheque Proposals', - 'page callback' => 'cheque_proposal_all', - 'access arguments' => array('cheque proposal'), - 'file' => 'cheque_manage.inc', - ); - $items['mycontact'] = array( - 'title' => 'Update Contact Details', - 'description' => 'Update Contact Details', - 'page callback' => 'drupal_get_form', - 'page arguments' => array('contact_details'), - 'access arguments' => array('contact_details'), - 'file' => 'cheque_contact.inc', - ); - - $items['cheque_contct'] = array( - 'title' => 'Report', - 'description' => 'Cheque Contact Form', - 'page callback' => 'drupal_get_form', - 'page arguments' => array('cheque_contct_form'), - 'access arguments' => array('cheque contct form'), - 'file' => 'cheque_contact.inc', - ); - $items['cheque_contact/status'] = array( - 'title' => 'Cheque Status', - 'description' => 'Cheque Status', - 'page callback' => 'drupal_get_form', - 'page arguments' => array('cheque_status_form'), - 'access' => 'user_is_logged_in', - 'access arguments' => array('cheque status form'), - 'file' => 'cheque_contact.inc', - ); - $items['cheque_contct/report'] = array( - 'title' => 'Report', - 'description' => 'Report', - 'page callback' => 'drupal_get_form', - 'page arguments' => array('cheque_report_form'), - 'access' => 'user_is_logged_in', - 'access arguments' => array('cheque report form'), - 'file' => 'cheque_contact.inc', - ); - // $items['certificate'] = array( - // 'title' => 'List Of All Certificates', - // 'description' => 'List Of All Certificates', - // 'page callback' => '_list_all_certificates', - // 'access arguments' => array('list all certificates'), - // 'file' => 'pdf/list_all_certificates.inc', - // ); - // $items['certificate/generate_pdf'] = array( - // 'title' => 'Download Certificate', - // 'description' => 'Download Certificate', - // 'page callback' => 'drupal_get_form', - // 'page arguments' => array('generate_pdf'), - // 'access arguments' => array('generate pdf'), - // 'file' => 'pdf/generate_pdf.inc', - // ); - $items['manage_proposal/paper_submission'] = array( - 'title' => 'Application Submission', - 'description' => 'Application Submission', - 'page callback' => 'drupal_get_form', - 'page arguments' => array('paper_submission_form'), - 'access arguments' => array('paper submission form'), - 'type' => MENU_CALLBACK, - 'file' => 'cheque_contact.inc', - ); - // $items["nonaicte_proposal"] = array( - // "title" => "Book Suggestion Form ", - // "description" => "NON-AICTE Book Proposal Form", - // 'page callback' => 'textbook_companion_nonaicte_proposal_all', - // 'access arguments' => array('create book proposal'), - // 'type' => MENU_NORMAL_ITEM, - // ); - return $items; + );*/ + $items['textbook-companion/download/example'] = array( + 'title' => 'Code Download', + 'description' => 'Code Download', + 'page callback' => 'textbook_companion_download_example', + 'access arguments' => array( + 'download code' + ), + 'type' => MENU_CALLBACK, + 'file' => 'download.inc' + ); + $items['textbook-companion/download/chapter'] = array( + 'title' => 'Code Download', + 'description' => 'Code Download', + 'page callback' => 'textbook_companion_download_chapter', + 'access arguments' => array( + 'download code' + ), + 'type' => MENU_CALLBACK, + 'file' => 'download.inc' + ); + $items['textbook-companion/download/book'] = array( + 'title' => 'Code Download', + 'description' => 'Code Download', + 'page callback' => 'textbook_companion_download_book', + 'access arguments' => array( + 'download code' + ), + 'type' => MENU_CALLBACK, + 'file' => 'download.inc' + ); + /* reviewer download */ + $items['textbook-companion/full-download/chapter'] = array( + 'title' => 'Code Download', + 'description' => 'Code Download', + 'page callback' => 'textbook_companion_download_full_chapter', + 'access arguments' => array( + 'approve code' + ), + 'type' => MENU_CALLBACK, + 'file' => 'full_download.inc' + ); + $items['textbook-companion/full-download/book'] = array( + 'title' => 'Code Download', + 'description' => 'Code Download', + 'page callback' => 'textbook_companion_download_full_book', + 'access arguments' => array( + 'approve code' + ), + 'type' => MENU_CALLBACK, + 'file' => 'full_download.inc' + ); + /* external reviewer download */ + $items['textbook-companion/full-download-external/chapter'] = array( + 'title' => 'Code Download', + 'description' => 'Code Download', + 'page callback' => 'textbook_companion_download_full_chapter', + 'access arguments' => array( + 'download books to review' + ), + 'type' => MENU_CALLBACK, + 'file' => 'full_download.inc' + ); + $items['textbook-companion/full-download-external/book'] = array( + 'title' => 'Code Download', + 'description' => 'Code Download', + 'page callback' => 'textbook_companion_download_full_book', + 'access arguments' => array( + 'download books to review' + ), + 'type' => MENU_CALLBACK, + 'file' => 'full_download.inc' + ); + /* latex script for book generation */ + $items['textbook-companion/generate-book'] = array( + 'title' => 'Generate Book', + 'description' => 'Generate Book From Latex Script', + 'page callback' => 'textbook_companion_download_book', + 'access arguments' => array( + 'generate book' + ), + 'type' => MENU_CALLBACK, + 'file' => 'latex.inc' + ); + $items['textbook-companion/delete-book'] = array( + 'title' => 'Delete Book PDF', + 'description' => 'Delete Book PDF', + 'page callback' => 'textbook_companion_delete_book', + 'access arguments' => array( + 'approve code' + ), + 'type' => MENU_CALLBACK, + 'file' => 'latex.inc' + ); + /* general purpose callbacks */ + $items['textbook-companion/ajax'] = array( + 'title' => 'Ajax', + 'description' => 'Ajax', + 'page callback' => 'textbook_companion_ajax', + 'access arguments' => array( + 'access content' + ), + 'type' => MENU_CALLBACK + ); + /* for admin */ + $items['admin/settings/book_companion'] = array( + 'title' => 'Book Companion Settings', + 'description' => 'Textbook Companion Settings', + 'page callback' => 'drupal_get_form', + 'page arguments' => array( + 'textbook_companion_settings_form' + ), + 'access arguments' => array( + 'administer book companion' + ), + 'type' => MENU_NORMAL_ITEM, + 'file' => 'settings.inc' + ); + /* for data entry */ + $items['textbook-companion/dataentry-book'] = array( + 'title' => 'Approved books list', + 'page callback' => '_data_entry_proposal_all', + 'access callback' => 'user_access', + 'access arguments' => array( + 'dataentry book proposal' + ), + 'file' => 'manage_proposal.inc' + ); + $items['textbook-companion/dataentry-edit'] = array( + 'title' => 'Edit book details', + 'page callback' => 'dataentry_edit', + 'access callback' => 'user_access', + 'access arguments' => array( + 'dataentry book proposal' + ), + 'type' => MENU_NORMAL_ITEM, + 'file' => 'manage_proposal.inc' + ); + /*Cheque Details and Contact Form */ + $items['textbook-companion/cheque-manage/all'] = array( + 'title' => 'Cheque Proposals', + 'description' => 'Cheque Proposals', + 'page callback' => 'cheque_proposal_all', + 'access arguments' => array( + 'cheque proposal' + ), + 'file' => 'cheque_manage.inc' + ); + $items['textbook-companion/mycontact'] = array( + 'title' => 'Update Contact Details', + 'description' => 'Update Contact Details', + 'page callback' => 'drupal_get_form', + 'page arguments' => array( + 'contact_details' + ), + 'access arguments' => array( + 'contact_details' + ), + 'file' => 'cheque_contact.inc' + ); + $items['textbook-companion/cheque-contct'] = array( + 'title' => 'Report', + 'description' => 'Cheque Contact Form', + 'page callback' => 'drupal_get_form', + 'page arguments' => array( + 'cheque_contct_form' + ), + 'access arguments' => array( + 'cheque contct form' + ), + 'file' => 'cheque_contact.inc' + ); + $items['textbook-companion/cheque-contact/status'] = array( + 'title' => 'Cheque Status', + 'description' => 'Cheque Status', + 'page callback' => 'drupal_get_form', + 'page arguments' => array( + 'cheque_status_form' + ), + 'access' => 'user_is_logged_in', + 'access arguments' => array( + 'cheque status form' + ), + 'file' => 'cheque_contact.inc' + ); + $items['textbook-companion/cheque-contct/report'] = array( + 'title' => 'Report', + 'description' => 'Report', + 'page callback' => 'drupal_get_form', + 'page arguments' => array( + 'cheque_report_form' + ), + 'access' => 'user_is_logged_in', + 'access arguments' => array( + 'cheque report form' + ), + 'file' => 'cheque_contact.inc' + ); + $items['textbook-companion/certificate'] = array( + 'title' => 'List Of All Certificates', + 'description' => 'List Of All Certificates', + 'page callback' => '_list_all_certificates', + 'access arguments' => array( + 'list all certificates' + ), + 'file' => 'pdf/list_all_certificates.inc' + ); + $items['textbook-companion/certificate/generate-pdf'] = array( + 'title' => 'Download Certificate', + 'description' => 'Download Certificate', + 'page callback' => 'drupal_get_form', + 'page arguments' => array( + 'generate_pdf' + ), + 'access arguments' => array( + 'generate pdf' + ), + 'file' => 'pdf/generate_pdf.inc' + ); + $items['textbook-companion/manage-proposal/paper-submission'] = array( + 'title' => 'Application Submission', + 'description' => 'Application Submission', + 'page callback' => 'drupal_get_form', + 'page arguments' => array( + 'paper_submission_form' + ), + 'access arguments' => array( + 'paper submission form' + ), + 'type' => MENU_CALLBACK, + 'file' => 'cheque_contact.inc' + ); + $items["textbook-companion/nonaicte-proposal"] = array( + "title" => "Book Suggestion Form ", + "description" => "NON-AICTE Book Proposal Form", + 'page callback' => 'textbook_companion_nonaicte_proposal_all', + 'access arguments' => array( + 'create book proposal' + ), + 'type' => MENU_CALLBACK + ); + return $items; } - /** * Implementation of hook_perm(). */ -function textbook_companion_perm() { - return array('create book proposal', 'approve book proposal', 'approve code', 'upload code', 'edit uploaded code', 'download code', 'create feedback', 'bulk manage code', 'bulk delete code', 'edit book proposal', 'administer book companion', 'generate book', 'cheque contct form', 'contact_details', 'comment cheque', 'list all certificates', 'generate pdf', 'paper submission form', 'cheque status form' ,'cheque report form' ,'cheque proposal', 'download books to review'); +function textbook_companion_permission() +{ + return array( + "create book proposal" => array( + "title" => t("Book Proposal Form"), + "description" => t("Book Proposal Form.") + ), + "approve book proposal" => array( + "title" => t("Approve book proposal"), + "description" => t("Allows users to approve book proposal.") + ), + "approve code" => array( + "title" => t("Approve code"), + "description" => t("Allows users to approve code.") + ), + "upload code" => array( + "title" => t("Upload code"), + "description" => t("Allows users to upload code.") + ), + "edit uploaded code" => array( + "title" => t("Edit uploaded code"), + "description" => t("Allows users to edit uploaded code.") + ), + "download code" => array( + "title" => t("Download code"), + "description" => t("Allows users to download code.") + ), + "create feedback" => array( + "title" => t("Create feedback"), + "description" => t("Allows users to create feedback.") + ), + "bulk manage code" => array( + "title" => t("Bulk manage code"), + "description" => t("Allows users to manage Bulk code.") + ), + "bulk delete code" => array( + "title" => t("Bulk delete code"), + "description" => t("Allows users to delete bulk code.") + ), + "edit book proposal" => array( + "title" => t("Edit book proposal"), + "description" => t("Allows users to edit book proposal.") + ), + "administer book companion" => array( + "title" => t("Administer book companion"), + "description" => t("Allows users to administer book companion.") + ), + "generate book" => array( + "title" => t("Generate book"), + "description" => t("Allows users to generate book.") + ), + "cheque contct form" => array( + "title" => t("Cheque contact form"), + "description" => t("Cheque contct form.") + ), + "contact_details" => array( + "title" => t("Contact_details"), + "description" => t("Contact_details.") + ), + "comment cheque" => array( + "title" => t("Comment cheque"), + "description" => t("Comment cheque.") + ), + "list all certificates" => array( + "title" => t("list all certificates"), + "description" => t("Allows users to list all certificates.") + ), + "generate pdf" => array( + "title" => t("Generate pdf"), + "description" => t("Allows users to Generate pdf.") + ), + "paper submission form" => array( + "title" => t("paper submission form"), + "description" => t("Paper submission form.") + ), + "cheque status form" => array( + "title" => t("Cheque status form"), + "description" => t("Cheque status form.") + ), + "cheque report form" => array( + "title" => t("Cheque report form"), + "description" => t("Cheque report form.") + ), + "cheque proposal" => array( + "title" => t("Cheque proposal"), + "description" => t("Cheque proposal.") + ), + "download books to review" => array( + "title" => t("download books to review"), + "description" => t("Download books to review.") + ) + ); } - /* Aicte books pickup before the proposal form */ -function textbook_companion_aicte_proposal_form($form_state) { - $query = " - SELECT * FROM textbook_companion_aicte - WHERE status = 0 AND selected = 0 - "; - $result = db_query($query); - - $form = array(); - $form["wrapper"] = array( - "#type" => "fieldset", - "#prefix" => "<div id='aicte-form-wrapper'>", - "#suffix" => "</div>", - ); - $num_rows = mysql_num_rows($result); - if ($num_rows > 0) { - while($row = db_fetch_object($result)) { - /* fixing title string */ - $title = ""; - $edition = ""; - $year = ""; - $title = "{$row->book} by {$row->author}"; - if($row->edition) { - $edition = "<i>ed</i>: {$row->edition}"; - } - if($row->year) { - if($row->edition) { - $year = ", <i>pub</i>: {$row->year}"; - } else { - $year = "<i>pub</i>: {$row->year}"; - } - } - if($edition or $year) { - $title .= "({$edition} {$year})"; - } - $form["wrapper"][$row->id] = array( - "#type" => "checkbox", - "#title" => $title, - "#prefix" => "<div class='title'>", - "#suffix" => "</div>", - ); - } - } - $form["submit"] = array( - "#type" => "submit", - "#value" => "Submit Book Selections" - ); - return $form; +/*function textbook_companion_aicte_proposal_form($form_state) { +/* $query = " +SELECT * FROM textbook_companion_aicte +WHERE status = 0 AND selected = 0 +"; +$result = db_query($query);*/ +/* $query = " +SELECT * FROM textbook_companion_aicte +WHERE status = :status AND selected = :selected +"; +$args = array( +':status' => 0, +':selected' => 0, +); +$result = db_query($query,$args); */ +/* $query = db_select('textbook_companion_aicte'); +$query->fields('textbook_companion_aicte'); +$query->condition('status', 0); +$query->condition('selected', 0); +$result = $query->execute(); + +$form = array(); +$form["wrapper"] = array( +"#type" => "fieldset", +"#prefix" => "<div id='aicte-form-wrapper'>", +"#suffix" => "</div>", +); +// $num_rows = mysql_num_rows($result); +$num_rows = $query->countQuery(); +if ($num_rows > 0) { +while($row = $result->fetchObject()) { +/* fixing title string */ +/* $title = ""; +$edition = ""; +$year = ""; +$title = "{$row->book} by {$row->author}"; +if($row->edition) { +$edition = "<i>ed</i>: {$row->edition}"; } - -function textbook_companion_aicte_proposal_form_validate($form, &$form_state) { - $query = " - SELECT * FROM textbook_companion_aicte - WHERE status = 0 AND selected = 0 - "; - $result = db_query($query); - - $count = 0; - $selections = array(); - while($row = db_fetch_object($result)) { - if($form_state["values"][$row->id] == 1) { - $count++; - array_push($selections, $row->id); - } - } - /* user can choose only 3 books to propose */ - if($count != 3) { - form_set_error("", "Please select exactly <strong>3</strong> books. You currently selected <strong>{$count}</strong>"); - } else { - $form_state["values"]["selections"] = $selections; - } +if($row->year) { +if($row->edition) { +$year = ", <i>pub</i>: {$row->year}"; +} else { +$year = "<i>pub</i>: {$row->year}"; } - -function textbook_companion_aicte_proposal_form_submit($form, &$form_state) { - global $user; - $selections = $form_state["values"]["selections"]; - variable_set("aicte_".$user->uid, $selections); - drupal_goto("proposal"); } - - - - -function textbook_companion_aicte_proposal_all() { +if($edition or $year) { +$title .= "({$edition} {$year})"; +} +$form["wrapper"][$row->id] = array( +"#type" => "checkbox", +"#title" => $title, +"#prefix" => "<div class='title'>", +"#suffix" => "</div>", +); +} +} +$form["submit"] = array( +"#type" => "submit", +"#value" => "Submit Book Selections" +); +return $form; +}*/ +/*function textbook_companion_aicte_proposal_form_validate($form, &$form_state) { +/*$query = " +SELECT * FROM textbook_companion_aicte +WHERE status = 0 AND selected = 0 +"; +$result = db_query($query);*/ +/*$query = db_select('textbook_companion_aicte'); +$query->fields('textbook_companion_aicte'); +$query->condition('status', 0); +$query->condition('selected', 0); +$result = $query->execute(); + +$count = 0; +$selections = array(); +while($row = $result->fetchObject()) { +if($form_state["values"][$row->id] == 1) { +$count++; +array_push($selections, $row->id); +} +} +/* user can choose only 3 books to propose */ +/* if($count != 3) { +form_set_error("", "Please select exactly <strong>3</strong> books. You currently selected <strong>{$count}</strong>"); +} else { +$form_state["values"]["selections"] = $selections; +} +}*/ +/*function textbook_companion_aicte_proposal_form_submit($form, &$form_state) { +global $user; +$selections = $form_state["values"]["selections"]; +var_dump($selections); +variable_set("aicte_".$user->uid, $selections); +drupal_goto("proposal"); +}*/ +/*function textbook_companion_aicte_report_form($form_state) { +/*$query = " +SELECT * FROM textbook_companion_aicte +WHERE status = 0 +ORDER BY book +"; +$result = db_query($query);*/ +/*$query = db_select('textbook_companion_aicte'); +$query->fields('textbook_companion_aicte'); +$query->condition('status', 0); +$query->orderBy('book', 'ASC'); +$result = $query->execute(); + +$books = array(); +$books[0] = "Please select a book"; +while($row = $result->fetchObject()) { +$books[$row->id] = "{$row->book} ({$row->author})"; +} +$form = array(); +$form["name"] = array( +"#type" => "textfield", +"#title" => "Name", +"#description" => t("Please enter your name."), +); +$form["email"] = array( +"#type" => "textfield", +"#title" => "Email", +"#description" => t("Please enter your valid email id."), +); +$form["number"] = array( +"#type" => "textfield", +"#title" => "Number", +"#description" => t("Please enter your valid phone number."), +); +$form["book"] = array( +"#type" => "select", +"#title" => "AICTE Book", +"#description" => t("Please select a book."), +"#options" => $books +); +$form["comment"] = array( +"#type" => "textarea", +"#title" => "Any other comment?", +"#description" => t("Please enter your query (if any)") +); +$form["submit"] = array( +"#type" => "submit", +"#value" => "Submit" +); +return $form; +} +*/ +/*function textbook_companion_aicte_report_form_submit($form, &$form_state) { +$v = $form_state["values"]; + +/*$query = " +INSERT INTO textbook_companion_aicte_report +(aicte_id, name, number, email, comment) +VALUES +(%d, '%s', '%s', '%s', '%s') +"; +$result = db_query($query, +$v["book"], $v["name"], $v["number"], $v["email"], $v["comment"] +);*/ +/*$query = "INSERT INTO textbook_companion_aicte_report +(aicte_id, name, number, email, comment) +VALUES (:aicte_id, :name, :number, :email, :comment)"; +$args = array( +":aicte_id" => $v["book"], +":name" => $v["name"], +":number" => $v["number"], +":email" =>$v["email"], +":comment" => $v["comment"] +); +$result = db_query($query, $args, array('return' => Database::RETURN_INSERT_ID)); + +drupal_set_message("Thank you for reporting.", "status"); +} +*/ +function textbook_companion_aicte_proposal_all() +{ global $user; $page_content = ""; - if (!$user->uid) { - $query = " - SELECT * FROM textbook_companion_aicte - WHERE status = 0 + /*$query = " + SELECT * FROM textbook_companion_aicte + WHERE status = 0 "; - $result = db_query($query); - + $result = db_query($query);*/ + $query = db_select('textbook_companion_aicte'); + $query->fields('textbook_companion_aicte'); + $query->condition('status', 0); + $result = $query->execute(); $page_content .= "<ul>"; $page_content .= "<li>These are the list of books available for <em>Textbook Companion</em> proposal.</li>"; $page_content .= "<li>Please <a href='/user'><b><u>Login</u></b></a> to create a proposal.</li>"; @@ -662,26 +1032,26 @@ function textbook_companion_aicte_proposal_all() { $page_content .= "Search : <input type='text' id='searchtext' style='width:82%'/>"; $page_content .= "<input type='button' value ='clear' id='search_clear'/>"; $page_content .= "<div id='aicte-list-wrapper'>"; - $num_rows = mysql_num_rows($result); + $num_rows = $result->rowCount(); if ($num_rows > 0) { $i = 1; - while($row = db_fetch_object($result)) { + while ($row = $result->fetchObject()) { /* fixing title string */ $title = ""; $edition = ""; $year = ""; $title = "{$row->book} by {$row->author}"; - if($row->edition) { + if ($row->edition) { $edition = "<i>ed</i>: {$row->edition}"; } - if($row->year) { - if($row->edition) { + if ($row->year) { + if ($row->edition) { $year = ", <i>pub</i>: {$row->year}"; } else { $year = "<i>pub</i>: {$row->year}"; } } - if($edition or $year) { + if ($edition or $year) { $title .= "({$edition} {$year})"; } $page_content .= "<div class='title'>{$i}) {$title}</div>"; @@ -693,742 +1063,1592 @@ function textbook_companion_aicte_proposal_all() { //$page_content .= drupal_get_form("textbook_companion_aicte_report_form"); return $page_content; } - /* check if user has already submitted a proposal */ - $proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid = %d ORDER BY id DESC LIMIT 1", $user->uid); + /* $proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid = %d ORDER BY id DESC LIMIT 1", $user->uid);*/ + $query = db_select('textbook_companion_proposal'); + $query->fields('textbook_companion_proposal'); + $query->condition('uid', $user->uid); + $query->orderBy('id', 'DESC'); + $query->range(0, 1); + $proposal_q = $query->execute(); if ($proposal_q) { - if ($proposal_data = db_fetch_object($proposal_q)) { - switch ($proposal_data->proposal_status) { - case 0: - drupal_set_message(t('We have already received your proposal. We will get back to you soon.'), 'status'); - drupal_goto(''); - return; - break; - case 1: - drupal_set_message(t('Your proposal has been approved. Please go to ' . l('Code Submission', 'textbook_companion/code') . ' to upload your code'), 'status'); - drupal_goto(''); - return; - break; - case 2: - drupal_set_message(t('Your proposal has been dis-approved. Please create another proposal below.'), 'error'); - break; - case 3: - drupal_set_message(t('Congratulations! You have completed your last book proposal. You can create another proposal below.'), 'status'); - break; - default: - drupal_set_message(t('Invalid proposal state. Please contact site administrator for further information.'), 'error'); - drupal_goto(''); - return; - break; + if ($proposal_data = $proposal_q->fetchObject()) { + switch ($proposal_data->proposal_status) { + case 0: + drupal_set_message(t('We have already received your proposal. We will get back to you soon.'), 'status'); + drupal_goto(''); + return; + break; + case 1: + drupal_set_message(t('Your proposal has been approved. Please go to ' . l('Code Submission', 'textbook-companion/code') . ' to upload your code'), 'status'); + drupal_goto(''); + return; + break; + case 2: + drupal_set_message(t('Your proposal has been dis-approved. Please create another proposal below.'), 'error'); + break; + case 3: + drupal_set_message(t('Congratulations! You have completed your last book proposal. You can create another proposal below.'), 'status'); + break; + default: + drupal_set_message(t('Invalid proposal state. Please contact site administrator for further information.'), 'error'); + drupal_goto(''); + return; + break; } } } - - variable_del("aicte_".$user->uid); + variable_del("aicte_" . $user->uid); $page_content .= "<h5><b>* Please select any 3 books from the below list.</b></h5></br>"; //$page_content .= "Unable to propose particular book: <a id='aicte-report' href='#'>Click here</a></br></br>"; //$page_content .= "Do not wish to propose any of the below books: <a id='aicte-report' href='http://fossee.in/feedback/scilab-aicte' target = _blank>Click here</a></br></br>"; $page_content .= "Search : <input type='text' id='searchtext' style='width:82%'/>"; - $page_content .= "<input type='button' value ='clear' id='search_clear'/>"; + $page_content .= "<input type='button' value ='clear' id='search_clear'/>"; //$page_content .= drupal_get_form("textbook_companion_aicte_report_form"); - $page_content .= drupal_get_form("textbook_companion_aicte_proposal_form"); + $textbook_companion_aicte_proposal_form = drupal_get_form("textbook_companion_aicte_proposal_form"); + $page_content .= drupal_render($textbook_companion_aicte_proposal_form); return $page_content; } /*non aicte book proposal */ -function textbook_companion_nonaicte_proposal_all() { +function textbook_companion_nonaicte_proposal_all() +{ global $user; $page_content = ""; - if (!$user->uid) { - - $page_content .= "<ul>"; - $page_content .= "<li>Please <a href='/user'><b><u>Login</u></b></a> to create a proposal.</li>"; - $page_content .= "</ul>"; + $page_content .= "<ul>"; + $page_content .= "<li>Please <a href='/user'><b><u>Login</u></b></a> to create a proposal.</li>"; + $page_content .= "</ul>"; return $page_content; } - /* check if user has already submitted a proposal */ - $proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid = %d ORDER BY id DESC LIMIT 1", $user->uid); + /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid = %d ORDER BY id DESC LIMIT 1", $user->uid);*/ + $query = db_select('textbook_companion_proposal'); + $query->fields('textbook_companion_proposal'); + $query->condition('uid', $user->uid); + $query->orderBy('id', 'DESC'); + $query->range(0, 1); + $proposal_q = $query->execute(); if ($proposal_q) { - if ($proposal_data = db_fetch_object($proposal_q)) { - switch ($proposal_data->proposal_status) { - case 0: - drupal_set_message(t('We have already received your proposal. We will get back to you soon.'), 'status'); - drupal_goto(''); - return; - break; - case 1: - drupal_set_message(t('Your proposal has been approved. Please go to ' . l('Code Submission', 'textbook_companion/code') . ' to upload your code'), 'status'); - drupal_goto(''); - return; - break; - case 2: - drupal_set_message(t('Your proposal has been dis-approved. Please create another proposal below.'), 'error'); - break; - case 3: - drupal_set_message(t('Congratulations! You have completed your last book proposal. You can create another proposal below.'), 'status'); - break; - default: - drupal_set_message(t('Invalid proposal state. Please contact site administrator for further information.'), 'error'); - drupal_goto(''); - return; - break; + if ($proposal_data = $proposal_q->fetchObject()) { + switch ($proposal_data->proposal_status) { + case 0: + drupal_set_message(t('We have already received your proposal. We will get back to you soon.'), 'status'); + drupal_goto(''); + return; + break; + case 1: + drupal_set_message(t('Your proposal has been approved. Please go to ' . l('Code Submission', 'textbook-companion/code') . ' to upload your code'), 'status'); + drupal_goto(''); + return; + break; + case 2: + drupal_set_message(t('Your proposal has been dis-approved. Please create another proposal below.'), 'error'); + break; + case 3: + drupal_set_message(t('Congratulations! You have completed your last book proposal. You can create another proposal below.'), 'status'); + break; + case 5: + drupal_set_message(t('You have submitted your all codes.'), 'status'); + drupal_goto(''); + return; + break; + default: + drupal_set_message(t('Invalid proposal state. Please contact site administrator for further information.'), 'error'); + drupal_goto(''); + return; + break; } } } - - //variable_del("aicte_".$user->uid); - $page_content .= drupal_get_form("book_proposal_nonaicte_form"); + //variable_del("aicte_".$user->uid); + $book_proposal_nonaicte_form = drupal_get_form("book_proposal_nonaicte_form"); + $page_content .= drupal_render($book_proposal_nonaicte_form); return $page_content; } - /* Textbook Companion Proposal */ -function textbook_companion_proposal_all() { +function textbook_companion_proposal_all() +{ global $user; $page_content = ""; - - // if (!$user->uid) { - // drupal_set_message('It is mandatory to login on this website to access the proposal form', 'error'); - // return; - // } - + if (!$user->uid) { + drupal_set_message('It is mandatory to login on this website to access the proposal form', 'error'); + drupal_goto(''); + return; + } /* check if user has already submitted a proposal */ - $proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid = %d ORDER BY id DESC LIMIT 1", $user->uid); + /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE uid = %d ORDER BY id DESC LIMIT 1", $user->uid);*/ + $query = db_select('textbook_companion_proposal'); + $query->fields('textbook_companion_proposal'); + $query->condition('uid', $user->uid); + $query->orderBy('id', 'DESC'); + $query->range(0, 1); + $proposal_q = $query->execute(); if ($proposal_q) { - if ($proposal_data = db_fetch_object($proposal_q)) { - switch ($proposal_data->proposal_status) { - case 0: - drupal_set_message(t('We have already received your proposal. We will get back to you soon.'), 'status'); - drupal_goto(''); - return; - break; - case 1: - drupal_set_message(t('Your proposal has been approved. Please go to ' . l('Code Submission', 'textbook_companion/code') . ' to upload your code'), 'status'); - drupal_goto(''); - return; - break; - case 2: - drupal_set_message(t('Your proposal has been dis-approved. Please create another proposal below.'), 'error'); - break; - case 3: - drupal_set_message(t('Congratulations! You have completed your last book proposal. You can create another proposal below.'), 'status'); - break; - default: - drupal_set_message(t('Invalid proposal state. Please contact site administrator for further information.'), 'error'); - drupal_goto(''); - return; - break; + if ($proposal_data = $proposal_q->fetchObject()) { + switch ($proposal_data->proposal_status) { + case 0: + drupal_set_message(t('We have already received your proposal. We will get back to you soon.'), 'status'); + drupal_goto(''); + return; + break; + case 1: + drupal_set_message(t('Your proposal has been approved. Please go to ' . l('Code Submission', 'textbook-companion/code') . ' to upload your code'), 'status'); + drupal_goto(''); + return; + break; + case 2: + drupal_set_message(t('Your proposal has been dis-approved. Please create another proposal below.'), 'error'); + break; + case 3: + drupal_set_message(t('Congratulations! You have completed your last book proposal. You can create another proposal below.'), 'status'); + break; + default: + drupal_set_message(t('Invalid proposal state. Please contact site administrator for further information.'), 'error'); + drupal_goto(''); + return; + break; } } } - - $selections = variable_get("aicte_".$user->uid, ""); - if($selections) { - $selections = implode(",", $selections); - $query = " - SELECT * FROM textbook_companion_aicte - WHERE id IN ({$selections}) - "; - $result = db_query($query); - $row1 = db_fetch_object($result); - $row2 = db_fetch_object($result); - $row3 = db_fetch_object($result); - $page_content .= drupal_get_form("book_proposal_form", $row1, $row2, $row3); - } else { - $page_content .= drupal_get_form("book_proposal_form"); - // drupal_goto("aicte_proposal"); - } - + $book_proposal_form = drupal_get_form("book_proposal_form"); + $page_content .= drupal_render($book_proposal_form); + // drupal_goto("aicte_proposal"); return $page_content; } - -function book_proposal_form($form_state, $row1=NULL, $row2=NULL, $row3=NULL) +/*function book_proposal_form($form, $form_state) { - global $user; - $form = array(); - $form['imp_notice'] = array( - '#type' => 'item', - '#value' => '<font color="red"><b>Please fill up this form carefully as the details entered here will be exactly written in the Textbook Companion</b></font>', - ); - - $form['full_name'] = array( - '#type' => 'textfield', - '#title' => t('Full Name'), - '#size' => 30, - '#maxlength' => 50, - '#required' => TRUE, - ); - $form['email_id'] = array( - '#type' => 'textfield', - '#title' => t('Email'), - '#size' => 30, - '#value' => $user->mail, - '#disabled' => TRUE, - ); - $form['mobile'] = array( - '#type' => 'textfield', - '#title' => t('Mobile No.'), - '#size' => 30, - '#maxlength' => 15, - '#required' => TRUE, - ); - $form['gender'] = array( - '#type' => 'radios', - '#title' => t('Gender'), - '#options' => array('M' => 'Male', 'F' => 'Female'), - '#required' => TRUE, - ); - - $form['how_project'] = array( - '#type' => 'select', - '#title' => t('How did you come to know about this project'), - '#options' => array('DWSIM Website' => 'DWSIM Website', - 'Friend' => 'Friend', - 'Professor/Teacher' => 'Professor/Teacher', - 'Mailing List' => 'Mailing List', - 'Poster in my/other college' => 'Poster in my/other college', - 'Others' => 'Others'), - '#required' => TRUE, - ); - $form['course'] = array( - '#type' => 'textfield', - '#title' => t('Course'), - '#size' => 30, - '#maxlength' => 50, - '#required' => TRUE, - ); - $form['branch'] = array( - '#type' => 'select', - '#title' => t('Department/Branch'), - '#options' => array('Electrical Engineering' => 'Electrical Engineering', - 'Electronics Engineering' => 'Electronics Engineering', - 'Computer Engineering' => 'Computer Engineering', - 'Chemical Engineering' => 'Chemical Engineering', - 'Instrumentation Engineering' => 'Instrumentation Engineering', - 'Mechanical Engineering' => 'Mechanical Engineering', - 'Civil Engineering' => 'Civil Engineering', - 'Physics' => 'Physics', - 'Mathematics' => 'Mathematics', - 'Others' => 'Others'), - '#required' => TRUE, - ); - $form['university'] = array( - '#type' => 'textfield', - '#title' => t('University/Institute'), - '#size' => 30, - '#maxlength' => 50, - '#required' => TRUE, - ); - $form['faculty'] = array( - '#type' => 'hidden', - '#value' => 'None', - '#title' => t('College Teacher/Professor'), - '#size' => 30, - '#maxlength' => 50, - '#required' => TRUE, - ); - $form['faculty_email'] = array( - '#type' => 'hidden', - '#value' => 'None', - '#title' => t('Teacher/Professor Email Id'), - '#default_value' => '@email.com', - '#size' => 30, - '#maxlength' => 50, - ); - $form['reviewer'] = array( - '#type' => 'hidden', - '#value' => 'None', - '#title' => t('Reviewer'), - '#size' => 30, - '#maxlength' => 50, - ); - $form['version'] = array( - '#type' => 'select', - '#title' => t('Version'), - '#options' => array('scilab 5.4.1' => 'Scilab 5.4.1', - 'scilab 5.3.3' => 'Scilab 5.3.3', - 'olderversion' => 'Older Version'), - '#required' => TRUE, - ); - $form['older'] = array( - '#type' => 'textfield', - '#size' => 30, - '#maxlength' => 50, - //'#required' => TRUE, - '#description' => t('Specify the Older version used'), - ); - $form['completion_date'] = array( - '#type' => 'textfield', - '#title' => t('Expected Date of Completion'), - '#description' => t('Input date format should be DD-MM-YYYY. Eg: 23-03-2011'), - '#size' => 10, - '#maxlength' => 10, - ); - $form['operating_system'] = array( - '#type' => 'textfield', - '#title' => t('Operating System'), - '#required' => TRUE, - '#size' => 30, - '#maxlength' => 50, - ); - /*$form['scilab_version'] = array( - '#type' => 'textfield', - '#title' => t('Scilab Version'), - '#required' => TRUE, - '#size' => 10, - '#maxlength' => 10, - );*/ - $form['preference1'] = array( - '#type' => 'fieldset', - '#title' => t('Book Preference 1'), - '#collapsible' => TRUE, - '#collapsed' => FALSE, - ); - $form['preference1']['book1'] = array( - '#type' => 'textfield', - '#title' => t('Title of the book'), - '#size' => 30, - '#maxlength' => 100, - '#required' => TRUE, - '#value' => $row1->book, - '#disabled' => ($row1->book?TRUE:FALSE), - ); - $form['preference1']['author1'] = array( - '#type' => 'textfield', - '#title' => t('Author Name'), - '#size' => 30, - '#maxlength' => 100, - '#required' => TRUE, - '#value' => $row1->author, - '#disabled' => ($row1->author?TRUE:FALSE), - ); - $form['preference1']['isbn1'] = array( - '#type' => 'textfield', - '#title' => t('ISBN No'), - '#size' => 30, - '#maxlength' => 25, - '#required' => TRUE, - '#value' => $row1->isbn, - '#disabled' => ($row1->isbn?TRUE:FALSE), - ); - $form['preference1']['publisher1'] = array( - '#type' => 'textfield', - '#title' => t('Publisher & Place'), - '#size' => 30, - '#maxlength' => 50, - '#required' => TRUE, - '#value' => $row1->publisher, - ); - $form['preference1']['edition1'] = array( - '#type' => 'textfield', - '#title' => t('Edition'), - '#size' => 4, - '#maxlength' => 2, - '#required' => TRUE, - '#value' => $row1->edition, - ); - $form['preference1']['year1'] = array( - '#type' => 'textfield', - '#title' => t('Year of pulication'), - '#size' => 4, - '#maxlength' => 4, - '#required' => TRUE, - '#value' => $row1->year, - ); - $form['preference2'] = array( +global $user; +$form = array(); +$form['imp_notice'] = array( +'#type' => 'item', +'#markup' => '<font color="red"><b>Please fill up this form carefully as the details entered here will be exactly written in the Textbook Companion</b></font>' +); +$form['full_name'] = array( +'#type' => 'textfield', +'#title' => t('Full Name'), +'#size' => 30, +'#maxlength' => 50, +'#required' => TRUE +); +$form['email_id'] = array( +'#type' => 'textfield', +'#title' => t('Email'), +'#size' => 30, +'#value' => $user->mail, +'#disabled' => TRUE +); +$form['mobile'] = array( +'#type' => 'textfield', +'#title' => t('Mobile No.'), +'#size' => 30, +'#maxlength' => 15, +'#required' => TRUE +); +$form['gender'] = array( +'#type' => 'radios', +'#title' => t('Gender'), +'#options' => array( +'M' => 'Male', +'F' => 'Female' +), +'#required' => TRUE +); +$form['how_project'] = array( +'#type' => 'select', +'#title' => t('How did you come to know about this project'), +'#options' => array( +'DWSIM Website' => 'DWSIM Website', +'Friend' => 'Friend', +'Professor/Teacher' => 'Professor/Teacher', +'Mailing List' => 'Mailing List', +'Poster in my/other college' => 'Poster in my/other college', +'Others' => 'Others' +), +'#required' => TRUE +); +$form['course'] = array( +'#type' => 'textfield', +'#title' => t('Course'), +'#size' => 30, +'#maxlength' => 50, +'#required' => TRUE +); +$form['branch'] = array( +'#type' => 'select', +'#title' => t('Department/Branch'), +'#options' => _list_of_departments(), +'#required' => TRUE +); +$form['university'] = array( +'#type' => 'textfield', +'#title' => t('University/ Institute'), +'#size' => 80, +'#maxlength' => 200, +'#required' => TRUE, +'#attributes' => array( +'placeholder' => 'Insert full name of your institute/ university.... ' +) +); +$form['country'] = array( +'#type' => 'select', +'#title' => t('Country'), +'#options' => array( +'India' => 'India', +'Others' => 'Others' +), +'#required' => TRUE, +'#tree' => TRUE, +'#validated' => TRUE +); +$form['other_country'] = array( +'#type' => 'textfield', +'#title' => t('Other than India'), +'#size' => 100, +'#attributes' => array( +'placeholder' => t('Enter your country name') +), +'#states' => array( +'visible' => array( +':input[name="country"]' => array( +'value' => 'Others' +) +) +) +); +$form['other_state'] = array( +'#type' => 'textfield', +'#title' => t('State other than India'), +'#size' => 100, +'#attributes' => array( +'placeholder' => t('Enter your state/region name') +), +'#states' => array( +'visible' => array( +':input[name="country"]' => array( +'value' => 'Others' +) +) +) +); +$form['other_city'] = array( +'#type' => 'textfield', +'#title' => t('City other than India'), +'#size' => 100, +'#attributes' => array( +'placeholder' => t('Enter your city name') +), +'#states' => array( +'visible' => array( +':input[name="country"]' => array( +'value' => 'Others' +) +) +) +); +$form['all_state'] = array( +'#type' => 'select', +'#title' => t('State'), +'#selected' => array( +'' => '-select-' +), +'#options' => _list_of_states(), +'#validated' => TRUE, +'#states' => array( +'visible' => array( +':input[name="country"]' => array( +'value' => 'India' +) +) +) +); +$form['city'] = array( +'#type' => 'select', +'#title' => t('City'), +'#options' => _list_of_cities(), +'#states' => array( +'visible' => array( +':input[name="country"]' => array( +'value' => 'India' +) +) +) +); +$form['pincode'] = array( +'#type' => 'textfield', +'#title' => t('Pincode'), +'#size' => 30, +'#maxlength' => 6, +'#required' => False, +'#attributes' => array( +'placeholder' => 'Enter pincode....' +) +); +/***************************************************************************/ +/* $form['hr'] = array( +'#type' => 'item', +'#markup' => '<hr>' +); +$form['faculty'] = array( +'#type' => 'hidden', +'#value' => 'None', +'#title' => t('College Teacher/Professor'), +'#size' => 30, +'#maxlength' => 50, +'#required' => TRUE +); +$form['faculty_email'] = array( +'#type' => 'hidden', +'#value' => 'None', +'#title' => t('Teacher/Professor Email Id'), +'#value' => '@email.com', +'#size' => 30, +'#maxlength' => 50 +); +$form['reviewer'] = array( +'#type' => 'hidden', +'#value' => 'None', +'#title' => t('Reviewer'), +'#size' => 30, +'#maxlength' => 50 +); + +$form['version'] = array( +'#type' => 'select', +'#title' => t('Version'), +'#options' => _list_of_software_version(), +'#required' => TRUE +); +$form['older'] = array( +'#type' => 'textfield', +'#size' => 30, +'#maxlength' => 50, +//'#required' => TRUE, +'#description' => t('Specify the Older version used'), +'#states' => array( +'visible' => array( +':input[name="version"]' => array( +'value' => 'olderversion' +) +) +) +); +$form['completion_date'] = array( +'#type' => 'textfield', +'#title' => t('Expected Date of Completion'), +'#description' => t('Input date format should be DD-MM-YYYY. Eg: 23-03-2011'), +'#size' => 10, +'#maxlength' => 10 +); +$form['operating_system'] = array( +'#type' => 'textfield', +'#title' => t('Operating System'), +'#required' => TRUE, +'#size' => 30, +'#maxlength' => 50 +); +$reason = array( +'Used in more than one University' => t('Used in more than one University'), +'The book has multiple editions' => t('The book has multiple editions'), +'Extremely useful' => t('Extremely useful'), +'Other reason' => t('Any other reason state below') +); +$form['reason'] = array( +'#type' => 'hidden', +'#default_value' => 'Not available' +); +/*$form['reason'] = array( +'#type' => 'checkboxes', +'#title' => t('Reasons'), +'#options' => $reason, +'#required' => TRUE +); +$form['other_reason'] = array( +'#type' => 'textarea', +'#size' => 300, +'#maxlength' => 300, +'#states' => array( +'visible' => array( +':input[name="reason[Other reason]"]' => array( +'checked' => TRUE +) +) +) +//'#required' => FALSE, +);*/ +/*$form['proposal_type'] = array( +'#type' => 'hidden', +'#default_value' => '0', +'#required' => FALSE +); +$form['reference'] = array( +'#type' => 'hidden', +'#default_value' => 'Not available', +); +/*$form['reference'] = array( +'#type' => 'textarea', +'#title' => t('Reference'), +'#required' => TRUE, +'#size' => 500, +'#maxlength' => 500, +'#attributes' => array( +'placeholder' => 'Links of the syllabus must be provided....' +) +);*/ +/*$form['scilab_version'] = array( +'#type' => 'textfield', +'#title' => t('Scilab Version'), +'#required' => TRUE, +'#size' => 10, +'#maxlength' => 10, +);*/ +/*$form['form_type'] = array( +'#type' => 'hidden', +'#value' => 1 +); +$form['preference1'] = array( +'#type' => 'fieldset', +'#title' => t('Book Preference 1'), +'#collapsible' => TRUE, +'#collapsed' => FALSE +); +$form['preference1']['book1'] = array( +'#type' => 'textfield', +'#title' => t('Title of the book'), +'#size' => 30, +'#maxlength' => 100, +'#required' => TRUE +); +$form['preference1']['author1'] = array( +'#type' => 'textfield', +'#title' => t('Author Name'), +'#size' => 30, +'#maxlength' => 100, +'#required' => TRUE +//'#value' => $row1->author, +//'#disabled' => ($row1->author?TRUE:FALSE), +); +$form['preference1']['isbn1'] = array( +'#type' => 'textfield', +'#title' => t('ISBN No'), +'#size' => 30, +'#maxlength' => 25, +'#required' => TRUE +// '#value' => $row1->isbn, +// '#disabled' => ($row1->isbn?TRUE:FALSE), +); +$form['preference1']['publisher1'] = array( +'#type' => 'textfield', +'#title' => t('Publisher & Place'), +'#size' => 30, +'#maxlength' => 50, +'#required' => TRUE +//'#value' => $row1->publisher, +); +$form['preference1']['edition1'] = array( +'#type' => 'textfield', +'#title' => t('Edition'), +'#size' => 4, +'#maxlength' => 2, +'#required' => TRUE +//'#value' => $row1->edition, +); +$form['preference1']['year1'] = array( +'#type' => 'textfield', +'#title' => t('Year of pulication'), +'#size' => 4, +'#maxlength' => 4, +'#required' => TRUE +//'#value' => $row1->year, +); +$form['preference2'] = array( +'#type' => 'fieldset', +'#title' => t('Book Preference 2'), +'#collapsible' => TRUE, +'#collapsed' => FALSE +); +$form['preference2']['book2'] = array( +'#type' => 'textfield', +'#title' => t('Title of the book'), +'#size' => 30, +'#maxlength' => 100, +'#required' => TRUE +//'#value' => $row2->book, +//'#disabled' => ($row2->book?TRUE:FALSE), +); +$form['preference2']['author2'] = array( +'#type' => 'textfield', +'#title' => t('Author Name'), +'#size' => 30, +'#maxlength' => 100, +'#required' => TRUE +//'#value' => $row2->author, +//'#disabled' => ($row2->author?TRUE:FALSE), +); +$form['preference2']['isbn2'] = array( +'#type' => 'textfield', +'#title' => t('ISBN No'), +'#size' => 30, +'#maxlength' => 25, +'#required' => TRUE +// '#value' => $row2->isbn, +// '#disabled' => ($row2->isbn?TRUE:FALSE), +); +$form['preference2']['publisher2'] = array( +'#type' => 'textfield', +'#title' => t('Publisher & Place'), +'#size' => 30, +'#maxlength' => 50, +'#required' => TRUE +//'#value' => $row2->publisher, +); +$form['preference2']['edition2'] = array( +'#type' => 'textfield', +'#title' => t('Edition'), +'#size' => 4, +'#maxlength' => 2, +'#required' => TRUE +//'#value' => $row2->edition, +); +$form['preference2']['year2'] = array( +'#type' => 'textfield', +'#title' => t('Year of pulication'), +'#size' => 4, +'#maxlength' => 4, +'#required' => TRUE +//'#value' => $row2->year, +); +$form['preference3'] = array( +'#type' => 'fieldset', +'#title' => t('Book Preference 3'), +'#collapsible' => TRUE, +'#collapsed' => FALSE +); +$form['preference3']['book3'] = array( +'#type' => 'textfield', +'#title' => t('Title of the book'), +'#size' => 30, +'#maxlength' => 100, +'#required' => TRUE +//'#value' => $row3->book, +//'#disabled' => ($row3->book?TRUE:FALSE), +); +$form['preference3']['author3'] = array( +'#type' => 'textfield', +'#title' => t('Author Name'), +'#size' => 30, +'#maxlength' => 100, +'#required' => TRUE +//'#value' => $row3->author, +// '#disabled' => ($row3->author?TRUE:FALSE), +); +$form['preference3']['isbn3'] = array( +'#type' => 'textfield', +'#title' => t('ISBN No'), +'#size' => 30, +'#maxlength' => 25, +'#required' => TRUE +//'#value' => $row3->isbn, +//'#disabled' => ($row3->isbn?TRUE:FALSE), +); +$form['preference3']['publisher3'] = array( +'#type' => 'textfield', +'#title' => t('Publisher & Place'), +'#size' => 30, +'#maxlength' => 50, +'#required' => TRUE +// '#value' => $row3->publisher, +); +$form['preference3']['edition3'] = array( +'#type' => 'textfield', +'#title' => t('Edition'), +'#size' => 4, +'#maxlength' => 2, +'#required' => TRUE +//'#value' => $row3->edition, +); +$form['preference3']['year3'] = array( +'#type' => 'textfield', +'#title' => t('Year of pulication'), +'#size' => 4, +'#maxlength' => 4, +'#required' => TRUE +//'#value' => $row3->year, +); +/*$form['termconditions'] = array( +'#type' => 'checkboxes', +'#title' => t('Terms And Conditions'), +'#options' => array( +'status' => t('<a href="term-and-conditions" target="_blank">I agree to the Terms and Conditions</a>'),), +'#required' => TRUE, +);*/ +/*$form['samplefile'] = array( +'#type' => 'fieldset', +'#title' => t('Sample Source Files'), +'#collapsible' => FALSE, +'#collapsed' => FALSE +);*/ +/*$form['samplefile']['samplefile1'] = array( +'#type' => 'file', +'#title' => t('Upload sample source file'), +'#size' => 48, +'#description' => t('Separate filenames with underscore. No spaces or any special characters allowed in filename.') . '<br />' . t('<span style="color:red;">Allowed file extensions : ') . variable_get('textbook_companion_source_extensions', '') . '</span>' +);*/ +/*$form['submit'] = array( +'#type' => 'submit', +'#value' => t('Submit') +); +$form['dir_name1'] = array( +'#type' => 'hidden', +'#value' => 'None' +); +$form['dir_name2'] = array( +'#type' => 'hidden', +'#value' => 'None' +); +$form['dir_name3'] = array( +'#type' => 'hidden', +'#value' => 'None' +); +/* #value fix for #default_value bug drupal6 +foreach(array("preference1", "preference2", "preference3") as $preference) { +foreach($form[$preference] as $key => $value) { +if(!$form[$preference][$key]["#value"]) { +unset($form[$preference][$key]["#value"]); +} +} +}*/ +/* return $form; +}*/ +function book_proposal_form($form, $form_state) +{ + global $user; + $form = array(); + $form['imp_notice'] = array( + '#type' => 'item', + '#markup' => '<font color="red"><b>Please fill up this form carefully as the details entered here will be exactly written in the Textbook Companion</b></font>' + ); + $form['full_name'] = array( + '#type' => 'textfield', + '#title' => t('Full Name'), + '#size' => 30, + '#maxlength' => 50, + '#required' => TRUE + ); + $form['email_id'] = array( + '#type' => 'textfield', + '#title' => t('Email'), + '#size' => 30, + '#value' => $user->mail, + '#disabled' => TRUE + ); + $form['mobile'] = array( + '#type' => 'textfield', + '#title' => t('Mobile No.'), + '#size' => 30, + '#maxlength' => 15, + '#required' => TRUE + ); + $form['gender'] = array( + '#type' => 'radios', + '#title' => t('Gender'), + '#options' => array( + 'M' => 'Male', + 'F' => 'Female' + ), + '#required' => TRUE + ); + $form['how_project'] = array( + '#type' => 'select', + '#title' => t('How did you come to know about this project'), + '#options' => array( + 'DWSIM Website' => 'DWSIM Website', + 'Friend' => 'Friend', + 'Professor/Teacher' => 'Professor/Teacher', + 'Mailing List' => 'Mailing List', + 'Poster in my/other college' => 'Poster in my/other college', + 'Others' => 'Others' + ), + '#required' => TRUE + ); + $form['course'] = array( + '#type' => 'textfield', + '#title' => t('Course'), + '#size' => 30, + '#maxlength' => 50, + '#required' => TRUE + ); + $form['branch'] = array( + '#type' => 'select', + '#title' => t('Department/Branch'), + '#options' => _list_of_departments(), + '#required' => TRUE + ); + $form['university'] = array( + '#type' => 'textfield', + '#title' => t('University/ Institute'), + '#size' => 80, + '#maxlength' => 200, + '#required' => TRUE, + '#attributes' => array( + 'placeholder' => 'Insert full name of your institute/ university.... ' + ) + ); + $form['country'] = array( + '#type' => 'select', + '#title' => t('Country'), + '#options' => array( + 'India' => 'India', + 'Others' => 'Others' + ), + '#required' => TRUE, + '#tree' => TRUE, + '#validated' => TRUE + ); + $form['other_country'] = array( + '#type' => 'textfield', + '#title' => t('Other than India'), + '#size' => 100, + '#attributes' => array( + 'placeholder' => t('Enter your country name') + ), + '#states' => array( + 'visible' => array( + ':input[name="country"]' => array( + 'value' => 'Others' + ) + ) + ) + ); + $form['other_state'] = array( + '#type' => 'textfield', + '#title' => t('State other than India'), + '#size' => 100, + '#attributes' => array( + 'placeholder' => t('Enter your state/region name') + ), + '#states' => array( + 'visible' => array( + ':input[name="country"]' => array( + 'value' => 'Others' + ) + ) + ) + ); + $form['other_city'] = array( + '#type' => 'textfield', + '#title' => t('City other than India'), + '#size' => 100, + '#attributes' => array( + 'placeholder' => t('Enter your city name') + ), + '#states' => array( + 'visible' => array( + ':input[name="country"]' => array( + 'value' => 'Others' + ) + ) + ) + ); + $form['all_state'] = array( + '#type' => 'select', + '#title' => t('State'), + '#selected' => array( + '' => '-select-' + ), + '#options' => _list_of_states(), + '#validated' => TRUE, + '#states' => array( + 'visible' => array( + ':input[name="country"]' => array( + 'value' => 'India' + ) + ) + ) + ); + $form['city'] = array( + '#type' => 'select', + '#title' => t('City'), + '#options' => _list_of_cities(), + '#states' => array( + 'visible' => array( + ':input[name="country"]' => array( + 'value' => 'India' + ) + ) + ) + ); + $form['pincode'] = array( + '#type' => 'textfield', + '#title' => t('Pincode'), + '#size' => 30, + '#maxlength' => 6, + '#required' => False, + '#attributes' => array( + 'placeholder' => 'Enter pincode....' + ) + ); + /***************************************************************************/ + $form['hr'] = array( + '#type' => 'item', + '#markup' => '<hr>' + ); + $form['faculty'] = array( + '#type' => 'hidden', + '#value' => 'None', + '#title' => t('College Teacher/Professor'), + '#size' => 30, + '#maxlength' => 50, + '#required' => TRUE + ); + $form['faculty_email'] = array( + '#type' => 'hidden', + '#value' => 'None', + '#title' => t('Teacher/Professor Email Id'), + '#value' => '@email.com', + '#size' => 30, + '#maxlength' => 50 + ); + $form['reviewer'] = array( + '#type' => 'hidden', + '#value' => 'None', + '#title' => t('Reviewer'), + '#size' => 30, + '#maxlength' => 50 + ); + $form['version'] = array( + '#type' => 'select', + '#title' => t('Version'), + '#options' => _list_of_software_version(), + '#required' => TRUE + ); + $form['older'] = array( + '#type' => 'textfield', + '#size' => 30, + '#maxlength' => 50, + //'#required' => TRUE, + '#description' => t('Specify the Older version used'), + '#states' => array( + 'visible' => array( + ':input[name="version"]' => array( + 'value' => 'olderversion' + ) + ) + ) + ); + $form['completion_date'] = array( + '#type' => 'textfield', + '#title' => t('Expected Date of Completion'), + '#description' => t('Input date format should be DD-MM-YYYY. Eg: 23-03-2011'), + '#size' => 10, + '#maxlength' => 10 + ); + $form['operating_system'] = array( + '#type' => 'textfield', + '#title' => t('Operating System'), + '#required' => TRUE, + '#size' => 30, + '#maxlength' => 50 + ); + $reason = array( + 'Used in more than one University' => t('Used in more than one University'), + 'The book has multiple editions' => t('The book has multiple editions'), + 'Extremely useful' => t('Extremely useful'), + 'Other reason' => t('Any other reason state below') + ); + $form['reason'] = array( + '#type' => 'checkboxes', + '#title' => t('Reasons'), + '#options' => $reason, + '#required' => TRUE + ); + $form['other_reason'] = array( + '#type' => 'textarea', + '#size' => 300, + '#maxlength' => 300, + '#states' => array( + 'visible' => array( + ':input[name="reason[Other reason]"]' => array( + 'checked' => TRUE + ) + ) + ) + //'#required' => FALSE, + ); + $form['proposal_type'] = array( + '#type' => 'hidden', + '#default_value' => '1', + '#required' => FALSE + ); + $form['reference'] = array( + '#type' => 'textarea', + '#title' => t('Reference'), + '#required' => TRUE, + '#size' => 500, + '#maxlength' => 500, + '#attributes' => array( + 'placeholder' => 'Links of the syllabus must be provided....' + ) + ); + $form['form_type'] = array( + '#type' => 'hidden', + '#value' => 1 + ); + $form['preference1'] = array( + '#type' => 'fieldset', + '#title' => t('Book Preference'), + '#collapsible' => TRUE, + '#collapsed' => FALSE + ); + $form['preference1']['book1'] = array( + '#type' => 'textfield', + '#title' => t('Title of the book'), + '#size' => 30, + '#maxlength' => 100, + '#required' => TRUE + ); + $form['preference1']['author1'] = array( + '#type' => 'textfield', + '#title' => t('Author Name'), + '#size' => 30, + '#maxlength' => 100, + '#required' => TRUE + //'#value' => $row1->author, + //'#disabled' => ($row1->author?TRUE:FALSE), + ); + $form['preference1']['isbn1'] = array( + '#type' => 'textfield', + '#title' => t('ISBN No'), + '#size' => 30, + '#maxlength' => 25, + '#required' => TRUE + // '#value' => $row1->isbn, + // '#disabled' => ($row1->isbn?TRUE:FALSE), + ); + $form['preference1']['publisher1'] = array( + '#type' => 'textfield', + '#title' => t('Publisher & Place'), + '#size' => 30, + '#maxlength' => 50, + '#required' => TRUE + //'#value' => $row1->publisher, + ); + $form['preference1']['edition1'] = array( + '#type' => 'textfield', + '#title' => t('Edition'), + '#size' => 4, + '#maxlength' => 2, + '#required' => TRUE + //'#value' => $row1->edition, + ); + $form['preference1']['year1'] = array( + '#type' => 'textfield', + '#title' => t('Year of publication'), + '#size' => 4, + '#maxlength' => 4, + '#required' => TRUE + //'#value' => $row1->year, + ); + /*$form['preference2'] = array( '#type' => 'fieldset', '#title' => t('Book Preference 2'), '#collapsible' => TRUE, - '#collapsed' => FALSE, - ); - $form['preference2']['book2'] = array( + '#collapsed' => FALSE + ); + $form['preference2']['book2'] = array( '#type' => 'textfield', '#title' => t('Title of the book'), '#size' => 30, '#maxlength' => 100, - '#required' => TRUE, - '#value' => $row2->book, - '#disabled' => ($row2->book?TRUE:FALSE), - ); - $form['preference2']['author2'] = array( + '#required' => TRUE + //'#value' => $row2->book, + //'#disabled' => ($row2->book?TRUE:FALSE), + ); + $form['preference2']['author2'] = array( '#type' => 'textfield', '#title' => t('Author Name'), '#size' => 30, '#maxlength' => 100, - '#required' => TRUE, - '#value' => $row2->author, - '#disabled' => ($row2->author?TRUE:FALSE), - ); - $form['preference2']['isbn2'] = array( + '#required' => TRUE + //'#value' => $row2->author, + //'#disabled' => ($row2->author?TRUE:FALSE), + ); + $form['preference2']['isbn2'] = array( '#type' => 'textfield', '#title' => t('ISBN No'), '#size' => 30, '#maxlength' => 25, - '#required' => TRUE, - '#value' => $row2->isbn, - '#disabled' => ($row2->isbn?TRUE:FALSE), - ); - $form['preference2']['publisher2'] = array( + '#required' => TRUE + // '#value' => $row2->isbn, + // '#disabled' => ($row2->isbn?TRUE:FALSE), + ); + $form['preference2']['publisher2'] = array( '#type' => 'textfield', '#title' => t('Publisher & Place'), '#size' => 30, '#maxlength' => 50, - '#required' => TRUE, - '#value' => $row2->publisher, - ); - $form['preference2']['edition2'] = array( + '#required' => TRUE + //'#value' => $row2->publisher, + ); + $form['preference2']['edition2'] = array( '#type' => 'textfield', '#title' => t('Edition'), '#size' => 4, '#maxlength' => 2, - '#required' => TRUE, - '#value' => $row2->edition, - ); - $form['preference2']['year2'] = array( + '#required' => TRUE + //'#value' => $row2->edition, + ); + $form['preference2']['year2'] = array( '#type' => 'textfield', '#title' => t('Year of pulication'), '#size' => 4, '#maxlength' => 4, - '#required' => TRUE, - '#value' => $row2->year, - ); - $form['preference3'] = array( + '#required' => TRUE + //'#value' => $row2->year, + ); + $form['preference3'] = array( '#type' => 'fieldset', '#title' => t('Book Preference 3'), '#collapsible' => TRUE, - '#collapsed' => FALSE, - ); - $form['preference3']['book3'] = array( + '#collapsed' => FALSE + ); + $form['preference3']['book3'] = array( '#type' => 'textfield', '#title' => t('Title of the book'), '#size' => 30, '#maxlength' => 100, - '#required' => TRUE, - '#value' => $row3->book, - '#disabled' => ($row3->book?TRUE:FALSE), - ); - $form['preference3']['author3'] = array( + '#required' => TRUE + //'#value' => $row3->book, + //'#disabled' => ($row3->book?TRUE:FALSE), + ); + $form['preference3']['author3'] = array( '#type' => 'textfield', '#title' => t('Author Name'), '#size' => 30, '#maxlength' => 100, - '#required' => TRUE, - '#value' => $row3->author, - '#disabled' => ($row3->author?TRUE:FALSE), - ); - $form['preference3']['isbn3'] = array( + '#required' => TRUE + //'#value' => $row3->author, + // '#disabled' => ($row3->author?TRUE:FALSE), + ); + $form['preference3']['isbn3'] = array( '#type' => 'textfield', '#title' => t('ISBN No'), '#size' => 30, '#maxlength' => 25, - '#required' => TRUE, - '#value' => $row3->isbn, - '#disabled' => ($row3->isbn?TRUE:FALSE), - ); - $form['preference3']['publisher3'] = array( + '#required' => TRUE + //'#value' => $row3->isbn, + //'#disabled' => ($row3->isbn?TRUE:FALSE), + ); + $form['preference3']['publisher3'] = array( '#type' => 'textfield', '#title' => t('Publisher & Place'), '#size' => 30, '#maxlength' => 50, - '#required' => TRUE, - '#value' => $row3->publisher, - ); - $form['preference3']['edition3'] = array( + '#required' => TRUE + // '#value' => $row3->publisher, + ); + $form['preference3']['edition3'] = array( '#type' => 'textfield', '#title' => t('Edition'), '#size' => 4, '#maxlength' => 2, - '#required' => TRUE, - '#value' => $row3->edition, - ); - $form['preference3']['year3'] = array( + '#required' => TRUE + //'#value' => $row3->edition, + ); + $form['preference3']['year3'] = array( '#type' => 'textfield', '#title' => t('Year of pulication'), '#size' => 4, '#maxlength' => 4, + '#required' => TRUE + //'#value' => $row3->year, + ); + /*$form['termconditions'] = array( + '#type' => 'checkboxes', + '#title' => t('Terms And Conditions'), + '#options' => array( + 'status' => t('<a href="term-and-conditions" target="_blank">I agree to the Terms and Conditions</a>'),), '#required' => TRUE, - '#value' => $row3->year, - ); - $form['termconditions'] = array( - '#type' => 'checkboxes', - '#title' => t('Terms And Conditions'), - '#options' => array( - 'status' => t('<a href="term-and-conditions" target="_blank">I agree to the Terms and Conditions</a>'),), - '#required' => TRUE, - ); - $form['submit'] = array( - '#type' => 'submit', - '#value' => t('Submit') - ); - - /* #value fix for #default_value bug drupal6 - foreach(array("preference1", "preference2", "preference3") as $preference) { + );*/ + $form['samplefile'] = array( + '#type' => 'fieldset', + '#title' => t('Sample Source Files'), + '#collapsible' => FALSE, + '#collapsed' => FALSE + ); + $form['samplefile']['samplefile1'] = array( + '#type' => 'file', + '#title' => t('Upload sample source file'), + '#size' => 48, + '#description' => t('Separate filenames with underscore. No spaces or any special characters allowed in filename.') . '<br />' . t('<span style="color:red;">Allowed file extensions : ') . variable_get('textbook_companion_source_extensions', '') . '</span>' + ); + $form['submit'] = array( + '#type' => 'submit', + '#value' => t('Submit') + ); + $form['dir_name'] = array( + '#type' => 'hidden', + '#value' => 'None' + ); + /* #value fix for #default_value bug drupal6 + foreach(array("preference1", "preference2", "preference3") as $preference) { foreach($form[$preference] as $key => $value) { - if(!$form[$preference][$key]["#value"]) { - unset($form[$preference][$key]["#value"]); - } + if(!$form[$preference][$key]["#value"]) { + unset($form[$preference][$key]["#value"]); } - } */ - return $form; + } + }*/ + return $form; } - function book_proposal_form_validate($form, &$form_state) { - /* mobile */ - if (!preg_match('/^[0-9\ \+]{0,15}$/', $form_state['values']['mobile'])) - form_set_error('mobile', t('Invalid mobile number')); - - /* date of completion */ - if (!preg_match('/^[0-9]{1,2}-[0-9]{1,2}-[0-9]{4}$/', $form_state['values']['completion_date'])) - form_set_error('completion_date', t('Invalid expected date of completion')); - - list($d, $m, $y) = explode('-', $form_state['values']['completion_date']); - $d = (int)$d; $m = (int)$m; $y = (int)$y; - if (!checkdate($m, $d, $y)) - form_set_error('completion_date', t('Invalid expected date of completion')); - if (mktime(0, 0, 0, $m, $d, $y) <= time()) - form_set_error('completion_date', t('Expected date of completion should be in future')); - - /* edition */ - if (!preg_match('/^[1-9][0-9]{0,1}$/', $form_state['values']['edition1'])) - form_set_error('edition1', t('Invalid edition for Book Preference 1')); - if (!preg_match('/^[1-9][0-9]{0,1}$/', $form_state['values']['edition2'])) + /* mobile */ + if (!preg_match('/^[0-9\ \+]{0,15}$/', $form_state['values']['mobile'])) + form_set_error('mobile', t('Invalid mobile number')); + /* date of completion */ + if (!preg_match('/^[0-9]{1,2}-[0-9]{1,2}-[0-9]{4}$/', $form_state['values']['completion_date'])) + form_set_error('completion_date', t('Invalid expected date of completion')); + list($d, $m, $y) = explode('-', $form_state['values']['completion_date']); + $d = (int) $d; + $m = (int) $m; + $y = (int) $y; + if (!checkdate($m, $d, $y)) + form_set_error('completion_date', t('Invalid expected date of completion')); + if (mktime(0, 0, 0, $m, $d, $y) <= time()) + form_set_error('completion_date', t('Expected date of completion should be in future')); + /* edition */ + $cur_year = date('Y'); + if (!preg_match('/^[A-Za-z]/', $form_state['values']['book1'])) + form_set_error('book1', t('Invalid book name for Book Preference 1')); + if (!preg_match('/^[A-Za-z]/', $form_state['values']['author1'])) + if (!preg_match('/^[0-9\-xX]+$/', $form_state['values']['isbn1'])) + form_set_error('isbn1', t('Invalid ISBN for Book Preference 1')); + if (!preg_match('/^[1-9][0-9]{0,1}$/', $form_state['values']['edition1'])) + form_set_error('edition1', t('Invalid edition for Book Preference 1')); + if (!preg_match('/^[1-3][0-9][0-9][0-9]$/', $form_state['values']['year1'])) + form_set_error('year1', t('Invalid year of pulication for Book Preference 1')); + if ((int) $form_state['values']['year1'] > $cur_year) + form_set_error('year1', t('Year of pulication should be not in the future for Book Preference 1')); + if ($form_state['values']['book1'] && $form_state['values']['author1']) { + $bk1 = trim($form_state['values']['book1']); + $auth1 = trim($form_state['values']['author1']); + //var_dump(_dir_name($bk1, $auth1)) + $pref_id = NULL; + if (_dir_name($bk1, $auth1, $pref_id) != NULL) { + $form_state['values']['dir_name1'] = _dir_name($bk1, $auth1, $pref_id); + } + } + /***************************************************************************** + if (!preg_match('/^[0-9\-xX]+$/', $form_state['values']['isbn2'])) + form_set_error('isbn2', t('Invalid ISBN for Book Preference 2')); + if (!preg_match('/^[1-9][0-9]{0,1}$/', $form_state['values']['edition2'])) form_set_error('edition2', t('Invalid edition for Book Preference 2')); - if (!preg_match('/^[1-9][0-9]{0,1}$/', $form_state['values']['edition3'])) - form_set_error('edition3', t('Invalid edition for Book Preference 3')); - - /* year of publication */ - if (!preg_match('/^[1-3][0-9][0-9][0-9]$/', $form_state['values']['year1'])) - form_set_error('year1', t('Invalid year of pulication for Book Preference 1')); - if (!preg_match('/^[1-3][0-9][0-9][0-9]$/', $form_state['values']['year2'])) + if (!preg_match('/^[1-3][0-9][0-9][0-9]$/', $form_state['values']['year2'])) form_set_error('year2', t('Invalid year of pulication for Book Preference 2')); - if (!preg_match('/^[1-3][0-9][0-9][0-9]$/', $form_state['values']['year3'])) - form_set_error('year3', t('Invalid year of pulication for Book Preference 3')); - - /* year of publication */ - $cur_year = date('Y'); - if ((int)$form_state['values']['year1'] > $cur_year) - form_set_error('year1', t('Year of pulication should be not in the future for Book Preference 1')); - if ((int)$form_state['values']['year2'] > $cur_year) + if ((int) $form_state['values']['year2'] > $cur_year) form_set_error('year2', t('Year of pulication should be not in the future for Book Preference 2')); - if ((int)$form_state['values']['year3'] > $cur_year) - form_set_error('year3', t('Year of pulication should be not in the future for Book Preference 3')); - - /* isbn */ - if (!preg_match('/^[0-9\-xX]+$/', $form_state['values']['isbn1'])) - form_set_error('isbn1', t('Invalid ISBN for Book Preference 1')); - if (!preg_match('/^[0-9\-xX]+$/', $form_state['values']['isbn2'])) - form_set_error('isbn2', t('Invalid ISBN for Book Preference 2')); - if (!preg_match('/^[0-9\-xX]+$/', $form_state['values']['isbn3'])) + if ($form_state['values']['book2'] && $form_state['values']['author2']) { + $bk2 = trim($form_state['values']['book2']); + $auth2 = trim($form_state['values']['author2']); + //var_dump(_dir_name($bk1, $auth1)) + $pref_id = NULL; + if (_dir_name($bk2, $auth2, $pref_id) != NULL) { + $form_state['values']['dir_name2'] = _dir_name($bk2, $auth2, $pref_id); + } + /***************************************************************************** + } + if (!preg_match('/^[0-9\-xX]+$/', $form_state['values']['isbn3'])) form_set_error('isbn3', t('Invalid ISBN for Book Preference 3')); - - if($form_state['values']['version'] == 'olderversion'){ - if($form_state['values']['older'] == ''){ - form_set_error('older', t('Please provide valid version')); - } - } - return; + if (!preg_match('/^[1-9][0-9]{0,1}$/', $form_state['values']['edition3'])) + form_set_error('edition3', t('Invalid edition for Book Preference 3')); + if (!preg_match('/^[1-3][0-9][0-9][0-9]$/', $form_state['values']['year3'])) + form_set_error('year3', t('Invalid year of pulication for Book Preference 3')); + if ((int) $form_state['values']['year3'] > $cur_year) + form_set_error('year3', t('Year of pulication should be not in the future for Book Preference 3')); + if ($form_state['values']['book3'] && $form_state['values']['author3']) { + $bk3 = trim($form_state['values']['book3']); + $auth3 = trim($form_state['values']['author3']); + //var_dump(_dir_name($bk1, $auth1)) + $pref_id = NULL; + if (_dir_name($bk1, $auth1, $pref_id) != NULL) { + $form_state['values']['dir_name3'] = _dir_name($bk3, $auth3, $pref_id); + } + /***************************************************************************** + + }*/ + if ($form_state['values']['version'] == 'olderversion') { + if ($form_state['values']['older'] == '') { + form_set_error('older', t('Please provide valid version')); + } + } + if (isset($_FILES['files'])) { + /* check if atleast one source or result file is uploaded */ + if (!($_FILES['files']['name']['samplefile1'])) + form_set_error('samplefile1', t('Please upload sample code main or source file.')); + /* check for valid filename extensions */ + foreach ($_FILES['files']['name'] as $file_form_name => $file_name) { + if ($file_name) { + /* checking file type */ + if (strstr($file_form_name, 'sample')) + $file_type = 'S'; + else + $file_type = 'U'; + $allowed_extensions_str = ''; + switch ($file_type) { + case 'S': + $allowed_extensions_str = variable_get('textbook_companion_source_extensions', ''); + break; + } + $allowed_extensions = explode(',', $allowed_extensions_str); + $fnames = explode('.', strtolower($_FILES['files']['name'][$file_form_name])); + $temp_extension = end($fnames); + if (!in_array($temp_extension, $allowed_extensions)) + form_set_error($file_form_name, t('Only file with ' . $allowed_extensions_str . ' extensions can be uploaded.')); + if ($_FILES['files']['size'][$file_form_name] <= 0) + form_set_error($file_form_name, t('File size cannot be zero.')); + /* check if valid file name */ + if (!textbook_companion_check_valid_filename($_FILES['files']['name'][$file_form_name])) + form_set_error($file_form_name, t('Invalid file name specified. Only alphabets and numbers are allowed as a valid filename.')); + } + } + } + if ($form_state['values']['version'] == 'olderversion') { + if ($form_state['values']['older'] == '') { + form_set_error('older', t('Please provide valid version')); + } + } + return; } - -function book_proposal_form_submit($form, &$form_state) +function book_proposal_form_submit($form, &$form_state, $directory_name = NULL) { - global $user; - $selections = variable_get("aicte_".$user->uid, ""); - - if (!$user->uid) { - drupal_set_message('It is mandatory to login on this website to access the proposal form', 'error'); - return; - } - - /* completion date to timestamp */ - list($d, $m, $y) = explode('-', $form_state['values']['completion_date']); - $completion_date_timestamp = mktime(0, 0, 0, $m, $d, $y); - - - $dwsim_version = $form_state['values']['version']; - - if($form_state['values']['version'] == 'olderversion'){ - $dwsim_version = $form_state['values']['older']; - } - - //var_dump($form_state['values']); - - $query = "INSERT INTO {textbook_companion_proposal} - (uid, approver_uid, full_name, mobile, gender, how_project, course, branch, university, faculty, reviewer, completion_date, creation_date, approval_date, proposal_status, dwsim_version, operating_system, teacher_email) VALUES (".$user->uid.", 0, '".ucwords(strtolower($form_state['values']['full_name']))."', '".$form_state['values']['mobile']."', '".$form_state['values']['gender']."', '".$form_state['values']['how_project']."', '".$form_state['values']['course']."', '".$form_state['values']['branch']."', '".$form_state['values']['university']."', '".ucwords(strtolower($form_state['values']['faculty']))."', '".ucwords(strtolower($form_state['values']['reviewer']))."', '".$completion_date_timestamp."', '".time()."', 0, 0, '".$dwsim_version."', '".$form_state['values']['operating_system']."', '".$form_state['values']['faculty_email']."')"; - - $result = db_query($query); - if (!$result) - { - drupal_set_message(t('Error receiving your proposal. Please try again.'), 'error'); - return; - } - /* proposal id */ - $proposal_id = db_last_insert_id('textbook_companion_proposal', 'id'); - - /* inserting first book preference */ - if ($form_state['values']['book1']) - { - $result = db_query("INSERT INTO {textbook_companion_preference} - (proposal_id, pref_number, book, author, isbn, publisher, edition, year, category, approval_status) VALUES - (%d, %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)", - $proposal_id, - 1, - ucwords(strtolower($form_state['values']['book1'])), - ucwords(strtolower($form_state['values']['author1'])), - $form_state['values']['isbn1'], - ucwords(strtolower($form_state['values']['publisher1'])), - $form_state['values']['edition1'], - $form_state['values']['year1'], - 0, - 0 - ); - if (!$result) - { - drupal_set_message(t('Error receiving your first book preference.'), 'error'); - } else { - $preference_id = db_last_insert_id("textbook_companion_preference", "id"); - $query = " - UPDATE textbook_companion_aicte - SET preference_id = {$preference_id} - WHERE id = {$selections[0]} - "; - db_query($query); + global $user; + $root_path = textbook_companion_samplecode_path(); + $selections = variable_get("aicte_" . $user->uid, ""); + if (!$user->uid) { + drupal_set_message('It is mandatory to login on this website to access the proposal form', 'error'); + return; } - } - - /* inserting second book preference */ - if ($form_state['values']['book2']) - { - $result = db_query("INSERT INTO {textbook_companion_preference} - (proposal_id, pref_number, book, author, isbn, publisher, edition, year, category, approval_status) VALUES - (%d, %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)", - $proposal_id, - 2, - ucwords(strtolower($form_state['values']['book2'])), - ucwords(strtolower($form_state['values']['author2'])), - $form_state['values']['isbn2'], - ucwords(strtolower($form_state['values']['publisher2'])), - $form_state['values']['edition2'], - $form_state['values']['year2'], - 0, - 0 - ); - if (!$result) - { - drupal_set_message(t('Error receiving your second book preference.'), 'error'); - } else { - $preference_id = db_last_insert_id("textbook_companion_preference", "id"); - $query = " - UPDATE textbook_companion_aicte - SET preference_id = {$preference_id} - WHERE id = {$selections[1]} - "; - db_query($query); + /* completion date to timestamp */ + list($d, $m, $y) = explode('-', $form_state['values']['completion_date']); + $completion_date_timestamp = mktime(0, 0, 0, $m, $d, $y); + $dwsim_version = $form_state['values']['version']; + if ($form_state['values']['version'] == 'olderversion') { + $form_state['values']['version'] = $form_state['values']['older']; } - } - - /* inserting third book preference */ - if ($form_state['values']['book3']) - { - $result = db_query("INSERT INTO {textbook_companion_preference} - (proposal_id, pref_number, book, author, isbn, publisher, edition, year, category, approval_status) VALUES - (%d, %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)", - $proposal_id, - 3, - ucwords(strtolower($form_state['values']['book3'])), - ucwords(strtolower($form_state['values']['author3'])), - $form_state['values']['isbn3'], - ucwords(strtolower($form_state['values']['publisher3'])), - $form_state['values']['edition3'], - $form_state['values']['year3'], - 0, - 0 - ); - if (!$result) - { - drupal_set_message(t('Error receiving your third book preference.'), 'error'); - } else { - $preference_id = db_last_insert_id("textbook_companion_preference", "id"); - $query = " - UPDATE textbook_companion_aicte - SET preference_id = {$preference_id} - WHERE id = {$selections[2]} - "; - db_query($query); + if ($form_state['values']['country'] == 'other') { + $form_state['values']['country'] = trim($form_state['values']['other_country']); + $form_state['values']['all_state'] = trim($form_state['values']['other_state']); } - - /* locking the books in the textbook_companion_aicte table */ - foreach ($selections as $selection) { - $query = " - UPDATE textbook_companion_aicte - SET status = 1, uid = {$user->uid}, proposal_id = {$proposal_id} - WHERE id = {$selection} AND status = 0 - "; - db_query($query); + if (isset($_POST['reason'])) { + if (!($form_state['values']['other_reason'])) { + $my_reason = implode(", ", $_POST['reason']); + } else { + $my_reason = implode(", ", $_POST['reason']); + $my_reason = $my_reason . "-" . " " . $form_state['values']['other_reason']; + } + $form_state['values']['reason'] = $my_reason; + } + //var_dump($form_state['values']); + /*$query = "INSERT INTO {textbook_companion_proposal} + (uid, approver_uid, full_name, mobile, gender, how_project, course, branch, university, faculty, reviewer, completion_date, creation_date, approval_date, proposal_status, scilab_version, operating_system, teacher_email) VALUES (".$user->uid.", 0, '".ucwords(strtolower($form_state['values']['full_name']))."', '".$form_state['values']['mobile']."', '".$form_state['values']['gender']."', '".$form_state['values']['how_project']."', '".$form_state['values']['course']."', '".$form_state['values']['branch']."', '".$form_state['values']['university']."', '".ucwords(strtolower($form_state['values']['faculty']))."', '".ucwords(strtolower($form_state['values']['reviewer']))."', '".$completion_date_timestamp."', '".time()."', 0, 0, '".$scilab_version."', '".$form_state['values']['operating_system']."', '".$form_state['values']['faculty_email']."')"; + + $result = db_query($query);*/ + $query = "INSERT INTO {textbook_companion_proposal} + (uid, approver_uid, full_name, mobile, gender, how_project, course, branch, university,city,pincode,state,country, faculty, reviewer,reference, completion_date, creation_date, approval_date, proposal_status, dwsim_version, operating_system, teacher_email,reason,samplefilepath,proposal_type) VALUES (:uid, :approver_uid, :full_name, :mobile, :gender, :how_project, :course, :branch, :university, :city,:pincode,:state,:country, :faculty, :reviewer,:reference, :completion_date, + :creation_date, :approval_date, :proposal_status, :dwsim_version, :operating_system, +:teacher_email,:reason,:samplefilepath,:proposal_type)"; + $args = array( + ":uid" => $user->uid, + ":approver_uid" => 0, + ":full_name" => trim(ucwords(strtolower($form_state['values']['full_name']))), + ":mobile" => trim($form_state['values']['mobile']), + ":gender" => $form_state['values']['gender'], + ":how_project" => $form_state['values']['how_project'], + ":course" => trim($form_state['values']['course']), + ":branch" => $form_state['values']['branch'], + ":university" => trim($form_state['values']['university']), + ":city" => trim($form_state['values']['city']), + ":pincode" => $form_state['values']['pincode'], + ":state" => trim($form_state['values']['all_state']), + ":country" => $form_state['values']['country'], + ":faculty" => ucwords(strtolower($form_state['values']['faculty'])), + ":reviewer" => ucwords(strtolower($form_state['values']['reviewer'])), + ":reference" => trim($form_state['values']['reference']), + ":completion_date" => $completion_date_timestamp, + ":creation_date" => time(), + ":approval_date" => 0, + ":proposal_status" => 0, + ":dwsim_version" => trim($form_state['values']['version']), + ":operating_system" => trim($form_state['values']['operating_system']), + ":teacher_email" => $form_state['values']['faculty_email'], + ":reason" => $form_state['values']['reason'], + ":samplefilepath" => "", + ":proposal_type" => 0 + ); + $result = db_query($query, $args, array( + 'return' => Database::RETURN_INSERT_ID + )); + $dest_path = $result . '/'; + if (!is_dir($root_path . $dest_path)) + mkdir($root_path . $dest_path); + /* uploading files */ + foreach ($_FILES['files']['name'] as $file_form_name => $file_name) { + if ($file_name) { + /* checking file type */ + $file_type = 'S'; + if (file_exists($root_path . $dest_path . $_FILES['files']['name'][$file_form_name])) { + // drupal_set_message(t("Error uploading file. File !filename already exists.", array('!filename' => $_FILES['files']['name'][$file_form_name])), 'error'); + unlink($root_path . $dest_path . $_FILES['files']['name'][$file_form_name]); + } + /* uploading file */ + if (move_uploaded_file($_FILES['files']['tmp_name'][$file_form_name], $root_path . $dest_path . $_FILES['files']['name'][$file_form_name])) { + $query = "UPDATE {textbook_companion_proposal} SET samplefilepath = :samplefilepath WHERE id = :id"; + $args = array( + ":samplefilepath" => $dest_path . $_FILES['files']['name'][$file_form_name], + ":id" => $result + ); + $updateresult = db_query($query, $args); + drupal_set_message($file_name . ' uploaded successfully.', 'status'); + } else { + drupal_set_message('Error uploading file : ' . $dest_path . '/' . $file_name, 'error'); + } + } } - if (!$result) - { - drupal_set_message(t('Error receiving your third book preference.'), 'error'); + if (!$result) { + drupal_set_message(t('Error receiving your proposal. Please try again.'), 'error'); + return; } - } - - /* sending email */ - $email_to = $user->mail; - $param['proposal_received']['proposal_id'] = $proposal_id; - $param['proposal_received']['user_id'] = $user->uid; - if (!drupal_mail('textbook_companion', 'proposal_received', $email_to , language_default(), $param, variable_get('textbook_companion_from_email', NULL), TRUE)) - drupal_set_message('Error sending email message.', 'error'); - - drupal_set_message(t('We have received you book proposal. We will get back to you soon.'), 'status'); - drupal_goto(''); + /* proposal id */ + $proposal_id = $result; + /* inserting first book preference */ + if ($form_state['values']['book1']) { + /*$result = db_query("INSERT INTO {textbook_companion_preference} + (proposal_id, pref_number, book, author, isbn, publisher, edition, year, category, approval_status) VALUES + (%d, %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)", + $proposal_id, + 1, + ucwords(strtolower($form_state['values']['book1'])), + ucwords(strtolower($form_state['values']['author1'])), + $form_state['values']['isbn1'], + ucwords(strtolower($form_state['values']['publisher1'])), + $form_state['values']['edition1'], + $form_state['values']['year1'], + 0, + 0 + );*/ + $bk1 = trim($form_state['values']['book1']); + $auth1 = trim($form_state['values']['author1']); + $pref_id = NULL; + $directory_name = _dir_name($bk1, $auth1, $pref_id); + $query = "INSERT INTO {textbook_companion_preference} + (proposal_id, pref_number, book, author, isbn, publisher, edition, year, category, approval_status, directory_name) VALUES (:proposal_id, :pref_number, :book, :author, :isbn, :publisher, :edition, :year, :category, :approval_status, :directory_name) + "; + $args = array( + ":proposal_id" => $proposal_id, + ":pref_number" => 1, + ":book" => trim(ucwords(strtolower($form_state['values']['book1']))), + ":author" => trim(ucwords(strtolower($form_state['values']['author1']))), + ":isbn" => trim($form_state['values']['isbn1']), + ":publisher" => trim(ucwords(strtolower($form_state['values']['publisher1']))), + ":edition" => trim($form_state['values']['edition1']), + ":year" => trim($form_state['values']['year1']), + ":category" => 0, + ":approval_status" => 0, + ":directory_name" => $form_state['values']['dir_name1'] + ); + $result = db_query($query, $args, array( + 'return' => Database::RETURN_INSERT_ID + )); + if (!$result) { + drupal_set_message(t('Error receiving your first book preference.'), 'error'); + } + } + /*******************************************************/ + /* if ($form_state['values']['book2']) { + /*$result = db_query("INSERT INTO {textbook_companion_preference} + (proposal_id, pref_number, book, author, isbn, publisher, edition, year, category, approval_status) VALUES + (%d, %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)", + $proposal_id, + 1, + ucwords(strtolower($form_state['values']['book1'])), + ucwords(strtolower($form_state['values']['author1'])), + $form_state['values']['isbn1'], + ucwords(strtolower($form_state['values']['publisher1'])), + $form_state['values']['edition1'], + $form_state['values']['year1'], + 0, + 0 + );*/ + /**$bk2 = trim($form_state['values']['book2']); + $auth2 = trim($form_state['values']['author2']); + $pref_id = NULL; + $directory_name = _dir_name($bk2, $auth2, $pref_id); + $query = "INSERT INTO {textbook_companion_preference} + (proposal_id, pref_number, book, author, isbn, publisher, edition, year, category, approval_status, directory_name) VALUES (:proposal_id, :pref_number, :book, :author, :isbn, :publisher, :edition, :year, :category, :approval_status, :directory_name) + "; + $args = array( + ":proposal_id" => $proposal_id, + + + ":pref_number" => 2, + ":book" => trim(ucwords(strtolower($form_state['values']['book2']))), + ":author" => trim(ucwords(strtolower($form_state['values']['author2']))), + ":isbn" => trim($form_state['values']['isbn2']), + ":publisher" => trim(ucwords(strtolower($form_state['values']['publisher2']))), + ":edition" => trim($form_state['values']['edition2']), + ":year" => trim($form_state['values']['year2']), + ":category" => 0, + ":approval_status" => 0, + ":directory_name" => $form_state['values']['dir_name2'] + ); + $result = db_query($query, $args, array( + 'return' => Database::RETURN_INSERT_ID + )); + if (!$result) { + drupal_set_message(t('Error receiving your second book preference.'), 'error'); + } + }**/ + /*******************************************************/ + /**if ($form_state['values']['book3']) { + /*$result = db_query("INSERT INTO {textbook_companion_preference} + (proposal_id, pref_number, book, author, isbn, publisher, edition, year, category, approval_status) VALUES + (%d, %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)", + $proposal_id, + 1, + ucwords(strtolower($form_state['values']['book1'])), + ucwords(strtolower($form_state['values']['author1'])), + $form_state['values']['isbn1'], + ucwords(strtolower($form_state['values']['publisher1'])), + $form_state['values']['edition1'], + $form_state['values']['year1'], + 0, + 0 + );*/ + /** $bk3 = trim($form_state['values']['book3']); + $auth3 = trim($form_state['values']['author3']); + $pref_id = NULL; + $directory_name = _dir_name($bk3, $auth3, $pref_id); + $query = "INSERT INTO {textbook_companion_preference} + (proposal_id, pref_number, book, author, isbn, publisher, edition, year, category, approval_status, directory_name) VALUES (:proposal_id, :pref_number, :book, :author, :isbn, :publisher, :edition, :year, :category, :approval_status, :directory_name) + "; + $args = array( + ":proposal_id" => $proposal_id, + ":pref_number" => 3, + ":book" => trim(ucwords(strtolower($form_state['values']['book3']))), + ":author" => trim(ucwords(strtolower($form_state['values']['author3']))), + ":isbn" => trim($form_state['values']['isbn3']), + ":publisher" => trim(ucwords(strtolower($form_state['values']['publisher3']))), + ":edition" => trim($form_state['values']['edition3']), + ":year" => trim($form_state['values']['year3']), + ":category" => 0, + ":approval_status" => 0, + ":directory_name" => $form_state['values']['dir_name3'] + ); + $result = db_query($query, $args, array( + 'return' => Database::RETURN_INSERT_ID + )); + if (!$result) { + drupal_set_message(t('Error receiving your third book preference.'), 'error'); + } + + }**/ + /*******************************************************/ + /* sending email */ + $email_to = $user->mail; + $from = variable_get('textbook_companion_from_email', ''); + $bcc = variable_get('textbook_companion_emails', ''); + $cc = variable_get('textbook_companion_cc_emails', ''); + $param['proposal_received']['proposal_id'] = $proposal_id; + $param['proposal_received']['user_id'] = $user->uid; + $param['proposal_received']['headers'] = array( + 'From' => $from, + 'MIME-Version' => '1.0', + 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes', + 'Content-Transfer-Encoding' => '8Bit', + 'X-Mailer' => 'Drupal', + 'Cc' => $cc, + 'Bcc' => $bcc + ); + if (!drupal_mail('textbook_companion', 'proposal_received', $email_to, language_default(), $param, $from, TRUE)) + drupal_set_message('Error sending email message.', 'error'); + drupal_set_message(t('We have received you book proposal. We will get back to you soon.'), 'status'); + drupal_goto(''); } - /** * Implementation of hook_mail(). */ function textbook_companion_mail($key, &$message, $params) { - global $user; - $language = $message['lianguage']; - $tbc_bcc_emails = array( - 'Bcc' => variable_get('textbook_companion_emails', ''), - ); - - switch ($key) - { - case 'proposal_received': - // bcc to textbook_companion_emails - $message['headers'] += $tbc_bcc_emails; - /* initializing data */ - $proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d LIMIT 1", $params['proposal_received']['proposal_id']); - $proposal_data = db_fetch_object($proposal_q); - $preference1_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND pref_number = %d LIMIT 1", $params['proposal_received']['proposal_id'], 1); - $preference1_data = db_fetch_object($preference1_q); - $preference2_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND pref_number = %d LIMIT 1", $params['proposal_received']['proposal_id'], 2); - $preference2_data = db_fetch_object($preference2_q); - $preference3_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND pref_number = %d LIMIT 1", $params['proposal_received']['proposal_id'], 3); - $preference3_data = db_fetch_object($preference3_q); - $user_data = user_load($params['proposal_received']['user_id']); - - $message['subject'] = t('[!site_name] Your book proposal has been received', array('!site_name' => variable_get('site_name', '')), $language->language); - $message['body'] = t(' + global $user; + // $language = $message['lianguage']; + $tbc_bcc_emails = array( + 'Bcc' => variable_get('textbook_companion_emails', '') + ); + switch ($key) { + case 'proposal_received': + // bcc to textbook_companion_emails + //$message['headers'] += $tbc_bcc_emails; + /* initializing data */ + /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d LIMIT 1", $params['proposal_received']['proposal_id']); + $proposal_data = db_fetch_object($proposal_q);*/ + $query = db_select('textbook_companion_proposal'); + $query->fields('textbook_companion_proposal'); + $query->condition('id', $params['proposal_received']['proposal_id']); + $query->range(0, 1); + $result = $query->execute(); + $proposal_data = $result->fetchObject(); + $samplecodefilename = ""; + if (strlen($proposal_data->samplefilepath) >= 5) { + $samplecodefilename = substr($proposal_data->samplefilepath, strrpos($proposal_data->samplefilepath, '/') + 1); + } else { + $samplecodefilename = "Not provided"; + } + /*$preference1_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND pref_number = %d LIMIT 1", $params['proposal_received']['proposal_id'], 1); + $preference1_data = db_fetch_object($preference1_q);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('proposal_id', $params['proposal_received']['proposal_id']); + $query->condition('pref_number', 1); + $query->range(0, 1); + $result = $query->execute(); + $preference1_data = $result->fetchObject(); + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('proposal_id', $params['proposal_received']['proposal_id']); + $query->condition('pref_number', 2); + $query->range(0, 1); + $result = $query->execute(); + $preference2_data = $result->fetchObject(); + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('proposal_id', $params['proposal_received']['proposal_id']); + $query->condition('pref_number', 3); + $query->range(0, 1); + $result = $query->execute(); + $preference3_data = $result->fetchObject(); + $user_data = user_load($params['proposal_received']['user_id']); + $message['subject'] = t('[!site_name] Your textbook companion book proposal has been received', array( + '!site_name' => variable_get('site_name', '') + )); + $message['body'] = array( + 'body' => t(' Dear !user_name, -We have received your following book proposal: +We have received your proposal for DWSIM Textbook Companion with the following details: Full Name : ' . $proposal_data->full_name . ' Email : ' . $user_data->mail . ' Mobile : ' . $proposal_data->mobile . ' Course : ' . $proposal_data->course . ' Department/Branch : ' . $proposal_data->branch . ' -University/Institute : ' . $proposal_data->university . ' -College Teacher / Professor : ' . $proposal_data->faculty . ' -Reviewer : ' . $proposal_data->reviewer . ' -Expected date of completion : ' . date('d-m-Y', $proposal_data->completion_date) . ' +University/Institute : ' . $proposal_data->university . ' +City : ' . $proposal_data->city . ' +State : ' . $proposal_data->state . ' +Expected date of completion : ' . date('d-m-Y', $proposal_data->completion_date) . ' + Your Book Preferences : -Book Preference 1 :- +Book Preference :- Title of the book : ' . $preference1_data->book . ' Author name : ' . $preference1_data->author . ' ISBN No. : ' . $preference1_data->isbn . ' @@ -1436,64 +2656,68 @@ Publisher and Place : ' . $preference1_data->publisher . ' Edition : ' . $preference1_data->edition . ' Year of publication : ' . $preference1_data->year . ' -Book Preference 2 :- -Title of the book : ' . $preference2_data->book . ' -Author name : ' . $preference2_data->author . ' -ISBN No. : ' . $preference2_data->isbn . ' -Publisher and Place : ' . $preference2_data->publisher . ' -Edition : ' . $preference2_data->edition . ' -Year of publication : ' . $preference2_data->year . ' - -Book Preference 3 :- -Title of the book : ' . $preference3_data->book . ' -Author name : ' . $preference3_data->author . ' -ISBN No. : ' . $preference3_data->isbn . ' -Publisher and Place : ' . $preference3_data->publisher . ' -Edition : ' . $preference3_data->edition . ' -Year of publication : ' . $preference3_data->year . ' - -Your proposal is under review and you will soon receive an email from us regarding the same. -Note: -Send sample codes to contact_dwsim@fossee.in in a .zip or .tgz file. The sample codes should be sent utmost by the 3rd day of the proposal. The subject of the email containing sample code should be "New Book Proposal-Sample Codes-(Student Name)"​. -The book will not be alloted to you until we receive the sample codes. + + + +Your proposal is under review. You will soon receive an email when your proposal has been approved/ disapproved. Thank you for your submission. Best Wishes, -!site_name', array('!site_name' => variable_get('site_name', ''), '!user_name' => $user_data->name), $language->language); - break; - - case 'proposal_disapproved': - // bcc to textbook_companion_emails - $message['headers'] += $tbc_bcc_emails; - /* initializing data */ - $proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d LIMIT 1", $params['proposal_disapproved']['proposal_id']); - $proposal_data = db_fetch_object($proposal_q); - $preference1_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND pref_number = %d LIMIT 1", $params['proposal_disapproved']['proposal_id'], 1); - $preference1_data = db_fetch_object($preference1_q); - $preference2_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND pref_number = %d LIMIT 1", $params['proposal_disapproved']['proposal_id'], 2); - $preference2_data = db_fetch_object($preference2_q); - $preference3_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND pref_number = %d LIMIT 1", $params['proposal_disapproved']['proposal_id'], 3); - $preference3_data = db_fetch_object($preference3_q); - $user_data = user_load($params['proposal_disapproved']['user_id']); - - $message['subject'] = t('[!site_name] Your book proposal has been disapproved', array('!site_name' => variable_get('site_name', '')), $language->language); - if($proposal_data->proposal_type != 1){ - $message['body'] = t(' +!site_name Team, +FOSSEE,IIT Bombay', array( + '!site_name' => variable_get('site_name', ''), + '!user_name' => $user_data->name + )) + ); + break; + break; + case 'proposal_disapproved': + // bcc to textbook_companion_emails + //$message['headers'] += $tbc_bcc_emails; + /* initializing data */ + /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d LIMIT 1", $params['proposal_disapproved']['proposal_id']); + $proposal_data = db_fetch_object($proposal_q);*/ + $query = db_select('textbook_companion_proposal'); + $query->fields('textbook_companion_proposal'); + $query->condition('id', $params['proposal_disapproved']['proposal_id']); + $query->range(0, 1); + $result = $query->execute(); + $proposal_data = $result->fetchObject(); + /*$preference1_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND pref_number = %d LIMIT 1", $params['proposal_disapproved']['proposal_id'], 1); + $preference1_data = db_fetch_object($preference1_q);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('proposal_id', $params['proposal_disapproved']['proposal_id']); + $query->condition('pref_number', 1); + $query->range(0, 1); + $result = $query->execute(); + $preference1_data = $result->fetchObject(); + $user_data = user_load($params['proposal_disapproved']['user_id']); + $message['subject'] = t('[!site_name] Your textbook companion book proposal has been disapproved', array( + '!site_name' => variable_get('site_name', '') + )); + $message['body'] = array( + 'body' => t(' Dear !user_name, -Your following book proposal has been disapproved: - -Reason for disapproval: ' . $proposal_data->message . ' +We regret to inform you that all the uploaded examples including the book +with following details have been deleted permanently. Full Name : ' . $proposal_data->full_name . ' Email : ' . $user_data->mail . ' Mobile : ' . $proposal_data->mobile . ' Course : ' . $proposal_data->course . ' Department/Branch : ' . $proposal_data->branch . ' -University/Institute : ' . $proposal_data->university . ' -College Teacher / Professor : ' . $proposal_data->faculty . ' -Reviewer : ' . $proposal_data->reviewer . ' -Expected date of completion : ' . date('d-m-Y', $proposal_data->completion_date) . ' +University/Institute : ' . $proposal_data->university . ' +City : ' . $proposal_data->city . ' +State : ' . $proposal_data->state . ' + +Expected date of completion : ' . date('d-m-Y', $proposal_data->completion_date) . ' + +Reason : ' . $proposal_data->reason . ' + + +Reference : ' . $proposal_data->reference . ' Your Book Preferences : @@ -1505,180 +2729,189 @@ Publisher and Place : ' . $preference1_data->publisher . ' Edition : ' . $preference1_data->edition . ' Year of publication : ' . $preference1_data->year . ' -Book Preference 2 :- -Title of the book : ' . $preference2_data->book . ' -Author name : ' . $preference2_data->author . ' -ISBN No. : ' . $preference2_data->isbn . ' -Publisher and Place : ' . $preference2_data->publisher . ' -Edition : ' . $preference2_data->edition . ' -Year of publication : ' . $preference2_data->year . ' - -Book Preference 3 :- -Title of the book : ' . $preference3_data->book . ' -Author name : ' . $preference3_data->author . ' -ISBN No. : ' . $preference3_data->isbn . ' -Publisher and Place : ' . $preference3_data->publisher . ' -Edition : ' . $preference3_data->edition . ' -Year of publication : ' . $preference3_data->year . ' +Reason for disapproval: ' . $proposal_data->message . ' + +You are welcome to submit a new proposal. Best Wishes, -!site_name', array('!site_name' => variable_get('site_name', ''), '!user_name' => $user_data->name), $language->language); -} -else{ -//Non AICTE book proposal dissaprove// -$message['body'] = t(' +!site_name Team, +FOSSEE,IIT Bombay', array( + '!site_name' => variable_get('site_name', ''), + '!user_name' => $user_data->name + )) + ); + break; + case 'proposal_approved': + // bcc to textbook_companion_emails + //$message['headers'] += $tbc_bcc_emails; + /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d LIMIT 1", $params['proposal_approved']['proposal_id']); + $proposal_data = db_fetch_object($proposal_q);*/ + $query = db_select('textbook_companion_proposal'); + $query->fields('textbook_companion_proposal'); + $query->condition('id', $params['proposal_approved']['proposal_id']); + $query->range(0, 1); + $result = $query->execute(); + $proposal_data = $result->fetchObject(); + /* $approved_preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND approval_status = 1 LIMIT 1", $params['proposal_approved']['proposal_id']); + $approved_preference_data = db_fetch_object($approved_preference_q);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('proposal_id', $params['proposal_approved']['proposal_id']); + $query->condition('approval_status', 1); + $query->range(0, 1); + $result = $query->execute(); + $approved_preference_data = $result->fetchObject(); + $user_data = user_load($params['proposal_approved']['user_id']); + $message['headers'] = $params['proposal_approved']['headers']; + $message['subject'] = t('[!site_name] Your book proposal has been approved', array( + '!site_name' => variable_get('site_name', '') + )); + $message['body'] = array( + 'body' => t(' Dear !user_name, -Your following book proposal has been disapproved: - -Reason for disapproval: ' . $proposal_data->message . ' +Congratulations! Your proposal for DWSIM Textbook Companion with the following details is approved. Full Name : ' . $proposal_data->full_name . ' Email : ' . $user_data->mail . ' Mobile : ' . $proposal_data->mobile . ' Course : ' . $proposal_data->course . ' Department/Branch : ' . $proposal_data->branch . ' -University/Institute : ' . $proposal_data->university . ' +University/Institute : ' . $proposal_data->university . ' College Teacher / Professor : ' . $proposal_data->faculty . ' -Reviewer : ' . $proposal_data->reviewer . ' -Expected date of completion : ' . date('d-m-Y', $proposal_data->completion_date) . ' +Reviewer : ' . $proposal_data->reviewer . ' +Expected date of completion : ' . date('d-m-Y', $proposal_data->completion_date) . ' -Your Book Preferences : +Reason : ' . $proposal_data->reason . ' -Book Preference :- -Title of the book : ' . $preference1_data->book . ' -Author name : ' . $preference1_data->author . ' -ISBN No. : ' . $preference1_data->isbn . ' -Publisher and Place : ' . $preference1_data->publisher . ' -Edition : ' . $preference1_data->edition . ' -Year of publication : ' . $preference1_data->year . ' +Reference : ' . $proposal_data->reference . ' + +Title of the book : ' . $approved_preference_data->book . ' +Author name : ' . $approved_preference_data->author . ' +ISBN No. : ' . $approved_preference_data->isbn . ' +Publisher and Place : ' . $approved_preference_data->publisher . ' +Edition : ' . $approved_preference_data->edition . ' +Year of publication : ' . $approved_preference_data->year . ' +Please ensure that ALL the guidelines for coding are strictly followed: + +http://dwsim.fossee.in/textbook-companion/guidelines-coding Best Wishes, -!site_name', array('!site_name' => variable_get('site_name', ''), '!user_name' => $user_data->name), $language->language); -} - break; - - /* Non AICTE Book Proposal */ - case 'nonaicte_proposal_received': - // bcc to textbook_companion_emails - $message['headers'] += $tbc_bcc_emails; - /* initializing data */ - $proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d LIMIT 1", $params['proposal_received']['proposal_id']); - $proposal_data = db_fetch_object($proposal_q); - $preference1_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND pref_number = %d LIMIT 1", $params['proposal_received']['proposal_id'], 1); - $preference1_data = db_fetch_object($preference1_q); - - $user_data = user_load($params['proposal_received']['user_id']); - - $message['subject'] = t('[!site_name] Your book proposal has been received', array('!site_name' => variable_get('site_name', '')), $language->language); - $message['body'] = t(' +!site_name Team, +FOSSEE,IIT Bombay', array( + '!site_name' => variable_get('site_name', ''), + '!user_name' => $user_data->name + )) + ); + break; + case 'proposal_completed': + // bcc to textbook_companion_emails + //$message['headers'] += $tbc_bcc_emails; + /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d LIMIT 1", $params['proposal_completed']['proposal_id']); + $proposal_data = db_fetch_object($proposal_q);*/ + $query = db_select('textbook_companion_proposal'); + $query->fields('textbook_companion_proposal'); + $query->condition('id', $params['proposal_completed']['proposal_id']); + $query->range(0, 1); + $result = $query->execute(); + $proposal_data = $result->fetchObject(); + /*$approved_preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND approval_status = 1 LIMIT 1", $params['proposal_completed']['proposal_id']); + $approved_preference_data = db_fetch_object($approved_preference_q);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('proposal_id', $params['proposal_completed']['proposal_id']); + $query->condition('approval_status', 1); + $query->range(0, 1); + $result = $query->execute(); + $approved_preference_data = $result->fetchObject(); + $user_data = user_load($params['proposal_completed']['user_id']); + $message['subject'] = t('[!site_name] Congratulations on the completion of the Textbook Companion.', array( + '!site_name' => variable_get('site_name', '') + )); + $message['body'] = array( + 'body' => t(' Dear !user_name, -We have received your following book proposal: +The textbook companion on the following book has been completed successfully by you: Full Name : ' . $proposal_data->full_name . ' Email : ' . $user_data->mail . ' Mobile : ' . $proposal_data->mobile . ' Course : ' . $proposal_data->course . ' Department/Branch : ' . $proposal_data->branch . ' -University/Institute : ' . $proposal_data->university . ' +University/Institute : ' . $proposal_data->university . ' College Teacher / Professor : ' . $proposal_data->faculty . ' -Reviewer : ' . $proposal_data->reviewer . ' -Expected date of completion : ' . date('d-m-Y', $proposal_data->completion_date) . ' - -Your Non AICTE Book Preferences : - -Book Preference :- -Title of the book : ' . $preference1_data->book . ' -Author name : ' . $preference1_data->author . ' -ISBN No. : ' . $preference1_data->isbn . ' -Publisher and Place : ' . $preference1_data->publisher . ' -Edition : ' . $preference1_data->edition . ' -Year of publication : ' . $preference1_data->year . ' - - -Your proposal is under review and you will soon receive an email from us regarding the same. -Note: -Send sample codes to contact_dwsim@fossee.in in a .zip or .tgz file. The sample codes should be sent utmost by the 3rd day of the proposal. The subject of the email containing sample code should be "New Book Proposal-Sample Codes-(Student Name)"​. -The book will not be alloted to you until we receive the sample codes. - -Best Wishes, - -!site_name', array('!site_name' => variable_get('site_name', ''), '!user_name' => $user_data->name), $language->language); - break; -case 'nonaicte_proposal_to_pi': - // bcc to textbook_companion_emails - $message['headers'] += $tbc_bcc_emails; - /* initializing data */ - $proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d LIMIT 1", $params['proposal_received']['proposal_id']); - $proposal_data = db_fetch_object($proposal_q); - $preference1_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND pref_number = %d LIMIT 1", $params['proposal_received']['proposal_id'], 1); - $preference1_data = db_fetch_object($preference1_q); - - $user_data = user_load($params['proposal_received']['user_id']); - - $message['subject'] = t('[!site_name] New Non AICTE book suggestion has been received', array('!site_name' => variable_get('site_name', '')), $language->language); - $message['body'] = t(' -Dear all, - -We have received following Non AICTE book suggestion: - -Full Name : ' . $proposal_data->full_name . ' -University/Institute :' . $proposal_data->university . ' - - -Reason(s): '. $proposal_data->reason . ' - +Reviewer : ' . $proposal_data->reviewer . ' +Expected date of completion : ' . date('d-m-Y', $proposal_data->completion_date) . ' -Your Non AICTE Book Preference : - -Title of the book : ' . $preference1_data->book . ' -Author name : ' . $preference1_data->author . ' -ISBN No. : ' . $preference1_data->isbn . ' -Publisher and Place : ' . $preference1_data->publisher . ' -Edition : ' . $preference1_data->edition . ' -Year of publication : ' . $preference1_data->year . ' -Reference :- '.$proposal_data->reference.' +Title of the book : ' . $approved_preference_data->book . ' +Author name : ' . $approved_preference_data->author . ' +ISBN No. : ' . $approved_preference_data->isbn . ' +Publisher and Place : ' . $approved_preference_data->publisher . ' +Edition : ' . $approved_preference_data->edition . ' +Year of publication : ' . $approved_preference_data->year . ' +Your book is now available at following link to download. +http://dwsim.fossee.in/textbook-companion/textbook-run/' . $approved_preference_data->id . ' +Now you should be able to propose a new book. Best Wishes, -!site_name', array('!site_name' => variable_get('site_name', ''), '!user_name' => $user_data->name), $language->language); - break; - - - - case 'proposal_approved': - // bcc to textbook_companion_emails - $message['headers'] += $tbc_bcc_emails; - $proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d LIMIT 1", $params['proposal_approved']['proposal_id']); - $proposal_data = db_fetch_object($proposal_q); - $approved_preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND approval_status = 1 LIMIT 1", $params['proposal_approved']['proposal_id']); - $approved_preference_data = db_fetch_object($approved_preference_q); - $user_data = user_load($params['proposal_approved']['user_id']); - - $message['subject'] = t('[!site_name] Your book proposal has been approved', array('!site_name' => variable_get('site_name', '')), $language->language); - $message['body'] = t(' +!site_name Team, +FOSSEE,IIT Bombay', array( + '!site_name' => variable_get('site_name', ''), + '!user_name' => $user_data->name + )) + ); + break; + /***********************************************************************************************/ + case 'all_code_submitted': + // bcc to textbook_companion_emails + //$message['headers'] += $tbc_bcc_emails; + /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d LIMIT 1", $params['proposal_completed']['proposal_id']); + $proposal_data = db_fetch_object($proposal_q);*/ + $query = db_select('textbook_companion_proposal'); + $query->fields('textbook_companion_proposal'); + $query->condition('id', $params['all_code_submitted']['proposal_id']); + $query->range(0, 1); + $result = $query->execute(); + $proposal_data = $result->fetchObject(); + /*$approved_preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND approval_status = 1 LIMIT 1", $params['proposal_completed']['proposal_id']); + $approved_preference_data = db_fetch_object($approved_preference_q);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('proposal_id', $params['all_code_submitted']['proposal_id']); + $query->condition('approval_status', 1); + $query->range(0, 1); + $result = $query->execute(); + $approved_preference_data = $result->fetchObject(); + $user_data = user_load($params['all_code_submitted']['user_id']); + $message['subject'] = t('[!site_name][Textbook Companion] You have marked to submited code for all examples.', array( + '!site_name' => variable_get('site_name', '') + )); + $message['body'] = array( + 'body' => t(' Dear !user_name, -Your following book proposal has been approved: +You have submitted codes for all examples: Full Name : ' . $proposal_data->full_name . ' Email : ' . $user_data->mail . ' -Mobile : ' . $proposal_data->mobile . ' +Mobile : ' . $proposal_data->mobile . ' Course : ' . $proposal_data->course . ' Department/Branch : ' . $proposal_data->branch . ' -University/Institute : ' . $proposal_data->university . ' +University/Institute : ' . $proposal_data->university . ' College Teacher / Professor : ' . $proposal_data->faculty . ' -Reviewer : ' . $proposal_data->reviewer . ' -Expected date of completion : ' . date('d-m-Y', $proposal_data->completion_date) . ' +Reviewer : ' . $proposal_data->reviewer . ' +Expected date of completion : ' . date('d-m-Y', $proposal_data->completion_date) . ' + Title of the book : ' . $approved_preference_data->book . ' Author name : ' . $approved_preference_data->author . ' @@ -1687,42 +2920,57 @@ Publisher and Place : ' . $approved_preference_data->publisher . ' Edition : ' . $approved_preference_data->edition . ' Year of publication : ' . $approved_preference_data->year . ' -According the new Textbook Companion procedure, a student doing a textbook companion is not required to have a mentor. For more details check the links given below. -http://dwsim.fossee.in/tbc_honorarium -http://dwsim.fossee.in/Textbook_Companion_Internship - -Please contact us by sending an e-mail to contact_dwsim@fossee.in in case you wish to cancel this book proposal. +You shall be notified after the code is reviewed. Best Wishes, -!site_name', array('!site_name' => variable_get('site_name', ''), '!user_name' => $user_data->name), $language->language); - break; - - case 'proposal_completed': - // bcc to textbook_companion_emails - $message['headers'] += $tbc_bcc_emails; - - $proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d LIMIT 1", $params['proposal_completed']['proposal_id']); - $proposal_data = db_fetch_object($proposal_q); - $approved_preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND approval_status = 1 LIMIT 1", $params['proposal_completed']['proposal_id']); - $approved_preference_data = db_fetch_object($approved_preference_q); - $user_data = user_load($params['proposal_completed']['user_id']); - - $message['subject'] = t('[!site_name] Congratulations for completion of the book.', array('!site_name' => variable_get('site_name', '')), $language->language); - $message['body'] = t(' +!site_name Team, +FOSSEE,IIT Bombay', array( + '!site_name' => variable_get('site_name', ''), + '!user_name' => $user_data->name + )) + ); + break; + case 'all_code_submitted_status_changed': + // bcc to textbook_companion_emails + //$message['headers'] += $tbc_bcc_emails; + /*$proposal_q = db_query("SELECT * FROM {textbook_companion_proposal} WHERE id = %d LIMIT 1", $params['proposal_completed']['proposal_id']); + $proposal_data = db_fetch_object($proposal_q);*/ + $query = db_select('textbook_companion_proposal'); + $query->fields('textbook_companion_proposal'); + $query->condition('id', $params['all_code_submitted_status_changed']['proposal_id']); + $query->range(0, 1); + $result = $query->execute(); + $proposal_data = $result->fetchObject(); + /*$approved_preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE proposal_id = %d AND approval_status = 1 LIMIT 1", $params['proposal_completed']['proposal_id']); + $approved_preference_data = db_fetch_object($approved_preference_q);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('proposal_id', $params['all_code_submitted_status_changed']['proposal_id']); + $query->condition('approval_status', 1); + $query->range(0, 1); + $result = $query->execute(); + $approved_preference_data = $result->fetchObject(); + $user_data = user_load($params['all_code_submitted_status_changed']['user_id']); + $message['subject'] = t('[!site_name][Textbook Companion] Your interface for code submission has been enabled by the reviewer', array( + '!site_name' => variable_get('site_name', '') + )); + $message['body'] = array( + 'body' => t(' Dear !user_name, -Following book has been completed sucessfully by you: +Your interface for code submission has been enabled by the reviewer, you can now able to send more code for this book. Full Name : ' . $proposal_data->full_name . ' Email : ' . $user_data->mail . ' -Mobile : ' . $proposal_data->mobile . ' +Mobile : ' . $proposal_data->mobile . ' Course : ' . $proposal_data->course . ' Department/Branch : ' . $proposal_data->branch . ' -University/Institute : ' . $proposal_data->university . ' +University/Institute : ' . $proposal_data->university . ' College Teacher / Professor : ' . $proposal_data->faculty . ' -Reviewer : ' . $proposal_data->reviewer . ' -Expected date of completion : ' . date('d-m-Y', $proposal_data->completion_date) . ' +Reviewer : ' . $proposal_data->reviewer . ' +Expected date of completion : ' . date('d-m-Y', $proposal_data->completion_date) . ' + Title of the book : ' . $approved_preference_data->book . ' Author name : ' . $approved_preference_data->author . ' @@ -1730,118 +2978,238 @@ ISBN No. : ' . $approved_preference_data->isbn . ' Publisher and Place : ' . $approved_preference_data->publisher . ' Edition : ' . $approved_preference_data->edition . ' Year of publication : ' . $approved_preference_data->year . ' - - - -Now you should be able to propose a new book... - + Best Wishes, -!site_name', array('!site_name' => variable_get('site_name', ''), '!user_name' => $user_data->name), $language->language); - break; - - case 'example_uploaded': - // bcc to textbook_companion_emails - $message['headers'] += $tbc_bcc_emails; - $example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE id = %d LIMIT 1", $params['example_uploaded']['example_id']); - $example_data = db_fetch_object($example_q); - $user_data = user_load($params['example_uploaded']['user_id']); - - $message['subject'] = t('[!site_name] You have uploaded example', array('!site_name' => variable_get('site_name', '')), $language->language); - $message['body'] = t(' +!site_name Team, +FOSSEE,IIT Bombay', array( + '!site_name' => variable_get('site_name', ''), + '!user_name' => $user_data->name + )) + ); + break; + /*****************************************************************************************/ + case 'example_uploaded': + // bcc to textbook_companion_emails + //$message['headers'] += $tbc_bcc_emails; + /*$example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE id = %d LIMIT 1", $params['example_uploaded']['example_id']); + $example_data = db_fetch_object($example_q);*/ + $query = db_select('textbook_companion_example'); + $query->fields('textbook_companion_example'); + $query->condition('id', $params['example_uploaded']['example_id']); + $query->range(0, 1); + $result = $query->execute(); + $example_data = $result->fetchObject(); + $query = db_select('textbook_companion_chapter'); + $query->fields('textbook_companion_chapter'); + $query->condition('id', $example_data->chapter_id); + $query->range(0, 1); + $result = $query->execute(); + $chapter_data = $result->fetchObject(); + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('id', $chapter_data->preference_id); + $query->range(0, 1); + $result = $query->execute(); + $preference_data = $result->fetchObject(); + $user_data = user_load($params['example_uploaded']['user_id']); + $message['subject'] = t('[!site_name] You have uploaded example for Textbook Companion', array( + '!site_name' => variable_get('site_name', '') + )); + $message['body'] = array( + 'body' => t(' Dear !user_name, -You have uploaded the following example: +You have uploaded the following solution : +Title of the book : ' . $preference_data->book . ' +Title of the chapter : ' . $chapter_data->name . ' Example number : ' . $example_data->number . ' -Caption : ' . $example_data->caption . ' - -The example is under review. You will be notified when it has been approved. +Caption : ' . $example_data->caption . ' -Please ensure that ALL the codes have followed the naming convention and contain captions as described here. -The codes cannot be approved unless the convention is followed. +You shall be notified after the solution is reviewed Best Wishes, -!site_name', array('!site_name' => variable_get('site_name', ''), '!user_name' => $user_data->name), $language->language); - break; - - case 'example_updated': - // bcc to textbook_companion_emails - $message['headers'] += $tbc_bcc_emails; - $example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE id = %d LIMIT 1", $params['example_updated']['example_id']); - $example_data = db_fetch_object($example_q); - $user_data = user_load($params['example_updated']['user_id']); - - $message['subject'] = t('[!site_name] You have updated example', array('!site_name' => variable_get('site_name', '')), $language->language); - $message['body'] = t(' +!site_name Team, +FOSSEE,IIT Bombay', array( + '!site_name' => variable_get('site_name', ''), + '!user_name' => $user_data->name + )) + ); + break; + case 'example_updated': + // bcc to textbook_companion_emails + //$message['headers'] += $tbc_bcc_emails; + /*$example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE id = %d LIMIT 1", $params['example_updated']['example_id']); + $example_data = db_fetch_object($example_q);*/ + $query = db_select('textbook_companion_example'); + $query->fields('textbook_companion_example'); + $query->condition('id', $params['example_updated']['example_id']); + $query->range(0, 1); + $result = $query->execute(); + $example_data = $result->fetchObject(); + $query = db_select('textbook_companion_chapter'); + $query->fields('textbook_companion_chapter'); + $query->condition('id', $example_data->chapter_id); + $query->range(0, 1); + $result = $query->execute(); + $chapter_data = $result->fetchObject(); + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('id', $chapter_data->preference_id); + $query->range(0, 1); + $result = $query->execute(); + $preference_data = $result->fetchObject(); + $user_data = user_load($params['example_updated']['user_id']); + $message['subject'] = t('[!site_name] You have updated example for Textbook Companion', array( + '!site_name' => variable_get('site_name', '') + )); + $message['body'] = array( + 'body' => t(' Dear !user_name, You have updated the following example: +Title of the book : ' . $preference_data->book . ' +Title of the chapter : ' . $chapter_data->name . ' Example number : ' . $example_data->number . ' -Caption : ' . $example_data->caption . ' +Caption : ' . $example_data->caption . ' The example is still under review. You will be notified when it has been approved. Best Wishes, -!site_name', array('!site_name' => variable_get('site_name', ''), '!user_name' => $user_data->name), $language->language); - break; - - case 'example_updated_admin': - // bcc to textbook_companion_emails - $message['headers'] += $tbc_bcc_emails; - $example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE id = %d LIMIT 1", $params['example_updated_admin']['example_id']); - $example_data = db_fetch_object($example_q); - $user_data = user_load($params['example_updated_admin']['user_id']); - - $message['subject'] = t('[!site_name] Reviewer have updated example', array('!site_name' => variable_get('site_name', '')), $language->language); - $message['body'] = t(' +!site_name Team, +FOSSEE,IIT Bombay', array( + '!site_name' => variable_get('site_name', ''), + '!user_name' => $user_data->name + )) + ); + break; + case 'example_updated_admin': + // bcc to textbook_companion_emails + //$message['headers'] += $tbc_bcc_emails; + /*$example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE id = %d LIMIT 1", $params['example_updated_admin']['example_id']); + $example_data = db_fetch_object($example_q);*/ + $query = db_select('textbook_companion_example'); + $query->fields('textbook_companion_example'); + $query->condition('id', $params['example_updated_admin']['example_id']); + $query->range(0, 1); + $result = $query->execute(); + $example_data = $result->fetchObject(); + $query = db_select('textbook_companion_chapter'); + $query->fields('textbook_companion_chapter'); + $query->condition('id', $example_data->chapter_id); + $query->range(0, 1); + $result = $query->execute(); + $chapter_data = $result->fetchObject(); + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('id', $chapter_data->preference_id); + $query->range(0, 1); + $result = $query->execute(); + $preference_data = $result->fetchObject(); + $user_data = user_load($params['example_updated_admin']['user_id']); + $message['subject'] = t('[!site_name] Reviewer have updated example for Textbook Companion ', array( + '!site_name' => variable_get('site_name', '') + )); + $message['body'] = array( + 'body' => t(' Dear !user_name, Reviewer have updated the following example: +Title of the book : ' . $preference_data->book . ' +Title of the chapter : ' . $chapter_data->name . ' Example number : ' . $example_data->number . ' -Caption : ' . $example_data->caption . ' +Caption : ' . $example_data->caption . ' Best Wishes, -!site_name', array('!site_name' => variable_get('site_name', ''), '!user_name' => $user_data->name), $language->language); - break; - - case 'example_approved': - // bcc to textbook_companion_emails - $message['headers'] += $tbc_bcc_emails; - $example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE id = %d LIMIT 1", $params['example_approved']['example_id']); - $example_data = db_fetch_object($example_q); - $user_data = user_load($params['example_approved']['user_id']); - - $message['subject'] = t('[!site_name] Your uploaded example has been approved', array('!site_name' => variable_get('site_name', '')), $language->language); - $message['body'] = t(' +!site_name Team, +FOSSEE,IIT Bombay', array( + '!site_name' => variable_get('site_name', ''), + '!user_name' => $user_data->name + )) + ); + break; + case 'example_approved': + // bcc to textbook_companion_emails + //$message['headers'] += $tbc_bcc_emails; + /*$example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE id = %d LIMIT 1", $params['example_approved']['example_id']); + $example_data = db_fetch_object($example_q);*/ + $query = db_select('textbook_companion_example'); + $query->fields('textbook_companion_example'); + $query->condition('id', $params['example_approved']['example_id']); + $query->range(0, 1); + $result = $query->execute(); + $example_data = $result->fetchObject(); + $query = db_select('textbook_companion_chapter'); + $query->fields('textbook_companion_chapter'); + $query->condition('id', $example_data->chapter_id); + $query->range(0, 1); + $result = $query->execute(); + $chapter_data = $result->fetchObject(); + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('id', $chapter_data->preference_id); + $query->range(0, 1); + $result = $query->execute(); + $preference_data = $result->fetchObject(); + $user_data = user_load($params['example_approved']['user_id']); + $message['subject'] = t('[!site_name] Your uploaded example has been approved for Textbook Companion', array( + '!site_name' => variable_get('site_name', '') + )); + $message['body'] = array( + 'body' => t(' Dear !user_name, -Your following example has been approved: +Your example for DWSIM Textbook Companion with the following details is approved. +Title of the book : ' . $preference_data->book . ' +Title of the chapter : ' . $chapter_data->name . ' Example number : ' . $example_data->number . ' -Caption : ' . $example_data->caption . ' +Caption : ' . $example_data->caption . ' Best Wishes, -!site_name', array('!site_name' => variable_get('site_name', ''), '!user_name' => $user_data->name), $language->language); - break; - - case 'example_disapproved': - // bcc to textbook_companion_emails - $message['headers'] += $tbc_bcc_emails; - $user_data = user_load($params['example_disapproved']['user_id']); - - $message['subject'] = t('[!site_name] Your uploaded example has been disapproved', array('!site_name' => variable_get('site_name', '')), $language->language); - $message['body'] = t(' +!site_name Team, +FOSSEE,IIT Bombay', array( + '!site_name' => variable_get('site_name', ''), + '!user_name' => $user_data->name + )) + ); + break; + case 'example_disapproved': + // bcc to textbook_companion_emails + //$message['headers'] += $tbc_bcc_emails; + $user_data = user_load($params['example_disapproved']['user_id']); + $preference_id = $param['example_disapproved']['preference_id']; + $chapter_id = $param['example_disapproved']['chapter_id']; + $query = db_select('textbook_companion_chapter'); + $query->fields('textbook_companion_chapter'); + $query->condition('id', $chapter_id); + $query->range(0, 1); + $result = $query->execute(); + $chapter_data = $result->fetchObject(); + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('id', $preference_id); + $query->range(0, 1); + $result = $query->execute(); + $preference_data = $result->fetchObject(); + $message['subject'] = t('[!site_name] Your uploaded example has been disapproved for Textbook Companion', array( + '!site_name' => variable_get('site_name', '') + )); + $message['body'] = array( + 'body' => t(' Dear !user_name, Your following example has been disapproved: +Title of the book : ' . $preference_data->book . ' +Title of the chapter : ' . $chapter_data->name . ' Example number : ' . $params['example_disapproved']['example_number'] . ' Caption : ' . $params['example_disapproved']['example_caption'] . ' @@ -1849,16 +3217,22 @@ Reason for dis-approval : ' . $params['example_disapproved']['message'] . ' Best Wishes, -!site_name', array('!site_name' => variable_get('site_name', ''), '!user_name' => $user_data->name), $language->language); - break; - - case 'example_deleted_user': - // bcc to textbook_companion_emails - $message['headers'] += $tbc_bcc_emails; - $user_data = user_load($params['example_deleted_user']['user_id']); - - $message['subject'] = t('[!site_name] User has deleted pending example', array('!site_name' => variable_get('site_name', '')), $language->language); - $message['body'] = t(' +!site_name Team, +FOSSEE,IIT Bombay', array( + '!site_name' => variable_get('site_name', ''), + '!user_name' => $user_data->name + )) + ); + break; + case 'example_deleted_user': + // bcc to textbook_companion_emails + //$message['headers'] += $tbc_bcc_emails; + $user_data = user_load($params['example_deleted_user']['user_id']); + $message['subject'] = t('[!site_name] User has deleted pending example for Textbook Companion', array( + '!site_name' => variable_get('site_name', '') + )); + $message['body'] = array( + 'body' => t(' Dear !user_name, Your following pending example has been deleted : @@ -1870,17 +3244,23 @@ Caption : ' . $params['example_deleted_user']['example_caption'] . ' Best Wishes, -!site_name', array('!site_name' => variable_get('site_name', ''), '!user_name' => $user_data->name), $language->language); - break; - - case 'dependency_uploaded': - // bcc to textbook_companion_emails - $message['headers'] += $tbc_bcc_emails; - $user_data = user_load($params['dependency_uploaded']['user_id']); - $dependency_files = implode(',', $params['dependency_uploaded']['dependency_names']); - - $message['subject'] = t('[!site_name] You have uploaded dependency file', array('!site_name' => variable_get('site_name', '')), $language->language); - $message['body'] = t(' +!site_name Team, +FOSSEE,IIT Bombay', array( + '!site_name' => variable_get('site_name', ''), + '!user_name' => $user_data->name + )) + ); + break; + case 'dependency_uploaded': + // bcc to textbook_companion_emails + //$message['headers'] += $tbc_bcc_emails; + $user_data = user_load($params['dependency_uploaded']['user_id']); + $dependency_files = implode(',', $params['dependency_uploaded']['dependency_names']); + $message['subject'] = t('[!site_name] You have uploaded dependency file', array( + '!site_name' => variable_get('site_name', '') + )); + $message['body'] = array( + 'body' => t(' Dear !user_name, You have uploaded following dependency files : @@ -1888,16 +3268,22 @@ You have uploaded following dependency files : Best Wishes, -!site_name', array('!site_name' => variable_get('site_name', ''), '!user_name' => $user_data->name), $language->language); - break; - - case 'feedback_received': - // bcc to textbook_companion_emails - $message['headers'] += $tbc_bcc_emails; - $user_data = user_load($params['feedback_received']['user_id']); - - $message['subject'] = t('[!site_name] We have received your feedback', array('!site_name' => variable_get('site_name', '')), $language->language); - $message['body'] = t(' +!site_name Team, +FOSSEE,IIT Bombay', array( + '!site_name' => variable_get('site_name', ''), + '!user_name' => $user_data->name + )) + ); + break; + case 'feedback_received': + // bcc to textbook_companion_emails + //$message['headers'] += $tbc_bcc_emails; + $user_data = user_load($params['feedback_received']['user_id']); + $message['subject'] = t('[!site_name] We have received your feedback', array( + '!site_name' => variable_get('site_name', '') + )); + $message['body'] = array( + 'body' => t(' Dear !user_name, We have received your following feedback @@ -1911,17 +3297,22 @@ Your feedback : Best Wishes, -!site_name', array('!site_name' => variable_get('site_name', ''), '!user_name' => $user_data->name), $language->language); - break; - - case 'internshipform': - // bcc to textbook_companion_emails - $message['headers'] += $tbc_bcc_emails; - - $user_data = user_load($params['internshipform']['user_id']); - - $message['subject'] = t('[!site_name] We have received your feedback', array('!site_name' => variable_get('site_name', '')), $language->language); - $message['body'] = t(' +!site_name Team, +FOSSEE,IIT Bombay', array( + '!site_name' => variable_get('site_name', ''), + '!user_name' => $user_data->name + )) + ); + break; + case 'internshipform': + // bcc to textbook_companion_emails + //$message['headers'] += $tbc_bcc_emails; + $user_data = user_load($params['internshipform']['user_id']); + $message['subject'] = t('[!site_name] We have received your feedback', array( + '!site_name' => variable_get('site_name', '') + )); + $message['body'] = array( + 'body' => t(' Dear !user_name, We have received your Internship Form Application for the book @@ -1932,17 +3323,22 @@ Example No.: ' . $params['internshipform']['example_no'] . ' Best Wishes, -!site_name', array('!site_name' => variable_get('site_name', ''), '!user_name' => $user_data->name), $language->language); - break; - -case 'copyrighttransferform': - // bcc to textbook_companion_emails - $message['headers'] += $tbc_bcc_emails; - - $user_data = user_load($params['copyrighttransferform']['user_id']); - - $message['subject'] = t('[!site_name] We have received your feedback', array('!site_name' => variable_get('site_name', '')), $language->language); - $message['body'] = t(' +!site_name Team, +FOSSEE,IIT Bombay', array( + '!site_name' => variable_get('site_name', ''), + '!user_name' => $user_data->name + )) + ); + break; + case 'copyrighttransferform': + // bcc to textbook_companion_emails + //$message['headers'] += $tbc_bcc_emails; + $user_data = user_load($params['copyrighttransferform']['user_id']); + $message['subject'] = t('[!site_name] We have received your feedback', array( + '!site_name' => variable_get('site_name', '') + )); + $message['body'] = array( + 'body' => t(' Dear !user_name, We have received your Copyright Form Application for the book @@ -1953,17 +3349,22 @@ Example No.: ' . $params['copyrighttransferform']['example_no'] . ' Best Wishes, -!site_name', array('!site_name' => variable_get('site_name', ''), '!user_name' => $user_data->name), $language->language); - break; - -case 'undertakingform': - // bcc to textbook_companion_emails - $message['headers'] += $tbc_bcc_emails; - - $user_data = user_load($params['undertakingform']['user_id']); - - $message['subject'] = t('[!site_name] We have received your feedback', array('!site_name' => variable_get('site_name', '')), $language->language); - $message['body'] = t(' +!site_name Team, +FOSSEE,IIT Bombay', array( + '!site_name' => variable_get('site_name', ''), + '!user_name' => $user_data->name + )) + ); + break; + case 'undertakingform': + // bcc to textbook_companion_emails + //$message['headers'] += $tbc_bcc_emails; + $user_data = user_load($params['undertakingform']['user_id']); + $message['subject'] = t('[!site_name] We have received your feedback', array( + '!site_name' => variable_get('site_name', '') + )); + $message['body'] = array( + 'body' => t(' Dear !user_name, We have received your Undertaking Form Application for the book @@ -1974,18 +3375,22 @@ Example No.: ' . $params['undertakingform']['example_no'] . ' Best Wishes, -!site_name', array('!site_name' => variable_get('site_name', ''), '!user_name' => $user_data->name), $language->language); - break; - - -case 'remark': - // bcc to textbook_companion_emails - $message['headers'] += $tbc_bcc_emails; - - $user_data = user_load($params['remark']['user_id']); - - $message['subject'] = t('[!site_name] A remark has been given.Please check your contact detail form', array('!site_name' => variable_get('site_name', '')), $language->language); - $message['body'] = t(' +!site_name Team, +FOSSEE,IIT Bombay', array( + '!site_name' => variable_get('site_name', ''), + '!user_name' => $user_data->name + )) + ); + break; + case 'remark': + // bcc to textbook_companion_emails + //$message['headers'] += $tbc_bcc_emails; + $user_data = user_load($params['remark']['user_id']); + $message['subject'] = t('[!site_name] A remark has been given.Please check your contact detail form', array( + '!site_name' => variable_get('site_name', '') + )); + $message['body'] = array( + 'body' => t(' Dear !user_name, A Remark has been given.Please check your Contact Detail Form @@ -1996,17 +3401,22 @@ Example No.: ' . $params['internshipform']['example_no'] . ' Best Wishes, -!site_name', array('!site_name' => variable_get('site_name', ''), '!user_name' => $user_data->name), $language->language); - break; - - case 'cheque_sent': - // bcc to textbook_companion_emails - $message['headers'] += $tbc_bcc_emails; - - $user_data = user_load($params['cheque_sent']['user_id']); - - $message['subject'] = t('[!site_name] We have received your feedback', array('!site_name' => variable_get('site_name', '')), $language->language); - $message['body'] = t(' +!site_name Team, +FOSSEE,IIT Bombay', array( + '!site_name' => variable_get('site_name', ''), + '!user_name' => $user_data->name + )) + ); + break; + case 'cheque_sent': + // bcc to textbook_companion_emails + //$message['headers'] += $tbc_bcc_emails; + $user_data = user_load($params['cheque_sent']['user_id']); + $message['subject'] = t('[!site_name] We have received your feedback', array( + '!site_name' => variable_get('site_name', '') + )); + $message['body'] = array( + 'body' => t(' Dear !user_name, We have Sent Cheque for the following book proposed @@ -2017,690 +3427,944 @@ Example No.: ' . $params['cheque_sent']['example_no'] . ' Best Wishes, -!site_name', array('!site_name' => variable_get('site_name', ''), '!user_name' => $user_data->name), $language->language); - break; - - - case 'standard': - // bcc to textbook_companion_emails - $message['headers'] += $tbc_bcc_emails; - $message['subject'] = $params['standard']['subject']; - $message['body'] = $params['standard']['body']; - break; - } +!site_name Team, +FOSSEE,IIT Bombay', array( + '!site_name' => variable_get('site_name', ''), + '!user_name' => $user_data->name + )) + ); + break; + case 'standard': + // bcc to textbook_companion_emails + //$message['headers'] += $tbc_bcc_emails; + $message['subject'] = $params['standard']['subject']; + $message['body'] = $params['standard']['body']; + break; + } } - /* AJAX CALLS */ function textbook_companion_ajax() { - $query_type = arg(2); - if ($query_type == 'chapter_title') - { - $chapter_number = arg(3); - $preference_id = arg(4); - $chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE number = %d AND preference_id = %d LIMIT 1", $chapter_number, $preference_id); - if ($chapter_data = db_fetch_object($chapter_q)) - { - echo $chapter_data->name; - return; - } - } else if ($query_type == 'example_exists') { - $chapter_number = arg(3); - $preference_id = arg(4); - $example_number = arg(5); - - $chapter_id = 0; - $chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE number = %d AND preference_id = %d LIMIT 1", $chapter_number, $preference_id); - if (!$chapter_data = db_fetch_object($chapter_q)) - { - echo ''; - return; - } else { - $chapter_id = $chapter_data->id; - } - - $example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE chapter_id = %d AND number = '%s' LIMIT 1", $chapter_id, $example_number); - if ($example_data = db_fetch_object($example_q)) - { - if ($example_data->approval_status == 1) - echo 'Warning! Example already approved. You cannot upload the same example again.'; - else - echo 'Warning! Example already uploaded. Delete the example and reupload it.'; - return; + $query_type = arg(2); + if ($query_type == 'chapter_title') { + $chapter_number = arg(3); + $preference_id = arg(4); + /*$chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE number = %d AND preference_id = %d LIMIT 1", $chapter_number, $preference_id);*/ + $query = db_select('textbook_companion_chapter'); + $query->fields('textbook_companion_chapter'); + $query->condition('number', $chapter_number); + $query->condition('preference_id', $preference_id); + $query->range(0, 1); + $chapter_q = $query->execute(); + if ($chapter_data = $chapter_q->fetchObject()) { + echo $chapter_data->name; + return; + } + } else if ($query_type == 'example_exists') { + $chapter_number = arg(3); + $preference_id = arg(4); + $example_number = arg(5); + $chapter_id = 0; + /* $chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE number = %d AND preference_id = %d LIMIT 1", $chapter_number, $preference_id);*/ + $query = db_select('textbook_companion_chapter'); + $query->fields('textbook_companion_chapter'); + $query->condition('number', $chapter_number); + $query->condition('preference_id', $preference_id); + $query->range(0, 1); + $chapter_q = $query->execute(); + if (!$chapter_data = $chapter_q->fetchObject()) { + echo ''; + return; + } else { + $chapter_id = $chapter_data->id; + } + /*$example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE chapter_id = %d AND number = '%s' LIMIT 1", $chapter_id, $example_number);*/ + $query = db_select('textbook_companion_example'); + $query->fields('textbook_companion_example'); + $query->condition('chapter_id', $chapter_id); + $query->condition('number', $example_number); + $query->range(0, 1); + $example_q = $query->execute(); + if ($example_data = $example_q->fetchObject()) { + if ($example_data->approval_status == 1) + echo 'Warning! Example already approved. You cannot upload the same example again.'; + else + echo 'Warning! Example already uploaded. Delete the example and reupload it.'; + return; + } } - } - echo ''; + echo ''; } - /*************************** VALIDATION FUNCTIONS *****************************/ -function textbook_companion_check_valid_filename($file_name) { - if (!preg_match('/^[0-9a-zA-Z\_\.]+$/', $file_name)) - return FALSE; - else - if (substr_count($file_name, ".") > 1) - return FALSE; +function textbook_companion_check_valid_filename($file_name) +{ + if (!preg_match('/^[0-9a-zA-Z\_\.]+$/', $file_name)) + return FALSE; + else if (substr_count($file_name, ".") > 1) + return FALSE; else - return TRUE; + return TRUE; } - -function check_name($name = '') { - if (!preg_match('/^[0-9a-zA-Z\ ]+$/', $name)) - return FALSE; - else - return TRUE; +function check_name($name = '') +{ + if (!preg_match('/^[0-9a-zA-Z\ ]+$/', $name)) + return FALSE; + else + return TRUE; } - -function check_chapter_number($name = '') { - if (!preg_match('/^([0-9])+(\.([0-9a-zA-Z])+)+$/', $name)) - return FALSE; - else - return TRUE; +function check_chapter_number($name = '') +{ + if (!preg_match('/^([0-9])+(\.([0-9a-zA-Z])+)+$/', $name)) + return FALSE; + else + return TRUE; } - -function textbook_companion_path() { - return $_SERVER['DOCUMENT_ROOT'] . base_path() . 'uploads/'; +function textbook_companion_path() +{ + return $_SERVER['DOCUMENT_ROOT'] . base_path() . 'dwsim_uploads/tbc_uploads/'; +} +function textbook_companion_temp_path() +{ + return $_SERVER['DOCUMENT_ROOT'] . base_path() . 'dwsim_uploads/'; +} +function textbook_companion_samplecode_path() +{ + return $_SERVER['DOCUMENT_ROOT'] . base_path() . 'dwsim_uploads/tbc_sample_code/'; } - /****************************** DELETION FUNCTIONS ****************************/ - function delete_example($example_id) { - global $user; - $root_path = textbook_companion_path(); - $status = TRUE; - - $example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE id = %d", $example_id); - $example_data = db_fetch_object($example_q); - if (!$example_data) - { - drupal_set_message(t('Invalid example.'), 'error'); - return FALSE; - } - - $chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE id = %d", $example_data->chapter_id); - $chapter_data = db_fetch_object($chapter_q); - if (!$chapter_data) - { - drupal_set_message(t('Invalid example chapter.'), 'error'); - return FALSE; - } - - /* deleting example files */ - $examples_files_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE example_id = %d", $example_id); - while ($examples_files_data = db_fetch_object($examples_files_q)) - { - if (!file_exists($root_path . $examples_files_data->filepath)) - { - $status = FALSE; - drupal_set_message(t('Error deleting !file. File does not exists.', array('!file' => $examples_files_data->filepath)), 'error'); - continue; + global $user; + $root_path = textbook_companion_path(); + $status = TRUE; + /*$example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE id = %d", $example_id); + $example_data = db_fetch_object($example_q);*/ + $query = db_select('textbook_companion_example'); + $query->fields('textbook_companion_example'); + $query->condition('id', $example_id); + $example_q = $query->execute(); + $example_data = $example_q->fetchObject(); + if (!$example_data) { + drupal_set_message(t('Invalid example.'), 'error'); + return FALSE; } - - /* removing example file */ - if (!unlink($root_path . $examples_files_data->filepath)) - { - $status = FALSE; - drupal_set_message(t('Error deleting !file', array('!file' => $examples_files_data->filepath)), 'error'); - - /* sending email to admins */ - $email_to = variable_get('textbook_companion_emails', ''); - $param['standard']['subject'] = "[ERROR] Error deleting example file"; - $param['standard']['body'] = "Error deleting example files by " . $user->uid . " at " . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . " : + /*$chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE id = %d", $example_data->chapter_id); + $chapter_data = db_fetch_object($chapter_q);*/ + $chapter_q = db_query("SELECT tcp.id as pref_id, tcp.directory_name, tcc.* +FROM textbook_companion_preference tcp +JOIN textbook_companion_chapter tcc +ON tcp.id= tcc.preference_id +WHERE tcc.id = :chapter_id", array( + ":chapter_id" => $example_data->chapter_id + )); + /*$query = db_select('textbook_companion_chapter'); + $query->fields('textbook_companion_chapter'); + $query->condition('id', $example_data->chapter_id); + $chapter_q = $query->execute();*/ + $chapter_data = $chapter_q->fetchObject(); + if (!$chapter_data) { + drupal_set_message(t('Invalid example chapter.'), 'error'); + return FALSE; + } + /* deleting example files */ + /*$examples_files_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE example_id = %d", $example_id);*/ + $query = db_select('textbook_companion_example_files'); + $query->fields('textbook_companion_example_files'); + $query->condition('example_id', $example_id); + $examples_files_q = $query->execute(); + while ($examples_files_data = $examples_files_q->fetchObject()) { + if (!file_exists($root_path . $chapter_data->directory_name . '/' . $examples_files_data->filepath)) { + $status = FALSE; + var_dump($root_path . $chapter_data->directory_name . '/' . $examples_files_data->filepath); + die; + drupal_set_message(t('Error deleting !file. File does not exists.', array( + '!file' => $examples_files_data->filepath + )), 'error'); + continue; + } + /* removing example file */ + if (!unlink($root_path . $chapter_data->directory_name . '/' . $examples_files_data->filepath)) { + $status = FALSE; + drupal_set_message(t('Error deleting !file', array( + '!file' => $examples_files_data->filepath + )), 'error'); + /* sending email to admins */ + $email_to = variable_get('textbook_companion_emails', ''); + $param['standard']['subject'] = "[ERROR] Error deleting example file"; + $param['standard']['body'] = "Error deleting example files by " . $user->uid . " at " . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . " : example id : " . $example_id . " - file id : " . $examples_files_data->id . " + file id : " . $examples_files_data->id . " file path : " . $examples_files_data->filepath; - if (!drupal_mail('textbook_companion', 'standard', $email_to, language_default(), $param, variable_get('textbook_companion_from_email', NULL), TRUE)) - drupal_set_message('Error sending email message.', 'error'); - } else { - /* deleting example files database entries */ - db_query("DELETE FROM {textbook_companion_example_files} WHERE id = %d", $examples_files_data->id); + if (!drupal_mail('textbook_companion', 'standard', $email_to, language_default(), $param, variable_get('textbook_companion_from_email', NULL), TRUE)) + drupal_set_message('Error sending email message.', 'error'); + } else { + /* deleting example files database entries */ + /*db_query("DELETE FROM {textbook_companion_example_files} WHERE id = %d", $examples_files_data->id);*/ + $query = db_delete('textbook_companion_example_files'); + $query->condition('id', $examples_files_data->id); + $num_deleted = $query->execute(); + } } - } - - if (!$status) - return FALSE; - - /* removing example folder */ - $ex_path = $chapter_data->preference_id . '/' . 'CH' . $chapter_data->number . '/' . 'EX' . $example_data->number; - $dir_path = $root_path . $ex_path; - if (is_dir($dir_path)) - { - if (!rmdir($dir_path)) - { - drupal_set_message(t('Error deleting folder !folder', array('!folder' => $dir_path)), 'error'); - - /* sending email to admins */ - $email_to = variable_get('textbook_companion_emails', ''); - $param['standard']['subject'] = "[ERROR] Error deleting folder"; - $param['standard']['body'] = "Error deleting folder " . $dir_path . " by " . $user->uid . " at " . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; - if (!drupal_mail('textbook_companion', 'standard', $email_to, language_default(), $param, variable_get('textbook_companion_from_email', NULL), TRUE)) - drupal_set_message('Error sending email message.', 'error'); - return FALSE; + if (!$status) + return FALSE; + /* removing example folder */ + $ex_path = $chapter_data->directory_name . '/' . 'CH' . $chapter_data->number . '/' . 'EX' . $example_data->number; + $dir_path = $root_path . $ex_path; + if (is_dir($dir_path)) { + if (!rmdir($dir_path)) { + drupal_set_message(t('Error deleting folder !folder', array( + '!folder' => $dir_path + )), 'error'); + /* sending email to admins */ + $email_to = variable_get('textbook_companion_emails', ''); + $param['standard']['subject'] = "[ERROR] Error deleting folder"; + $param['standard']['body'] = "Error deleting folder " . $dir_path . " by " . $user->uid . " at " . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; + if (!drupal_mail('textbook_companion', 'standard', $email_to, language_default(), $param, variable_get('textbook_companion_from_email', NULL), TRUE)) + drupal_set_message('Error sending email message.', 'error'); + return FALSE; + } + } else { + drupal_set_message(t('Cannot delete example folder. !folder does not exists.', array( + '!folder' => $dir_path + )), 'error'); + return FALSE; } - } else { - drupal_set_message(t('Cannot delete example folder. !folder does not exists.', array('!folder' => $dir_path)), 'error'); - return FALSE; - } - - /* deleting example dependency and exmaple database entries */ - db_query("DELETE FROM {textbook_companion_example_dependency} WHERE example_id = %d", $example_id); - db_query("DELETE FROM {textbook_companion_example} WHERE id = %d", $example_id); - - return $status; + /* deleting example dependency and exmaple database entries */ + /*db_query("DELETE FROM {textbook_companion_example_dependency} WHERE example_id = %d", $example_id);*/ + //$query = db_delete('textbook_companion_example_dependency'); + //$query->condition('example_id', $example_id); + //$num_deleted = $query->execute(); + /*db_query("DELETE FROM {textbook_companion_example} WHERE id = %d", $example_id);*/ + $query = db_delete('textbook_companion_example'); + $query->condition('id', $example_id); + $num_deleted = $query->execute(); + return $status; } - -function delete_chapter($chapter_id) +function delete_chapter($chapter_id) { - $status = TRUE; - $root_path = textbook_companion_path(); - - $chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE id = %d", $chapter_id); - $chapter_data = db_fetch_object($chapter_q); - if (!$chapter_data) - { - drupal_set_message('Invalid chapter.', 'error'); - return FALSE; - } - - /* deleting examples */ - $example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE chapter_id = %d", $chapter_id); - while ($example_data = db_fetch_object($example_q)) - { - if (!delete_example($example_data->id)) - $status = FALSE; - } - - if ($status) - { - $dir_path = $root_path . $chapter_data->preference_id . '/CH' . $chapter_data->number; - - if (is_dir($dir_path)) - { - $res = rmdir($dir_path); - if (!$res) - { - drupal_set_message(t('Error deleting chapter folder !folder', array('!folder' => $dir_path)), 'error'); - - /* sending email to admins */ - $email_to = variable_get('textbook_companion_emails', ''); - $param['standard']['subject'] = "[ERROR] Error deleting folder"; - $param['standard']['body'] = "Error deleting folder " . $dir_path; - if (!drupal_mail('textbook_companion', 'standard', $email_to, language_default(), $param, variable_get('textbook_companion_from_email', NULL), TRUE)) - drupal_set_message('Error sending email message.', 'error'); + $status = TRUE; + $root_path = textbook_companion_path(); + /*$chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE id = %d", $chapter_id); + $chapter_data = db_fetch_object($chapter_q);*/ + /*$query = db_select('textbook_companion_chapter'); + $query->fields('textbook_companion_chapter'); + $query->condition('id', $chapter_id); + $chapter_q = $query->execute(); + $chapter_data = $chapter_q->fetchObject();*/ + $chapter_q = db_query("SELECT tcp.id as pref_id, tcp.directory_name, tcc.* +FROM textbook_companion_preference tcp +JOIN textbook_companion_chapter tcc +ON tcp.id= tcc.preference_id +WHERE tcc.id = :chapter_id", array( + ":chapter_id" => $chapter_id + )); + $chapter_data = $chapter_q->fetchObject(); + if (!$chapter_data) { + drupal_set_message('Invalid chapter.', 'error'); return FALSE; - } else { - /* deleting chapter details from database */ - db_query("DELETE FROM {textbook_companion_chapter} WHERE id = %d", $chapter_id); - return TRUE; - } - } else { - drupal_set_message(t('Cannot delete chapter folder. !folder does not exists.', array('!folder' => $dir_path)), 'error'); - return FALSE; } - } - return FALSE; + /* deleting examples */ + /*$example_q = db_query("SELECT * FROM {textbook_companion_example} WHERE chapter_id = %d", $chapter_id);*/ + $query = db_select('textbook_companion_example'); + $query->fields('textbook_companion_example'); + $query->condition('chapter_id', $chapter_id); + $example_q = $query->execute(); + while ($example_data = $example_q->fetchObject()) { + if (!delete_example($example_data->id)) + $status = FALSE; + } + if ($status) { + $dir_path = $root_path . $chapter_data->directory_name . '/CH' . $chapter_data->number; + if (is_dir($dir_path)) { + $res = rmdir($dir_path); + if (!$res) { + drupal_set_message(t('Error deleting chapter folder !folder', array( + '!folder' => $dir_path + )), 'error'); + /* sending email to admins */ + $email_to = variable_get('textbook_companion_emails', ''); + $param['standard']['subject'] = "[ERROR] Error deleting folder"; + $param['standard']['body'] = "Error deleting folder " . $dir_path; + if (!drupal_mail('textbook_companion', 'standard', $email_to, language_default(), $param, variable_get('textbook_companion_from_email', NULL), TRUE)) + drupal_set_message('Error sending email message.', 'error'); + return FALSE; + } else { + /* deleting chapter details from database */ + /*db_query("DELETE FROM {textbook_companion_chapter} WHERE id = %d", $chapter_id);*/ + $query = db_delete('textbook_companion_chapter'); + $query->condition('id', $chapter_id); + $num_deleted = $query->execute(); + return TRUE; + } + } else { + drupal_set_message(t('Cannot delete chapter folder. !folder does not exists.', array( + '!folder' => $dir_path + )), 'error'); + return FALSE; + } + } + return FALSE; } - function delete_book($book_id) { - $status = TRUE; - $root_path = textbook_companion_path(); - - $preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d", $book_id); - $preference_data = db_fetch_object($preference_q); - if (!$preference_data) - { - drupal_set_message('Invalid book.', 'error'); - return FALSE; - } - - /* delete chapters */ - $chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE preference_id = %d", $preference_data->id); - while ($chapter_data = db_fetch_object($chapter_q)) - { - if (!delete_chapter($chapter_data->id)) - { - $status = FALSE; + $status = TRUE; + $root_path = textbook_companion_path(); + /*$preference_q = db_query("SELECT * FROM {textbook_companion_preference} WHERE id = %d", $book_id); + $preference_data = db_fetch_object($preference_q);*/ + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('id', $book_id); + $preference_q = $query->execute(); + $preference_data = $preference_q->fetchObject(); + if (!$preference_data) { + drupal_set_message('Invalid book.', 'error'); + return FALSE; + } + /* delete chapters */ + /*$chapter_q = db_query("SELECT * FROM {textbook_companion_chapter} WHERE preference_id = %d", $preference_data->id);*/ + $query = db_select('textbook_companion_chapter'); + $query->fields('textbook_companion_chapter'); + $query->condition('preference_id', $preference_data->id); + $chapter_q = $query->execute(); + while ($chapter_data = $chapter_q->fetchObject()) { + if (!delete_chapter($chapter_data->id)) { + $status = FALSE; + } } - } - return $status; + return $status; } - function delete_file($file_id) { - $root_path = textbook_companion_path(); - - $file_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE id = %d LIMIT 1", $file_id); - $file_data = db_fetch_object($file_q); - if (!$file_data) - { - drupal_set_message('Invalid file specified.', 'error'); - return FALSE; - } - - if (!file_exists($root_path . $file_data->filepath)) - { - drupal_set_message(t('Error deleting !file. File does not exists.', array('!file' => $file_data->filepath)), 'error'); - return FALSE; - } - - /* removing example file */ - if (!unlink($root_path . $file_data->filepath)) - { - drupal_set_message(t('Error deleting !file', array('!file' => $file_data->filepath)), 'error'); - - /* sending email to admins */ - $email_to = variable_get('textbook_companion_emails', ''); - $param['standard']['subject'] = "[ERROR] Error deleting file"; - $param['standard']['body'] = "Error deleting file by " . $user->uid . " at " . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . " : - file id : " . $file_id . " - file path : " . $file_data->filepath; - if (!drupal_mail('textbook_companion', 'standard', $email_to, language_default(), $param, variable_get('textbook_companion_from_email', NULL), TRUE)) - drupal_set_message('Error sending email message.', 'error'); - return FALSE; - } else { - /* deleting example files database entries */ - db_query("DELETE FROM {textbook_companion_example_files} WHERE id = %d", $file_id); - return TRUE; - } + $root_path = textbook_companion_path(); + /*$file_q = db_query("SELECT * FROM {textbook_companion_example_files} WHERE id = %d LIMIT 1", $file_id);*/ + $file_q = db_query("SELECT * FROM textbook_companion_preference tcp JOIN textbook_companion_chapter tcc ON tcp.id = tcc.preference_id JOIN textbook_companion_example tce ON tcc.id=tce.chapter_id JOIN textbook_companion_example_files tcef on tce.id = tcef.example_id WHERE tcef.id = :example_id", array( + ':example_id' => $file_id + )); + /*$query = db_select('textbook_companion_example_files'); + $query->fields('textbook_companion_example_files'); + $query->condition('id', $file_id); + $query->range(0, 1); + $file_q = $query->execute();*/ + $file_data = $file_q->fetchObject(); + if (!$file_data) { + drupal_set_message('Invalid file specified.', 'error'); + return FALSE; + } + if (!file_exists($root_path . $file_data->directory_name . '/' . $file_data->filepath)) { + drupal_set_message(t('Error deleting !file. File does not exists.', array( + '!file' => $file_data->filepath + )), 'error'); + return FALSE; + } + /* removing example file */ + if (!unlink($root_path . $file_data->directory_name . '/' . $file_data->filepath)) { + drupal_set_message(t('Error deleting !file', array( + '!file' => $file_data->filepath + )), 'error'); + /* sending email to admins */ + $email_to = variable_get('textbook_companion_emails', ''); + $param['standard']['subject'] = "[ERROR] Error deleting file"; + $param['standard']['body'] = "Error deleting file by " . $user->uid . " at " . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . " : + file id : " . $file_id . " + file path : " . $file_data->directory_name . '/' . $file_data->filepath; + if (!drupal_mail('textbook_companion', 'standard', $email_to, language_default(), $param, variable_get('textbook_companion_from_email', NULL), TRUE)) + drupal_set_message('Error sending email message.', 'error'); + return FALSE; + } else { + /* deleting example files database entries */ + /*db_query("DELETE FROM {textbook_companion_example_files} WHERE id = %d", $file_id);*/ + $query = db_delete('textbook_companion_example_files'); + $query->condition('id', $file_id); + $num_deleted = $query->execute(); + return TRUE; + } } - //Non aicte book proposal form - function book_proposal_nonaicte_form($form_state) { - - global $user; - - $form = array(); - $form['imp_notice'] = array( - '#type' => 'item', - '#value' => '<font color="red"><b>Please fill up this form carefully as the details entered here will be exactly written in the Textbook Companion and also follow the additional guidelines.</b></font>', - ); -// $form['guidelines'] = array( -// '#type' => 'fieldset', -// '#title' => t('Guidelines'), -// '#attributes' => array('style'=>'font-weight: bold'), -// '#collapsible' => TRUE, -// '#collapsed' => FALSE, -// ); -// $form['guidelines']['book'] = array( -// '#type' => 'item', -// '#required' => TRUE, -// '#value' => '<ul style="list-style-type:disc;font-weight: normal"> -// <li>All the fields are compulsory</li> -// <li>Proof (example: syllabus) to the usage/ popularity of the textbook must be provided in the references box below</li> -// <li>Please make sure that the book proposed by you has <b>at least 80</b> examples which include numerical computations and which can be coded in Scilab</li> -// <li>If the book has less than 80 examples the <a href="tbc_honorarium" target="_blank">honorarium</a> will be provided on a pro-rata basis </li> -// <li>Make sure the book you propose is not already an <a href="aicte_proposal" target="_blank">AICTE recommended book</a>, <a href="Completed_Books" target="_blank">completed book</a> -// or a <a href="Books_Progress" target="_blank">book in progress</a> </li> -// <li>You will be intimated about the approval or rejection of your suggestion via e-mail</li> - -// </ul> ', - -// ); - - - $form['full_name'] = array( - '#type' => 'textfield', - '#title' => t('Full Name'), - '#size' => 30, - '#maxlength' => 50, - '#required' => TRUE, - ); - $form['email_id'] = array( - '#type' => 'textfield', - '#title' => t('Email'), - '#size' => 30, - '#value' => $user->mail, - '#disabled' => TRUE, - ); - $form['mobile'] = array( - '#type' => 'textfield', - '#title' => t('Mobile No.'), - '#size' => 30, - '#maxlength' => 15, - '#required' => TRUE, - ); - $form['gender'] = array( - '#type' => 'radios', - '#title' => t('Gender'), - '#options' => array('M' => 'Male', 'F' => 'Female'), - '#required' => TRUE, - ); - - $form['how_project'] = array( - '#type' => 'select', - '#title' => t('How did you come to know about this project'), - '#options' => array('DWSIM Website' => 'DWSIM Website', - 'Friend' => 'Friend', - 'Professor/Teacher' => 'Professor/Teacher', - 'Mailing List' => 'Mailing List', - 'Poster in my/other college' => 'Poster in my/other college', - 'Others' => 'Others'), - '#required' => TRUE, - ); - $form['course'] = array( - '#type' => 'textfield', - '#title' => t('Course'), - '#size' => 30, - '#maxlength' => 50, - '#required' => TRUE, - ); - $form['branch'] = array( - '#type' => 'select', - '#title' => t('Department/Branch'), - '#options' => array('Electrical Engineering' => 'Electrical Engineering', - 'Electronics Engineering' => 'Electronics Engineering', - 'Computer Engineering' => 'Computer Engineering', - 'Chemical Engineering' => 'Chemical Engineering', - 'Instrumentation Engineering' => 'Instrumentation Engineering', - 'Mechanical Engineering' => 'Mechanical Engineering', - 'Civil Engineering' => 'Civil Engineering', - 'Physics' => 'Physics', - 'Mathematics' => 'Mathematics', - 'Others' => 'Others'), - '#required' => TRUE, - ); - $form['university'] = array( - '#type' => 'textfield', - '#title' => t('University/Institute'), - '#size' => 30, - '#maxlength' => 50, - '#required' => TRUE, - ); - $form['faculty'] = array( - '#type' => 'hidden', - '#value' => 'None', - '#title' => t('College Teacher/Professor'), - '#size' => 30, - '#maxlength' => 50, - '#required' => TRUE, - ); - $form['faculty_email'] = array( - '#type' => 'hidden', - '#value' => 'None', - '#title' => t('Teacher/Professor Email Id'), - '#default_value' => '@email.com', - '#size' => 30, - '#maxlength' => 50, - ); - $form['reviewer'] = array( - '#type' => 'hidden', - '#value' => 'None', - '#title' => t('Reviewer'), - '#size' => 30, - '#maxlength' => 50, - ); - - $form['version'] = array( - '#type' => 'textfield', - '#title' => t('Version'), - '#size' => 30, - '#value' => 'Dwsim 3.3', - '#disabled' => TRUE, - ); - // $form['version'] = array( - // '#type' => 'select', - // '#title' => t('Version'), - // '#options' => array('dwsim 3.3' => 'Dwsim 3.3', - // 'dwsim 3.2' => 'Dwsim 3.2', - // 'olderversion' => 'Older Version'), - // '#required' => TRUE, - // ); - $form['older'] = array( - '#type' => 'textfield', - '#size' => 30, - '#maxlength' => 50, - //'#required' => TRUE, - '#description' => t('Specify the Older version used'), - ); - $form['completion_date'] = array( - '#type' => 'textfield', - '#title' => t('Expected Date of Completion'), - '#description' => t('Input date format should be DD-MM-YYYY. Eg: 23-03-2011'), - '#size' => 10, - '#maxlength' => 10, - '#required' => TRUE, - ); - $form['operating_system'] = array( - '#type' => 'textfield', - '#title' => t('Operating System'), - '#required' => TRUE, - '#size' => 30, - '#maxlength' => 50, - ); - - $reason=array( - 'Used in more than one University' =>t('Used in more than one University'), - 'The book has multiple editions' => t('The book has multiple editions'), - 'Extremely useful' => t('Extremely useful'), - 'Other reason' => t('Any other reason state below') - ); - $form['reason'] = array( - '#type' => 'checkboxes', - '#title' => t('Reasons'), - '#options' => $reason, - '#required' => TRUE, - ); + global $user; + $form = array(); + $form['imp_notice'] = array( + '#type' => 'item', + '#markup' => '<font color="red"><b>Please fill up this form carefully as the details entered here will be exactly written in the Textbook Companion and also follow the additional guidelines.</b></font>' + ); + $form['guidelines'] = array( + '#type' => 'fieldset', + '#title' => t('Guidelines'), + '#attributes' => array( + 'style' => 'font-weight: bold' + ), + '#collapsible' => TRUE, + '#collapsed' => FALSE + ); + $form['guidelines']['book'] = array( + '#type' => 'item', + '#required' => TRUE, + '#markup' => '<ul style="list-style-type:disc;font-weight: normal"> + <li>All the fields are compulsory</li> + <li>Proof (example: syllabus) to the usage/ popularity of the textbook must be provided in the references box below</li> + <li>Please make sure that the book proposed by you has <b>at least 80</b> examples which include numerical computations and which can be coded in DWSIM</li> + <li>If the book has less than 80 examples the <a href="tbc_honorarium" target="_blank">honorarium</a> will be provided on a pro-rata basis </li> + <li>Make sure the book you propose is not already an <a href="aicte_proposal" target="_blank">AICTE recommended book</a>, <a href="Completed_Books" target="_blank">completed book</a> + or a <a href="Books_Progress" target="_blank">book in progress</a> </li> + <li>You will be intimated about the approval or rejection of your suggestion via e-mail</li> + +</ul> ' + ); + $form['full_name'] = array( + '#type' => 'textfield', + '#title' => t('Full Name'), + '#size' => 30, + '#maxlength' => 50, + '#required' => TRUE + ); + $form['email_id'] = array( + '#type' => 'textfield', + '#title' => t('Email'), + '#size' => 30, + '#value' => $user->mail, + '#disabled' => TRUE + ); + $form['mobile'] = array( + '#type' => 'textfield', + '#title' => t('Mobile No.'), + '#size' => 30, + '#maxlength' => 15, + '#required' => TRUE + ); + $form['gender'] = array( + '#type' => 'radios', + '#title' => t('Gender'), + '#options' => array( + 'M' => 'Male', + 'F' => 'Female' + ), + '#required' => TRUE + ); + $form['how_project'] = array( + '#type' => 'select', + '#title' => t('How did you come to know about this project'), + '#options' => array( + 'DWSIM Website' => 'DWSIM Website', + 'Friend' => 'Friend', + 'Professor/Teacher' => 'Professor/Teacher', + 'Mailing List' => 'Mailing List', + 'Poster in my/other college' => 'Poster in my/other college', + 'Others' => 'Others' + ), + '#required' => TRUE + ); + $form['course'] = array( + '#type' => 'textfield', + '#title' => t('Course'), + '#size' => 30, + '#maxlength' => 50, + '#required' => TRUE + ); + $form['department'] = array( + '#type' => 'select', + '#title' => t('Department/Branch'), + '#options' => _list_of_departments(), + '#required' => TRUE + ); + $form['university'] = array( + '#type' => 'textfield', + '#title' => t('University/ Institute'), + '#size' => 80, + '#maxlength' => 200, + '#required' => TRUE, + '#attributes' => array( + 'placeholder' => 'Insert full name of your institute/ university.... ' + ) + ); + $form['country'] = array( + '#type' => 'select', + '#title' => t('Country'), + '#options' => array( + 'India' => 'India', + 'Others' => 'Others' + ), + '#required' => TRUE + //'#tree' => TRUE, + // '#validated' => TRUE, + ); + $form['other_country'] = array( + '#type' => 'textfield', + '#title' => t('Other than India'), + '#size' => 100, + '#attributes' => array( + 'placeholder' => t('Enter your country name') + ), + '#states' => array( + 'visible' => array( + ':input[name="country"]' => array( + 'value' => 'Others' + ) + ) + ) + ); + $form['other_state'] = array( + '#type' => 'textfield', + '#title' => t('State other than India'), + '#size' => 100, + '#attributes' => array( + 'placeholder' => t('Enter your state/region name') + ), + '#states' => array( + 'visible' => array( + ':input[name="country"]' => array( + 'value' => 'Others' + ) + ) + ) + ); + $form['other_city'] = array( + '#type' => 'textfield', + '#title' => t('City other than India'), + '#size' => 100, + '#attributes' => array( + 'placeholder' => t('Enter your city name') + ), + '#states' => array( + 'visible' => array( + ':input[name="country"]' => array( + 'value' => 'Others' + ) + ) + ) + ); + $form['all_state'] = array( + '#type' => 'select', + '#title' => t('State'), + '#options' => _list_of_states(), + '#validated' => TRUE, + '#states' => array( + 'visible' => array( + ':input[name="country"]' => array( + 'value' => 'India' + ) + ) + ) + ); + $form['city'] = array( + '#type' => 'select', + '#title' => t('City'), + '#options' => _list_of_cities(), + '#states' => array( + 'visible' => array( + ':input[name="country"]' => array( + 'value' => 'India' + ) + ) + ) + ); + $form['pincode'] = array( + '#type' => 'textfield', + '#title' => t('Pincode'), + '#size' => 30, + '#maxlength' => 6, + '#required' => False, + '#attributes' => array( + 'placeholder' => 'Enter pincode....' + ) + ); + /***************************************************************************/ + $form['hr'] = array( + '#type' => 'item', + '#markup' => '<hr>' + ); + $form['faculty'] = array( + '#type' => 'hidden', + '#value' => 'None', + '#title' => t('College Teacher/Professor'), + '#size' => 30, + '#maxlength' => 50, + '#required' => TRUE + ); + $form['faculty_email'] = array( + '#type' => 'hidden', + '#value' => 'None', + '#title' => t('Teacher/Professor Email Id'), + '#value' => '@email.com', + '#size' => 30, + '#maxlength' => 50 + ); + $form['reviewer'] = array( + '#type' => 'hidden', + '#value' => 'None', + '#title' => t('Reviewer'), + '#size' => 30, + '#maxlength' => 50 + ); + $form['version'] = array( + '#type' => 'hidden', + '#default_value' => 'Not available' + ); + $form['version'] = array( + '#type' => 'select', + '#title' => t('Version'), + '#options' => _list_of_software_version(), + '#required' => TRUE + ); + $form['older'] = array( + '#type' => 'textfield', + '#size' => 30, + '#maxlength' => 50, + //'#required' => TRUE, + '#description' => t('Specify the Older version used') + ); + $form['completion_date'] = array( + '#type' => 'textfield', + '#title' => t('Expected Date of Completion'), + '#description' => t('Input date format should be DD-MM-YYYY. Eg: 23-03-2011'), + '#size' => 10, + '#maxlength' => 10, + '#required' => TRUE + ); + $form['operating_system'] = array( + '#type' => 'textfield', + '#title' => t('Operating System'), + '#required' => TRUE, + '#size' => 30, + '#maxlength' => 50 + ); + $reason = array( + 'Used in more than one University' => t('Used in more than one University'), + 'The book has multiple editions' => t('The book has multiple editions'), + 'Extremely useful' => t('Extremely useful'), + 'Other reason' => t('Any other reason state below') + ); + $form['reason'] = array( + '#type' => 'checkboxes', + '#title' => t('Reasons'), + '#options' => $reason, + '#required' => TRUE + ); $form['other_reason'] = array( - '#type' => 'textarea', - '#size' => 300, - '#maxlength' => 300, - //'#required' => FALSE, - ); - $form['proposal_type'] = array( - '#type' => 'hidden', - '#default_value' => '1', - '#required' => FALSE, - ); - $form['reference'] = array( - '#type' => 'textarea', - '#title' => t('Reference'), - '#required' => TRUE, - '#size' => 500, - '#maxlength' => 500, - '#attributes' =>array('placeholder' =>'Links of the syllabus must be provided....'), - ); - $form['preference1'] = array( - '#type' => 'fieldset', - '#title' => t('Book Preference'), - '#collapsible' => TRUE, - '#collapsed' => FALSE, - ); - $form['preference1']['book1'] = array( - '#type' => 'textfield', - '#title' => t('Title of the book'), - '#size' => 30, - '#maxlength' => 100, - '#required' => TRUE, - '#value' => $row1->book, - '#disabled' => ($row1->book?TRUE:FALSE), - ); - $form['preference1']['author1'] = array( - '#type' => 'textfield', - '#title' => t('Author Name'), - '#size' => 30, - '#maxlength' => 100, - '#required' => TRUE, - '#value' => $row1->author, - '#disabled' => ($row1->author?TRUE:FALSE), - ); - $form['preference1']['isbn1'] = array( - '#type' => 'textfield', - '#title' => t('ISBN No'), - '#size' => 30, - '#maxlength' => 25, - '#required' => TRUE, - '#value' => $row1->isbn, - '#disabled' => ($row1->isbn?TRUE:FALSE), - ); - $form['preference1']['publisher1'] = array( - '#type' => 'textfield', - '#title' => t('Publisher & Place'), - '#size' => 30, - '#maxlength' => 50, - '#required' => TRUE, - '#value' => $row1->publisher, - ); - $form['preference1']['edition1'] = array( - '#type' => 'textfield', - '#title' => t('Edition'), - '#size' => 4, - '#maxlength' => 2, - '#required' => TRUE, - '#value' => $row1->edition, - ); - $form['preference1']['year1'] = array( - '#type' => 'textfield', - '#title' => t('Year of pulication'), - '#size' => 4, - '#maxlength' => 4, + '#type' => 'textarea', + '#size' => 300, + '#maxlength' => 300 + //'#required' => FALSE, + ); + $form['proposal_type'] = array( + '#type' => 'hidden', + '#value' => '1', + '#required' => FALSE + ); + $form['reference'] = array( + '#type' => 'textarea', + '#title' => t('Reference'), + '#required' => TRUE, + '#size' => 500, + '#maxlength' => 500, + '#attributes' => array( + 'placeholder' => 'Links of the syllabus must be provided....' + ) + ); + $form['preference1'] = array( + '#type' => 'fieldset', + '#title' => t('Book Preference'), + '#collapsible' => TRUE, + '#collapsed' => FALSE + ); + $form['preference1']['book1'] = array( + '#type' => 'textfield', + '#title' => t('Title of the book'), + '#size' => 30, + '#maxlength' => 100, + '#required' => TRUE, + '#value' => $row1->book, + '#disabled' => ($row1->book ? TRUE : FALSE) + ); + $form['preference1']['author1'] = array( + '#type' => 'textfield', + '#title' => t('Author Name'), + '#size' => 30, + '#maxlength' => 100, + '#required' => TRUE, + '#value' => $row1->author, + '#disabled' => ($row1->author ? TRUE : FALSE) + ); + $form['preference1']['isbn1'] = array( + '#type' => 'textfield', + '#title' => t('ISBN No'), + '#size' => 30, + '#maxlength' => 25, + '#required' => TRUE, + '#value' => $row1->isbn, + '#disabled' => ($row1->isbn ? TRUE : FALSE) + ); + $form['preference1']['publisher1'] = array( + '#type' => 'textfield', + '#title' => t('Publisher & Place'), + '#size' => 30, + '#maxlength' => 50, + '#required' => TRUE, + '#value' => $row1->publisher + ); + $form['preference1']['edition1'] = array( + '#type' => 'textfield', + '#title' => t('Edition'), + '#size' => 4, + '#maxlength' => 2, + '#required' => TRUE, + '#value' => $row1->edition + ); + $form['preference1']['year1'] = array( + '#type' => 'textfield', + '#title' => t('Year of publication'), + '#size' => 4, + '#maxlength' => 4, + '#required' => TRUE, + '#value' => $row1->year + ); + /*$form['termconditions'] = array( + '#type' => 'checkboxes', + '#title' => t('Terms And Conditions'), + '#options' => array( + 'status' => t('<a href="term-and-conditions" target="_blank">I agree to the Terms and Conditions</a>'),), '#required' => TRUE, - '#value' => $row1->year, - ); - - - $form['termconditions'] = array( - '#type' => 'checkboxes', - '#title' => t('Terms And Conditions'), - '#options' => array( - 'status' => t('<a href="term-and-conditions" target="_blank">I agree to the Terms and Conditions</a>'),), - '#required' => TRUE, - ); - $form['submit'] = array( - '#type' => 'submit', - '#value' => t('Submit') - ); - - /* #value fix for #default_value bug drupal6 */ - foreach(array("preference1") as $preference) { + );*/ + $form['submit'] = array( + '#type' => 'submit', + '#value' => t('Submit') + ); + /* #value fix for #default_value bug drupal6 + foreach(array("preference1") as $preference) { foreach($form[$preference] as $key => $value) { - if(!$form[$preference][$key]["#value"]) { - unset($form[$preference][$key]["#value"]); - } + if(!$form[$preference][$key]["#value"]) { + unset($form[$preference][$key]["#value"]); } - } - - return $form; + } + }*/ + return $form; } - function book_proposal_nonaicte_form_submit($form, &$form_state) { - global $user; - $selections = variable_get("aicte_".$user->uid, ""); - $tbc_to_emails = variable_get("textbook_companion_emails_all", ""); - - - if (!$user->uid) { - drupal_set_message('It is mandatory to login on this website to access the proposal form', 'error'); - return; - } - - /* completion date */ - list($d, $m, $y) = explode('-', $form_state['values']['completion_date']); - $con_date = $y.'-'.$m.'-'.$d; - $date = new DateTime($con_date); - $expected_completion_date = $date->format('Y-m-d'); - // var_dump($expected_completion_date) ; - - $dt = new DateTime(); - $current_date = $dt->format("Y-m-d"); - - /* Reasons for suggesting a book*/ - - - if (isset($_POST['reason'])) { - - if(!($form_state['values']['other_reason'])){ - - $my_reason = implode(", ", $_POST['reason']); - + global $user; + $selections = variable_get("aicte_" . $user->uid, ""); + $tbc_to_emails = variable_get("textbook_companion_emails_all"); + if (!$user->uid) { + drupal_set_message('It is mandatory to login on this website to access the proposal form', 'error'); + return; } - - else{ - $my_reason = implode(", ", $_POST['reason']); - $my_reason = $my_reason."-"." ".$form_state['values']['other_reason']; + /* completion date to timestamp */ + list($d, $m, $y) = explode('-', $form_state['values']['completion_date']); + $completion_date_timestamp = mktime(0, 0, 0, $m, $d, $y); + /* Reasons for suggesting a book*/ + if (isset($_POST['reason'])) { + if (!($form_state['values']['other_reason'])) { + $my_reason = implode(", ", $_POST['reason']); + } else { + $my_reason = implode(", ", $_POST['reason']); + $my_reason = $my_reason . "-" . " " . $form_state['values']['other_reason']; + } + $form_state['values']['other_reason'] = $my_reason; } - } - - /************************************/ - - - $dwsim_version = $form_state['values']['version']; - - if($form_state['values']['version'] == 'olderversion'){ - $dwsim_version = $form_state['values']['older']; - } - - var_dump($form_state['values']); - - $query = "INSERT INTO {textbook_companion_proposal} - (uid, approver_uid, full_name, mobile, gender, how_project, course, branch, university, faculty, reviewer, reference, expected_completion_date, creation_date, approval_date, proposal_status, dwsim_version, operating_system, teacher_email, proposal_type, reason ) VALUES (".$user->uid.", 0, '".ucwords(strtolower($form_state['values']['full_name']))."', '".$form_state['values']['mobile']."', '".$form_state['values']['gender']."', '".$form_state['values']['how_project']."', '".$form_state['values']['course']."', '".$form_state['values']['branch']."', '".$form_state['values']['university']."', '".ucwords(strtolower($form_state['values']['faculty']))."', '".ucwords(strtolower($form_state['values']['reviewer']))."', '".strtolower($form_state['values']['reference'])."', '".$expected_completion_date."', '".$current_date."', 0, 0, '".$dwsim_version."', '".$form_state['values']['operating_system']."', '".$form_state['values']['faculty_email']."','".$form_state['values']['proposal_type']."','".$my_reason."')"; - - $result = db_query($query); - if (!$result) - { - drupal_set_message(t('Error receiving your proposal. Please try again.'), 'error'); - return; - } - /* proposal id */ - $proposal_id = db_last_insert_id('textbook_companion_proposal', 'id'); - - /* inserting first book preference */ - if ($form_state['values']['book1']) - { - $result = db_query("INSERT INTO {textbook_companion_preference} + /************************************/ + $dwsim_version = $form_state['values']['version']; + if ($form_state['values']['version'] == 'olderversion') { + $dwsim_version = $form_state['values']['older']; + } + $form_state['values']['version'] = $dwsim_version; + //var_dump($form_state['values']); + /*$query = "INSERT INTO {textbook_companion_proposal} + (uid, approver_uid, full_name, mobile, gender, how_project, course, branch, university, faculty, reviewer, reference, completion_date, creation_date, approval_date, proposal_status, scilab_version, operating_system, teacher_email, proposal_type, reason ) VALUES (".$user->uid.", 0, '".ucwords(strtolower($form_state['values']['full_name']))."', '".$form_state['values']['mobile']."', '".$form_state['values']['gender']."', '".$form_state['values']['how_project']."', '".$form_state['values']['course']."', '".$form_state['values']['branch']."', '".$form_state['values']['university']."', '".ucwords(strtolower($form_state['values']['faculty']))."', '".ucwords(strtolower($form_state['values']['reviewer']))."', '".strtolower($form_state['values']['reference'])."', '".$completion_date_timestamp."', '".time()."', 0, 0, '".$scilab_version."', '".$form_state['values']['operating_system']."', '".$form_state['values']['faculty_email']."','".$form_state['values']['proposal_type']."','".$my_reason."')";*/ + $query = "INSERT INTO {textbook_companion_proposal} + (uid, approver_uid, full_name, mobile, gender, how_project, course, branch, university,city,pincode,state,faculty, reviewer, reference, completion_date, creation_date,approval_date, proposal_status, version, operating_system, teacher_email, proposal_type, reason ) VALUES (:uid, :approver_uid, :full_name, :mobile, :gender, :how_project, :course, :branch, :university,:city,:pincode,:state, :faculty, :reviewer, :reference, +:expected_completion_date, :actual_completion_date,:creation_date,:message, :approval_date, :proposal_status, :dwsim_version, :operating_system, :teacher_email, +:proposal_type, :reason)"; + $args = array( + "uid" => $user->uid, + "approver_uid" => 0, + "full_name" => ucwords(strtolower($form_state['values']['full_name'])), + "mobile" => $form_state['values']['mobile'], + "gender" => $form_state['values']['gender'], + "how_project" => $form_state['values']['how_project'], + "course" => $form_state['values']['course'], + "branch" => $form_state['values']['branch'], + "university" => $form_state['values']['university'], + ":city" => $form_state['values']['city'], + ":pincode" => $form_state['values']['pincode'], + ":state" => $form_state['values']['all_state'], + "faculty" => ucwords(strtolower($form_state['values']['faculty'])), + "reviewer" => ucwords(strtolower($form_state['values']['reviewer'])), + "reference" => strtolower($form_state['values']['reference']), + "completion_date" => $completion_date_timestamp, + "creation_date" => time(), + "approval_date" => time(), + "proposal_status" => 0, + "dwsim_version" => $dwsim_version, + "operating_system" => $form_state['values']['operating_system'], + "teacher_email" => $form_state['values']['faculty_email'], + "proposal_type" => $form_state['values']['proposal_type'], + "reason" => $my_reason + ); + $result = db_query($query, $args, array( + 'return' => Database::RETURN_INSERT_ID + )); + if (!$result) { + drupal_set_message(t('Error receiving your proposal. Please try again.'), 'error'); + return; + } + /* proposal id */ + $proposal_id = db_last_insert_id('textbook_companion_proposal', 'id'); + /* inserting first book preference */ + if ($form_state['values']['book1']) { + /*$result = db_query("INSERT INTO {textbook_companion_preference} + (proposal_id, pref_number, book, author, isbn, publisher, edition, year, category, approval_status, nonaicte_book) VALUES + (%d, %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d)", + $proposal_id, + 1, + ucwords(strtolower($form_state['values']['book1'])), + ucwords(strtolower($form_state['values']['author1'])), + $form_state['values']['isbn1'], + ucwords(strtolower($form_state['values']['publisher1'])), + $form_state['values']['edition1'], + $form_state['values']['year1'], + 0, + 0, + 1 + );*/ + $query = "INSERT INTO {textbook_companion_preference} (proposal_id, pref_number, book, author, isbn, publisher, edition, year, category, approval_status, nonaicte_book) VALUES - (%d, %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d)", - $proposal_id, - 1, - ucwords(strtolower($form_state['values']['book1'])), - ucwords(strtolower($form_state['values']['author1'])), - $form_state['values']['isbn1'], - ucwords(strtolower($form_state['values']['publisher1'])), - $form_state['values']['edition1'], - $form_state['values']['year1'], - 0, - 0, - 1 - ); - if (!$result) - { - drupal_set_message(t('Error receiving your first book preference.'), 'error'); + (:proposal_id, :pref_number, :book, :author, :isbn, :publisher, :edition, :year, :category, :approval_status, :nonaicte_book)"; + $args = array( + ":proposal_id" => $proposal_id, + ":pref_number" => 1, + ":book" => ucwords(strtolower($form_state['values']['book1'])), + ":author" => ucwords(strtolower($form_state['values']['author1'])), + ":isbn" => $form_state['values']['isbn1'], + ":publisher" => ucwords(strtolower($form_state['values']['publisher1'])), + ":edition" => $form_state['values']['edition1'], + ":year" => $form_state['values']['year1'], + ":category" => 0, + ":approval_status" => 0, + ":nonaicte_book" => 1 + ); + $result = db_query($query, $args, array( + 'return' => Database::RETURN_INSERT_ID + )); + if (!$result) { + drupal_set_message(t('Error receiving your first book preference.'), 'error'); + } } - } - - /* sending email */ - $email_to = $user->mail; - $param['proposal_received']['proposal_id'] = $proposal_id; - $param['proposal_received']['user_id'] = $user->uid; - if (!drupal_mail('textbook_companion', 'nonaicte_proposal_received', $email_to , language_default(), $param, variable_get('textbook_companion_from_email', NULL), TRUE)) - drupal_set_message('Error sending email message.', 'error'); - if (!drupal_mail('textbook_companion', 'nonaicte_proposal_to_pi', $tbc_to_emails, language_default(), $param, variable_get('textbook_companion_from_email', NULL), TRUE)) - drupal_set_message('Error sending email message.', 'error'); - - drupal_set_message(t('We have received your book proposal. We will get back to you soon.'), 'status'); - drupal_goto(''); + /* sending email */ + $email_to = $user->mail; + $param['proposal_received']['proposal_id'] = $proposal_id; + $param['proposal_received']['user_id'] = $user->uid; + if (!drupal_mail('textbook_companion', 'nonaicte_proposal_received', $email_to, language_default(), $param, variable_get('textbook_companion_from_email', NULL), TRUE)) + drupal_set_message('Error sending email message.', 'error'); + if (!drupal_mail('textbook_companion', 'nonaicte_proposal_to_pi', $tbc_to_emails, language_default(), $param, variable_get('textbook_companion_from_email', NULL), TRUE)) + drupal_set_message('Error sending email message.', 'error'); + drupal_set_message(t('We have received your book proposal. We will get back to you soon.'), 'status'); + drupal_goto(''); } - // - function del_book_pdf($book_id) { - $root_path = textbook_companion_path(); - $dir_path = $root_path . "latex/"; - $pdf_filename = "book_" . $book_id . ".pdf"; - if (file_exists($dir_path . $pdf_filename)) - unlink($dir_path . $pdf_filename); + $root_path = textbook_companion_path(); + $dir_path = $root_path . "latex/"; + $pdf_filename = "book_" . $book_id . ".pdf"; + if (file_exists($dir_path . $pdf_filename)) + unlink($dir_path . $pdf_filename); +} +function _list_of_software_version() +{ + $software_version = array(); + $query = db_select('dwsim_software_version'); + $query->fields('dwsim_software_version'); + $query->orderBy('dwsim_version', 'ASC'); + $software_version_list = $query->execute(); + while ($software_version_list_data = $software_version_list->fetchObject()) { + $software_version[$software_version_list_data->dwsim_version] = $software_version_list_data->dwsim_version; + } + return $software_version; } -function textbook_companion_init(){ - //drupal_add_css('http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css', array('type' => 'external')); - //drupal_add_js('http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css', array('type' => 'external')); - //drupal_add_js(drupal_get_path('module', 'textbook_companion') .'/js/jquery-ui.js'); - //drupal_add_js(drupal_get_path('module', 'textbook_companion') .'/js/jquery.js'); - drupal_add_css(drupal_get_path('module', 'textbook_companion') .'/css/textbook_companion.css'); - drupal_add_js(drupal_get_path('module', 'textbook_companion') .'/js/textbook_companion.js'); - - +function _list_of_departments() +{ + $department = array(); + $query = db_select('list_of_departments'); + $query->fields('list_of_departments'); + $query->orderBy('id', 'DESC'); + $department_list = $query->execute(); + while ($department_list_data = $department_list->fetchObject()) { + $department[$department_list_data->department] = $department_list_data->department; + } + return $department; +} +function _list_of_states() +{ + $states = array( + '' => '-select-' + ); + $query = db_select('list_states_of_india'); + $query->fields('list_states_of_india'); + //$query->orderBy('', ''); + $states_list = $query->execute(); + while ($states_list_data = $states_list->fetchObject()) { + $states[$states_list_data->state] = $states_list_data->state; + } + return $states; +} +function _list_of_cities() +{ + $city = array( + '' => '-select-' + ); + $query = db_select('list_cities_of_india'); + $query->fields('list_cities_of_india'); + $query->orderBy('city', 'ASC'); + $city_list = $query->execute(); + while ($city_list_data = $city_list->fetchObject()) { + $city[$city_list_data->city] = $city_list_data->city; + } + return $city; +} +/*************************************************************************/ +/***** Function To convert only first charater of string in uppercase ****/ +/*************************************************************************/ +/*function ucname($string) { +$string =ucwords(strtolower($string)); + +foreach (array('-', '\'') as $delimiter) { +if (strpos($string, $delimiter)!==false) { +$string =implode($delimiter, array_map('ucfirst', explode($delimiter, $string))); +} +} +return $string; +}*/ +function _dir_name($book, $author, $pref_id) +{ + if (!$pref_id) { + $book_title = ucname($book); + $author = ucname($author); + $dir_name = $book_title . " " . "by" . " " . $author; + $directory_name = str_replace("__", "_", str_replace(" ", "_", $dir_name)); + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('directory_name', $directory_name); + $query->condition('approval_status', 1); + $result = $query->execute()->rowCount(); + if ($result > 0) { + //var_dump('this');die; + form_set_error('', t('Book is already allotted. Please try another book or contact to administrator')); + return; + } + } else { + $book_title = ucname($book); + $author = ucname($author); + $dir_name = $book_title . " " . "by" . " " . $author; + $directory_name = str_replace("__", "_", str_replace(" ", "_", $dir_name)); + $query = db_select('textbook_companion_preference'); + $query->fields('textbook_companion_preference'); + $query->condition('directory_name', $directory_name); + $query->condition('id', $pref_id); + $result = $query->execute()->rowCount(); + if ($result > 1) { + form_set_error('', t('Book is already present. Please try another book or contact to administrator')); + return; + } + } + return $directory_name; } |