From 1206043caff3c489121aaf5a825e07008147714b Mon Sep 17 00:00:00 2001
From: Mayur Jadhav <mayur@mayur-desktop.(none)>
Date: Thu, 14 Mar 2013 13:06:42 +0530
Subject: [PATCH] initial commit of all code after repository gets created.

---
 CRM/Grant/BAO/EntityPayment.php               | 108 +++
 CRM/Grant/BAO/Grant.php                       | 567 ++++++++++++
 CRM/Grant/BAO/GrantPayment.php                | 339 +++++++
 CRM/Grant/BAO/GrantProgram.php                | 215 +++++
 CRM/Grant/BAO/PaymentSearch.php               | 864 ++++++++++++++++++
 CRM/Grant/BAO/Query.php                       | 428 +++++++++
 CRM/Grant/Config.php                          |  43 +
 CRM/Grant/Controller/PaymentSearch.php        |  72 ++
 CRM/Grant/DAO/EntityPayment.php               | 257 ++++++
 CRM/Grant/DAO/Grant.php                       | 437 +++++++++
 CRM/Grant/DAO/GrantPayment.php                | 413 +++++++++
 CRM/Grant/DAO/GrantProgram.php                | 389 ++++++++
 CRM/Grant/Form/Grant.php                      | 446 +++++++++
 CRM/Grant/Form/GrantProgram.php               | 219 +++++
 CRM/Grant/Form/GrantProgramView.php           | 293 ++++++
 CRM/Grant/Form/Payment/View.php               | 141 +++
 CRM/Grant/Form/PaymentSearch.php              | 475 ++++++++++
 CRM/Grant/Form/PaymentTask.php                | 170 ++++
 CRM/Grant/Form/Search.php                     | 454 +++++++++
 CRM/Grant/Form/Search.php~                    | 454 +++++++++
 CRM/Grant/Form/Task/Cancel.php                | 119 +++
 CRM/Grant/Form/Task/GrantPayment.php          | 383 ++++++++
 CRM/Grant/Form/Task/Pay.php                   | 149 +++
 CRM/Grant/Form/Task/Reprint.php               | 319 +++++++
 CRM/Grant/Form/Task/SearchTaskHookSample.php  |  95 ++
 CRM/Grant/Form/Task/Update.php                | 135 +++
 CRM/Grant/Info.php                            | 125 +++
 CRM/Grant/Page/DashBoard.php                  |  85 ++
 CRM/Grant/Page/GrantProgram.php               | 143 +++
 CRM/Grant/Page/Payment.php                    |  97 ++
 CRM/Grant/PaymentTask.php                     | 161 ++++
 CRM/Grant/PseudoConstant.php                  | 126 +++
 CRM/Grant/Selector/PaymentSearch.php          | 418 +++++++++
 CRM/Grant/Selector/Search.php                 | 487 ++++++++++
 CRM/Grant/StateMachine/PaymentSearch.php      | 117 +++
 CRM/Grant/StateMachine/Search.php             | 117 +++
 CRM/Grant/Task.php                            | 173 ++++
 CRM/Grant/Words.php                           | 158 ++++
 CRM/Grant/xml/Menu/Grant.xml                  |  92 ++
 grantprograms.civix.php                       | 169 ++++
 grantprograms.php                             | 154 ++++
 info.xml                                      |  21 +
 templates/CRM/Grant/Form/Grant.tpl            | 173 ++++
 templates/CRM/Grant/Form/GrantProgram.tpl     |  88 ++
 templates/CRM/Grant/Form/GrantProgramView.tpl | 164 ++++
 templates/CRM/Grant/Form/GrantView.extra.tpl  |  83 ++
 templates/CRM/Grant/Form/GrantViewaaa.php     | 151 +++
 templates/CRM/Grant/Form/Payment/View.tpl     |  96 ++
 templates/CRM/Grant/Form/PaymentSearch.tpl    | 113 +++
 templates/CRM/Grant/Form/PaymentSelector.tpl  |  87 ++
 templates/CRM/Grant/Form/PaymentTask.tpl      |  42 +
 templates/CRM/Grant/Form/Search.tpl           |  80 ++
 templates/CRM/Grant/Form/Search/Common.tpl    | 117 +++
 templates/CRM/Grant/Form/Search/Payment.tpl   | 117 +++
 templates/CRM/Grant/Form/Selector.tpl         |  91 ++
 templates/CRM/Grant/Form/Task.tpl             |  42 +
 templates/CRM/Grant/Form/Task/Cancel.tpl      |  32 +
 .../CRM/Grant/Form/Task/GrantPayment.tpl      |  61 ++
 templates/CRM/Grant/Form/Task/Pay.tpl         |  38 +
 templates/CRM/Grant/Form/Task/Reprint.tpl     |  73 ++
 templates/CRM/Grant/Form/Task/Update.tpl      |  73 ++
 .../CRM/Grant/Form/Task/paymentResultTask.tpl |  80 ++
 templates/CRM/Grant/Page/DashBoard.tpl        |  69 ++
 templates/CRM/Grant/Page/GrantProgram.tpl     |  82 ++
 templates/CRM/Grant/Page/Payment.tpl          |  28 +
 xml/Menu/grantprograms.xml                    |  55 ++
 66 files changed, 12662 insertions(+)
 create mode 100755 CRM/Grant/BAO/EntityPayment.php
 create mode 100755 CRM/Grant/BAO/Grant.php
 create mode 100755 CRM/Grant/BAO/GrantPayment.php
 create mode 100755 CRM/Grant/BAO/GrantProgram.php
 create mode 100755 CRM/Grant/BAO/PaymentSearch.php
 create mode 100755 CRM/Grant/BAO/Query.php
 create mode 100755 CRM/Grant/Config.php
 create mode 100755 CRM/Grant/Controller/PaymentSearch.php
 create mode 100755 CRM/Grant/DAO/EntityPayment.php
 create mode 100755 CRM/Grant/DAO/Grant.php
 create mode 100755 CRM/Grant/DAO/GrantPayment.php
 create mode 100755 CRM/Grant/DAO/GrantProgram.php
 create mode 100755 CRM/Grant/Form/Grant.php
 create mode 100755 CRM/Grant/Form/GrantProgram.php
 create mode 100755 CRM/Grant/Form/GrantProgramView.php
 create mode 100755 CRM/Grant/Form/Payment/View.php
 create mode 100755 CRM/Grant/Form/PaymentSearch.php
 create mode 100755 CRM/Grant/Form/PaymentTask.php
 create mode 100755 CRM/Grant/Form/Search.php
 create mode 100755 CRM/Grant/Form/Search.php~
 create mode 100755 CRM/Grant/Form/Task/Cancel.php
 create mode 100755 CRM/Grant/Form/Task/GrantPayment.php
 create mode 100755 CRM/Grant/Form/Task/Pay.php
 create mode 100755 CRM/Grant/Form/Task/Reprint.php
 create mode 100755 CRM/Grant/Form/Task/SearchTaskHookSample.php
 create mode 100755 CRM/Grant/Form/Task/Update.php
 create mode 100755 CRM/Grant/Info.php
 create mode 100755 CRM/Grant/Page/DashBoard.php
 create mode 100755 CRM/Grant/Page/GrantProgram.php
 create mode 100755 CRM/Grant/Page/Payment.php
 create mode 100755 CRM/Grant/PaymentTask.php
 create mode 100755 CRM/Grant/PseudoConstant.php
 create mode 100755 CRM/Grant/Selector/PaymentSearch.php
 create mode 100755 CRM/Grant/Selector/Search.php
 create mode 100755 CRM/Grant/StateMachine/PaymentSearch.php
 create mode 100755 CRM/Grant/StateMachine/Search.php
 create mode 100755 CRM/Grant/Task.php
 create mode 100755 CRM/Grant/Words.php
 create mode 100755 CRM/Grant/xml/Menu/Grant.xml
 create mode 100644 grantprograms.civix.php
 create mode 100644 grantprograms.php
 create mode 100644 info.xml
 create mode 100755 templates/CRM/Grant/Form/Grant.tpl
 create mode 100755 templates/CRM/Grant/Form/GrantProgram.tpl
 create mode 100755 templates/CRM/Grant/Form/GrantProgramView.tpl
 create mode 100755 templates/CRM/Grant/Form/GrantView.extra.tpl
 create mode 100755 templates/CRM/Grant/Form/GrantViewaaa.php
 create mode 100755 templates/CRM/Grant/Form/Payment/View.tpl
 create mode 100755 templates/CRM/Grant/Form/PaymentSearch.tpl
 create mode 100755 templates/CRM/Grant/Form/PaymentSelector.tpl
 create mode 100755 templates/CRM/Grant/Form/PaymentTask.tpl
 create mode 100755 templates/CRM/Grant/Form/Search.tpl
 create mode 100755 templates/CRM/Grant/Form/Search/Common.tpl
 create mode 100755 templates/CRM/Grant/Form/Search/Payment.tpl
 create mode 100755 templates/CRM/Grant/Form/Selector.tpl
 create mode 100755 templates/CRM/Grant/Form/Task.tpl
 create mode 100755 templates/CRM/Grant/Form/Task/Cancel.tpl
 create mode 100755 templates/CRM/Grant/Form/Task/GrantPayment.tpl
 create mode 100755 templates/CRM/Grant/Form/Task/Pay.tpl
 create mode 100755 templates/CRM/Grant/Form/Task/Reprint.tpl
 create mode 100755 templates/CRM/Grant/Form/Task/Update.tpl
 create mode 100755 templates/CRM/Grant/Form/Task/paymentResultTask.tpl
 create mode 100755 templates/CRM/Grant/Page/DashBoard.tpl
 create mode 100755 templates/CRM/Grant/Page/GrantProgram.tpl
 create mode 100755 templates/CRM/Grant/Page/Payment.tpl
 create mode 100755 xml/Menu/grantprograms.xml

diff --git a/CRM/Grant/BAO/EntityPayment.php b/CRM/Grant/BAO/EntityPayment.php
new file mode 100755
index 0000000..c27576a
--- /dev/null
+++ b/CRM/Grant/BAO/EntityPayment.php
@@ -0,0 +1,108 @@
+<?php
+
+/*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.0                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*/
+
+/**
+ *
+ * @package CRM
+ * @copyright CiviCRM LLC (c) 2004-2011
+ * $Id$
+ *
+ */
+
+require_once 'CRM/Grant/DAO/EntityPayment.php';
+
+/**
+ * This class contains  entity payment related functions.
+ */
+class CRM_Grant_BAO_EntityPayment extends CRM_Grant_DAO_EntityPayment 
+{
+  /**
+   * class constructor
+   */
+  function __construct( ) 
+  {
+    parent::__construct( );
+  }
+
+  /**
+   * Takes a bunch of params that are needed to match certain criteria and
+   * retrieves the relevant objects. It also stores all the retrieved
+   * values in the default array
+   *
+   * @param array $params   (reference ) an assoc array of name/value pairs
+   * @param array $defaults (reference ) an assoc array to hold the flattened values
+   *
+   * @return object CRM_Grant_DAO_EntityPayment object on success, null otherwise
+   * @access public
+   * @static
+   */
+  static function retrieve( &$params, &$defaults ) 
+  {
+    $entityPayment = new CRM_Grant_DAO_EntityPayment( );
+    $entityPayment->copyValues( $params );
+    if ( $entityPayment->find( true ) ) {
+      CRM_Core_DAO::storeValues( $entityPayment, $defaults );
+      return $entityPayment;
+    }
+    return null;
+  }
+  /**
+   * Function  to delete Entity Payment
+   * 
+   * @param  int  $entityPaymentID  ID of the entity payment to be deleted.
+   * 
+   * @access public
+   * @static
+   */
+  static function del( $id )
+  { 
+    require_once 'CRM/Utils/Hook.php';
+    CRM_Utils_Hook::pre( 'delete', 'EntityPayment', $id, CRM_Core_DAO::$_nullArray );
+
+    require_once 'CRM/Grant/DAO/EntityPayment.php';
+    $entityPayment    = new CRM_Grant_DAO_EntityPayment( );
+    $entityPayment->id = $id; 
+
+    $entityPayment->find();
+
+    // delete the recently created Grant
+    require_once 'CRM/Utils/Recent.php';
+    $entityPaymentRecent = array(
+                                 'id'   => $id,
+                                 'type' => 'EntityPayment'
+                                 );
+    CRM_Utils_Recent::del( $entityPaymentRecent );
+
+    if ( $entityPayment->fetch() ) {
+      $results = $entityPayment->delete();
+      CRM_Utils_Hook::post( 'delete', 'EntityPayment', $entityPayment->id, $entityPayment );
+      return $results;
+    }
+    return false;
+  }
+}
diff --git a/CRM/Grant/BAO/Grant.php b/CRM/Grant/BAO/Grant.php
new file mode 100755
index 0000000..14ade8c
--- /dev/null
+++ b/CRM/Grant/BAO/Grant.php
@@ -0,0 +1,567 @@
+<?php
+
+/*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.1                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*/
+
+/**
+ *
+ * @package CRM
+ * @copyright CiviCRM LLC (c) 2004-2011
+ * $Id$
+ *
+ */
+
+require_once 'CRM/Grant/DAO/Grant.php';
+
+class CRM_Grant_BAO_Grant extends CRM_Grant_DAO_Grant 
+{
+
+    /**
+        * static field for all the grant information that we can potentially export
+        * @var array
+        * @static
+        */
+    static $_exportableFields = null;
+
+    /**
+        * class constructor
+        */
+    function __construct( ) 
+    {
+        parent::__construct( );
+    }
+
+    /**
+        * Function to get events Summary
+        *
+        * @static
+        * @return array Array of event summary values
+        */
+    static function getGrantSummary( $admin = false )
+    {
+        $query = "
+            SELECT status_id, count(id) as status_total 
+            FROM civicrm_grant  GROUP BY status_id";
+
+        $dao = CRM_Core_DAO::executeQuery( $query, CRM_Core_DAO::$_nullArray );
+
+        require_once 'CRM/Grant/PseudoConstant.php';
+        $status = array( );
+        $summary = array( );
+        $summary['total_grants'] = null;
+        $status = CRM_Grant_PseudoConstant::grantStatus( );
+
+        foreach( $status as $id => $name ) {
+            $stats[$id] = array( 'label' => $name,
+                                 'total' => 0 );
+        }
+
+        while ( $dao->fetch( ) ) {
+            $stats[$dao->status_id] = array( 'label' => $status[$dao->status_id],
+                                             'total' => $dao->status_total );
+            $summary['total_grants'] += $dao->status_total;
+        }
+
+        $summary['per_status'] = $stats;
+        return $summary;
+    }
+
+    /**
+        * Function to get events Summary
+        *
+        * @static
+        * @return array Array of event summary values
+        */
+    static function getGrantStatusOptGroup( ) 
+    {
+        require_once 'CRM/Core/BAO/OptionGroup.php';
+
+        $params = array( );
+        $params['name'] = CRM_Grant_BAO_Grant::$statusGroupName;
+
+        $defaults = array();
+
+        $bao = new CRM_Core_BAO_OptionGroup( );
+        $og = $bao->retrieve( $params, $defaults );
+
+        if ( ! $og ) {
+            CRM_Core_Error::fatal('No option group for grant statuses - database discrepancy! Make sure you loaded civicrm_data.mysql');
+        }
+
+        return $og;
+    }
+
+    /**
+     * Function to retrieve statistics for grants.
+     * 
+     * @static
+     * @return array Array of grant summary statistics
+     */
+    static function getGrantStatistics( $admin = false ) 
+    {
+        $grantStatuses = array(); 
+    }
+
+    /**
+     * Takes a bunch of params that are needed to match certain criteria and
+     * retrieves the relevant objects. Typically the valid params are only
+     * contact_id. We'll tweak this function to be more full featured over a period
+     * of time. This is the inverse function of create. It also stores all the retrieved
+     * values in the default array
+     *
+     * @param array $params   (reference ) an assoc array of name/value pairs
+     * @param array $defaults (reference ) an assoc array to hold the flattened values
+     *
+     * @return object CRM_Grant_BAO_ManageGrant object
+     * @access public
+     * @static
+     */
+    static function retrieve( &$params, &$defaults ) 
+    {
+        $grant  = new CRM_Grant_DAO_Grant( );
+        $grant->copyValues( $params );
+        if ( $grant->find( true ) ) {
+            CRM_Core_DAO::storeValues( $grant, $defaults );
+            return $grant;
+        }
+        return null;
+    }
+
+    /**
+     * function to add grant
+     *
+     * @param array $params reference array contains the values submitted by the form
+     * @param array $ids    reference array contains the id
+     * 
+     * @access public
+     * @static 
+     * @return object
+     */
+    static function add( &$params, &$ids )
+    {
+        require_once 'CRM/Utils/Hook.php';
+        
+        if ( CRM_Utils_Array::value( 'grant_id', $ids ) ) {
+            CRM_Utils_Hook::pre( 'edit', 'Grant', $ids['grant_id'], $params );
+        } else {
+            CRM_Utils_Hook::pre( 'create', 'Grant', null, $params ); 
+        }
+        
+        // first clean up all the money fields
+        $moneyFields = array( 'amount_total',
+                              'amount_granted',
+                              'amount_requested' );
+        foreach ( $moneyFields as $field ) {
+            if ( isset( $params[$field] ) ) {
+                $params[$field] = CRM_Utils_Rule::cleanMoney( $params[$field] );
+            }
+        }
+        // convert dates to mysql format
+        $dates = array( 'application_received_date',
+                        'decision_date',
+                        'money_transfer_date',
+                        'grant_due_date' );
+        
+        foreach ( $dates as $d ) {
+            if ( isset( $params[$d] ) ) {
+                $params[$d] = CRM_Utils_Date::processDate( $params[$d], null, true );
+            }
+        }           
+        $grant = new CRM_Grant_DAO_Grant( );
+        $grant->id = CRM_Utils_Array::value( 'grant', $ids );
+        
+        $grant->copyValues( $params );
+        
+        // set currency for CRM-1496
+        if ( ! isset( $grant->currency ) ) {
+            $config = CRM_Core_Config::singleton( );
+            $grant->currency = $config->defaultCurrency;
+        }
+        
+        $result = $grant->save( );
+        $grant->find(true);
+        require_once 'CRM/Utils/Recent.php';
+        require_once 'CRM/Grant/PseudoConstant.php';
+        require_once 'CRM/Contact/BAO/Contact.php';
+        $url = CRM_Utils_System::url( 'civicrm/contact/view/grant', 
+                                      "action=view&reset=1&id={$grant->id}&cid={$grant->contact_id}&context=home" );
+        
+        $grantTypes = CRM_Grant_PseudoConstant::grantType();
+        $title = CRM_Contact_BAO_Contact::displayName( $grant->contact_id ) . ' - ' . ts('Grant') . ': ' . $grantTypes[$grant->grant_type_id];
+        
+        $recentOther = array( );
+        if ( CRM_Core_Permission::checkActionPermission( 'CiviGrant', CRM_Core_Action::UPDATE ) ) {
+            $recentOther['editUrl'] = CRM_Utils_System::url( 'civicrm/contact/view/grant', 
+                                                             "action=update&reset=1&id={$grant->id}&cid={$grant->contact_id}&context=home" );
+        }
+        if ( CRM_Core_Permission::checkActionPermission( 'CiviGrant', CRM_Core_Action::DELETE ) ) {
+            $recentOther['deleteUrl'] = CRM_Utils_System::url( 'civicrm/contact/view/grant', 
+                                                               "action=delete&reset=1&id={$grant->id}&cid={$grant->contact_id}&context=home" );
+        }
+
+        // add the recently created Grant
+        CRM_Utils_Recent::add( $title,
+                               $url,
+                               $grant->id,
+                               'Grant',
+                               $grant->contact_id,
+                               null,
+                               $recentOther
+                               );
+
+        if ( CRM_Utils_Array::value( 'grant', $ids ) ) {
+            CRM_Utils_Hook::post( 'edit', 'Grant', $grant->id, $grant );
+        } else {
+            CRM_Utils_Hook::post( 'create', 'Grant', $grant->id, $grant );
+        }
+
+        return $result;
+    }
+
+    /**
+        * function to create the event
+        *
+        * @param array $params reference array contains the values submitted by the form
+        * @param array $ids    reference array contains the id
+        * 
+        * @access public
+        * @static 
+        * 
+        */
+    public static function create( &$params, &$ids ) 
+    {
+      require_once 'CRM/Core/Transaction.php';
+      $transaction = new CRM_Core_Transaction( );
+      $assessmentAmount = 0;
+      if ( empty($params['assessment'] ) ) {
+        foreach ( $params['custom'] as $key => $value ) {
+          foreach( $value as $fieldKey => $fieldValue ) {
+            $customParams = array( 'id' => $key, 'is_active' => 1, 'html_type' => 'Select' );
+            $customFields = CRM_Core_BAO_CustomField::retrieve( $customParams, $default = array() );
+            if ( !empty( $customFields ) ) { 
+              $optionValueParams = array( 'option_group_id' => $customFields->option_group_id, 'value' => $fieldValue['value'], 'is_active' => 1 );
+              $optionValues = CRM_Core_BAO_OptionValue::retrieve( $optionValueParams,  $default = array() );
+              if( !empty( $optionValues->description ) ) {
+                $assessmentAmount += $optionValues->description;
+              }
+            }
+          }
+        }
+      }
+        
+      if( !empty( $assessmentAmount ) ) {
+        $params['assessment'] = $assessmentAmount;
+      }
+      CRM_Utils_Hook::grantAssessment( $params );
+        
+      $grant = self::add($params, $ids);
+        
+      if ( is_a( $grant, 'CRM_Core_Error') ) {
+        $transaction->rollback( );
+        return $grant;
+      }
+
+      $session = CRM_Core_Session::singleton();
+      $id = $session->get('userID');
+      if ( !$id ) {
+        $id = $params['contact_id'];
+      } 
+      if ( CRM_Utils_Array::value('note', $params) || CRM_Utils_Array::value( 'id', $ids['note'] ) ) {
+        require_once 'CRM/Core/BAO/Note.php';
+        $noteParams = array(
+                            'entity_table'  => 'civicrm_grant',
+                            'note'          => $params['note'] = $params['note'] ? $params['note'] : "null",
+                            'entity_id'     => $grant->id,
+                            'contact_id'    => $id,
+                            'modified_date' => date('Ymd')
+                            );
+
+        CRM_Core_BAO_Note::add( $noteParams, $ids['note'] );
+      }        
+      // Log the information on successful add/edit of Grant
+      require_once 'CRM/Core/BAO/Log.php';
+      $logParams = array(
+                         'entity_table'  => 'civicrm_grant',
+                         'entity_id'     => $grant->id,
+                         'modified_id'   => $id,
+                         'modified_date' => date('Ymd')
+                         );
+
+      CRM_Core_BAO_Log::add( $logParams );
+
+      // add custom field values
+      if (CRM_Utils_Array::value('custom', $params) && is_array( $params['custom'] ) ) {
+        require_once 'CRM/Core/BAO/CustomValueTable.php';
+        CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_grant', $grant->id);
+      }
+        
+      // check and attach and files as needed
+      require_once 'CRM/Core/BAO/File.php';
+      CRM_Core_BAO_File::processAttachment( $params,
+                                            'civicrm_grant',
+                                            $grant->id );
+
+      $transaction->commit( );
+      require_once 'CRM/Grant/DAO/GrantProgram.php';
+      $grantProgram  = new CRM_Grant_DAO_GrantProgram( );
+      $grantProgram->id = $params['grant_program_id'];
+      require_once 'CRM/Core/Page.php';
+      $page = new CRM_Core_Page();
+      if ( $grantProgram->find( true ) ) {
+        $params['is_auto_email'] = $grantProgram->is_auto_email;
+      }
+      if ( $params['is_auto_email'] == 1 && !array_key_exists('resrictEmail', $params) ) {
+        foreach( $params['custom'] as $key => $value ) {
+          foreach ( $value as $index => $field ) {
+            if ( !empty( $field['value'] ) ) {
+              $customData[$field['custom_group_id']][$field['custom_field_id']] = $field['value'];
+            }
+          }
+        }
+        require_once 'CRM/Core/DAO.php';
+        if ( !empty( $customData ) ) {
+          foreach ( $customData as $dataKey => $dataValue ) {
+            $customGroupName = CRM_Core_DAO::getFieldValue( 'CRM_Core_DAO_CustomGroup',$dataKey,'title' );
+            $customGroup[$customGroupName] = $customGroupName;
+            $count = 0;
+            foreach ( $dataValue  as $dataValueKey => $dataValueValue ) {
+              $customField[$customGroupName][$count]['label'] = CRM_Core_DAO::getFieldValue( 'CRM_Core_DAO_CustomField',$dataValueKey,'label' );
+              $customField[$customGroupName][$count]['value'] = $dataValueValue;
+              $count++;
+            }
+          }
+          $page->assign( 'customGroup', $customGroup );
+          $page->assign( 'customField', $customField );
+        }
+        require_once 'CRM/Core/OptionGroup.php';  
+        require_once 'CRM/Grant/BAO/Grant.php';
+        $grantStatuses = CRM_Core_OptionGroup::values( 'grant_status' );
+        $grantPrograms = CRM_Grant_BAO_Grant::getGrantPrograms();
+        $grantTypes    = CRM_Core_OptionGroup::values( 'grant_type' );
+        $grantProgram  = $grantPrograms[$params['grant_program_id']];
+        $grantType     = $grantTypes[$params['grant_type_id']];
+        $grantStatus   = $grantStatuses[$params['status_id']];
+          
+        $page->assign( 'grant_type', $grantType );
+        $page->assign( 'grant_programs', $grantProgram );
+        $page->assign( 'grant_status', $grantStatus );
+        $page->assign( 'params', $params );
+        self::sendMail( $params['contact_id'], $params, $grantStatus );
+      }
+      return $grant;
+    }
+
+    /**
+        * Function to delete the Contact
+        *
+        * @param int $cid  contact id
+        *
+        * @access public
+        * @static
+        *
+        */
+    static function deleteContact( $id )
+    {
+        require_once 'CRM/Grant/DAO/Grant.php';
+        $grant = new CRM_Grant_DAO_Grant( );
+        $grant->contact_id = $id; 
+        $grant->delete();
+        return false;
+    }
+
+    /**
+        * Function to delete the grant
+        *
+        * @param int $id  grant id
+        *
+        * @access public
+        * @static
+        *
+        */
+    static function del( $id )
+    { 
+      require_once 'CRM/Utils/Hook.php';
+      CRM_Utils_Hook::pre( 'delete', 'Grant', $id, CRM_Core_DAO::$_nullArray );
+
+      require_once 'CRM/Grant/DAO/Grant.php';
+      $grant     = new CRM_Grant_DAO_Grant( );
+      $grant->id = $id; 
+
+      $grant->find();
+
+      // delete the recently created Grant
+      require_once 'CRM/Utils/Recent.php';
+      $grantRecent = array(
+                           'id'   => $id,
+                           'type' => 'Grant'
+                           );
+      CRM_Utils_Recent::del( $grantRecent );
+
+      if ( $grant->fetch() ) {
+        $results = $grant->delete();
+        CRM_Utils_Hook::post( 'delete', 'Grant', $grant->id, $grant );
+        return $results;
+      }
+      return false;
+    }
+    /**
+        * combine all the exportable fields from the lower levels object
+        *     
+        * @return array array of exportable Fields
+        * @access public
+        */
+    function &exportableFields( ) 
+    {
+        if ( ! self::$_exportableFields ) {
+            if ( ! self::$_exportableFields ) {
+                self::$_exportableFields = array( );
+            }
+            
+            $grantFields = array( 'grant_status'                    => array( 
+                                                                             'title'     => 'Grant Status',
+                                                                             'name'      => 'grant_status',
+                                                                             'data_type' => CRM_Utils_Type::T_STRING ),
+                                  'grant_type'                      => array( 
+                                                                             'title'     => 'Grant Type',
+                                                                             'name'      => 'grant_type',
+                                                                             'data_type' => CRM_Utils_Type::T_STRING ),
+                                  'grant_money_transfer_date'       => array( 
+                                                                             'title'     => 'Grant Money Transfer Date',
+                                                                             'name'      => 'grant_money_transfer_date',
+                                                                             'data_type' => CRM_Utils_Type::T_DATE ),
+                                  'grant_amount_requested'          => array( 
+                                                                             'title'     => 'Grant Amount Requested',
+                                                                             'name'      => 'grant_amount_requested',
+                                                                             'data_type' => CRM_Utils_Type::T_FLOAT ),
+                                  'grant_application_received_date' => array( 
+                                                                             'title' => 'Grant Application Recieved Date',
+                                                                             'name'  => 'grant_application_received_date',
+                                                                             'data_type' => CRM_Utils_Type::T_DATE ) );
+                                                           
+            require_once 'CRM/Grant/DAO/Grant.php';
+            $fields = CRM_Grant_DAO_Grant::export( );
+            $grantNote = array( 'grant_note' => array( 'title'     => ts('Grant Note'),
+                                                       'name'      => 'grant_note',
+                                                       'data_type' => CRM_Utils_Type::T_TEXT ) );
+            $fields = array_merge( $fields, $grantFields, $grantNote,
+                                   CRM_Core_BAO_CustomField::getFieldsForImport('Grant'));
+            self::$_exportableFields = $fields;
+        }
+
+        return self::$_exportableFields;
+    }
+    
+    /**
+     * Function to get grant record count for a Contact
+     *
+     * @param int $contactId Contact ID
+     * 
+     * @return int count of grant records
+     * @access public
+     * @static
+     */
+    static function getContactGrantCount( $contactID ) {
+        $query = "SELECT count(*) FROM civicrm_grant WHERE civicrm_grant.contact_id = {$contactID} ";
+        return CRM_Core_DAO::singleValueQuery( $query );
+    }
+
+    static function getGrantPrograms( $id = null ) {
+        $grantPrograms = array();
+        $where = ' WHERE is_active = 1';
+        if ( !empty( $id ) ) {
+            $where .= " AND id = {$id}";
+        }
+        $query = "SELECT id, name FROM civicrm_grant_program ".$where;
+        $dao = CRM_Core_DAO::executeQuery( $query );
+        while($dao->fetch()) {
+            $grantPrograms[$dao->id] = $dao->name;
+        }
+        return $grantPrograms;
+    }
+    
+    static function getGrants( $params ) {
+        if ( !empty ($params) ) {
+            $where = "WHERE "; 
+            foreach ( $params as $key => $value ) {
+              if( $key == 'status_id') {
+                $where .= "{$key} IN ( {$value} ) AND ";
+              } else {
+                if ( strstr($value, 'NULL') ) {
+                  $where .= "{$key} IS {$value} AND ";
+                } else {
+                  $where .= "{$key} = '{$value}' AND ";
+                }
+              }
+            }
+            $where = rtrim( $where ," AND ");
+            $query = "SELECT * FROM civicrm_grant {$where} ORDER BY application_received_date ASC";
+            $dao = CRM_Core_DAO::executeQuery($query);
+            while( $dao->fetch() ) {
+                $grants[$dao->id]['assessment']       = $dao->assessment;
+                $grants[$dao->id]['amount_total']     = $dao->amount_total;
+                $grants[$dao->id]['amount_requested'] = $dao->amount_requested;
+                $grants[$dao->id]['amount_granted']   = $dao->amount_granted;
+                $grants[$dao->id]['status_id']        = $dao->status_id;
+                $grants[$dao->id]['contact_id']       = $dao->contact_id;
+                $grants[$dao->id]['grant_id']         = $dao->id;
+                
+            }
+        }
+        return $grants;
+    }
+    
+    static function sendMail( $contactID, &$values, $grantStatus ) {
+        
+      if ( CRM_Utils_Array::value( 'is_auto_email', $values ) ) {
+        require_once 'CRM/Contact/BAO/Contact/Location.php';
+        list( $displayName, $email ) = CRM_Contact_BAO_Contact_Location::getEmailDetails( $contactID );
+        if ( isset( $email ) ) {
+          $valueName = strtolower($grantStatus);
+          if ( $grantStatus == 'Awaiting Information' )  {
+            $explode = explode(' ', $grantStatus);
+            $valueName = strtolower($explode[0]).'_info';
+          }
+          $sendTemplateParams = array(
+                                      'groupName' => 'msg_tpl_workflow_grant',
+                                      'valueName' => 'grant_'.$valueName,
+                                      'contactId' => $contactID,
+                                      'tplParams' => array(
+                                                           'email'              => $email,
+                                                           'confirm_email_text' => CRM_Utils_Array::value('confirm_email_text', $value['event']),
+                                                           'isShowLocation'     => CRM_Utils_Array::value('is_show_location',   $value['event']),
+                                                           ),
+                                      'PDFFilename' => '',
+                                      );
+          require_once 'CRM/Core/BAO/MessageTemplates.php';
+          $sendTemplateParams['from']    = $email;
+          $sendTemplateParams['toName']  = $displayName;
+          $sendTemplateParams['toEmail'] = $email;
+          $sendTemplateParams['autoSubmitted'] = true;
+          CRM_Core_BAO_MessageTemplates::sendTemplate($sendTemplateParams);
+        }
+      }
+    }
+}
diff --git a/CRM/Grant/BAO/GrantPayment.php b/CRM/Grant/BAO/GrantPayment.php
new file mode 100755
index 0000000..25600ef
--- /dev/null
+++ b/CRM/Grant/BAO/GrantPayment.php
@@ -0,0 +1,339 @@
+<?php
+
+/*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.1                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*/
+
+/**
+ *
+ * @package CRM
+ * @copyright CiviCRM LLC (c) 2004-2011
+ * $Id$
+ *
+ */
+
+require_once 'CRM/Grant/DAO/GrantPayment.php';
+require_once 'CRM/Grant/BAO/GrantProgram.php';
+
+class CRM_Grant_BAO_GrantPayment extends CRM_Grant_DAO_GrantPayment 
+{
+
+  /**
+   * static field for all the grant information that we can potentially export
+   * @var array
+   * @static
+   */
+  static $_exportableFields = null;
+
+  /**
+   * class constructor
+   */
+  function __construct( ) 
+  {
+    parent::__construct( );
+  }
+
+  /**
+   * Takes a bunch of params that are needed to match certain criteria and
+   * retrieves the relevant objects. Typically the valid params are only
+   * contact_id. We'll tweak this function to be more full featured over a period
+   * of time. This is the inverse function of create. It also stores all the retrieved
+   * values in the default array
+   *
+   * @param array $params   (reference ) an assoc array of name/value pairs
+   * @param array $defaults (reference ) an assoc array to hold the flattened values
+   *
+   * @return object CRM_Grant_BAO_ManageGrant object
+   * @access public
+   * @static
+   */
+  static function retrieve( &$params, &$defaults ) 
+  {
+    $grantPayment  = new CRM_Grant_DAO_GrantPayment( );
+    $grantPayment->copyValues( $params );
+    if ( $grantPayment->find( true ) ) {
+      CRM_Core_DAO::storeValues( $grantPayment, $defaults );
+      return $grantPayment;
+    }
+    return null;
+  }
+  function &exportableFields( ) 
+    {
+      if ( ! self::$_exportableFields ) {
+        if ( ! self::$_exportableFields ) {
+          self::$_exportableFields = array( );
+        }
+            
+        $grantFields = array( 'id'                       => array( 
+                                                                  'title'     => 'Payment ID',
+                                                                  'name'      => 'id',
+                                                                  'data_type' => CRM_Utils_Type::T_INT ),
+                              'payment_batch_number'     => array( 
+                                                                  'title'     => 'Payment Batch Nnumber',
+                                                                  'name'      => 'payment_batch_number',
+                                                                  'data_type' => CRM_Utils_Type::T_INT ),
+                              'payment_number'           => array( 
+                                                                  'title'     => 'Payment Number',
+                                                                  'name'      => 'payment_number',
+                                                                  'data_type' => CRM_Utils_Type::T_INT ),
+                              'contribution_type_id'     => array( 
+                                                                  'title'     => 'Contribution Type ID',
+                                                                  'name'      => 'contribution_type_id',
+                                                                  'data_type' => CRM_Utils_Type::T_INT ),
+                              'contact_id'               => array( 
+                                                                  'title'     => 'Contact ID',
+                                                                  'name'      => 'contact_id',
+                                                                  'data_type' => CRM_Utils_Type::T_INT ),
+                              'payment_created_date'     => array( 
+                                                                  'title'     => 'Payment Created Date',
+                                                                  'name'      => 'payment_created_date',
+                                                                  'data_type' => CRM_Utils_Type::T_DATE ),
+                              'payment_date'             => array( 
+                                                                  'title'     => 'Payment Date',
+                                                                  'name'      => 'payment_date',
+                                                                  'data_type' => CRM_Utils_Type::T_DATE ),
+                              'payable_to_name'          => array(
+                                                                  'title'     => 'Payable To Name',
+                                                                  'name'      => 'payable_to_name',
+                                                                  'data_type' => CRM_Utils_Type::T_STRING ),
+                              'payable_to_address'       => array(
+                                                                  'title'     => 'Payable To Address',
+                                                                  'name'      => 'payable_to_address',
+                                                                  'data_type' => CRM_Utils_Type::T_STRING),
+                              'amount'                   => array(
+                                                                  'title'     => 'Amount',
+                                                                  'name'      => 'amount',
+                                                                  'data_type' => CRM_Utils_Type::T_MONEY),
+                              'currency'                 => array(
+                                                                  'title'     => 'Currency',
+                                                                  'name'      => 'currency',
+                                                                  'data_type' => CRM_Utils_Type::T_STRING),
+                              'payment_reason'           => array(
+                                                                  'title'     => 'Payment Reason',
+                                                                  'name'      => 'payment_reason',
+                                                                  'data_type' => CRM_Utils_Type::T_STRING),
+                              'payment_status_id'        => array(
+                                                                  'title'     => 'Payment Status ID',
+                                                                  'name'      => 'payment_status_id',
+                                                                  'data_type' => CRM_Utils_Type::T_STRING),
+                              'replaces_payment_id'      => array(
+                                                                  'title'     => 'Payment Reason',
+                                                                  'name'      => 'replaces_payment_id',
+                                                                  'data_type' => CRM_Utils_Type::T_STRING));
+                                                           
+        require_once 'CRM/Grant/DAO/GrantPayment.php';
+        $fields = CRM_Grant_DAO_GrantPayment::export( );
+        self::$_exportableFields = $fields;
+      }
+
+      return self::$_exportableFields;
+    }
+  /**
+   * function to add grant
+   *
+   * @param array $params reference array contains the values submitted by the form
+   * @param array $ids    reference array contains the id
+   * 
+   * @access public
+   * @static 
+   * @return object
+   */ 
+    
+
+  static function add( &$params, &$ids )
+  {
+
+    if ( empty($params) ) {
+      return;
+    }
+    
+    if ( isset( $params['total_amount'] ) ) {
+      $params[$field] = CRM_Utils_Rule::cleanMoney( $params['total_amount'] );
+    }
+    // convert dates to mysql format
+    $dates = array( 'payment_date',
+                    'payment_created_date' );
+        
+    foreach ( $dates as $d ) {
+      if ( isset( $params[$d] ) ) {
+        $params[$d] = CRM_Utils_Date::processDate( $params[$d], null, true );
+      }
+    }           
+    $grantPayment = new CRM_Grant_DAO_GrantPayment( );
+    $grantPayment->id = CRM_Utils_Array::value( 'id', $ids );
+        
+    $grantPayment->copyValues( $params );
+    return $grantPayment->save( );
+  }
+    
+
+  static function del( $id )
+  { 
+    require_once 'CRM/Utils/Hook.php';
+    CRM_Utils_Hook::pre( 'delete', 'GrantPayment', $id, CRM_Core_DAO::$_nullArray );
+
+    require_once 'CRM/Grant/DAO/GrantPayment.php';
+    $grantPayment     = new CRM_Grant_DAO_GrantPayment( );
+    $grantPayment->id = $id; 
+
+    $grantPayment->find();
+
+    // delete the recently created Grant
+    require_once 'CRM/Utils/Recent.php';
+    $grantPaymentRecent = array(
+                                'id'   => $id,
+                                'type' => 'GrantPayment'
+                                );
+    CRM_Utils_Recent::del( $grantPaymentRecent );
+
+    if ( $grantPayment->fetch() ) {
+      $results = $grantPayment->delete();
+      CRM_Utils_Hook::post( 'delete', 'GrantPayment', $grantPayment->id, $grantPayment );
+      return $results;
+    }
+    return false;
+  }
+    
+  static function getMaxPayementBatchNumber( ) {
+    $query = "SELECT MAX(payment_number) as payment_number, MAX(payment_batch_number) as payment_batch_number FROM civicrm_payment ";
+    $dao = CRM_Core_DAO::executeQuery( $query );
+    while( $dao->fetch() ) {
+      $grantPrograms['payment_number'] = $dao->payment_number;
+      $grantPrograms['payment_batch_number'] = $dao->payment_batch_number;
+    }
+    return $grantPrograms;
+  }
+    
+  static function getPaymentNumber( $id ) {
+    $query = "SELECT id FROM civicrm_payment WHERE payment_number = {$id} ";
+    return CRM_Core_DAO::singleValueQuery( $query );
+  }
+    
+  static function getPaymentBatchNumber( $id ) {
+    $query = "SELECT id FROM civicrm_payment WHERE payment_batch_number = {$id} ";
+    return CRM_Core_DAO::singleValueQuery( $query );
+  }
+    
+  static function makeReport( $fileName, $rows ) {
+    require_once 'CRM/Utils/PDF/Utils.php'; 
+    $config = CRM_Core_Config::singleton();
+    $pdf_filename = $config->customFileUploadDir . $fileName;
+    $query = "SELECT msg_subject subject, msg_text text, msg_html html, pdf_format_id format FROM civicrm_msg_template WHERE msg_title = 'Grant Payment Report'";
+    $dao = CRM_Core_DAO::executeQuery($query);
+    $dao->fetch();
+    if (!$dao->N) {
+      if ($params['messageTemplateID']) {
+        CRM_Core_Error::fatal(ts('No such message template: id=%1.', array(1 => $params['messageTemplateID'])));
+      } else {
+        CRM_Core_Error::fatal(ts('No such message template: option group %1, option value %2.', array(1 => $params['groupName'], 2 => $params['valueName'])));
+      }
+    }
+
+    $subject = $dao->subject;
+    $text    = $dao->text;
+    $html    = $dao->html;
+    $format  = $dao->format;
+    $dao->free( );
+
+    require_once 'CRM/Core/Smarty/resources/String.php';
+    civicrm_smarty_register_string_resource( );
+    $smarty = CRM_Core_Smarty::singleton( );
+    foreach( array( 'text', 'html') as $elem) {
+      $$elem = $smarty->fetch("string:{$$elem}");
+    }
+    $output = file_put_contents( $pdf_filename, CRM_Utils_PDF_Utils::html2pdf( $html,
+                                                                               $fileName,
+                                                                               true,
+                                                                               'Letter'
+                                                                               )
+                                 );
+    return $fileName;
+    
+  }
+    
+  static function createCSV( $filename, $grantPayment ) {
+    
+    $headers[] =  array ( 'Contact Id', 'Contribution Type', 'Batch Number', 'Payment Number', 'Payment Date', 'Payment Created Date', 
+                          'Payable To Name', 'Payable To Address', 'Amount', 'Currency', 'Payment Reason', 'Payment Replaces Id');
+    
+    $rows = array_merge( $headers, $grantPayment );
+    $fp = fopen($filename, "w");
+    $line = "";
+    $comma = "";
+    $contributionTypes = CRM_Grant_BAO_GrantProgram::contributionTypes();
+    foreach($rows as $value) {
+      if ( isset( $value['contribution_type_id'] ) ) {
+        $value['contribution_type_id'] = $contributionTypes[$value['contribution_type_id']];
+      }
+      $line .= implode( '; ', $value );
+      $line .= "\n";
+    }
+    fputs($fp, $line);
+    fclose($fp);
+  }
+ 
+  static function replaceVariables(  $html, $values ) {
+    foreach ( $values as $key => $value ) {
+      $html = str_replace($key, $value, $html);
+    }
+    return $html;
+  }
+  
+  static function makePDF( $fileName, $rows ) {
+    require_once 'CRM/Utils/PDF/Utils.php';
+    $config = CRM_Core_Config::singleton();
+    $pdf_filename = $config->customFileUploadDir . $fileName;
+    $query = "SELECT msg_subject subject, msg_html html
+                      FROM civicrm_msg_template 
+                      WHERE msg_title = 'Grant Payment Check' AND is_default = 1;";
+    $grantDao = CRM_Core_DAO::executeQuery($query);
+    $grantDao->fetch();
+                
+    if (!$grantDao->N) {
+      if ($params['messageTemplateID'])
+        CRM_Core_Error::fatal(ts('No such message template.'));
+    }
+    $subject = $grantDao->subject;
+    $html    = $grantDao->html;
+
+    $final_html = null;
+    foreach ( $rows as $values ) {
+      require_once 'CRM/Grant/Words.php';
+      $words = new CRM_Grant_Words();
+      $amount = $values['amount'];
+      $values['check_total'] = ltrim( $amount, '$' );
+      $amount = str_replace (',', '',$amount );
+      $values['total_in_words'] = ucwords($words->convert_number_to_words( ltrim( $amount, '$' ) ) );
+      $final_html .= self::replaceVariables( $html, $values )."<br>";
+    }
+    $output = file_put_contents( $pdf_filename, CRM_Utils_PDF_Utils::html2pdf( $final_html,
+                                                                               $fileName,
+                                                                               true,
+                                                                               'Letter'
+                                                                               )
+                                 );
+    return $fileName;
+  }
+}
\ No newline at end of file
diff --git a/CRM/Grant/BAO/GrantProgram.php b/CRM/Grant/BAO/GrantProgram.php
new file mode 100755
index 0000000..4014c9a
--- /dev/null
+++ b/CRM/Grant/BAO/GrantProgram.php
@@ -0,0 +1,215 @@
+<?php
+
+/*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.0                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*/
+
+/**
+ *
+ * @package CRM
+ * @copyright CiviCRM LLC (c) 2004-2011
+ * $Id$
+ *
+ */
+
+require_once 'CRM/Grant/DAO/GrantProgram.php';
+
+/**
+ * This class contains  grant program related functions.
+ */
+class CRM_Grant_BAO_GrantProgram extends CRM_Grant_DAO_GrantProgram 
+{
+    /**
+     * class constructor
+     */
+    function __construct( ) 
+    {
+        parent::__construct( );
+    }
+
+    /**
+     * Takes a bunch of params that are needed to match certain criteria and
+     * retrieves the relevant objects. It also stores all the retrieved
+     * values in the default array
+     *
+     * @param array $params   (reference ) an assoc array of name/value pairs
+     * @param array $defaults (reference ) an assoc array to hold the flattened values
+     *
+     * @return object CRM_Contribute_DAO_GrantProgram object on success, null otherwise
+     * @access public
+     * @static
+     */
+    static function retrieve( &$params, &$defaults ) 
+    {
+        $program = new CRM_Grant_DAO_GrantProgram( );
+        $program->copyValues( $params );
+        if ( $program->find( true ) ) {
+            CRM_Core_DAO::storeValues( $program, $defaults );
+            return $program;
+        }
+        return null;
+    }
+    /**
+     * Function  to delete Grant Program
+     * 
+     * @param  int  $grantProgramID     ID of the par service fee to be deleted.
+     * 
+     * @access public
+     * @static
+     */
+    static function del( $grantProgramID ) {
+        if ( ! $grantProgramID ) {
+            CRM_Core_Error::fatal( ts( 'Invalid value passed to delete function' ) );
+        }
+
+        $dao            = new CRM_Grant_DAO_GrantProgram( );
+        $dao->id        =  $grantProgramID;
+        if ( ! $dao->find( true ) ) {
+            return null;
+        }
+        $dao->delete( );
+    }
+
+    static function getOptionValueID( $optioGroupID, $value ) {
+        $query = "SELECT id FROM civicrm_option_value WHERE  option_group_id = {$optioGroupID} AND value = {$value} ";
+        return CRM_Core_DAO::singleValueQuery( $query );
+    }
+    
+    static function getOptionValue( $id ) {
+        $query = "SELECT value FROM civicrm_option_value WHERE id = {$id} ";
+        return CRM_Core_DAO::singleValueQuery( $query );
+    }
+
+    static function getOptionName ( $id ) {
+        $query = "SELECT label FROM civicrm_option_value WHERE id = {$id} ";
+        return CRM_Core_DAO::singleValueQuery( $query );
+    }
+
+    static function grantPrograms( $id = null ) {
+        $where = '';
+        if ( !empty( $id ) ) {
+            $where =  "WHERE id = {$id}";
+        }
+        $query = "SELECT id, label FROM civicrm_grant_program {$where}";
+        $dao = CRM_Core_DAO::executeQuery( $query );
+        while( $dao->fetch() ) {
+            if( !empty( $id ) ) {
+                $grantPrograms = $dao->label;
+            } else {
+                $grantPrograms[$dao->id] = $dao->label;
+            }
+        }
+        return $grantPrograms;
+    }  
+
+    static function contributionTypes( ) {
+        require_once 'CRM/Contribute/DAO/ContributionType.php';
+        $typeDao = new CRM_Contribute_DAO_ContributionType();
+        $typeDao->find();
+        while( $typeDao->fetch() ){
+            $contributionTypes[ $typeDao->id ] = $typeDao->name;
+        }
+        return $contributionTypes;
+    }
+    
+    static function create( &$params, &$ids )
+    {
+      if ( empty($params) ) {
+        return;
+      }
+      $moneyFields = array( 'total_amount',
+                            'remainder_amount' );
+      foreach ( $moneyFields as $field ) {
+        if ( isset( $params[$field] ) ) {
+          $params[$field] = CRM_Utils_Rule::cleanMoney( $params[$field] );
+        }
+      }
+      // convert dates to mysql format
+      $dates = array( 'allocation_date' );
+        
+      foreach ( $dates as $d ) {
+        if ( isset( $params[$d] ) ) {
+          $params[$d] = CRM_Utils_Date::processDate( $params[$d], null, true );
+        }
+      }
+      $grantProgram = new CRM_Grant_DAO_GrantProgram( );
+      $grantProgram->id = CRM_Utils_Array::value( 'grant_program', $ids );
+        
+      $grantProgram->copyValues( $params );
+        
+      return $result = $grantProgram->save( );
+    }
+
+    public function getDisplayName( $id ) {
+        $sql = "SELECT display_name FROM civicrm_contact WHERE civicrm_contact.id = $id ";
+        return CRM_Core_DAO::singleValueQuery( $sql );
+    }
+     
+     
+    public function getAddress( $id, $locationTypeID = null ) {
+        $sql = "
+   SELECT civicrm_contact.id as contact_id,
+          civicrm_address.street_address as street_address,
+          civicrm_address.supplemental_address_1 as supplemental_address_1,
+          civicrm_address.supplemental_address_2 as supplemental_address_2,
+          civicrm_address.city as city,
+          civicrm_address.postal_code as postal_code,
+          civicrm_address.postal_code_suffix as postal_code_suffix,
+          civicrm_state_province.abbreviation as state,
+          civicrm_country.name as country,
+          civicrm_location_type.name as location_type
+     FROM civicrm_contact
+LEFT JOIN civicrm_address ON civicrm_address.contact_id = civicrm_contact.id
+LEFT JOIN civicrm_state_province ON civicrm_address.state_province_id = civicrm_state_province.id
+LEFT JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id
+LEFT JOIN civicrm_location_type ON civicrm_location_type.id = civicrm_address.location_type_id
+WHERE civicrm_contact.id = $id ";
+
+        $params = array( );
+        if (!$locationTypeID) {
+            $sql .= " AND civicrm_address.is_primary = 1";
+        } else {
+            $sql .= " AND civicrm_address.location_type_id = %1";
+            $params[1] = array( $locationTypeID, 'Integer' );
+        }
+        $dao = CRM_Core_DAO::executeQuery( $sql, $params );
+        $location = array( );
+        $config = CRM_Core_Config::singleton( );
+        while ( $dao->fetch( ) ) {
+            $address = '';
+            CRM_Utils_String::append( $address, ', ',
+                                      array( $dao->street_address,
+                                             $dao->supplemental_address_1,
+                                             $dao->supplemental_address_2,
+                                             $dao->city,
+                                             $dao->state,
+                                             $dao->postal_code,
+                                             $dao->country
+                                             ) );
+            $location['address'] = addslashes( $address );
+        } 
+        return $location;
+    }
+}
diff --git a/CRM/Grant/BAO/PaymentSearch.php b/CRM/Grant/BAO/PaymentSearch.php
new file mode 100755
index 0000000..9ca49a9
--- /dev/null
+++ b/CRM/Grant/BAO/PaymentSearch.php
@@ -0,0 +1,864 @@
+<?php 
+
+/*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.1                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*/
+
+/**
+ *
+ * @package CRM
+ * @copyright CiviCRM LLC (c) 2004-2011
+ * $Id$
+ *
+ */
+
+require_once 'CRM/Grant/BAO/Grant.php';
+class CRM_Grant_BAO_PaymentSearch 
+{ 
+
+    const
+        MODE_GRANT_PAYMENT   =    1;
+    
+    static function &getFields( ) 
+    {
+        $fields = array( );
+        require_once 'CRM/Grant/BAO/GrantPayment.php';
+        $fields = CRM_Grant_BAO_GrantPayment::exportableFields( );
+        return $fields;
+    }
+    
+    function __construct( $params = null, $returnProperties = null, $fields = null,
+                          $includeContactIds = false, $strict = false, $mode = 1,
+                          $skipPermission = false, $searchDescendentGroups = true,
+                          $smartGroupCache = true, $displayRelationshipType = null,
+                          $operator = 'AND' ) 
+    {
+        $this->_params =& $params;
+
+        if ( $this->_params == null ) {
+            $this->_params = array( );
+        }
+        if ( empty( $returnProperties ) ) {
+            $this->_returnProperties = self::defaultReturnProperties( $mode );
+        } else {
+            $this->_returnProperties =& $returnProperties;
+           
+        }
+        $this->_includeContactIds       = $includeContactIds;
+        $this->_strict                  = $strict;
+        $this->_mode                    = $mode;
+        $this->_skipPermission          = $skipPermission;
+        $this->_smartGroupCache         = $smartGroupCache;
+        $this->_displayRelationshipType = $displayRelationshipType;
+        $this->setOperator( $operator );
+        
+        if ( $fields ) {
+            $this->_fields =& $fields;
+            $this->_search = false;
+            $this->_skipPermission = true;
+        } else {
+            require_once 'CRM/Grant/BAO/GrantPayment.php';
+            $this->_fields = CRM_Grant_BAO_GrantPayment::exportableFields( 'All', false, true, true );
+        }
+        // basically do all the work once, and then reuse it
+        $this->initialize( );
+
+
+    }
+
+    function initialize( ) 
+    {
+        $this->_select      = array( ); 
+        $this->_element     = array( ); 
+        $this->_tables      = array( );
+        $this->_whereTables = array( );
+        $this->_where       = array( ); 
+        $this->_qill        = array( );
+        $this->_options     = array( );
+        $this->_cfIDs       = array( );
+        $this->_paramLookup = array( );
+        $this->_having 		= array( );
+
+        $this->_customQuery = null;
+        $this->select(  ); 
+        $this->element(  );
+        if ( ! empty( $this->_params ) ) {
+            $this->buildParamsLookup( );
+        }
+        $this->_whereClause      = $this->whereClause( );
+        $this->_tables = array( 'civicrm_payment' => 1);
+        $this->_whereTables = array( 'civicrm_payment' => 1);
+        
+        $this->_fromClause       = "FROM civicrm_payment";
+        $this->_simpleFromClause = "FROM civicrm_payment";
+    }
+
+    function buildParamsLookup( ) 
+    {
+        foreach ( $this->_params as $value ) {
+            if ( !CRM_Utils_Array::value(0, $value) ) {
+                continue;
+            }
+            require_once 'CRM/Core/BAO/CustomField.php';
+
+            $cfID = CRM_Core_BAO_CustomField::getKeyID( $value[0] );
+            if ( $cfID ) {
+                if ( ! array_key_exists( $cfID, $this->_cfIDs ) ) {
+                    $this->_cfIDs[$cfID] = array( );
+                }
+                $this->_cfIDs[$cfID][] = $value;
+            }
+             
+            if ( ! array_key_exists( $value[0], $this->_paramLookup ) ) {
+                $this->_paramLookup[$value[0]] = array( );
+            }
+            $this->_paramLookup[$value[0]][] = $value;
+        }
+    }
+     
+    function whereClause( ) 
+    {
+        $this->_where[0] = array( );
+        $this->_qill[0]  = array( );
+        $config = CRM_Core_Config::singleton( );
+        
+        if ( ! empty( $this->_params ) ) {
+
+            foreach ( array_keys( $this->_params ) as $id ) {
+                if ( !CRM_Utils_Array::value(0, $this->_params[$id]) ) {
+                    continue;
+                }
+                $this->whereClauseSingle( $this->_params[$id] );
+            }
+        }
+
+        if ( $this->_customQuery ) {
+            // Added following if condition to avoid the wrong value diplay for 'myaccount' / any UF info.
+            // Hope it wont affect the other part of civicrm.. if it does please remove it.
+            if ( !empty($this->_customQuery->_where) ) {
+                $this->_where = CRM_Utils_Array::crmArrayMerge( $this->_where, $this->_customQuery->_where );
+            }
+             
+            $this->_qill  = CRM_Utils_Array::crmArrayMerge( $this->_qill , $this->_customQuery->_qill  );
+        }
+         
+        $clauses    = array( );
+        $andClauses = array( );
+         
+        $validClauses = 0;
+        if ( ! empty( $this->_where ) ) {
+            foreach ( $this->_where as $grouping => $values ) {
+                if ( $grouping > 0 && ! empty( $values ) ) {
+                    $clauses[$grouping] = ' ( ' . implode( " {$this->_operator} ", $values ) . ' ) ';
+                    $validClauses++;
+                }
+            }
+             
+            if ( ! empty( $this->_where[0] ) ) {
+                $andClauses[] = ' ( ' . implode( " AND", $this->_where[0] ) . ' ) ';
+            }
+            if ( ! empty( $clauses ) ) {
+                $andClauses[] = ' ( ' . implode( ' OR ', $clauses ) . ' ) ';
+            }
+             
+            if ( $validClauses > 1 ) {
+                $this->_useDistinct = true;
+            }
+        }
+         
+        return implode( ' AND ', $andClauses );
+    }
+    
+    function whereClauseSingle( &$values ) 
+    {
+        switch ( $values[0] ) {
+        case 'payment_status_id':
+            $this->payment_status( $values );
+            return;
+        case 'payable_to_name':
+            $this->payableName($values);
+            return;
+        case 'payment_batch_number':
+            $this->payment_batch_number($values);
+            return;
+        case 'payment_number':
+            $this->payment_number( $values );
+            return;
+        case 'amount':
+            $this->amount( $values ); 
+            return;
+        case 'payment_created_date_low':
+        case 'payment_created_date_high':
+          $this->paymentDates( $values );
+        return;
+
+        }
+    }
+    
+    function payment_status( &$values ) 
+    {
+        list( $name, $op, $value, $grouping, $wildcard ) = $values;
+         
+        if ( ! $op ) {
+            $op = '=';
+        }
+        $n = trim( $value ); 
+        if ( strtolower( $n ) == 'odd' ) {
+            $this->_where[$grouping][] = " ( civicrm_payment.payment_status_id % 2 = 1 )";
+            $this->_qill[$grouping][]  = ts( 'Payment Status Id is odd' );
+        } else if ( strtolower( $n ) == 'even' ) {
+            $this->_where[$grouping][] = " ( civicrm_payment.payment_status_id % 2 = 0 )";
+            $this->_qill[$grouping][]  = ts( 'Payment Status Id is even' );
+        } else {
+            $value = strtolower(CRM_Core_DAO::escapeString($n));
+            $value = "'$value'";
+             
+            $this->_where[$grouping][] = " ( civicrm_payment.payment_status_id $op $value )";
+            require_once 'CRM/Core/OptionGroup.php';
+            $paymentStatus = CRM_Core_OptionGroup::values( 'payment' );
+            $n =$paymentStatus[$n];
+            $this->_qill[$grouping][]  = ts( 'Payment Status' ) . " $op '$n'";
+        }
+         
+        $this->_tables['civicrm_payment'] = $this->_whereTables['civicrm_payment'] = 1; 
+    }
+
+    function payableName( &$values ) 
+    {
+        list( $name, $op, $value, $grouping, $wildcard ) = $values;
+        $op = 'LIKE';
+        $newName = $name;
+        $name    = trim( $value ); 
+        
+        if ( empty( $name ) ) {
+            return;
+        }
+
+        $config = CRM_Core_Config::singleton( );
+
+        $sub  = array( ); 
+
+        //By default, $sub elements should be joined together with OR statements (don't change this variable).
+        $subGlue = ' OR ';
+
+        $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
+        
+        if ( substr( $name, 0 , 1 ) == '"' &&
+             substr( $name, -1, 1 ) == '"' ) {
+            //If name is encased in double quotes, the value should be taken to be the string in entirety and the 
+            $value = substr( $name, 1, -1 );
+            $value = $strtolower(CRM_Core_DAO::escapeString($value));
+            $wc = ( $newName == 'payable_to_name') ? 'LOWER(civicrm_payment.payable_to_name)' : 'LOWER(civicrm_payment.payable_to_name)';
+
+            $sub[] = " ( $wc = '%$value%' ) ";
+        } else if ( strpos( $name, ',' ) !== false ) {
+            // if we have a comma in the string, search for the entire string 
+            $value = $strtolower(CRM_Core_DAO::escapeString($name));
+            if ( $wildcard ) {
+                if ( $config->includeWildCardInName ) {
+                    $value = "'%$value%'";
+                } else {
+                    $value = "'$value%'";
+                }
+                $op    = 'LIKE';
+            } else {
+                $value = "'%$value%'";
+            }
+            if( $newName == 'payable_to_name') {
+                $wc = ( $op != 'LIKE' ) ? "LOWER(civicrm_payment.payable_to_name)" : "civicrm_payment.payable_to_name";
+            }
+            $sub[] = " ( $wc $op $value )";
+        } else {
+            //Else, the string should be treated as a series of keywords to be matched with match ANY/ match ALL depending on Civi config settings (see CiviAdmin)
+            
+            // The Civi configuration setting can be overridden if the string *starts* with the case insenstive strings 'AND:' or 'OR:'  
+            // TO THINK ABOUT: what happens when someone searches for the following "AND: 'a string in quotes'"? - probably nothing - it would make the AND OR variable reduntant because there is only one search string?
+
+            // Check to see if the $subGlue is overridden in the search text
+            if(strtolower(substr( $name,  0,  4 ))=='and:'){
+                $name = substr( $name,  4 );
+                $subGlue = ' AND ';
+            }
+            if(strtolower(substr( $name,  0,  3 ))=='or:'){
+                $name = substr( $name,  3 );
+                $subGlue = ' OR ';
+            }
+        	
+            $firstChar = substr( $name,  0,  1 );
+            $lastChar  = substr( $name, -1, 1 );
+            $quotes    = array( "'", '"' );
+            if ( in_array( $firstChar, $quotes ) &&
+                 in_array( $lastChar , $quotes ) ) {
+                $name   = substr( $name,  1 );
+                $name   = substr( $name, 0, -1 );
+                $pieces = array( $name );
+            } else {
+                $pieces =  explode( ' ', $name );
+            }
+            foreach ( $pieces as $piece ) { 
+                $value = $strtolower( CRM_Core_DAO::escapeString( trim( $piece ) ) );
+                if ( strlen( $value ) ) {
+                    // Added If as a sanitization - without it, when you do an OR search, any string with
+                    // double spaces (i.e. "  ") or that has a space after the keyword (e.g. "OR: ") will
+                    // return all contacts because it will include a condition similar to "OR contact
+                    // name LIKE '%'".  It might be better to replace this with array_filter. 
+                    $fieldsub = array();
+                    if ( $wildcard ) {
+                        if ( $config->includeWildCardInName ) {
+                            $value = "'%$value%'";
+                        } else {
+                            $value = "'$value%'";
+                        }
+                        $op    = 'LIKE';
+                    } else {
+                        $value = "'%$value%'";
+                    }
+                    if( $newName == 'payable_to_name') {
+                        $wc = ( $op != 'LIKE' ) ? "LOWER(civicrm_payment.payable_to_name)" : "civicrm_payment.payable_to_name";
+                    }
+                    $fieldsub[] = " ( $wc $op $value )";
+                    $sub[] = ' ( ' . implode( ' OR ', $fieldsub ) . ' ) ';
+                    // I seperated the glueing in two.  The first stage should always be OR because we are searching for matches in *ANY* of these fields
+                }
+            }
+        } 
+
+        $sub = ' ( ' . implode( $subGlue, $sub ) . ' ) ';
+        $this->_where[$grouping][] = $sub;
+        $this->_qill[$grouping][]  = ts( 'Payee Name like' ) . " - '$name'";
+        $this->_tables['civicrm_payment'] = $this->_whereTables['civicrm_payment'] = 1; 
+    }
+
+    function paymentDates( $values ) {
+        list( $name, $op, $value, $grouping, $wildcard ) = $values;
+       
+        if ( ($name == 'payment_created_date_low') || ($name == 'payment_created_date_high') ) {
+            
+            $this->dateQueryBuilder( $values,
+                                     'civicrm_payment', 'payment_created_date', 'payment_created_date', ts('Date') );
+        } 
+    }
+    
+    
+    function &getWhereValues( $name, $grouping )  {
+        $result = null;
+        foreach ( $this->_params as $id => $values ) {
+            if ( $values[0] == $name && $values[3] == $grouping ) {
+                return $values;
+            }
+        }
+            
+        return $result;
+    }
+
+    function dateQueryBuilder( &$values,
+                               $tableName, $fieldName, $dbFieldName, $fieldTitle,
+                               $appendTimeStamp = true ) 
+    {
+        list( $name, $op, $value, $grouping, $wildcard ) = $values;
+
+        if ( ! $value ) {
+            return;
+        }
+
+        if ( $name == "{$fieldName}_low" ||
+             $name == "{$fieldName}_high" ) {
+            if ( isset( $this->_rangeCache[$fieldName] ) ) {
+                return;
+            }
+            $this->_rangeCache[$fieldName] = 1;
+
+            $secondOP = $secondPhrase = $secondValue = $secondDate = $secondDateFormat = null;
+
+            if ( $name == $fieldName . '_low' ) {
+                $firstOP      = '>=';
+                $firstPhrase  = 'greater than or equal to';
+                $firstDate    = CRM_Utils_Date::processDate( $value );
+
+                $secondValues = $this->getWhereValues( "{$fieldName}_high", $grouping );
+                if ( ! empty( $secondValues ) &&
+                     $secondValues[2] ) {
+                    $secondOP          = '<=';
+                    $secondPhrase      = 'less than or equal to';
+                    $secondValue       = $secondValues[2];
+
+                    if ( $appendTimeStamp &&
+                         strlen( $secondValue ) == 10 ) {
+                        $secondValue .= ' 23:59:59';
+                    }
+                    $secondDate = CRM_Utils_Date::processDate( $secondValue );
+                }
+
+            } else if ( $name == $fieldName . '_high' ) {
+                $firstOP           = '<=';
+                $firstPhrase       = 'less than or equal to';
+
+                if ( $appendTimeStamp &&
+                     strlen( $value ) == 10 ) {
+                    $value .= ' 23:59:59';
+                }
+                $firstDate    = CRM_Utils_Date::processDate( $value );
+
+                $secondValues = $this->getWhereValues( "{$fieldName}_low", $grouping );
+                if ( ! empty( $secondValues ) &&
+                     $secondValues[2] ) {
+                    $secondOP          = '>=';
+                    $secondPhrase      = 'greater than or equal to';
+                    $secondValue       = $secondValues[2];
+                    $secondDate = CRM_Utils_Date::processDate( $secondValue );
+                }
+            }
+
+            if ( ! $appendTimeStamp ) {
+                $firstDate = substr(  $date, 0, 8 );
+            }
+            $firstDateFormat = CRM_Utils_Date::customFormat( $firstDate );
+
+            if ( $secondDate ) {
+                if ( ! $appendTimeStamp ) {
+                    $secondDate = substr(  $secondDate, 0, 8 );
+                }
+                $secondDateFormat = CRM_Utils_Date::customFormat( $secondDate );
+            }
+
+            $this->_tables[$tableName] = $this->_whereTables[$tableName] = 1;
+            if ( $secondDate ) {
+                $this->_where[$grouping][] = "
+( {$tableName}.{$dbFieldName} $firstOP '$firstDate' ) AND
+( {$tableName}.{$dbFieldName} $secondOP '$secondDate' )
+";
+                $this->_qill[$grouping][]  = 
+                    "$fieldTitle - $firstPhrase \"$firstDateFormat\" " .
+                    ts('AND') .
+                    " $secondPhrase \"$secondDateFormat\"";
+            } else {
+                $this->_where[$grouping][] = "{$tableName}.{$dbFieldName} $firstOP '$firstDate'";
+                $this->_qill[$grouping][]  = "$fieldTitle - $firstPhrase \"$firstDateFormat\"";
+            }
+        }
+
+        if ( $name == $fieldName ) {
+            $op     = '=';
+            $phrase = '=';
+
+            $date = CRM_Utils_Date::processDate( $value );
+
+            if ( !$appendTimeStamp ) {
+                $date = substr(  $date, 0, 8 );
+            }
+
+            $format  = CRM_Utils_Date::customFormat( $date );
+            
+            if ( $date ) {
+                $this->_where[$grouping][] = "{$tableName}.{$dbFieldName} $op '$date'";
+                if ( $tableName == 'civicrm_log' &&
+                     $fieldName == 'added_log_date' ) {
+                    //CRM-6903 --hack to check modified date of first record.
+                    //as added date means first modified date of object.
+                    $addedDateQuery = 'select id from civicrm_log group by entity_id order by id';
+                    $this->_where[$grouping][] = "civicrm_log.id IN ( {$addedDateQuery} )";
+                }
+            } else {
+                $this->_where[$grouping][] = "{$tableName}.{$dbFieldName} $op";
+            }
+            $this->_tables[$tableName] = $this->_whereTables[$tableName] = 1;
+            $this->_qill[$grouping][]  = "$fieldTitle - $phrase \"$format\"";
+        }
+    }
+
+    function amount( &$values ) 
+    {
+        list( $name, $op, $value, $grouping, $wildcard ) = $values;
+        
+        if ( ! $op ) {
+            $op = '=';
+        }
+        $n = trim( $value ); 
+        if ( strtolower( $n ) == 'odd' ) {
+            $this->_where[$grouping][] = " ( civicrm_payment.amount % 2 = 1 )";
+            $this->_qill[$grouping][]  = ts( 'Payment Amount is odd' );
+        } else if ( strtolower( $n ) == 'even' ) {
+            $this->_where[$grouping][] = " ( civicrm_payment.amount % 2 = 0 )";
+            $this->_qill[$grouping][]  = ts( 'Payment Amount is even' );
+        } else {
+            $value = strtolower(CRM_Core_DAO::escapeString($n));
+            $value = "'$value'";
+             
+            $this->_where[$grouping][] = " ( civicrm_payment.amount $op $value )";
+            $this->_qill[$grouping][]  = ts( 'Payment Amount' ) . " $op '$n'";
+        }
+         
+        $this->_tables['civicrm_payment'] = $this->_whereTables['civicrm_payment'] = 1; 
+
+    }
+
+    function payment_number( &$values ) 
+    {
+        list( $name, $op, $value, $grouping, $wildcard ) = $values;
+         
+        if ( ! $op ) {
+            $op = '=';
+        }
+        $n = trim( $value ); 
+        if ( strtolower( $n ) == 'odd' ) {
+            $this->_where[$grouping][] = " ( civicrm_payment.payment_number % 2 = 1 )";
+            $this->_qill[$grouping][]  = ts( 'Payment Batch Number is odd' );
+        } else if ( strtolower( $n ) == 'even' ) {
+            $this->_where[$grouping][] = " ( civicrm_payment.payment_number % 2 = 0 )";
+            $this->_qill[$grouping][]  = ts( 'Payment Batch Number is even' );
+        } else {
+            $value = strtolower(CRM_Core_DAO::escapeString($n));
+            $value = "'$value'";
+             
+            $this->_where[$grouping][] = " ( civicrm_payment.payment_number $op $value )";
+            $this->_qill[$grouping][]  = ts( 'Payment Number' ) . " $op '$n'";
+        }
+         
+        $this->_tables['civicrm_payment'] = $this->_whereTables['civicrm_payment'] = 1; 
+    }
+     
+    function payment_batch_number( &$values ) 
+    {
+        list( $name, $op, $value, $grouping, $wildcard ) = $values;
+        
+        if ( ! $op ) {
+            $op = '=';
+        }
+        $n = trim( $value ); 
+        if ( strtolower( $n ) == 'odd' ) {
+            $this->_where[$grouping][] = " ( civicrm_payment.payment_batch_number % 2 = 1 )";
+            $this->_qill[$grouping][]  = ts( 'Payment Batch Number is odd' );
+        } else if ( strtolower( $n ) == 'even' ) {
+            $this->_where[$grouping][] = " ( civicrm_payment.payment_batch_number % 2 = 0 )";
+            $this->_qill[$grouping][]  = ts( 'Payment Batch Number is even' );
+        } else {
+            $value = strtolower(CRM_Core_DAO::escapeString($n));
+            $value = "'$value'";
+
+            $this->_where[$grouping][] = " ( civicrm_payment.payment_batch_number $op $value )";
+            $this->_qill[$grouping][]  = ts( 'Payment Batch Number' ) . " $op '$n'";
+        }
+
+        $this->_tables['civicrm_payment'] = $this->_whereTables['civicrm_payment'] = 1; 
+    }
+
+    function grantID( &$values ) 
+    {
+        $this->_where[$grouping][] = " ( civicrm_entity_payment.entity_id = $values )";
+        $this->_tables['civicrm_entity_payment'] = $this->_whereTables['civicrm_entity_payment'] = 1; 
+    }
+    /** 
+     * build select for CiviGrant 
+     * 
+     * @return void  
+     * @access public  
+     */
+    function select(  ) 
+    {   
+        $this->_select['id']                    = 'civicrm_payment.id as id';
+        $this->_select['payable_to_name']       = 'civicrm_payment.payable_to_name as payable_to_name';
+        $this->_select['payment_batch_number']  = 'civicrm_payment.payment_batch_number as payment_batch_number';
+        $this->_select['payment_number']        = 'civicrm_payment.payment_number as payment_number';
+        $this->_select['payment_status_id']     = 'civicrm_payment.payment_status_id as payment_status_id';
+        $this->_select['payment_created_date']  = 'civicrm_payment.payment_created_date as payment_created_date';
+        $this->_select['amount']                = 'civicrm_payment.amount as amount';
+        return $this->_select;
+    }
+    
+    function element(  ) 
+    {    
+        $this->_element['id']                    = 1;
+        $this->_element['payable_to_name']       = 1;
+        $this->_element['payment_batch_number']  = 1;
+        $this->_element['payment_number']        = 1;
+        $this->_element['payment_status_id']     = 1;
+        $this->_element['payment_created_date']  = 1;
+        $this->_element['amount']                = 1;
+        return $this->_select;
+        return $this->_element;
+    }
+    
+    /** 
+     * Given a list of conditions in params generate the required
+     * where clause
+     * 
+     * @return void 
+     * @access public 
+     */ 
+    static function where( &$query ) 
+    {
+        foreach ( array_keys( $query->_params ) as $id ) {
+            if ( substr( $query->_params[$id][0], 0, 6) == 'grant_' ) {
+                self::whereClauseSingle( $query->_params[$id], $query );
+            }
+        }
+    }
+  
+
+    /**
+     * getter for the qill object
+     *
+     * @return string
+     * @access public
+     */
+    function qill( ) {
+        return (isset($this->_qill)) ? $this->_qill : "";
+    }
+   
+    static function defaultReturnProperties( $mode,
+                                             $includeCustomFields = true )
+    {
+        $properties = null;
+        if ( $mode & CRM_Grant_BAO_PaymentSearch::MODE_GRANT_PAYMENT ) {
+
+            $properties = array('id'                  => 1,
+                                'payable_to_name'     => 1,
+                                'payment_batch_number'=> 1,
+                                'payment_number'      => 1,
+                                'payment_status_id'   => 1,
+                                'payment_created_date'=> 1,
+                                'amount'              => 1,
+                                );
+        }
+
+        return $properties;
+    }
+
+    /**
+     * add all the elements shared between grant search and advanaced search
+     *
+     * @access public 
+     * @return void
+     * @static
+     */   
+        
+    static function addShowHide( &$showHide ) 
+    {
+        $showHide->addHide( 'grantForm' );
+        $showHide->addShow( 'grantForm_show' );
+    }
+    
+    static function searchAction( &$row, $id ) 
+    {
+    }
+
+    static function tableNames( &$tables ) 
+    {
+    }
+  
+    function query( $count = false, $sortByChar = false, $groupContacts = false ) 
+    {
+        $select = 'SELECT ';
+        if ( !$count ) {
+            if (  ! empty( $this->_select ) ) {
+                $select .= implode( ', ', $this->_select );
+            }
+        } else {
+            $select .= "count( DISTINCT ".$this->_distinctComponentClause." ) ";
+        }
+        $from = '';
+        if (  ! empty( $this->_fromClause ) ) {
+            $from = $this->_fromClause;
+        }
+        $where = '';
+        if ( ! empty( $this->_whereClause ) ) {
+            $where = "WHERE {$this->_whereClause}";
+        }
+        
+        $having = '';
+        if ( ! empty( $this->_having ) ) {
+            foreach ( $this->_having as $havingsets ) {
+                foreach ( $havingsets as $havingset ) {
+                    $havingvalue[] = $havingset;
+                }
+            }
+            $having = ' HAVING ' . implode( ' AND ', $havingvalue );
+        }
+        return array( $select, $from, $where, $having );
+    }
+    
+    function searchQuery( $offset = 0, $rowCount = 0, $sort = null, 
+                          $count = false, $includeContactIds = false,
+                          $sortByChar = false, $groupContacts = false,
+                          $returnQuery = false,
+                          $additionalWhereClause = null, $sortOrder = null,
+                          $additionalFromClause = null, $skipOrderAndLimit = false ) 
+    {
+        
+        list( $select, $from, $where, $having ) = $this->query( $count, $sortByChar, $groupContacts );
+        $order = $orderBy = $limit = '';
+        if ( !$count )  {
+            
+            $config = CRM_Core_Config::singleton( );
+            if ( $config->includeOrderByClause ||
+                 isset( $this->_distinctComponentClause ) ) {
+             
+                if ($sort) {
+                    if ( is_string( $sort ) ) {
+                        $orderBy = $sort;
+                        
+                    } else {
+                        $orderBy = trim( $sort->orderBy() );
+                        
+                    }
+                    if ( ! empty( $orderBy ) ) {
+
+                        $order = " ORDER BY $orderBy";
+                        
+                        if ( $sortOrder ) {
+                            $order .= " $sortOrder";
+                        }
+                    }
+                } else if ($sortByChar) { 
+                    $order = " ORDER BY UPPER(LEFT(civicrm_payment.payable_to_name, 1)) asc";
+                } else {
+                    $order = " ORDER BY civicrm_payment.payable_to_name asc, civicrm_payment.id";
+                }
+            }
+
+            if ( $rowCount > 0 && $offset >= 0 ) {
+                $limit = " LIMIT $offset, $rowCount ";
+                
+                if ( isset( $this->_distinctComponentClause ) ) {
+                    $limitSelect = "SELECT {$this->_distinctComponentClause}";
+                } else {
+                    $limitSelect = ( $this->_useDistinct ) ?
+                        'SELECT DISTINCT(civicrm_payment.id) as id' :
+                        'SELECT civicrm_payment.id as id';
+                }
+            }
+            $groupBy = 'GROUP BY civicrm_payment.id';
+            $query = "$select $from $where $having $groupBy $order $limit";
+        }
+        
+        if ( $count ) {
+            $query = "$select $from $where";
+            return CRM_Core_DAO::singleValueQuery( $query );
+        }
+       
+        $dao = CRM_Core_DAO::executeQuery( $query );
+        if ( $groupContacts ) {
+            $ids = array( );
+            while ( $dao->fetch( ) ) {
+                $ids[] = $dao->id;
+            }
+            return implode( ',', $ids );
+        }
+        return $dao;
+    }
+
+    static function convertFormValues( &$formValues, $wildcard = 0, $useEquals = false ) 
+    {
+        $params = array( );
+        if ( empty( $formValues ) ) {
+            return $params;
+        }
+        foreach ( $formValues as $id => $values ) {
+            $values = CRM_Grant_BAO_PaymentSearch::fixWhereValues( $id, $values, $wildcard, $useEquals );
+            if ( ! $values ) {
+                continue;
+            }
+            $params[] = $values;
+        }
+        return $params;
+    }
+
+    static function &fixWhereValues( $id, &$values, $wildcard = 0, $useEquals = false ) 
+    {
+        // skip a few search variables
+        static $skipWhere   = null;
+        static $arrayValues = null;
+        static $likeNames   = null;
+        $result = null;
+
+        if ( CRM_Utils_System::isNull( $values ) ) {
+            return $result;
+        }
+
+        if  ( ! $skipWhere ) {
+            $skipWhere   = array( 'task', 'radio_ts', 'uf_group_id',
+                                  'component_mode', 'qfKey', 'operator',
+                                  'display_relationship_type' );
+        }
+
+        if ( in_array( $id, $skipWhere ) ||
+             substr( $id, 0, 4 ) == '_qf_' ||
+             substr( $id, 0, 7 ) == 'hidden_' ) {
+            return $result;
+        }
+
+        if ( ! $likeNames ) {
+            $likeNames = array( 'sort_name', 'email', 'note', 'display_name' );
+        }
+
+        if ( ! $useEquals &&
+             in_array( $id, $likeNames ) ) {
+            $result = array( $id, 'LIKE', $values, 0, 1 );
+        } else if ( is_string( $values ) && strpos( $values, '%' ) !== false ) {
+            $result = array( $id, 'LIKE', $values, 0, 0 );
+        } else if ( $id == 'group' ) {
+            if ( is_array( $values ) ) {
+                foreach ( $values as $groupIds => $val ) {
+                    $matches = array( );
+                    if ( preg_match( '/-(\d+)$/', $groupIds, $matches ) ) {
+                        if ( strlen( $matches[1] ) > 0 ) {
+                            $values[$matches[1]] = 1;
+                            unset( $values[$groupIds] );
+                        }
+                    }
+                }
+            } else {
+                $groupIds = explode( ',', $values );
+                unset( $values );
+                foreach( $groupIds as $groupId ) {
+                    $values[$groupId] = 1;
+                }
+            }
+
+            $result = array( $id, 'IN', $values, 0, 0 );
+        } else if ( $id == 'contact_tags' || $id == 'tag' ) {
+            if (! is_array( $values ) ) {
+                $tagIds = explode( ',', $values );
+                unset( $values );
+                foreach( $tagIds as $tagId ) {
+                    $values[$tagId] = 1;
+                }
+            }
+            $result = array( $id, 'IN', $values, 0, 0 );
+        } else {
+            $result = array( $id, '=', $values, 0, $wildcard );
+        }
+
+        return $result;
+    }
+    function setOperator( $operator ) {
+        $validOperators = array( 'AND', 'OR' );
+        if ( ! in_array( $operator, $validOperators ) ) {
+            $operator = 'AND';
+        }
+        $this->_operator = $operator;
+    }
+
+}
\ No newline at end of file
diff --git a/CRM/Grant/BAO/Query.php b/CRM/Grant/BAO/Query.php
new file mode 100755
index 0000000..9e7a3b3
--- /dev/null
+++ b/CRM/Grant/BAO/Query.php
@@ -0,0 +1,428 @@
+<?php 
+
+/*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.1                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*/
+
+/**
+ *
+ * @package CRM
+ * @copyright CiviCRM LLC (c) 2004-2011
+ * $Id$
+ *
+ */
+
+require_once 'CRM/Grant/BAO/Grant.php';
+class CRM_Grant_BAO_Query 
+{
+    static function &getFields( ) 
+    {
+        $fields = array( );
+        require_once 'CRM/Grant/BAO/Grant.php';
+        $fields = CRM_Grant_BAO_Grant::exportableFields( );
+        return $fields;
+    }
+   
+    /** 
+     * build select for CiviGrant 
+     * 
+     * @return void  
+     * @access public  
+     */
+    static function select( &$query ) 
+    {
+        if ( $query->_mode & CRM_Contact_BAO_Query::MODE_GRANT ) {
+            if ( CRM_Utils_Array::value( 'grant_status_id', $query->_returnProperties ) ) {
+                $query->_select['grant_status_id']  = 'grant_status.id as grant_status_id';
+                $query->_element['grant_status']    = 1;
+                $query->_tables['grant_status']     = $query->_whereTables['grant_status'] = 1;
+                $query->_tables['civicrm_grant']    = $query->_whereTables['civicrm_grant'] = 1;
+            }
+
+            if ( CRM_Utils_Array::value( 'grant_status', $query->_returnProperties ) ) {
+                $query->_select['grant_status']  = 'grant_status.label as grant_status';
+                $query->_element['grant_status']    = 1;
+                $query->_tables['grant_status']     = $query->_whereTables['grant_status'] = 1;
+                $query->_tables['civicrm_grant']    = $query->_whereTables['civicrm_grant'] = 1;
+            }
+
+            if ( CRM_Utils_Array::value( 'grant_type_id', $query->_returnProperties ) ) {
+                $query->_select['grant_type_id']  = 'grant_type.id as grant_type_id';
+                $query->_element['grant_type']    = 1;
+                $query->_tables['grant_type']     = $query->_whereTables['grant_type'] = 1;
+                $query->_tables['civicrm_grant']  = $query->_whereTables['civicrm_grant'] = 1;
+            }
+
+            if ( CRM_Utils_Array::value( 'grant_type', $query->_returnProperties ) ) {
+                $query->_select['grant_type']  = 'grant_type.label as grant_type';
+                $query->_element['grant_type']    = 1;
+                $query->_tables['grant_type']     = $query->_whereTables['grant_type'] = 1;
+                $query->_tables['civicrm_grant']  = $query->_whereTables['civicrm_grant'] = 1;
+            }
+            
+            if ( CRM_Utils_Array::value( 'grant_note', $query->_returnProperties ) ) {
+              $query->_select['grant_note']  = "civicrm_note.note as grant_note";
+              $query->_element['grant_note'] = 1;
+              $query->_tables['grant_note']  = 1;
+            }
+
+            // if ( CRM_Utils_Array::value( 'course_conference_type_21', $query->_returnProperties ) ) { 
+            //   $query->_select['course_type']  = "civicrm_value_course_conference_details_6.course_conference_type_21 as course_type";
+            //   $query->_element['course_type'] = 1;
+            //   $query->_tables['course_type']  = 1;
+            // }
+            
+            // if ( CRM_Utils_Array::value( 'course_conference_name_24', $query->_returnProperties ) ) {
+            //   $query->_select['course_name']  = "civicrm_value_course_conference_details_6.course_conference_name_24 as course_name";
+            //   $query->_element['course_name'] = 1;
+            //   $query->_tables['course_name']  = 1;
+            // }
+            
+            $query->_select['grant_amount_requested'] = 'civicrm_grant.amount_requested as grant_amount_requested';
+            $query->_select['grant_amount_granted']   = 'civicrm_grant.amount_granted as grant_amount_granted';
+            $query->_select['grant_amount_total']     = 'civicrm_grant.amount_total as grant_amount_total';
+            $query->_select['grant_application_received_date']  = 'civicrm_grant.application_received_date as grant_application_received_date ';
+            $query->_element['grant_type_id']     = 1;
+            $query->_element['grant_status_id']   = 1;
+            $query->_tables['civicrm_grant']      = 1;
+            $query->_whereTables['civicrm_grant'] = 1;
+        }
+    }
+    
+    /** 
+     * Given a list of conditions in params generate the required
+     * where clause
+     * 
+     * @return void 
+     * @access public 
+     */ 
+    static function where( &$query ) 
+    {
+        foreach ( array_keys( $query->_params ) as $id ) {
+            if ( substr( $query->_params[$id][0], 0, 6) == 'grant_' ) {
+                self::whereClauseSingle( $query->_params[$id], $query );
+            }
+        }
+    }
+  
+    static function whereClauseSingle( &$values, &$query ) 
+    {       
+        $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
+
+        
+        list( $name, $op, $value, $grouping, $wildcard ) = $values;
+        switch( $name ) {
+            
+        case 'grant_money_transfer_date_low':
+        case 'grant_money_transfer_date_high':
+            $query->dateQueryBuilder( $values, 'civicrm_grant',
+                                      'grant_money_transfer_date', 'money_transfer_date',
+                                      'Money Transfer Date' );
+            return;
+        
+        case 'grant_money_transfer_date_notset' :
+            $query->_where[$grouping][] = "civicrm_grant.money_transfer_date IS NULL";
+            $query->_qill[$grouping][]  = ts( "Grant Money Transfer Date is NULL" );
+            $query->_tables['civicrm_grant'] = $query->_whereTables['civicrm_grant'] = 1;
+            return;
+
+ 
+        case 'grant_application_received_date_low':
+        case 'grant_application_received_date_high':
+            $query->dateQueryBuilder( $values, 'civicrm_grant',
+                                      'grant_application_received_date',
+                                      'application_received_date', 'Application Received Date' );
+            return;
+
+        case 'grant_application_received_notset' :
+            $query->_where[$grouping][] = "civicrm_grant.application_received_date IS NULL";
+            $query->_qill[$grouping][]  = ts( "Grant Application Received Date is NULL" );
+            $query->_tables['civicrm_grant'] = $query->_whereTables['civicrm_grant'] = 1;
+            return ;
+        
+        case 'grant_due_date_low':
+        case 'grant_due_date_high':
+            $query->dateQueryBuilder( $values, 'civicrm_grant',
+                                      'grant_due_date',
+                                      'grant_due_date', 'Grant Due Date' );
+            return;
+
+        case 'grant_due_date_notset':
+           $query->_where[$grouping][] =   "civicrm_grant.grant_due_date IS NULL";
+           $query->_qill[$grouping][]  = ts( "Grant Due Date is NULL" );
+           $query->_tables['civicrm_grant'] = $query->_whereTables['civicrm_grant'] = 1;
+           return ;
+
+
+        case 'grant_decision_date_low':
+        case 'grant_decision_date_high':
+            $query->dateQueryBuilder( $values, 'civicrm_grant',
+                                      'grant_decision_date',
+                                      'decision_date', 'Grant Decision Date' );
+            return;
+        case 'grant_decision_date_notset':
+          $query->_where[$grouping][] = "civicrm_grant.decision_date IS NULL";
+          $query->_qill[$grouping][]  = ts( "Grant Decision Date is NULL" );
+          $query->_tables['civicrm_grant'] = $query->_whereTables['civicrm_grant'] = 1;
+          return ;
+
+        case 'grant_type_id':
+            
+            $value = $strtolower(CRM_Core_DAO::escapeString(trim($value)));
+
+            $query->_where[$grouping][] = "civicrm_grant.grant_type_id $op '{$value}'";
+            
+            require_once 'CRM/Core/OptionGroup.php';
+            $grantTypes  = CRM_Core_OptionGroup::values('grant_type' );
+            $value = $grantTypes[$value];
+            $query->_qill[$grouping ][] = ts( 'Grant Type %2 %1', array( 1 => $value, 2 => $op) );
+            $query->_tables['civicrm_grant'] = $query->_whereTables['civicrm_grant'] = 1;
+
+            return;
+            
+        case 'grant_program_id':
+            
+            $value = $strtolower(CRM_Core_DAO::escapeString(trim($value)));
+
+            $query->_where[$grouping][] = "civicrm_grant.grant_program_id $op '{$value}'";
+            
+            $grantPrograms = CRM_Grant_BAO_Grant::getGrantPrograms();
+            $value = $grantPrograms[$value];
+            $query->_qill[$grouping ][] = ts( 'Grant Type %2 %1', array( 1 => $value, 2 => $op) );
+            $query->_tables['civicrm_grant'] = $query->_whereTables['civicrm_grant'] = 1;
+
+            return;
+
+        case 'grant_status_id':
+            
+            $value = $strtolower(CRM_Core_DAO::escapeString(trim($value)));
+
+            $query->_where[$grouping][] = "civicrm_grant.status_id $op '{$value}'";
+            
+            require_once 'CRM/Core/OptionGroup.php';
+
+            $grantStatus  = CRM_Core_OptionGroup::values('grant_status' );
+            $value = $grantStatus[$value];
+
+            $query->_qill[$grouping ][] = ts( 'Grant Status %2 %1', array( 1 => $value, 2 => $op) );
+            $query->_tables['civicrm_grant'] = $query->_whereTables['civicrm_grant'] = 1;
+
+            return;
+
+        case 'grant_report_received':
+          
+          if ( $value == 1 ) {
+            $yesNo = 'Yes';
+            $query->_where[$grouping][] = "civicrm_grant.grant_report_received $op $value";
+          } else if ( $value == 0 ){
+                $yesNo = 'No';
+                $query->_where[$grouping][] = "civicrm_grant.grant_report_received IS NULL";
+          }
+          
+          $query->_qill[$grouping][]  = "Grant Report Received = $yesNo ";
+          $query->_tables['civicrm_grant'] = $query->_whereTables['civicrm_grant'] = 1;
+          
+          return;
+     
+        case 'grant_amount':
+        case 'grant_amount_low':
+        case 'grant_amount_high':
+            $query->numberRangeBuilder( $values,
+                                        'civicrm_grant', 'grant_amount', 'amount_granted', 'Amount Granted' );
+
+        case 'grant_amount_total':
+        case 'grant_amount_total_low':
+        case 'grant_amount_total_high':
+            $query->numberRangeBuilder( $values,
+                                        'civicrm_grant', 'grant_amount_total', 'amount_total', 'Amount Allocated' );
+        case 'grant_assessment':
+        case 'grant_assessment_low':
+        case 'grant_assessment_high':
+            $query->numberRangeBuilder( $values,
+                                        'civicrm_grant', 'grant_assessment', 'assessment', 'Assessment' );
+        } 
+    }
+
+    static function from( $name, $mode, $side ) 
+    { 
+        $from = null;
+        switch ( $name ) {
+        case 'civicrm_grant':
+            $from = " $side JOIN civicrm_grant ON civicrm_grant.contact_id = contact_a.id ";
+            break;
+            
+        case 'grant_status':
+            $from .= " $side JOIN civicrm_option_group option_group_grant_status ON (option_group_grant_status.name = 'grant_status')";
+            $from .= " $side JOIN civicrm_option_value grant_status ON (civicrm_grant.status_id = grant_status.value AND option_group_grant_status.id = grant_status.option_group_id ) ";
+            break;
+            
+        case 'grant_type':
+            $from .= " $side JOIN civicrm_option_group option_group_grant_type ON (option_group_grant_type.name = 'grant_type')";
+            if( $mode & CRM_Contact_BAO_Query::MODE_GRANT ) {
+                $from .= " INNER JOIN civicrm_option_value grant_type ON (civicrm_grant.grant_type_id = grant_type.value AND option_group_grant_type.id = grant_type.option_group_id ) ";
+            } else {
+                $from .= " $side JOIN civicrm_option_value grant_type ON (civicrm_grant.grant_type_id = grant_type.value AND option_group_grant_type.id = grant_type.option_group_id ) ";
+            }
+            break;
+        case 'grant_note':
+            $from .= " $side JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_grant' AND
+                                                        civicrm_grant.id = civicrm_note.entity_id )";
+            break;
+        case 'course_name':
+          $from .= " $side JOIN civicrm_value_course_conference_details_6 ON ( civicrm_grant.id = civicrm_value_course_conference_details_6.entity_id )";
+            break;
+        } 
+        return $from;
+        
+    }
+    
+    /**
+     * getter for the qill object
+     *
+     * @return string
+     * @access public
+     */
+    function qill( ) {
+        return (isset($this->_qill)) ? $this->_qill : "";
+    }
+   
+    static function defaultReturnProperties( $mode,
+                                             $includeCustomFields = true )
+    {
+        $properties = null;
+        if ( $mode & CRM_Contact_BAO_Query::MODE_GRANT ) {
+            $properties = array(
+                                'contact_type'                    => 1,
+                                'contact_sub_type'                => 1,
+                                'sort_name'                       => 1,
+                                'grant_id'                        => 1, 
+                                'grant_type'                      => 1, 
+                                'grant_status'                    => 1,
+                                'grant_amount_requested'          => 1,
+                                'grant_application_received_date' => 1,
+                                'course_conference_type_21'       => 1,
+                                'course_conference_name_24'       => 1,
+                                'grant_note'                      => 1,
+                                );
+       
+ 
+        }
+
+        return $properties;
+    }
+
+    /**
+     * add all the elements shared between grant search and advanaced search
+     *
+     * @access public 
+     * @return void
+     * @static
+     */   
+    static function buildSearchForm( &$form ) 
+    {
+        require_once 'CRM/Utils/Money.php';
+        
+        $grantType = CRM_Core_OptionGroup::values('grant_type');
+        $form->add('select', 'grant_type_id', ts('Grant Type'),
+          array(
+            '' => ts('- select -')) + $grantType
+        );
+        
+        $grantStatus = CRM_Core_OptionGroup::values('grant_status');
+        $form->add('select', 'grant_status_id', ts('Grant Status'),
+          array(
+            '' => ts('- select -')) + $grantStatus
+        );
+        $form->addDate( 'grant_application_received_date_low', ts('App. Received Date - From'), false, array( 'formatType' => 'searchDate') );
+        $form->addDate( 'grant_application_received_date_high', ts('To'), false, array( 'formatType' => 'searchDate') );
+        
+        $form->addElement('checkbox','grant_application_received_notset', ts(''),null );
+        
+        $form->addDate( 'grant_money_transfer_date_low', ts('Money Sent Date - From'), false, array( 'formatType' => 'searchDate') );
+        $form->addDate( 'grant_money_transfer_date_high', ts('To'), false, array( 'formatType' => 'searchDate') );
+        
+        $form->addElement('checkbox','grant_money_transfer_date_notset', ts(''),null );
+        
+        $form->addDate( 'grant_due_date_low', ts('Report Due Date - From'), false, array( 'formatType' => 'searchDate') );
+        $form->addDate( 'grant_due_date_high', ts('To'), false, array( 'formatType' => 'searchDate') );
+        
+        $form->addElement('checkbox','grant_due_date_notset', ts(''),null );
+        
+        $form->addDate( 'grant_decision_date_low', ts('Grant Decision Date - From'), false, array( 'formatType' => 'searchDate') );
+        $form->addDate( 'grant_decision_date_high', ts('To'), false, array( 'formatType' => 'searchDate') );
+        
+        $form->addElement('checkbox','grant_decision_date_notset', ts(''),null );
+         
+        $form->addYesNo( 'grant_report_received', ts( 'Grant report received?' ) );
+        
+        $form->add('text', 'grant_amount_total_low', ts('From'), array( 'size' => 8, 'maxlength' => 8 ) ); 
+        $form->addRule('grant_amount_total_low', ts('Please enter a valid money value (e.g. %1).', array(1 => CRM_Utils_Money::format('9.99', ' '))), 'money');
+        
+        $form->add('text', 'grant_amount_total_high', ts('To'), array( 'size' => 8, 'maxlength' => 8 ) ); 
+        $form->addRule('grant_amount_total_high', ts('Please enter a valid money value (e.g. %1).', array(1 => CRM_Utils_Money::format('99.99', ' '))), 'money');
+        
+        $form->add('text', 'grant_amount_low', ts('From'), array( 'size' => 8, 'maxlength' => 8 ) ); 
+        $form->addRule('grant_amount_low', ts('Please enter a valid money value (e.g. %1).', array(1 => CRM_Utils_Money::format('9.99', ' '))), 'money');
+        
+        $form->add('text', 'grant_amount_high', ts('To'), array( 'size' => 8, 'maxlength' => 8 ) ); 
+        $form->addRule('grant_amount_high', ts('Please enter a valid money value (e.g. %1).', array(1 => CRM_Utils_Money::format('99.99', ' '))), 'money');
+        
+        // add all the custom  searchable fields
+        require_once 'CRM/Core/BAO/CustomGroup.php';
+        $grant = array( 'Grant' );
+        $groupDetails = CRM_Core_BAO_CustomGroup::getGroupDetail( null, true, $grant );
+        if ( $groupDetails ) {
+            require_once 'CRM/Core/BAO/CustomField.php';
+            $form->assign('grantGroupTree', $groupDetails);
+            foreach ($groupDetails as $group) {
+                foreach ($group['fields'] as $field) {
+                    $fieldId = $field['id'];                
+                    $elementName = 'custom_' . $fieldId;
+                    CRM_Core_BAO_CustomField::addQuickFormElement( $form,
+                                                                   $elementName,
+                                                                   $fieldId,
+                                                                   false, false, true );
+                }
+            }
+        }
+        
+        $form->assign( 'validGrant', true );
+    }
+    
+    static function addShowHide( &$showHide ) 
+    {
+        $showHide->addHide( 'grantForm' );
+        $showHide->addShow( 'grantForm_show' );
+    }
+    
+    static function searchAction( &$row, $id ) 
+    {
+    }
+
+    static function tableNames( &$tables ) 
+    {
+    }  
+}
+
diff --git a/CRM/Grant/Config.php b/CRM/Grant/Config.php
new file mode 100755
index 0000000..30ee1a6
--- /dev/null
+++ b/CRM/Grant/Config.php
@@ -0,0 +1,43 @@
+<?php
+
+/*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.1                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*/
+
+/**
+ *
+ * @package CRM
+ * @copyright CiviCRM LLC (c) 2004-2011
+ * $Id$
+ *
+ */
+
+require_once 'CRM/Core/Component/Config.php';
+
+class CRM_Grant_Config extends CRM_Core_Component_Config {
+
+}
+
+
diff --git a/CRM/Grant/Controller/PaymentSearch.php b/CRM/Grant/Controller/PaymentSearch.php
new file mode 100755
index 0000000..8b9feb5
--- /dev/null
+++ b/CRM/Grant/Controller/PaymentSearch.php
@@ -0,0 +1,72 @@
+<?php
+
+/*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.1                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*/
+
+/**
+ *
+ * @package CRM
+ * @copyright CiviCRM LLC (c) 2004-2011
+ * $Id$
+ *
+ */
+
+require_once 'CRM/Core/Controller.php';
+require_once 'CRM/Core/Session.php';
+
+/**
+ * This class is used by the Search functionality.
+ *
+ *  - the search controller is used for building/processing multiform
+ *    searches.
+ *
+ * Typically the first form will display the search criteria and it's results
+ *
+ * The second form is used to process search results with the asscociated actions
+ *
+ */
+class CRM_Grant_Controller_PaymentSearch extends CRM_Core_Controller
+{
+  /**
+   * class constructor
+   */
+  function __construct( $title = null, $action = CRM_Core_Action::NONE, $modal = true )
+  {
+    require_once 'CRM/Grant/StateMachine/PaymentSearch.php';
+        
+    parent::__construct( $title, $modal );
+        
+    $this->_stateMachine = new CRM_Grant_StateMachine_PaymentSearch( $this, $action );
+        
+    // create and instantiate the pages
+    $this->addPages( $this->_stateMachine, $action );
+        
+    // add all the actions
+    $config = CRM_Core_Config::singleton( );
+    $this->addActions( );
+  }
+}
+
diff --git a/CRM/Grant/DAO/EntityPayment.php b/CRM/Grant/DAO/EntityPayment.php
new file mode 100755
index 0000000..032842d
--- /dev/null
+++ b/CRM/Grant/DAO/EntityPayment.php
@@ -0,0 +1,257 @@
+<?php
+/*
++--------------------------------------------------------------------+
+| CiviCRM version 4.1                                                |
++--------------------------------------------------------------------+
+| Copyright CiviCRM LLC (c) 2004-2011                                |
++--------------------------------------------------------------------+
+| This file is a part of CiviCRM.                                    |
+|                                                                    |
+| CiviCRM is free software; you can copy, modify, and distribute it  |
+| under the terms of the GNU Affero General Public License           |
+| Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+|                                                                    |
+| CiviCRM is distributed in the hope that it will be useful, but     |
+| WITHOUT ANY WARRANTY; without even the implied warranty of         |
+| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+| See the GNU Affero General Public License for more details.        |
+|                                                                    |
+| You should have received a copy of the GNU Affero General Public   |
+| License and the CiviCRM Licensing Exception along                  |
+| with this program; if not, contact CiviCRM LLC                     |
+| at info[AT]civicrm[DOT]org. If you have questions about the        |
+| GNU Affero General Public License or the licensing of CiviCRM,     |
+| see the CiviCRM license FAQ at http://civicrm.org/licensing        |
++--------------------------------------------------------------------+
+*/
+/**
+ *
+ * @package CRM
+ * @copyright CiviCRM LLC (c) 2004-2011
+ * $Id$
+ *
+ */
+require_once 'CRM/Core/DAO.php';
+require_once 'CRM/Utils/Type.php';
+class CRM_Grant_DAO_EntityPayment extends CRM_Core_DAO
+{
+    /**
+     * static instance to hold the table name
+     *
+     * @var string
+     * @static
+     */
+    static $_tableName = 'civicrm_entity_payment';
+    /**
+     * static instance to hold the field values
+     *
+     * @var array
+     * @static
+     */
+    static $_fields = null;
+    /**
+     * static instance to hold the FK relationships
+     *
+     * @var string
+     * @static
+     */
+    static $_links = null;
+    /**
+     * static instance to hold the values that can
+     * be imported
+     *
+     * @var array
+     * @static
+     */
+    static $_import = null;
+    /**
+     * static instance to hold the values that can
+     * be exported
+     *
+     * @var array
+     * @static
+     */
+    static $_export = null;
+    /**
+     * static value to see if we should log any modifications to
+     * this table in the civicrm_log table
+     *
+     * @var boolean
+     * @static
+     */
+    static $_log = true;
+    /**
+     * ID
+     *
+     * @var int unsigned
+     */
+    public $id;
+    /**
+     * Type of grant. Implicit FK to civicrm_payment.
+     *
+     * @var int unsigned
+     */
+    public $payment_id;
+    /**
+     * Entity Table.
+     *
+     * @var string
+     */
+    public $entity_table;
+    /**
+     * Entity ID
+     *
+     * @var int unsigned
+     */
+    public $entity_id;
+    /**
+     * class constructor
+     *
+     * @access public
+     * @return civicrm_entity_payment
+     */
+    function __construct()
+    {
+        parent::__construct();
+    }
+    /**
+     * return foreign links
+     *
+     * @access public
+     * @return array
+     */
+    function &links()
+    {
+        if (!(self::$_links)) {
+            self::$_links = array(
+                'payment_id' => 'civicrm_payment:id',
+            );
+        }
+        return self::$_links;
+    }
+    /**
+     * returns all the column names of this table
+     *
+     * @access public
+     * @return array
+     */
+    static function &fields()
+    {
+        if (!(self::$_fields)) {
+            self::$_fields = array(
+                'id' => array(
+                    'name' => 'id',
+                    'type' => CRM_Utils_Type::T_INT,
+                    'title' => ts('ID') ,
+                    'required' => true,
+                    'import' => true,
+                    'where' => 'civicrm_entity_payment.id',
+                    'headerPattern' => '',
+                    'dataPattern' => '',
+                    'export' => true,
+                ) ,
+                'payment_id' => array(
+                    'name' => 'payment_id',
+                    'type' => CRM_Utils_Type::T_INT,
+                    'title' => ts('Payment Id') ,
+                    'required' => true,
+                    'export' => false,
+                    'where' => 'civicrm_entity_payment.payment_id',
+                    'headerPattern' => '',
+                    'dataPattern' => '',
+                    'FKClassName' => 'CRM_Grant_DAO_GrantPayment',
+                ) ,
+                'entity_table' => array(
+                    'name' => 'entity_table',
+                    'type' => CRM_Utils_Type::T_STRING,
+                    'title' => ts('Entity Table') ,
+                    'maxlength' => 255,
+                    'size' => CRM_Utils_Type::HUGE,
+                    'import' => true,
+                    'where' => 'civicrm_entity_payment.entity_table',
+                    'headerPattern' => '',
+                    'dataPattern' => '',
+                    'export' => true,
+                ) ,
+                'id' => array(
+                    'name' => 'entity_id',
+                    'type' => CRM_Utils_Type::T_INT,
+                    'title' => ts('Entity ID') ,
+                    'required' => true,
+                    'import' => true,
+                    'where' => 'civicrm_entity_payment.entity_id',
+                    'headerPattern' => '',
+                    'dataPattern' => '',
+                    'export' => true,
+                ) ,
+            );
+        }
+        return self::$_fields;
+    }
+    /**
+     * returns the names of this table
+     *
+     * @access public
+     * @return string
+     */
+    static function getTableName()
+    {
+        return self::$_tableName;
+    }
+    /**
+     * returns if this table needs to be logged
+     *
+     * @access public
+     * @return boolean
+     */
+    function getLog()
+    {
+        return self::$_log;
+    }
+    /**
+     * returns the list of fields that can be imported
+     *
+     * @access public
+     * return array
+     */
+    function &import($prefix = false)
+    {
+        if (!(self::$_import)) {
+            self::$_import = array();
+            $fields = self::fields();
+            foreach($fields as $name => $field) {
+                if (CRM_Utils_Array::value('import', $field)) {
+                    if ($prefix) {
+                        self::$_import['entity_payment'] = & $fields[$name];
+                    } else {
+                        self::$_import[$name] = & $fields[$name];
+                    }
+                }
+            }
+        }
+        return self::$_import;
+    }
+    /**
+     * returns the list of fields that can be exported
+     *
+     * @access public
+     * return array
+     */
+    function &export($prefix = false)
+    {
+        if (!(self::$_export)) {
+            self::$_export = array();
+            $fields = self::fields();
+            foreach($fields as $name => $field) {
+                if (CRM_Utils_Array::value('export', $field)) {
+                    if ($prefix) {
+                        self::$_export['entity_payment'] = & $fields[$name];
+                    } else {
+                        self::$_export[$name] = & $fields[$name];
+                    }
+                }
+            }
+        }
+        return self::$_export;
+    }
+}
diff --git a/CRM/Grant/DAO/Grant.php b/CRM/Grant/DAO/Grant.php
new file mode 100755
index 0000000..b179955
--- /dev/null
+++ b/CRM/Grant/DAO/Grant.php
@@ -0,0 +1,437 @@
+<?php
+/*
++--------------------------------------------------------------------+
+| CiviCRM version 4.1                                                |
++--------------------------------------------------------------------+
+| Copyright CiviCRM LLC (c) 2004-2011                                |
++--------------------------------------------------------------------+
+| This file is a part of CiviCRM.                                    |
+|                                                                    |
+| CiviCRM is free software; you can copy, modify, and distribute it  |
+| under the terms of the GNU Affero General Public License           |
+| Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+|                                                                    |
+| CiviCRM is distributed in the hope that it will be useful, but     |
+| WITHOUT ANY WARRANTY; without even the implied warranty of         |
+| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+| See the GNU Affero General Public License for more details.        |
+|                                                                    |
+| You should have received a copy of the GNU Affero General Public   |
+| License and the CiviCRM Licensing Exception along                  |
+| with this program; if not, contact CiviCRM LLC                     |
+| at info[AT]civicrm[DOT]org. If you have questions about the        |
+| GNU Affero General Public License or the licensing of CiviCRM,     |
+| see the CiviCRM license FAQ at http://civicrm.org/licensing        |
++--------------------------------------------------------------------+
+*/
+/**
+ *
+ * @package CRM
+ * @copyright CiviCRM LLC (c) 2004-2011
+ * $Id$
+ *
+ */
+require_once 'CRM/Core/DAO.php';
+require_once 'CRM/Utils/Type.php';
+class CRM_Grant_DAO_Grant extends CRM_Core_DAO
+{
+    /**
+     * static instance to hold the table name
+     *
+     * @var string
+     * @static
+     */
+    static $_tableName = 'civicrm_grant';
+    /**
+     * static instance to hold the field values
+     *
+     * @var array
+     * @static
+     */
+    static $_fields = null;
+    /**
+     * static instance to hold the FK relationships
+     *
+     * @var string
+     * @static
+     */
+    static $_links = null;
+    /**
+     * static instance to hold the values that can
+     * be imported
+     *
+     * @var array
+     * @static
+     */
+    static $_import = null;
+    /**
+     * static instance to hold the values that can
+     * be exported
+     *
+     * @var array
+     * @static
+     */
+    static $_export = null;
+    /**
+     * static value to see if we should log any modifications to
+     * this table in the civicrm_log table
+     *
+     * @var boolean
+     * @static
+     */
+    static $_log = true;
+    /**
+     * Unique Grant id
+     *
+     * @var int unsigned
+     */
+    public $id;
+    /**
+     * Contact ID of contact record given grant belongs to.
+     *
+     * @var int unsigned
+     */
+    public $contact_id;
+    /**
+     * Grant Program ID of grant program record given grant belongs to.
+     *
+     * @var int unsigned
+     */
+    public $grant_program_id;
+    /**
+     * Date on which grant application was received by donor.
+     *
+     * @var date
+     */
+    public $application_received_date;
+    /**
+     * Date on which grant decision was made.
+     *
+     * @var date
+     */
+    public $decision_date;
+    /**
+     * Date on which grant money transfer was made.
+     *
+     * @var date
+     */
+    public $money_transfer_date;
+    /**
+     * Date on which grant report is due.
+     *
+     * @var date
+     */
+    public $grant_due_date;
+    /**
+     * Yes/No field stating whether grant report was received by donor.
+     *
+     * @var boolean
+     */
+    public $grant_report_received;
+    /**
+     * Type of grant. Implicit FK to civicrm_option_value in grant_type option_group.
+     *
+     * @var int unsigned
+     */
+    public $grant_type_id;
+    /**
+     * Requested grant amount, in default currency.
+     *
+     * @var float
+     */
+    public $amount_total;
+    /**
+     * Requested grant amount, in original currency (optional).
+     *
+     * @var float
+     */
+    public $amount_requested;
+    /**
+     * Granted amount, in default currency.
+     *
+     * @var float
+     */
+    public $amount_granted;
+    /**
+     * 3 character string, value from config setting or input via user.
+     *
+     * @var string
+     */
+    public $currency;
+    /**
+     * Grant rationale.
+     *
+     * @var text
+     */
+    public $rationale;
+    /**
+     * Id of Grant status.
+     *
+     * @var int unsigned
+     */
+    public $status_id;
+    /**
+     * assessment total.
+     *
+     * @var string
+     */
+    public $assessment;
+    /**
+     * class constructor
+     *
+     * @access public
+     * @return civicrm_grant
+     */
+    function __construct()
+    {
+        parent::__construct();
+    }
+    /**
+     * return foreign links
+     *
+     * @access public
+     * @return array
+     */
+    function &links()
+    {
+        if (!(self::$_links)) {
+            self::$_links = array(
+                'contact_id' => 'civicrm_contact:id',
+                'grant_program_id' => 'civicrm_grant_program:id',
+            );
+        }
+        return self::$_links;
+    }
+    /**
+     * returns all the column names of this table
+     *
+     * @access public
+     * @return array
+     */
+    static function &fields()
+    {
+        if (!(self::$_fields)) {
+            self::$_fields = array(
+                'grant_id' => array(
+                    'name' => 'id',
+                    'type' => CRM_Utils_Type::T_INT,
+                    'title' => ts('Grant ID') ,
+                    'required' => true,
+                    'import' => true,
+                    'where' => 'civicrm_grant.id',
+                    'headerPattern' => '',
+                    'dataPattern' => '',
+                    'export' => true,
+                ) ,
+                'grant_contact_id' => array(
+                    'name' => 'contact_id',
+                    'type' => CRM_Utils_Type::T_INT,
+                    'title' => ts('Contact ID') ,
+                    'required' => true,
+                    'export' => true,
+                    'where' => 'civicrm_grant.contact_id',
+                    'headerPattern' => '',
+                    'dataPattern' => '',
+                    'FKClassName' => 'CRM_Contact_DAO_Contact',
+                ) ,
+                'grant_program_id' => array(
+                    'name' => 'grant_program_id',
+                    'type' => CRM_Utils_Type::T_INT,
+                    'title' => ts('Grant Program ID') ,
+                    'required' => true,
+                    'export' => true,
+                    'where' => 'civicrm_grant.grant_program_id',
+                    'headerPattern' => '',
+                    'dataPattern' => '',
+                    'FKClassName' => 'CRM_Grant_DAO_GrantProgram',
+                ) ,
+                'application_received_date' => array(
+                    'name' => 'application_received_date',
+                    'type' => CRM_Utils_Type::T_DATE,
+                    'title' => ts('Application received date') ,
+                    'export' => true,
+                    'where' => 'civicrm_grant.application_received_date',
+                    'headerPattern' => '',
+                    'dataPattern' => '',
+                ) ,
+                'decision_date' => array(
+                    'name' => 'decision_date',
+                    'type' => CRM_Utils_Type::T_DATE,
+                    'title' => ts('Decision date') ,
+                    'import' => true,
+                    'where' => 'civicrm_grant.decision_date',
+                    'headerPattern' => '',
+                    'dataPattern' => '',
+                    'export' => true,
+                ) ,
+                'money_transfer_date' => array(
+                    'name' => 'money_transfer_date',
+                    'type' => CRM_Utils_Type::T_DATE,
+                    'title' => ts('Grant Money transfer date') ,
+                    'import' => true,
+                    'where' => 'civicrm_grant.money_transfer_date',
+                    'headerPattern' => '',
+                    'dataPattern' => '',
+                    'export' => true,
+                ) ,
+                'grant_due_date' => array(
+                    'name' => 'grant_due_date',
+                    'type' => CRM_Utils_Type::T_DATE,
+                    'title' => ts('Grant Due Date') ,
+                ) ,
+                'grant_report_received' => array(
+                    'name' => 'grant_report_received',
+                    'type' => CRM_Utils_Type::T_BOOLEAN,
+                    'title' => ts('Grant report received') ,
+                    'import' => true,
+                    'where' => 'civicrm_grant.grant_report_received',
+                    'headerPattern' => '',
+                    'dataPattern' => '',
+                    'export' => true,
+                ) ,
+                'grant_type_id' => array(
+                    'name' => 'grant_type_id',
+                    'type' => CRM_Utils_Type::T_INT,
+                    'title' => ts('Grant Type Id') ,
+                    'required' => true,
+                    'export' => false,
+                    'where' => 'civicrm_grant.grant_type_id',
+                    'headerPattern' => '',
+                    'dataPattern' => '',
+                ) ,
+                'amount_total' => array(
+                    'name' => 'amount_total',
+                    'type' => CRM_Utils_Type::T_MONEY,
+                    'title' => ts('Total Amount') ,
+                    'required' => true,
+                    'import' => true,
+                    'where' => 'civicrm_grant.amount_total',
+                    'headerPattern' => '',
+                    'dataPattern' => '/^\d+(\.\d{2})?$/',
+                    'export' => true,
+                ) ,
+                'amount_requested' => array(
+                    'name' => 'amount_requested',
+                    'type' => CRM_Utils_Type::T_MONEY,
+                    'title' => ts('Amount Requested') ,
+                ) ,
+                'amount_granted' => array(
+                    'name' => 'amount_granted',
+                    'type' => CRM_Utils_Type::T_MONEY,
+                    'title' => ts('Amount granted') ,
+                    'import' => true,
+                    'where' => 'civicrm_grant.amount_granted',
+                    'headerPattern' => '',
+                    'dataPattern' => '/^\d+(\.\d{2})?$/',
+                    'export' => true,
+                ) ,
+                'currency' => array(
+                    'name' => 'currency',
+                    'type' => CRM_Utils_Type::T_STRING,
+                    'title' => ts('Currency') ,
+                    'maxlength' => 8,
+                    'size' => CRM_Utils_Type::EIGHT,
+                    'default' => 'UL',
+                ) ,
+                'rationale' => array(
+                    'name' => 'rationale',
+                    'type' => CRM_Utils_Type::T_TEXT,
+                    'title' => ts('Rationale') ,
+                    'rows' => 4,
+                    'cols' => 60,
+                    'import' => true,
+                    'where' => 'civicrm_grant.rationale',
+                    'headerPattern' => '',
+                    'dataPattern' => '',
+                    'export' => true,
+                ) ,
+                'grant_status_id' => array(
+                    'name' => 'status_id',
+                    'type' => CRM_Utils_Type::T_INT,
+                    'title' => ts('Grant Status Id') ,
+                    'required' => true,
+                    'import' => true,
+                    'where' => 'civicrm_grant.status_id',
+                    'headerPattern' => '',
+                    'dataPattern' => '',
+                    'export' => false,
+                ) ,
+                'assessment' => array(
+                    'name' => 'assessment',
+                    'type' => CRM_Utils_Type::T_STRING,
+                    'title' => ts('Assessment') ,
+                    'maxlength' => 64,
+                    'size' => CRM_Utils_Type::BIG,
+                    'default' => 'UL',
+                ) ,
+            );
+        }
+        return self::$_fields;
+    }
+    /**
+     * returns the names of this table
+     *
+     * @access public
+     * @return string
+     */
+    static function getTableName()
+    {
+        return self::$_tableName;
+    }
+    /**
+     * returns if this table needs to be logged
+     *
+     * @access public
+     * @return boolean
+     */
+    function getLog()
+    {
+        return self::$_log;
+    }
+    /**
+     * returns the list of fields that can be imported
+     *
+     * @access public
+     * return array
+     */
+    function &import($prefix = false)
+    {
+        if (!(self::$_import)) {
+            self::$_import = array();
+            $fields = self::fields();
+            foreach($fields as $name => $field) {
+                if (CRM_Utils_Array::value('import', $field)) {
+                    if ($prefix) {
+                        self::$_import['grant'] = & $fields[$name];
+                    } else {
+                        self::$_import[$name] = & $fields[$name];
+                    }
+                }
+            }
+        }
+        return self::$_import;
+    }
+    /**
+     * returns the list of fields that can be exported
+     *
+     * @access public
+     * return array
+     */
+    function &export($prefix = false)
+    {
+        if (!(self::$_export)) {
+            self::$_export = array();
+            $fields = self::fields();
+            foreach($fields as $name => $field) {
+                if (CRM_Utils_Array::value('export', $field)) {
+                    if ($prefix) {
+                        self::$_export['grant'] = & $fields[$name];
+                    } else {
+                        self::$_export[$name] = & $fields[$name];
+                    }
+                }
+            }
+        }
+        return self::$_export;
+    }
+}
\ No newline at end of file
diff --git a/CRM/Grant/DAO/GrantPayment.php b/CRM/Grant/DAO/GrantPayment.php
new file mode 100755
index 0000000..bf172dd
--- /dev/null
+++ b/CRM/Grant/DAO/GrantPayment.php
@@ -0,0 +1,413 @@
+<?php
+/*
++--------------------------------------------------------------------+
+| CiviCRM version 4.1                                                |
++--------------------------------------------------------------------+
+| Copyright CiviCRM LLC (c) 2004-2011                                |
++--------------------------------------------------------------------+
+| This file is a part of CiviCRM.                                    |
+|                                                                    |
+| CiviCRM is free software; you can copy, modify, and distribute it  |
+| under the terms of the GNU Affero General Public License           |
+| Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+|                                                                    |
+| CiviCRM is distributed in the hope that it will be useful, but     |
+| WITHOUT ANY WARRANTY; without even the implied warranty of         |
+| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+| See the GNU Affero General Public License for more details.        |
+|                                                                    |
+| You should have received a copy of the GNU Affero General Public   |
+| License and the CiviCRM Licensing Exception along                  |
+| with this program; if not, contact CiviCRM LLC                     |
+| at info[AT]civicrm[DOT]org. If you have questions about the        |
+| GNU Affero General Public License or the licensing of CiviCRM,     |
+| see the CiviCRM license FAQ at http://civicrm.org/licensing        |
++--------------------------------------------------------------------+
+*/
+/**
+ *
+ * @package CRM
+ * @copyright CiviCRM LLC (c) 2004-2011
+ * $Id$
+ *
+ */
+require_once 'CRM/Core/DAO.php';
+require_once 'CRM/Utils/Type.php';
+class CRM_Grant_DAO_GrantPayment extends CRM_Core_DAO
+{
+    /**
+     * static instance to hold the table name
+     *
+     * @var string
+     * @static
+     */
+    static $_tableName = 'civicrm_payment';
+    /**
+     * static instance to hold the field values
+     *
+     * @var array
+     * @static
+     */
+    static $_fields = null;
+    /**
+     * static instance to hold the FK relationships
+     *
+     * @var string
+     * @static
+     */
+    static $_links = null;
+    /**
+     * static instance to hold the values that can
+     * be imported
+     *
+     * @var array
+     * @static
+     */
+    static $_import = null;
+    /**
+     * static instance to hold the values that can
+     * be exported
+     *
+     * @var array
+     * @static
+     */
+    static $_export = null;
+    /**
+     * static value to see if we should log any modifications to
+     * this table in the civicrm_log table
+     *
+     * @var boolean
+     * @static
+     */
+    static $_log = true;
+    /**
+     * Id
+     *
+     * @var int unsigned
+     */
+    public $id;
+    /**
+     * Payment Batch Nnumber
+     *
+     * @var int unsigned
+     */
+    public $payment_batch_number;
+    /**
+     * Payment Number
+     *
+     * @var int unsigned
+     */
+    public $payment_number;
+    /**
+     * Contribution Type ID
+     *
+     * @var int unsigned
+     */
+    public $contribution_type_id;
+    /**
+     * Contact ID
+     *
+     * @var int unsigned
+     */
+    public $contact_id;
+    /**
+     * Payment Created Date.
+     *
+     * @var date
+     */
+    public $payment_created_date;
+    /**
+     * Payment Date.
+     *
+     * @var date
+     */
+    public $payment_date;
+    /**
+     * Payable To Name.
+     *
+     * @var string
+     */
+    public $payable_to_name;
+    /**
+     * Payable To Address.
+     *
+     * @var string
+     */
+    public $payable_to_address;
+    /**
+     * Requested grant amount, in default currency.
+     *
+     * @var float
+     */
+    public $amount;
+    /**
+     * 3 character string, value from config setting or input via user.
+     *
+     * @var string
+     */
+    public $currency;
+    /**
+     * Payment Reason.
+     *
+     * @var string
+     */
+    public $payment_reason;
+    /**
+     * Payment Status ID
+     *
+     * @var int unsigned
+     */
+    public $payment_status_id;
+    /**
+     * Replaces Payment ID
+     *
+     * @var int unsigned
+     */
+    public $replaces_payment_id;
+    /**
+     * class constructor
+     *
+     * @access public
+     * @return civicrm_payment
+     */
+    function __construct()
+    {
+        parent::__construct();
+    }
+    /**
+     * returns all the column names of this table
+     *
+     * @access public
+     * @return array
+     */
+    static function &fields()
+    {
+        if (!(self::$_fields)) {
+            self::$_fields = array(
+                'id' => array(
+                    'name' => 'id',
+                    'type' => CRM_Utils_Type::T_INT,
+                    'title' => ts('Id') ,
+                    'required' => true,
+                    'import' => true,
+                    'where' => 'civicrm_payment.id',
+                    'headerPattern' => '',
+                    'dataPattern' => '',
+                    'export' => true,
+                ) ,
+                'payment_batch_number' => array(
+                    'name' => 'payment_batch_number',
+                    'type' => CRM_Utils_Type::T_INT,
+                    'title' => ts('Payment Batch Nnumber') ,
+                    'required' => true,
+                    'import' => true,
+                    'where' => 'civicrm_payment.payment_batch_number',
+                    'headerPattern' => '',
+                    'dataPattern' => '',
+                    'export' => true,
+                ) ,
+                'payment_number' => array(
+                    'name' => 'payment_number',
+                    'type' => CRM_Utils_Type::T_INT,
+                    'title' => ts('Payment Number') ,
+                    'required' => true,
+                    'import' => true,
+                    'where' => 'civicrm_payment.payment_number',
+                    'headerPattern' => '',
+                    'dataPattern' => '',
+                    'export' => true,
+                ) ,
+                'contribution_type_id' => array(
+                    'name' => 'contribution_type_id',
+                    'type' => CRM_Utils_Type::T_INT,
+                    'title' => ts('Contribution Type ID') ,
+                    'required' => true,
+                    'import' => true,
+                    'where' => 'civicrm_payment.contribution_type_id',
+                    'headerPattern' => '',
+                    'dataPattern' => '',
+                    'export' => true,
+                ) ,
+                'contact_id' => array(
+                    'name' => 'contact_id',
+                    'type' => CRM_Utils_Type::T_INT,
+                    'title' => ts('Contact ID') ,
+                    'required' => true,
+                    'import' => true,
+                    'where' => 'civicrm_payment.contact_id',
+                    'headerPattern' => '',
+                    'dataPattern' => '',
+                    'export' => true,
+                ) ,
+                'payment_created_date' => array(
+                    'name' => 'payment_created_date',
+                    'type' => CRM_Utils_Type::T_DATE,
+                    'title' => ts('Payment Created Date') ,
+                    'import' => true,
+                    'where' => 'civicrm_payment.payment_created_date',
+                    'headerPattern' => '',
+                    'dataPattern' => '',
+                    'export' => true,
+                ) ,
+                'payment_date' => array(
+                    'name' => 'payment_date',
+                    'type' => CRM_Utils_Type::T_DATE,
+                    'title' => ts('Payment Date') ,
+                    'import' => true,
+                    'where' => 'civicrm_payment.payment_date',
+                    'headerPattern' => '',
+                    'dataPattern' => '',
+                    'export' => true,
+                ) ,
+                'payable_to_name' => array(
+                    'name' => 'payable_to_name',
+                    'type' => CRM_Utils_Type::T_STRING,
+                    'title' => ts('Payable To Name') ,
+                    'maxlength' => 255,
+                    'size' => CRM_Utils_Type::HUGE,
+                    'import' => true,
+                    'where' => 'civicrm_payment.payable_to_name',
+                    'headerPattern' => '',
+                    'dataPattern' => '',
+                    'export' => true,
+                ) ,
+                'payable_to_address' => array(
+                    'name' => 'payable_to_address',
+                    'type' => CRM_Utils_Type::T_STRING,
+                    'title' => ts('Payable To Address') ,
+                    'maxlength' => 255,
+                    'size' => CRM_Utils_Type::HUGE,
+                    'import' => true,
+                    'where' => 'civicrm_payment.payable_to_address',
+                    'headerPattern' => '',
+                    'dataPattern' => '',
+                    'export' => true,
+                ) ,
+                'amount' => array(
+                    'name' => 'amount',
+                    'type' => CRM_Utils_Type::T_MONEY,
+                    'title' => ts('Amount') ,
+                    'required' => true,
+                    'import' => true,
+                    'where' => 'civicrm_payment.amount',
+                    'headerPattern' => '',
+                    'dataPattern' => '/^\d+(\.\d{2})?$/',
+                    'export' => true,
+                ) ,
+                'currency' => array(
+                    'name' => 'currency',
+                    'type' => CRM_Utils_Type::T_STRING,
+                    'title' => ts('Currency') ,
+                    'maxlength' => 3,
+                    'size' => CRM_Utils_Type::FOUR,
+                    'import' => true,
+                    'where' => 'civicrm_payment.currency',
+                    'headerPattern' => '/cur(rency)?/i',
+                    'dataPattern' => '/^[A-Z]{3}$/i',
+                    'export' => true,
+                ) ,
+                'payment_reason' => array(
+                    'name' => 'payment_reason',
+                    'type' => CRM_Utils_Type::T_STRING,
+                    'title' => ts('Payment Reason') ,
+                    'maxlength' => 255,
+                    'size' => CRM_Utils_Type::HUGE,
+                    'import' => true,
+                    'where' => 'civicrm_payment.payment_reason',
+                    'headerPattern' => '',
+                    'dataPattern' => '',
+                    'export' => true,
+                ) ,
+                'payment_status_id' => array(
+                    'name' => 'payment_status_id',
+                    'type' => CRM_Utils_Type::T_INT,
+                    'title' => ts('Payment Status ID') ,
+                    'required' => true,
+                    'import' => true,
+                    'where' => 'civicrm_payment.payment_status_id',
+                    'headerPattern' => '',
+                    'dataPattern' => '',
+                    'export' => true,
+                ) ,
+                'replaces_payment_id' => array(
+                    'name' => 'replaces_payment_id',
+                    'type' => CRM_Utils_Type::T_INT,
+                    'title' => ts('Replaces Payment ID') ,
+                    'required' => true,
+                    'import' => true,
+                    'where' => 'civicrm_payment.replaces_payment_id',
+                    'headerPattern' => '',
+                    'dataPattern' => '',
+                    'export' => true,
+                ) ,
+            );
+        }
+        return self::$_fields;
+    }
+    /**
+     * returns the names of this table
+     *
+     * @access public
+     * @return string
+     */
+    static function getTableName()
+    {
+        return self::$_tableName;
+    }
+    /**
+     * returns if this table needs to be logged
+     *
+     * @access public
+     * @return boolean
+     */
+    function getLog()
+    {
+        return self::$_log;
+    }
+    /**
+     * returns the list of fields that can be imported
+     *
+     * @access public
+     * return array
+     */
+    function &import($prefix = false)
+    {
+        if (!(self::$_import)) {
+            self::$_import = array();
+            $fields = self::fields();
+            foreach($fields as $name => $field) {
+                if (CRM_Utils_Array::value('import', $field)) {
+                    if ($prefix) {
+                        self::$_import['payment'] = & $fields[$name];
+                    } else {
+                        self::$_import[$name] = & $fields[$name];
+                    }
+                }
+            }
+        }
+        return self::$_import;
+    }
+    /**
+     * returns the list of fields that can be exported
+     *
+     * @access public
+     * return array
+     */
+    function &export($prefix = false)
+    {
+        if (!(self::$_export)) {
+            self::$_export = array();
+            $fields = self::fields();
+            foreach($fields as $name => $field) {
+                if (CRM_Utils_Array::value('export', $field)) {
+                    if ($prefix) {
+                        self::$_export['payment'] = & $fields[$name];
+                    } else {
+                        self::$_export[$name] = & $fields[$name];
+                    }
+                }
+            }
+        }
+        return self::$_export;
+    }
+}
diff --git a/CRM/Grant/DAO/GrantProgram.php b/CRM/Grant/DAO/GrantProgram.php
new file mode 100755
index 0000000..2b4fc1b
--- /dev/null
+++ b/CRM/Grant/DAO/GrantProgram.php
@@ -0,0 +1,389 @@
+<?php
+/*
++--------------------------------------------------------------------+
+| CiviCRM version 4.1                                                |
++--------------------------------------------------------------------+
+| Copyright CiviCRM LLC (c) 2004-2011                                |
++--------------------------------------------------------------------+
+| This file is a part of CiviCRM.                                    |
+|                                                                    |
+| CiviCRM is free software; you can copy, modify, and distribute it  |
+| under the terms of the GNU Affero General Public License           |
+| Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+|                                                                    |
+| CiviCRM is distributed in the hope that it will be useful, but     |
+| WITHOUT ANY WARRANTY; without even the implied warranty of         |
+| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+| See the GNU Affero General Public License for more details.        |
+|                                                                    |
+| You should have received a copy of the GNU Affero General Public   |
+| License and the CiviCRM Licensing Exception along                  |
+| with this program; if not, contact CiviCRM LLC                     |
+| at info[AT]civicrm[DOT]org. If you have questions about the        |
+| GNU Affero General Public License or the licensing of CiviCRM,     |
+| see the CiviCRM license FAQ at http://civicrm.org/licensing        |
++--------------------------------------------------------------------+
+*/
+/**
+ *
+ * @package CRM
+ * @copyright CiviCRM LLC (c) 2004-2011
+ * $Id$
+ *
+ */
+require_once 'CRM/Core/DAO.php';
+require_once 'CRM/Utils/Type.php';
+class CRM_Grant_DAO_GrantProgram extends CRM_Core_DAO
+{
+    /**
+     * static instance to hold the table name
+     *
+     * @var string
+     * @static
+     */
+    static $_tableName = 'civicrm_grant_program';
+    /**
+     * static instance to hold the field values
+     *
+     * @var array
+     * @static
+     */
+    static $_fields = null;
+    /**
+     * static instance to hold the FK relationships
+     *
+     * @var string
+     * @static
+     */
+    static $_links = null;
+    /**
+     * static instance to hold the values that can
+     * be imported
+     *
+     * @var array
+     * @static
+     */
+    static $_import = null;
+    /**
+     * static instance to hold the values that can
+     * be exported
+     *
+     * @var array
+     * @static
+     */
+    static $_export = null;
+    /**
+     * static value to see if we should log any modifications to
+     * this table in the civicrm_log table
+     *
+     * @var boolean
+     * @static
+     */
+    static $_log = true;
+    /**
+     * Grant Program ID
+     *
+     * @var int unsigned
+     */
+    public $id;
+    /**
+     * Label displayed to users
+     *
+     * @var string
+     */
+    public $label;
+    /**
+     * Stores a fixed (non-translated) name for the grant program.
+     *
+     * @var string
+     */
+    public $name;
+    /**
+     * Type of grant. Implicit FK to civicrm_option_value in grant_type option_group.
+     *
+     * @var int unsigned
+     */
+    public $grant_type_id;
+    /**
+     * Requested grant program amount, in default currency.
+     *
+     * @var float
+     */
+    public $total_amount;
+    /**
+     * Requested grant program remainder amount, in default currency.
+     *
+     * @var float
+     */
+    public $remainder_amount;
+    /**
+     * Contribution Type ID
+     *
+     * @var int unsigned
+     */
+    public $contribution_type_id;
+    /**
+     * Id of Grant status.
+     *
+     * @var int unsigned
+     */
+    public $status_id;
+    /**
+     * Allocation date.
+     *
+     * @var date
+     */
+    public $allocation_date;
+    /**
+     * Is this grant program active?
+     *
+     * @var boolean
+     */
+    public $is_active;
+    /**
+     * Is auto email active?
+     *
+     * @var boolean
+     */
+    public $is_auto_email;
+    /**
+     * Allocation Algorithm.
+     *
+     * @var int unsigned
+     */
+    public $allocation_algorithm;
+    /**
+     * Type of grant. Implicit FK to civicrm_payment.
+     *
+     * @var int unsigned
+     */
+    public $payment_id;
+    /**
+     * class constructor
+     *
+     * @access public
+     * @return civicrm_grant_program
+     */
+    function __construct()
+    {
+        parent::__construct();
+    }
+    /**
+     * return foreign links
+     *
+     * @access public
+     * @return array
+     */
+    function &links()
+    {
+        if (!(self::$_links)) {
+            self::$_links = array(
+                'grant_type_id' => 'civicrm_option_value:id',
+                'status_id' => 'civicrm_option_value:id',
+            );
+        }
+        return self::$_links;
+    }
+    /**
+     * returns all the column names of this table
+     *
+     * @access public
+     * @return array
+     */
+    static function &fields()
+    {
+        if (!(self::$_fields)) {
+            self::$_fields = array(
+                'grant_program_id' => array(
+                    'name' => 'id',
+                    'type' => CRM_Utils_Type::T_INT,
+                    'title' => ts('Grant Program ID') ,
+                    'required' => true,
+                    'import' => true,
+                    'where' => 'civicrm_grant_program.id',
+                    'headerPattern' => '',
+                    'dataPattern' => '',
+                    'export' => true,
+                ) ,
+                'label' => array(
+                    'name' => 'label',
+                    'type' => CRM_Utils_Type::T_STRING,
+                    'title' => ts('Label') ,
+                    'maxlength' => 255,
+                    'size' => CRM_Utils_Type::HUGE,
+                ) ,
+                'name' => array(
+                    'name' => 'name',
+                    'type' => CRM_Utils_Type::T_STRING,
+                    'title' => ts('Name') ,
+                    'maxlength' => 255,
+                    'size' => CRM_Utils_Type::HUGE,
+                ) ,
+                'grant_type_id' => array(
+                    'name' => 'grant_type_id',
+                    'type' => CRM_Utils_Type::T_INT,
+                    'title' => ts('Grant Type Id') ,
+                    'required' => true,
+                    'export' => false,
+                    'where' => 'civicrm_grant_program.grant_type_id',
+                    'headerPattern' => '',
+                    'dataPattern' => '',
+                    'FKClassName' => 'CRM_Core_DAO_OptionValue',
+                ) ,
+                'total_amount' => array(
+                    'name' => 'total_amount',
+                    'type' => CRM_Utils_Type::T_MONEY,
+                    'title' => ts('Total Amount') ,
+                    'required' => true,
+                    'import' => true,
+                    'where' => 'civicrm_grant_program.total_amount',
+                    'headerPattern' => '',
+                    'dataPattern' => '/^\d+(\.\d{2})?$/',
+                    'export' => true,
+                ) ,
+                'remainder_amount' => array(
+                    'name' => 'remainder_amount',
+                    'type' => CRM_Utils_Type::T_MONEY,
+                    'title' => ts('Remainder Amount') ,
+                    'required' => true,
+                    'import' => true,
+                    'where' => 'civicrm_grant_program.remainder_amount',
+                    'headerPattern' => '',
+                    'dataPattern' => '/^\d+(\.\d{2})?$/',
+                    'export' => true,
+                ) ,
+                'contribution_type_id' => array(
+                    'name' => 'contribution_type_id',
+                    'type' => CRM_Utils_Type::T_INT,
+                    'title' => ts('Contribution Type ID') ,
+                    'required' => true,
+                    'import' => true,
+                    'where' => 'civicrm_grant_program.contribution_type_id',
+                    'headerPattern' => '',
+                    'dataPattern' => '',
+                    'export' => true,
+                ) ,
+                'grant_status_id' => array(
+                    'name' => 'status_id',
+                    'type' => CRM_Utils_Type::T_INT,
+                    'title' => ts('Grant Program Status Id') ,
+                    'required' => true,
+                    'import' => true,
+                    'where' => 'civicrm_grant_program.status_id',
+                    'headerPattern' => '',
+                    'dataPattern' => '',
+                    'export' => false,
+                    'FKClassName' => 'CRM_Core_DAO_OptionValue',
+                ) ,
+                'allocation_date' => array(
+                    'name' => 'allocation_date',
+                    'type' => CRM_Utils_Type::T_DATE,
+                    'title' => ts('Allocation date') ,
+                    'import' => true,
+                    'where' => 'civicrm_grant_program.allocation_date',
+                    'headerPattern' => '',
+                    'dataPattern' => '',
+                    'export' => true,
+                ) ,
+                'is_active' => array(
+                    'name' => 'is_active',
+                    'type' => CRM_Utils_Type::T_BOOLEAN,
+                    'default' => '',
+                ) ,
+                'is_auto_email' => array(
+                    'name' => 'is_auto_email',
+                    'type' => CRM_Utils_Type::T_BOOLEAN,
+                    'default' => '',
+                ) ,
+                'allocation_algorithm' => array(
+                    'name' => 'allocation_algorithm',
+                    'type' => CRM_Utils_Type::T_INT,
+                    'title' => ts('Grant ProgramAallocation Algorithm') ,
+                    'required' => true,
+                    'import' => true,
+                    'where' => 'civicrm_grant_program.allocation_algorithm',
+                    'headerPattern' => '',
+                    'dataPattern' => '',
+                    'export' => false,
+                ) ,
+                'payment_id' => array(
+                    'name' => 'payment_id',
+                    'type' => CRM_Utils_Type::T_INT,
+                    'title' => ts('Payment Id') ,
+                    'required' => true,
+                    'export' => false,
+                    'where' => 'civicrm_grant_program.payment_id',
+                    'headerPattern' => '',
+                    'dataPattern' => '',
+                ) ,
+            );
+        }
+        return self::$_fields;
+    }
+    /**
+     * returns the names of this table
+     *
+     * @access public
+     * @return string
+     */
+    static function getTableName()
+    {
+        return self::$_tableName;
+    }
+    /**
+     * returns if this table needs to be logged
+     *
+     * @access public
+     * @return boolean
+     */
+    function getLog()
+    {
+        return self::$_log;
+    }
+    /**
+     * returns the list of fields that can be imported
+     *
+     * @access public
+     * return array
+     */
+    function &import($prefix = false)
+    {
+        if (!(self::$_import)) {
+            self::$_import = array();
+            $fields = self::fields();
+            foreach($fields as $name => $field) {
+                if (CRM_Utils_Array::value('import', $field)) {
+                    if ($prefix) {
+                        self::$_import['grant_program'] = & $fields[$name];
+                    } else {
+                        self::$_import[$name] = & $fields[$name];
+                    }
+                }
+            }
+        }
+        return self::$_import;
+    }
+    /**
+     * returns the list of fields that can be exported
+     *
+     * @access public
+     * return array
+     */
+    function &export($prefix = false)
+    {
+        if (!(self::$_export)) {
+            self::$_export = array();
+            $fields = self::fields();
+            foreach($fields as $name => $field) {
+                if (CRM_Utils_Array::value('export', $field)) {
+                    if ($prefix) {
+                        self::$_export['grant_program'] = & $fields[$name];
+                    } else {
+                        self::$_export[$name] = & $fields[$name];
+                    }
+                }
+            }
+        }
+        return self::$_export;
+    }
+}
diff --git a/CRM/Grant/Form/Grant.php b/CRM/Grant/Form/Grant.php
new file mode 100755
index 0000000..9633cc0
--- /dev/null
+++ b/CRM/Grant/Form/Grant.php
@@ -0,0 +1,446 @@
+<?php
+
+/*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.1                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*/
+
+/**
+ *
+ * @package CRM
+ * @copyright CiviCRM LLC (c) 2004-2011
+ * $Id$
+ *
+ */
+
+require_once 'CRM/Core/Form.php';
+require_once "CRM/Custom/Form/CustomData.php";
+
+/**
+ * This class generates form components for processing a case
+ * 
+ */
+class CRM_Grant_Form_Grant extends CRM_Core_Form
+{
+    /**
+     * the id of the case that we are proceessing
+     *
+     * @var int
+     * @protected
+     */
+    protected $_id;
+
+    /**
+     * the id of the contact associated with this contribution
+     *
+     * @var int
+     * @protected
+     */
+    protected $_contactID;
+
+    protected $_context;
+    /** 
+     * Function to set variables up before form is built 
+     *                                                           
+     * @return void 
+     * @access public
+     */ 
+    public function preProcess()  
+    {  
+        $this->_contactID = CRM_Utils_Request::retrieve( 'cid', 'Positive', $this );
+        $this->_id        = CRM_Utils_Request::retrieve( 'id', 'Positive', $this );
+        $this->_context   = CRM_Utils_Request::retrieve( 'context', 'String', $this );
+        $this->_key       = CRM_Utils_Request::retrieve( 'key', 'String', $this );
+        $this->_next      = CRM_Utils_Request::retrieve( 'next', 'Positive', $this );
+        $this->_prev      = CRM_Utils_Request::retrieve( 'prev', 'Positive', $this );
+        
+        $this->assign( 'action', $this->_action );
+        $this->assign( 'context', $this->_context );
+        
+        //check permission for action.
+        if ( !CRM_Core_Permission::checkActionPermission( 'CiviGrant', $this->_action ) ) {
+            CRM_Core_Error::fatal( ts( 'You do not have permission to access this page' ) );  
+        }
+
+        if ( $this->_action & CRM_Core_Action::DELETE ) {
+            return;
+        }
+        
+        $this->_noteId =null;
+        if ( $this->_id) {
+            require_once 'CRM/Core/BAO/Note.php';
+            $noteDAO               = new CRM_Core_BAO_Note();
+            $noteDAO->entity_table = 'civicrm_grant';
+            $noteDAO->entity_id    = $this->_id;
+            if ( $noteDAO->find(true) ) {
+                $this->_noteId = $noteDAO->id;
+            }
+        }
+
+		//build custom data
+        CRM_Custom_Form_Customdata::preProcess( $this, null, null, 1, 'Grant', $this->_id );
+        
+    }
+    
+    function setDefaultValues( ) 
+    {
+      $defaults = array( );
+      $defaults = parent::setDefaultValues();
+        
+      if ( $this->_action & CRM_Core_Action::DELETE ) {
+        return $defaults;
+      }
+        
+      $params['id'] =  $this->_id;
+      if ( $this->_noteId ) {
+        $defaults['note'] = CRM_Core_DAO::getFieldValue( 'CRM_Core_DAO_Note', $this->_noteId, 'note' );
+      }
+      if ( $this->_id){
+        CRM_Grant_BAO_Grant::retrieve( $params, $defaults);
+
+        // fix the display of the monetary value, CRM-4038 
+        require_once 'CRM/Utils/Money.php';
+        if (isset($defaults['amount_total'])) {
+          $defaults['amount_total'] = CRM_Utils_Money::format($defaults['amount_total'], null, '%a');
+        }
+        if (isset($defaults['amount_requested'])) {
+          $defaults['amount_requested'] = CRM_Utils_Money::format($defaults['amount_requested'], null, '%a');
+        }
+        if (isset($defaults['amount_granted'])) {
+          $defaults['amount_granted'] = CRM_Utils_Money::format($defaults['amount_granted'], null, '%a');
+        }
+            
+        $dates = array( 'application_received_date',
+                        'decision_date',
+                        'money_transfer_date',
+                        'grant_due_date' );
+            
+        foreach( $dates as $key ) { 
+          if ( CRM_Utils_Array::value( $key, $defaults ) ) {
+            list( $defaults[$key] ) = CRM_Utils_Date::setDateDefaults( $defaults[$key] );
+          }
+        }
+      } else {
+        require_once 'CRM/Utils/Date.php';
+        list( $defaults['application_received_date'] ) = CRM_Utils_Date::setDateDefaults( );
+      }
+                
+      // custom data set defaults
+      $defaults += CRM_Custom_Form_Customdata::setDefaultValues( $this );
+      return $defaults;
+    }
+    
+    /** 
+     * Function to build the form 
+     * 
+     * @return None 
+     * @access public 
+     */ 
+    public function buildQuickForm( )  
+    {         
+        if ( $this->_action & CRM_Core_Action::DELETE ) {
+            $this->addButtons(array( 
+                                    array ( 'type'      => 'next', 
+                                            'name'      => ts('Delete'), 
+                                            'spacing'   => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;', 
+                                            'isDefault' => true   ), 
+                                    array ( 'type'      => 'cancel', 
+                                            'name'      => ts('Cancel') ), 
+                                    ) 
+                              );
+            return;
+        }
+        
+        require_once 'CRM/Core/OptionGroup.php';
+        require_once 'CRM/Grant/BAO/Grant.php';
+        $attributes = CRM_Core_DAO::getAttribute('CRM_Grant_DAO_Grant');
+        $this->_grantType = CRM_Core_OptionGroup::values( 'grant_type' );
+        $this->add('select', 'grant_type_id',  ts( 'Grant Type' ),
+                   array( '' => ts( '- select -' ) ) + $this->_grantType , true);
+
+        $this->_grantStatus = CRM_Core_OptionGroup::values( 'grant_status' );
+        $this->add('select', 'status_id',  ts( 'Grant Status' ),
+                   array( '' => ts( '- select -' ) ) + $this->_grantStatus , true);
+
+        // $this->_reasonGrantRejected = CRM_Core_OptionGroup::values( 'reason_grant_rejected' );
+        // $this->add('select', 'grant_rejected_reason_id',  ts( 'Reason Grant Rejected' ),
+        //            array( '' => ts( '- select -' ) ) + $this->_reasonGrantRejected , false);
+        
+        // $this->_grantPrograms = CRM_Grant_BAO_Grant::getGrantPrograms();
+
+        // $this->add('select', 'grant_program_id',  ts( 'Grant Programs' ),
+        //            array( '' => ts( '- select -' ) ) + $this->_grantPrograms , true);
+        
+        $this->addDate( 'application_received_date', ts('Application Received'), false, array( 'formatType' => 'custom') );
+        $this->addDate( 'decision_date', ts('Grant Decision'), false, array( 'formatType' => 'custom') );
+        $this->addDate( 'money_transfer_date', ts('Money Transferred'), false, array( 'formatType' => 'custom') );
+        $this->addDate( 'grant_due_date', ts('Grant Report Due'), false, array( 'formatType' => 'custom') );
+
+        $this->addElement('checkbox','grant_report_received', ts('Grant Report Received?'),null );
+        $this->add('textarea', 'rationale', ts('Rationale'), $attributes['rationale']);
+        $this->add( 'text', 'amount_total', ts('Amount Requested'), null, true );
+        $this->addRule('amount_total', ts('Please enter a valid amount.'), 'money'); 
+        
+        $this->add( 'text', 'amount_granted', ts('Amount Granted') );         
+        $this->addRule('amount_granted', ts('Please enter a valid amount.'), 'money'); 
+
+        $this->add( 'text', 'amount_requested', ts('Amount Requested<br />(original currency)') );
+        // if ( CRM_Core_Permission::check('administer CiviGrant')  ) {
+        //   $this->add( 'text', 'assessment', ts( 'Assessment' ) );
+        // }
+        
+        $this->addRule('amount_requested', ts('Please enter a valid amount.'), 'money'); 
+
+        $noteAttrib = CRM_Core_DAO::getAttribute('CRM_Core_DAO_Note');
+        $this->add( 'textarea', 'note', ts('Notes'), $noteAttrib['note'] );
+        
+        //build custom data
+        CRM_Custom_Form_Customdata::buildQuickForm( $this );
+        
+        // add attachments part
+        require_once 'CRM/Core/BAO/File.php';
+        CRM_Core_BAO_File::buildAttachment( $this,
+                                            'civicrm_grant',
+                                            $this->_id );
+
+        // make this form an upload since we dont know if the custom data injected dynamically
+        // is of type file etc $uploadNames = $this->get( 'uploadNames' );
+        $this->addButtons(array( 
+                                  array ( 'type'      => 'upload',
+                                          'name'      => ts('Save'), 
+                                          'isDefault' => true   ),  
+                                  array ( 'type'      => 'upload',
+                                          'name'      => ts('Save and New'), 
+                                          'js'        => array( 'onclick' => "return verify( );" ),
+                                          'subName'   => 'new' ),
+                                  array ( 'type'      => 'cancel', 
+                                          'name'      => ts('Cancel') ), 
+                                   ) 
+                            );
+        
+        if ( $this->_context == 'standalone' ) {
+            require_once 'CRM/Contact/Form/NewContact.php';
+            CRM_Contact_Form_NewContact::buildQuickForm( $this );
+            $this->addFormRule( array( 'CRM_Grant_Form_Grant', 'formRule' ), $this );
+        }
+        if ( $this->_context == 'search' ) {
+
+          $this->addButtons(array( 
+                                  array ( 'type'      => 'upload',
+                                          'name'      => ts('Save'), 
+                                          'isDefault' => true   ),
+                                  array ( 'type'      => 'submit',
+                                          'name'      => ts('Save and Next'),
+                                          'subName'   => 'savenext' ),   
+                                  array ( 'type'      => 'upload',
+                                          'name'      => ts('Save and New'), 
+                                          'js'        => array( 'onclick' => "return verify( );" ),
+                                          'subName'   => 'new' ),
+                                  array ( 'type'      => 'cancel', 
+                                          'name'      => ts('Cancel') ), 
+                                   ) 
+                            );
+          $controller = new CRM_Core_Controller_Simple( 'CRM_Grant_Form_Search', ts('grants'), null );
+          $controller->setEmbedded( true ); 
+          $controller->reset( );
+          //$controller->set( 'limit', 20 );
+          $controller->set( 'force', 1 );
+          $controller->process( ); 
+          $controller->run( );
+        }
+    }
+    
+    /**  
+     * global form rule  
+     *  
+     * @param array $fields  the input form values  
+     * @param array $files   the uploaded files if any  
+     * @param array $options additional user data  
+     *  
+     * @return true if no errors, else array of errors  
+     * @access public  
+     * @static  
+     */  
+    static function formRule( $fields, $files, $self ) {  
+        $errors = array( ); 
+        
+        //check if contact is selected in standalone mode
+        if ( isset( $fields['contact_select_id'][1] ) && !$fields['contact_select_id'][1] ) {
+            $errors['contact[1]'] = ts('Please select a contact or create new contact');
+        }
+        
+        return $errors;
+    }
+    
+    
+    /** 
+     * Function to process the form 
+     * 
+     * @access public 
+     * @return None 
+     */ 
+    public function postProcess( )  
+    { 
+      
+      if ( $this->_action & CRM_Core_Action::DELETE ) {
+        require_once 'CRM/Grant/BAO/Grant.php';
+        CRM_Grant_BAO_Grant::del( $this->_id );
+        return;
+      }
+      
+      if ( $this->_action & CRM_Core_Action::UPDATE ) {
+        $ids['grant'] = $this->_id ;
+      }
+        
+      // get the submitted form values.  
+      $params = $this->controller->exportValues( $this->_name );
+
+      if ( !CRM_Utils_Array::value( 'grant_report_received', $params ) ) {
+        $params['grant_report_received'] = "null";
+      } 
+        
+      // set the contact, when contact is selected
+      if ( CRM_Utils_Array::value('contact_select_id', $params ) ) {
+        $this->_contactID = $params['contact_select_id'][1];
+      }
+        
+      $params['contact_id'] = $this->_contactID;
+      $ids['note'] = array( );
+      if ( $this->_noteId ) {
+        $ids['note']['id']   = $this->_noteId;
+      }
+      $array['contact_id'] = $this->_contactID;
+      // process custom data
+      $customFields = CRM_Core_BAO_CustomField::getFields( 'Grant' );
+      $params['custom'] = CRM_Core_BAO_CustomField::postProcess( $params,
+                                                                 $customFields,
+                                                                 $this->_id,
+                                                                 'Grant' );
+
+      // add attachments as needed
+      CRM_Core_BAO_File::formatAttachment( $params,
+                                           $params,
+                                           'civicrm_grant',
+                                           $this->_id );
+
+      require_once 'CRM/Grant/BAO/Grant.php';
+      require_once 'CRM/Grant/DAO/GrantProgram.php';
+      $grantProgram  = new CRM_Grant_DAO_GrantProgram( );
+      $grantProgram->id = $params['grant_program_id'];
+      if ( $grantProgram->find( true ) ) {
+        $params['is_auto_email'] = $grantProgram->is_auto_email;
+      }
+      $params['grant_status'] = $grantStatus = $this->_grantStatus[$params['status_id']];
+      $params['grant_type'] = $grantType = $this->_grantType[$params['grant_type_id']];
+      $params['grant_programs'] = $grantPrograms = $this->_grantPrograms[$params['grant_program_id']];
+      // foreach( $params['custom'] as $key => $value ) {
+      //   foreach ( $value as $vkey => $vval ) {
+      //     if ( !empty( $vval['value'] ) ) {
+      //       $data[$vval['custom_group_id']][$vval['custom_field_id']] = $vval['value'];
+      //     }
+      //   }
+      // }
+      // require_once 'CRM/Core/DAO.php';
+      // if ( !empty( $data ) ) {
+      //   foreach ( $data as $dataKey => $dataValue ) {
+      //     $customGroupName = CRM_Core_DAO::getFieldValue( 'CRM_Core_DAO_CustomGroup',$dataKey,'title' );
+      //     $customGroup[$customGroupName] = $customGroupName;
+      //     $c = 0;
+      //     foreach ( $dataValue  as $dataValueKey => $dataValueValue ) {
+      //       $customField[$customGroupName][$c]['label'] = CRM_Core_DAO::getFieldValue( 'CRM_Core_DAO_CustomField',$dataValueKey,'label' );
+      //       $customField[$customGroupName][$c]['value'] = $dataValueValue;
+      //       $c++;
+      //     }
+      //   }
+      //   $this->assign( 'customGroup', $customGroup );
+      //   $this->assign( 'customField', $customField );
+      // }
+        
+      // $this->assign( 'grant_type', $grantType );
+      // $this->assign( 'grant_programs', $grantPrograms );
+      // $this->assign( 'grant_status', $grantStatus );
+      // $this->assign( 'params', $params );
+        
+      //CRM_Grant_BAO_Grant::sendMail( $this->_contactID, $params, $grantStatus );
+      $grant = CRM_Grant_BAO_Grant::create($params, $ids);
+      
+      $grants = CRM_Grant_BAO_Grant::getGrants( $array );
+      $grants =  array_flip( array_keys($grants) );
+        
+      $foundit = false;
+      foreach( $grants as $gKey => $gVal ) {
+        if ($foundit) {
+          $next = $gKey; 
+          break;
+        }
+        if ( $gKey == $this->_next ) { 
+          $next = $gKey; 
+          if($gVal == end($grants)) {
+            reset($grants);
+            $next = key($grants);
+          }
+          $foundit = true;
+        }
+      }
+      $buttonName = $this->controller->getButtonName( );
+      
+      $session = CRM_Core_Session::singleton( );
+      
+      if ( $this->_context == 'search' ) {
+        if ( CRM_Utils_Array::value( $this->getButtonName( 'submit', 'savenext' ), $_POST ) ) {
+          if ($this->_id != $this->_prev) {
+            CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/grant', 
+                                                             "reset=1&action=update&id={$this->_next}&cid={$this->_contactID}&context=search&next={$next}&prev={$this->_prev}&key={$this->_key}") );
+
+          } else {
+            CRM_Core_Session::setStatus( ts( 'The next record in the Search no longer exists. Select another record to edit if desired.' ) );
+            CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/grant/search', 
+                                                             "force=1&qfKey={$this->_key}") );
+          }
+        } else if( CRM_Utils_Array::value( $this->getButtonName( 'upload', 'new' ), $_POST ) ) {
+          CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/grant', 
+                                                           "reset=1&action=add&context=grant&cid={$this->_contactID}") );
+
+        } else {
+          CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/grant/search', 
+                                                           "force=1&qfKey={$this->_key}") );
+        }
+      }
+      ///civicrm/contact/view/grant?reset=1&action=add&context=grant&cid=64
+      if ( $this->_context == 'standalone' ) {
+        if ( $buttonName == $this->getButtonName( 'upload', 'new' ) ) {
+          $session->replaceUserContext(CRM_Utils_System::url('civicrm/grant/add', 
+                                                             'reset=1&action=add&context=standalone') );
+        } else {
+          $session->replaceUserContext(CRM_Utils_System::url( 'civicrm/contact/view',
+                                                              "reset=1&cid={$this->_contactID}&selectedChild=grant" ) );
+        }
+      } else if ( $buttonName == $this->getButtonName( 'upload', 'new' ) ) {
+        $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/grant', 
+                                                           "reset=1&action=add&context=grant&cid={$this->_contactID}") );
+      }
+    }
+}
+
+
diff --git a/CRM/Grant/Form/GrantProgram.php b/CRM/Grant/Form/GrantProgram.php
new file mode 100755
index 0000000..1202636
--- /dev/null
+++ b/CRM/Grant/Form/GrantProgram.php
@@ -0,0 +1,219 @@
+<?php
+
+/*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.0                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*/
+
+/**
+ *
+ * @package CRM
+ * @copyright CiviCRM LLC (c) 2004-2011
+ * $Id$
+ *
+ */
+
+require_once 'CRM/Core/Form.php';
+require_once 'CRM/Grant/BAO/GrantProgram.php';
+/**
+ * This class generates form components for Par Service Fees
+ * 
+ */
+class CRM_Grant_Form_GrantProgram extends CRM_Core_Form
+{
+  protected $_id     = null;
+
+  protected $_fields = null;
+
+
+  function preProcess( ) {
+    $this->_action     = CRM_Utils_Request::retrieve('action', 'String', $this );
+    $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this );
+        
+    $title = null;
+    if ( $this->_action & CRM_Core_Action::UPDATE ) $title = ts('Edit Grant Program');
+    if ( $this->_action & CRM_Core_Action::DELETE ) $title = ts('Delete Grant Program');
+    if ( $title ) CRM_Utils_System::setTitle( $title );
+        
+    $session = CRM_Core_Session::singleton();
+    $session->pushUserContext( CRM_Utils_System::url('civicrm/grant_program', 'reset=1') );
+    $this->assign( 'action', $this->_action );
+
+    $this->_values = $this->get( 'values' );
+    if ( !is_array( $this->_values ) ) {
+      $this->_values = array( );
+            
+      // if we are editing
+      if ( isset( $this->_id ) && $this->_id ) {
+        $params = array( 'id' => $this->_id );
+        CRM_Grant_BAO_GrantProgram::retrieve( $params, $this->_values );
+      }
+      //lets use current object session.
+      $this->set( 'values', $this->_values );
+    }
+  }
+    
+  function setDefaultValues( ) 
+  {
+    $defaults = $this->_values;
+    if ( !empty( $defaults ) ) {
+      $defaults['grant_type_id'] = CRM_Grant_BAO_GrantProgram::getOptionValue( $defaults['grant_type_id'] );
+      $defaults['status_id']     = CRM_Grant_BAO_GrantProgram::getOptionValue( $defaults['status_id'] );
+      if ( !empty( $defaults['allocation_date'] ) ) {
+        $defaults['allocation_date']  = strftime("%m/%d/%Y", strtotime( $defaults['allocation_date'] ));
+      }
+      $defaults['allocation_algorithm'] = CRM_Grant_BAO_GrantProgram::getOptionValue( $defaults['allocation_algorithm'] );
+    }
+    if ( !$this->_id ) {
+      $defaults['is_active'] = 1;
+      $defaults['is_auto_email'] = 1;
+      return $defaults;
+    }
+    return $defaults;
+  }
+  /**
+   * Function to build the form
+   *
+   * @return None
+   * @access public
+   */
+  public function buildQuickForm( $check = false ) 
+  {
+    parent::buildQuickForm( );
+
+        
+    if ( $this->_action & CRM_Core_Action::DELETE ) {
+            
+      $this->addButtons( array(
+                               array ( 'type'      => 'next',
+                                       'name'      => ts('Delete'),
+                                       'isDefault' => true   ),
+
+                               array ( 'type'      => 'cancel',
+                                       'name'      => ts('Cancel') ),
+                               )
+                         );
+      return;
+    }
+
+    $this->applyFilter('__ALL__','trim');
+    $attributes = CRM_Core_DAO::getAttribute( 'CRM_Grant_DAO_GrantProgram' );
+        
+    $this->add( 'text', 'label', ts( 'Label' ),
+                $attributes['label'], true );
+        
+    $grantType = CRM_Core_OptionGroup::values( 'grant_type' );
+    $this->add('select', 'grant_type_id',  ts( 'Grant Type' ),
+               array( '' => ts( '- select -' ) ) + $grantType , true);
+
+    $this->add( 'text', 'total_amount', ts( 'Total Amount' ),
+                $attributes['total_amount'], false );         
+    $this->addRule('total_amount', ts('Please enter a valid amount.'), 'money'); 
+        
+    $this->add( 'text', 'remainder_amount', ts( 'Remainder Amount' ),
+                $attributes['remainder_amount'], false );
+    $this->addRule('remainder_amount', ts('Please enter a valid amount.'), 'money'); 
+
+    $contributionTypes = CRM_Grant_BAO_GrantProgram::contributionTypes();
+    $this->add('select', 'contribution_type_id',  ts( 'Contribution Types' ),
+               array( '' => ts( '- select -' ) ) + $contributionTypes , true);
+        
+    $grantStatus = CRM_Core_OptionGroup::values( 'grant_program_status' );
+    $this->add('select', 'status_id',  ts( 'Grant Status' ),
+               array( '' => ts( '- select -' ) ) + $grantStatus , true);
+
+    $grantAlgorithm = CRM_Core_OptionGroup::values( 'allocation_algorithm' );
+    $this->add('select', 'allocation_algorithm',  ts( 'Allocation Algorithm' ),
+               array( '' => ts( '- select -' ) ) + $grantAlgorithm , true); 
+
+    $this->addDate( 'allocation_date', ts('Allocation Date'), false, array( 'formatType' => 'custom') );
+
+    $this->add( 'checkbox', 'is_active', ts('Enabled?') );
+
+    $this->add( 'checkbox', 'is_auto_email', ts('Auto email?') );
+
+    $this->addButtons(array( 
+                            array ( 'type'      => 'upload',
+                                    'name'      => ts('Save'), 
+                                    'isDefault' => true   ),
+                            array ( 'type'      => 'cancel', 
+                                    'name'      => ts('Cancel') ), 
+                             ) 
+                      );
+        
+  }
+
+  /**
+   * Function to process the form
+   *
+   * @access public
+   * @return None
+   */
+  public function postProcess() 
+  {
+    CRM_Utils_System::flushCache( 'CRM_Grant_DAO_GrantProgram' );
+
+    if ( $this->_action & CRM_Core_Action::DELETE ) {
+      CRM_Grant_BAO_GrantProgram::del( $this->_id );
+      CRM_Core_Session::setStatus( ts('Selected Grant Program has been deleted successfully.') );
+      return;
+    }
+
+    $values   = $this->controller->exportValues( $this->_name );
+    $domainID = CRM_Core_Config::domainID( );
+
+    $result = $this->updateGrantProgram( $values, $domainID );
+    if ( $result ) {
+      CRM_Core_Session::setStatus( ts( 'Grant Program  %1 has been saved.', array( 1 => $result->label ) ) );
+      $session = CRM_Core_Session::singleton();
+      $session->pushUserContext(CRM_Utils_System::url('civicrm/grant_program', 'reset=1&action=browse&id=' . $result->id ));
+    }
+        
+  }//end of function
+
+  function updateGrantProgram( &$values, $domainID ) {
+    require_once 'CRM/Core/DAO.php';
+    $dao = new CRM_Grant_DAO_GrantProgram( );
+    if ( empty( $values['is_active']) )
+      $values['is_active'] = 0;
+    if ( empty( $values['is_auto_email']) )
+      $values['is_auto_email'] = 0;
+    $dao->id                    = $this->_id;
+    $dao->domain_id             = $domainID;
+    $dao->label                 = $values['label'];
+    $dao->name                  = $values['label'];
+    $dao->grant_type_id         = CRM_Grant_BAO_GrantProgram::getOptionValueID( CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup','grant_type','id','name'), $values['grant_type_id']);
+    $dao->total_amount          = $values['total_amount'];
+    $dao->remainder_amount      = $values['remainder_amount'];
+    $dao->contribution_type_id  = $values['contribution_type_id'];
+    $dao->status_id             = CRM_Grant_BAO_GrantProgram::getOptionValueID( CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup','grant_program_status','id','name'), $values['status_id']);
+    $dao->allocation_date       = CRM_Utils_Date::processDate( $values['allocation_date'] );
+    $dao->is_active             = $values['is_active'];
+    $dao->is_auto_email         = $values['is_auto_email'];
+    $dao->allocation_algorithm  = CRM_Grant_BAO_GrantProgram::getOptionValueID( CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup','allocation_algorithm','id','name'), $values['allocation_algorithm']);
+    return $dao->save( );
+  }
+}
+
+
diff --git a/CRM/Grant/Form/GrantProgramView.php b/CRM/Grant/Form/GrantProgramView.php
new file mode 100755
index 0000000..f97e989
--- /dev/null
+++ b/CRM/Grant/Form/GrantProgramView.php
@@ -0,0 +1,293 @@
+<?php
+
+/*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.1                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*/
+
+/**
+ *
+ * @package CRM
+ * @copyright CiviCRM LLC (c) 2004-2011
+ * $Id$
+ *
+ */
+
+require_once 'CRM/Core/Form.php';  
+require_once 'CRM/Grant/BAO/Grant.php';
+require_once 'CRM/Grant/BAO/GrantProgram.php';
+
+/**
+ * This class generates form components for processing a Grant
+ * 
+ */
+class CRM_Grant_Form_GrantProgramView extends CRM_Core_Form
+{
+
+    /**  
+     * Function to set variables up before form is built  
+     *                                                            
+     * @return void  
+     * @access public  
+     */
+    public function preProcess( ) 
+    {
+        $this->_id        = CRM_Utils_Request::retrieve( 'id', 'Positive', $this );
+        $values = array( ); 
+        $params['id'] = $this->_id;
+        CRM_Grant_BAO_GrantProgram::retrieve( $params, $values );
+        $contributionTypes = CRM_Grant_BAO_GrantProgram::contributionTypes();
+        $this->assign('grantType', CRM_Grant_BAO_GrantProgram::getOptionName( $values['grant_type_id'] ) );
+        $this->assign('grantProgramStatus', CRM_Grant_BAO_GrantProgram::getOptionName($values['status_id'] ) );
+        $this->assign('contributionType', $contributionTypes[$values['contribution_type_id']] );
+        $this->assign('grantProgramAlgorithm', CRM_Grant_BAO_GrantProgram::getOptionName( $values['allocation_algorithm'] ) );
+        $grantTokens = array( 'label','name','total_amount',
+                              'remainder_amount','allocation_date', 'is_active', 'is_auto_email' );
+
+        foreach ( $grantTokens as $token ) {
+            $this->assign( $token, CRM_Utils_Array::value( $token, $values ) );
+        }
+        $this->assign( 'id', $this->_id );
+    }
+
+    /**
+     * Function to build the form
+     *
+     * @return None
+     * @access public
+     */
+    public function buildQuickForm( ) 
+    {
+        $this->addButtons(array(  
+                                array ( 'type'      => 'cancel',  
+                                        'name'      => ts('Done'),  
+                                        'spacing'   => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',  
+                                        'isDefault' => true   )
+                                )
+                          );
+    }
+
+    public function allocate( ) 
+    {   
+      require_once 'CRM/Grant/BAO/Grant.php';
+      $grantStatus = CRM_Core_OptionGroup::values( 'grant_status' );
+      $grantStatus = array_flip($grantStatus);
+      $params = array(
+                      'status_id' => $grantStatus['Approved'],
+                      'grant_program_id' => $_POST['pid'],
+                      'amount_granted' => 'NULL',
+                      'assessment'     => 'NOT NULL',
+                      );
+      
+      // $grantAlgorithm = CRM_Core_OptionGroup::values( 'allocation_algorithm' );
+      // $grantAlgorithm = array_flip($grantAlgorithm);
+      // $grantAlgorithmId = $grantAlgorithm[$_POST['algorithm']];
+      $result = CRM_Grant_BAO_Grant::getGrants( $params );
+      
+      if ( !empty($result ) ) {
+        if ( $_POST['algorithm'] == 'Best to Worst, Fully Funded' ) {
+          foreach ( $result as $key => $row ) {
+            $order[$key] = $row['assessment'];
+          }
+          $sort_order = SORT_DESC;
+          array_multisort( $order, $sort_order, $result );
+        } 
+        
+        if( $_POST['remainder_amount'] == '0.00' ) {
+          $totalAmount = $_POST['amount'];
+        } else {
+          $totalAmount = $_POST['remainder_amount'];
+        }
+        
+        $contact = array(); 
+        $grantThresholds = CRM_Core_OptionGroup::values( 'grant_thresholds' );
+        $grantThresholds = array_flip($grantThresholds);
+         
+        foreach ( $result as $key => $value ) {
+            
+          if ( !in_array( $value['contact_id'], $contact ) ) {
+            if ( $_POST['algorithm'] == 'Best to Worst, Fully Funded' ) {
+              if( $value['amount_total'] > $totalAmount ) {
+                $grant['eligible'][] = $value['amount_total'];
+                continue;
+              } else {
+                if ( $value['amount_total'] >= $grantThresholds['Maximum Grant'] ) {
+                  $grant['granted'][] = $grantThresholds['Maximum Grant'];
+                  $totalAmount = $totalAmount - $grantThresholds['Maximum Grant'];
+                  $contact[] = $value['contact_id'];
+                  $value['amount_granted'] = $grantThresholds['Maximum Grant'];
+                } else {
+                  $grant['granted'][] = $value['amount_total'];
+                  $totalAmount = $totalAmount - $value['amount_total'];
+                  $value['amount_granted'] = $value['amount_total'];
+                }
+                $ids['grant']            = $value['grant_id'];
+              }
+            } elseif( $_POST['algorithm'] == 'Over Threshold, Percentage of Request Funded' ) {
+              if($value['assessment'] > $grantThresholds['Minimum Score For Grant Award'] ) {
+                if( ( $grantThresholds['Fixed Percentage Of Grant']/100 )*$value['amount_total'] > $totalAmount ) {
+                  $grant['eligible'][] = ( $grantThresholds['Fixed Percentage Of Grant']/100 )*$value['amount_total'];
+                  continue;
+                } else {
+                  $value['amount_granted'] = ( $grantThresholds['Fixed Percentage Of Grant']/100 )*$value['amount_total'];
+                  $grant['granted'][] = $value['amount_granted'];
+                  if ($value['amount_granted'] >= $grantThresholds['Maximum Grant']) {
+                    $contact[] = $value['contact_id'];
+                  }
+                  $totalAmount = $totalAmount - $value['amount_granted'];
+                }
+              } else {
+                if (  ( $value['assessment']/100 )*$value['amount_total'] > $totalAmount ) {
+                  $grant['eligible'][] = ( $value['assessment']/100 )*$value['amount_total'];
+                  continue;
+                }
+                else {
+                  $value['amount_granted'] = ( $value['assessment']/100 )*$value['amount_total'];
+                  $grant['granted'][] = $value['amount_granted'];
+                  if ($value['amount_granted'] >= $grantThresholds['Maximum Grant']) {
+                    $contact[] = $value['contact_id'];
+                  }
+                  $totalAmount = $totalAmount - $value['amount_granted'];
+                }
+              }
+              $ids['grant']            = $key;
+            } 
+            $result = CRM_Grant_BAO_Grant::add( &$value, &$ids );
+          } else {
+            $grant['nonEligible'][] = $value['amount_total'];
+          }
+        } 
+      }
+      
+      $grantProgramParams['remainder_amount'] = $totalAmount;
+      $grantProgramParams['id'] =  $_POST['pid'];
+      $ids['grant_program']     =  $_POST['pid'];
+      CRM_Grant_BAO_GrantProgram::create( $grantProgramParams, $ids );
+      $eligibleCount = $grantedAmount = $eligibleCount = $eligibleAmount = $nonEligibleCount = $nonEligibleAmount = 0;
+      foreach( $grant as $type => $amount ) {
+        if( $type == 'granted' ) {
+          $grantedCount  = count($amount);
+          $grantedAmount = array_sum($amount);
+        }
+        if( $type == 'eligible' ) {
+          $eligibleCount  = count($amount);
+          $eligibleAmount = array_sum($amount);
+        }
+        if( $type == 'nonEligible' ) {
+          $nonEligibleCount  = count($amount);
+          $nonEligibleAmount = array_sum($amount);
+        }
+      }
+      require_once 'CRM/Core/Page.php';
+      require_once 'CRM/Grant/BAO/Grant.php';
+      $page = new CRM_Core_Page();
+      $grantPrograms = CRM_Grant_BAO_Grant::getGrantPrograms();
+      $message = "Trial Allocation Completed. $".$grantedAmount.".00 allocated to {$grantedCount} eligible applications. ".$eligibleCount." eligible applications were not allocated $".$eligibleAmount.".00 in funds they would have received were funds available. $".$totalAmount." remains unallocated.";
+     
+
+     
+      $page->assign( 'message', $message );
+      
+      $page->assign( 'grant_program_name', $grantPrograms[$_POST['pid']] );
+      CRM_Core_Session::setStatus( $message );
+      $params['is_auto_email'] = 1;
+      CRM_Grant_BAO_Grant::sendMail( $_SESSION[ 'CiviCRM' ][ 'userID' ], $params, 'allocation' );
+    }
+    
+    public function finalize( ) 
+    {   
+      $grantedAmount = 0;
+      require_once 'CRM/Grant/BAO/Grant.php';
+      $grantStatus = CRM_Core_OptionGroup::values( 'grant_status' );
+      $grantStatus = array_flip($grantStatus);
+      $params = array(
+                      'status_id' => $grantStatus['Approved'],
+                      'grant_program_id' => $_POST['pid'],
+                      );
+      $result = CRM_Grant_BAO_Grant::getGrants( $params );
+      if ( !empty($result ) ) {
+        foreach ($result as $key => $row) {
+          $grantedAmount += $row['amount_granted'];
+        }
+        $totalAmount = $_POST['amount'];
+        if( $grantedAmount < $totalAmount ) {
+          $data['confirm'] = 'confirm';
+          $data['amount_granted'] =  $grantedAmount;
+          echo json_encode($data);
+          exit(); 
+        } else {
+          $data['total_amount'] =  $totalAmount;
+          $data['amount_granted'] =  $grantedAmount;
+          echo json_encode($data);
+          exit(); 
+        }
+      }
+    }
+    
+    public function processFinalization( ) {
+      require_once 'CRM/Grant/BAO/Grant.php';
+      $grantStatus = CRM_Core_OptionGroup::values( 'grant_status' );
+      $grantStatus = array_flip($grantStatus);
+      $params = array(
+                      'status_id' => $grantStatus['Approved'],
+                      'grant_program_id' => $_POST['pid'],
+                      );
+      $result = CRM_Grant_BAO_Grant::getGrants( $params );
+      if ( !empty($result ) ) {
+        foreach ($result as $key => $row) {
+          if ( $row['amount_granted'] > 0 ) {
+            $ids['grant'] = $key;
+            $row['status_id'] = $grantStatus['Granted'];
+                    
+            $result = CRM_Grant_BAO_Grant::add( &$row, &$ids );
+          } 
+        }
+        CRM_Core_Session::setStatus( 'Approved allocations finalized successfully.' );
+      }
+    }
+    
+    public function reject( ) 
+    {
+      require_once 'CRM/Grant/BAO/Grant.php';
+      $grantStatus = CRM_Core_OptionGroup::values( 'grant_status' );
+      $grantStatus = array_flip($grantStatus);
+      $id = $_POST['pid'];
+      $params = array(
+                      'status_id' => $grantStatus['Submitted'].','.$grantStatus['Approved'],
+                      'grant_program_id' => $_POST['pid'],
+                      );
+
+      $result = CRM_Grant_BAO_Grant::getGrants( $params );
+      
+      if ( !empty($result ) ) {
+        foreach ( $result as $key => $value ) {
+          $value['status_id'] = $grantStatus['Rejected'];
+          $value['amount_granted'] = 0.00;
+          $ids['grant'] = $key;
+          $result = CRM_Grant_BAO_Grant::add( &$value, &$ids );
+        } 
+        CRM_Core_Session::setStatus( 'Submitted and Approved grants rejected successfully.' );
+      }
+    }
+}
\ No newline at end of file
diff --git a/CRM/Grant/Form/Payment/View.php b/CRM/Grant/Form/Payment/View.php
new file mode 100755
index 0000000..d0f5777
--- /dev/null
+++ b/CRM/Grant/Form/Payment/View.php
@@ -0,0 +1,141 @@
+<?php
+
+/*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.1                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*/
+
+/**
+ *
+ * @package CRM
+ * @copyright CiviCRM LLC (c) 2004-2011
+ * $Id$
+ *
+ */
+
+require_once 'CRM/Core/Form.php';
+require_once 'CRM/Core/OptionGroup.php';
+
+/**
+ * This class generates form components for processing a Grant
+ * 
+ */
+class CRM_Grant_Form_Payment_View extends CRM_Core_Form
+{
+
+    /**  
+     * Function to set variables up before form is built  
+     *                                                            
+     * @return void  
+     * @access public  
+     */
+    public function preProcess( ) 
+    {
+        $this->_id        = CRM_Utils_Request::retrieve( 'id', 'Positive', $this );
+        $context          = CRM_Utils_Request::retrieve( 'context', 'String', $this );
+        $this->assign( 'context', $context );
+        $values = array( ); 
+        $params['id'] = $this->_id;
+        // $session = CRM_Core_Session::singleton();
+        // $url = CRM_Utils_System::url('civicrm/grant/payment/search', '_qf_PaymentSearch_display=true&qfKey='.$_GET['qfKey'] );
+        // $session->pushUserContext( $url );
+        require_once 'CRM/Grant/BAO/GrantPayment.php';
+        require_once 'CRM/Grant/BAO/GrantProgram.php';
+        CRM_Grant_BAO_GrantPayment::retrieve( $params, $values);
+        $paymentStatus = CRM_Core_OptionGroup::values( 'grant_payment_status' );
+        $contributionTypes = CRM_Grant_BAO_GrantProgram::contributionTypes();
+        $this->assign('payment_status_id',  $paymentStatus[$values['payment_status_id']] );
+        $this->assign('contribution_type_id',  $contributionTypes[$values['contribution_type_id']] );
+ 
+        $grantTokens = array( 'payment_batch_number','payment_number',
+                              'payment_created_date','payment_date', 'payable_to_name', 
+                              'payable_to_address', 'amount', 'currency', 'payment_reason', 'replaces_payment_id' );
+
+        foreach ( $grantTokens as $token ) {
+            $this->assign( $token, CRM_Utils_Array::value( $token, $values ) );
+        }
+
+        $this->assign( 'id', $this->_id );
+    }
+    /**
+     * Function to build the form
+     *
+     * @return None
+     * @access public
+     */
+    public function buildQuickForm( ) 
+    {
+      if (  $this->_action & CRM_Core_Action::VIEW ) {
+        $this->addButtons(array(  
+                                array ( 'type'      => 'cancel',  
+                                        'name'      => ts('Cancel'),  
+                                        'spacing'   => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',  
+                                        'isDefault' => true   )
+                                  )
+                          );     
+      } elseif (  ( $this->_action & CRM_Core_Action::STOP ) || (  $this->_action &  CRM_Core_Action::REPRINT  ) || (  $this->_action &  CRM_Core_Action::WITHDRAW  ) ) {
+        $this->addButtons(array( 
+                                array ( 'type'      => 'submit',  
+                                        'name'      => ts('OK'),  
+                                        'spacing'   => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',  
+                                        'isDefault' => true   ), 
+                                array ( 'type'      => 'cancel',  
+                                        'name'      => ts('Cancel'),  
+                                        'spacing'   => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',  
+                                        'isDefault' => true   )
+                                 )
+                          );
+      }
+    }
+
+    public function postProcess( ) {
+        // $session = CRM_Core_Session::singleton();
+        // $url = CRM_Utils_System::url('civicrm/grant/payment', 'reset=1&action=reprint&id='.$this->_id.'&context=search&key='.$_POST['qfKey'] );
+        // $session->pushUserContext( $url );
+
+        CRM_Utils_System::flushCache( 'CRM_Grant_DAO_GrantPayment' );
+        if ( $this->_action & CRM_Core_Action::STOP ) {
+            $domainID = CRM_Core_Config::domainID( );
+            $dao = new CRM_Grant_DAO_GrantPayment( );
+            $dao->id                    = $this->_id;
+            $dao->domain_id             = $domainID;
+            $dao->payment_status_id     = CRM_Core_OptionGroup::getValue( 'grant_payment_status', 'Stopped', 'name' );
+            $dao->save( );
+            CRM_Core_Session::setStatus( ts( 'Selected Grant Payment has been stopped successfully.' ) );
+            CRM_Utils_System::redirect( CRM_Utils_System::url( 'civicrm/grant/payment/search', 'reset=1&force=1' ) );
+        } elseif (  $this->_action & CRM_Core_Action::REPRINT  ) {
+            CRM_Utils_System::redirect( CRM_Utils_System::url( 'civicrm/grant/payment/reprint', 'reset=1&prid='.$this->_id.'&qfKey='.$_POST['qfKey'] ) );
+            
+        } elseif (  $this->_action & CRM_Core_Action::WITHDRAW  ) {
+            $domainID = CRM_Core_Config::domainID( );
+            $dao = new CRM_Grant_DAO_GrantPayment( );
+            $dao->id                    = $this->_id;
+            $dao->domain_id             = $domainID;
+            $dao->payment_status_id     = CRM_Core_OptionGroup::getValue( 'grant_payment_status', 'Withdrawn', 'name' );
+            $dao->save( );
+            CRM_Core_Session::setStatus( ts( 'Selected Grant Payment has been withdraw successfully.' ) );
+            CRM_Utils_System::redirect( CRM_Utils_System::url( 'civicrm/grant/payment/search', 'reset=1&force=1' ) );
+        }
+    }  
+}
\ No newline at end of file
diff --git a/CRM/Grant/Form/PaymentSearch.php b/CRM/Grant/Form/PaymentSearch.php
new file mode 100755
index 0000000..008c8db
--- /dev/null
+++ b/CRM/Grant/Form/PaymentSearch.php
@@ -0,0 +1,475 @@
+<?php
+
+/*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.1                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing   
+ +--------------------------------------------------------------------+
+*/
+
+/**
+ *
+ * @package CRM
+ * @copyright CiviCRM LLC (c) 2004-2011
+ * $Id$
+ *
+ */
+
+/**
+ * Files required
+ */
+require_once 'CRM/Grant/PseudoConstant.php';
+require_once 'CRM/Grant/Selector/PaymentSearch.php';
+require_once 'CRM/Core/Selector/Controller.php';
+require_once 'CRM/Contact/BAO/SavedSearch.php';
+
+/**
+ * This file is for civigrant search
+ */
+class CRM_Grant_Form_PaymentSearch extends CRM_Core_Form
+{
+    /** 
+     * Are we forced to run a search 
+     * 
+     * @var int 
+     * @access protected 
+     */ 
+    protected $_force; 
+
+    /** 
+     * name of search button 
+     * 
+     * @var string 
+     * @access protected 
+     */ 
+    protected $_searchButtonName;
+
+    /** 
+     * name of print button 
+     * 
+     * @var string 
+     * @access protected 
+     */ 
+    protected $_printButtonName; 
+ 
+    /** 
+     * name of action button 
+     * 
+     * @var string 
+     * @access protected 
+     */ 
+    protected $_actionButtonName;
+
+    /** 
+     * form values that we will be using 
+     * 
+     * @var array 
+     * @access protected 
+     */ 
+    protected $_formValues; 
+
+    /**
+     * the params that are sent to the query
+     * 
+     * @var array 
+     * @access protected 
+     */ 
+    protected $_queryParams;
+    
+    /** 
+     * have we already done this search 
+     * 
+     * @access protected 
+     * @var boolean 
+     */ 
+    protected $_done; 
+
+    /**
+     * are we restricting ourselves to a single contact
+     *
+     * @access protected  
+     * @var boolean  
+     */  
+    protected $_single = false;
+
+    /** 
+     * are we restricting ourselves to a single contact 
+     * 
+     * @access protected   
+     * @var boolean   
+     */   
+    protected $_limit = null;
+
+    /** 
+     * what context are we being invoked from 
+     *    
+     * @access protected      
+     * @var string 
+     */      
+    protected $_context = null; 
+    
+    /** 
+     * prefix for the controller
+     * 
+     */
+    protected $_prefix = "grant_";
+
+    protected $_defaults;
+
+
+    /** 
+     * processing needed for buildForm and later 
+     * 
+     * @return void 
+     * @access public 
+     */ 
+    function preProcess( ) 
+    { 
+        /** 
+         * set the button names 
+         */   
+        $this->_searchButtonName = $this->getButtonName( 'refresh' );
+        $this->_printButtonName  = $this->getButtonName( 'next'   , 'print' ); 
+        $this->_actionButtonName = $this->getButtonName( 'next'   , 'action' );
+        $this->_done = false;
+        $this->defaults = array( );
+        
+        /* 
+         * we allow the controller to set force/reset externally, useful when we are being 
+         * driven by the wizard framework 
+         */ 
+        $this->_reset    = CRM_Utils_Request::retrieve( 'reset', 'Boolean', CRM_Core_DAO::$_nullObject ); 
+        $this->_force    = CRM_Utils_Request::retrieve( 'force', 'Boolean',  $this, false ); 
+        $this->_download = CRM_Utils_Request::retrieve( 'download', 'String', $this, false );
+        $this->_batchId  = CRM_Utils_Request::retrieve( 'bid', 'Positive',  $this, false );
+        $this->_limit    = CRM_Utils_Request::retrieve( 'limit', 'Positive', $this );
+        $this->_context  = CRM_Utils_Request::retrieve( 'context', 'String', $this, false, 'search' );
+        
+        $this->assign( "context", $this->_context );
+        
+        // get user submitted values
+        // get it from controller only if form has been submitted, else preProcess has set this
+        if ( ! empty( $_POST ) ) { 
+            $this->_formValues = $this->controller->exportValues( $this->_name );
+        } else {
+            $this->_formValues = $this->get( 'formValues' ); 
+        } 
+        
+        
+        if ( $this->_force ) { 
+            $this->postProcess( );
+            $this->set( 'force', 0 );
+        }
+        $sortID = null; 
+        if ( $this->get( CRM_Utils_Sort::SORT_ID  ) ) { 
+            $sortID = CRM_Utils_Sort::sortIDValue( $this->get( CRM_Utils_Sort::SORT_ID  ), 
+                                                   $this->get( CRM_Utils_Sort::SORT_DIRECTION ) );
+        } 
+    
+        require_once 'CRM/Grant/BAO/PaymentSearch.php';
+ 
+        
+        $this->_queryParams = CRM_Grant_BAO_PaymentSearch::convertFormValues( $this->_formValues );
+        $selector = new CRM_Grant_Selector_PaymentSearch( $this->_queryParams,
+                                                          $this->_action,
+                                                          null,
+                                                          $this->_single,
+                                                          $this->_limit,
+                                                          $this->_context );
+      
+        
+        $prefix = null;
+        if ( $this->_context == 'user' ) {
+            $prefix = $this->_prefix;
+        }
+        $this->assign( "{$prefix}limit", $this->_limit );
+        $this->assign( "{$prefix}single", $this->_single );
+        $controller = new CRM_Core_Selector_Controller($selector ,  
+                                                       $this->get( CRM_Utils_Pager::PAGE_ID ),  
+                                                       $sortID,  
+                                                       CRM_Core_Action::VIEW, 
+                                                       $this, 
+                                                       CRM_Core_Selector_Controller::TRANSFER,
+                                                       $prefix);
+        
+        $controller->setEmbedded( true ); 
+        $controller->moveFromSessionToTemplate();
+        $this->assign( 'summary', $this->get( 'summary' ) ); 
+        $download = false;
+        if ( CRM_Utils_Array::value( 'bid', $_GET ) ) {
+            $download = true;
+        }
+        if ( $this->_download && $download ) {
+            global $base_url;
+            $config = CRM_Core_Config::singleton();
+            $directory = strstr( $config->customFileUploadDir, 'sites' );;
+            $config = CRM_Core_Config::singleton();
+            $file_name = $base_url.'/'.$directory.$this->_download;
+            $this->assign( 'download', $file_name ); 
+        }
+    }
+    
+    /**
+     * Build the form
+     *
+     * @access public
+     * @return void
+     */
+    function buildQuickForm( ) 
+    { 
+        require_once 'CRM/Core/OptionGroup.php';
+        $paymentStatus = CRM_Core_OptionGroup::values( 'grant_payment_status' );
+        $this->add('select', 'payment_status_id',  ts( 'Status' ),
+                   array( '' => ts( '- select -' ) ) + $paymentStatus);
+        
+        $this->addElement('text', 'payment_batch_number', ts('Batch Number'), array( 'size' => 8, 'maxlength' => 8 ) );
+       
+        $this->addElement('text', 'payment_number', ts('Payment Number'), array( 'size' => 8, 'maxlength' => 8 ) );
+       
+        $this->addDate( 'payment_created_date_low', ts('From'), false, array( 'formatType' => 'searchDate') );
+        $this->addDate( 'payment_created_date_high', ts('To'), false, array( 'formatType' => 'searchDate') );
+        
+        $this->addElement('text', 'payable_to_name', ts('Payee name'), CRM_Core_DAO::getAttribute('CRM_Grant_DAO_GrantPayment', 'payable_to_name') );
+ 
+        $this->add('text', 'amount', ts('Amount'), array( 'size' => 8, 'maxlength' => 8 ) ); 
+        //$this->addRule('amount', ts('Please enter a valid money value (e.g. %1).', array(1 => CRM_Utils_Money::format('99.99', ' '))), 'money');
+       
+        
+        /* 
+         * add form checkboxes for each row. This is needed out here to conform to QF protocol 
+         * of all elements being declared in builQuickForm 
+         */ 
+
+        $rows = $this->get( 'rows' );
+        
+        if ( is_array( $rows ) )  {
+            
+            if ( !$this->_single ) {
+                $this->addElement( 'checkbox', 'toggleSelect', null, null, array( 'onchange' => "toggleTaskAction( true );return toggleCheckboxVals('mark_x_',this);" ) ); 
+                foreach ($rows as $row) {
+                    $this->addElement( 'checkbox', CRM_Utils_Array::value( 'checkbox', $row ), 
+                                       null, null, 
+                                       array( 'onclick' => " toggleTaskAction( true ); return checkSelectedBox('" . CRM_Utils_Array::value( 'checkbox', $row ) . "');" )
+                                      
+                                       ); 
+                }
+            }
+
+            $total = $cancel = 0;
+
+            require_once "CRM/Core/Permission.php";
+            $permission = CRM_Core_Permission::getPermission( );
+
+            require_once 'CRM/Grant/PaymentTask.php';
+            $tasks = array( '' => ts('- actions -') );
+            $permissionedTask = CRM_Grant_PaymentTask::permissionedTaskTitles( $permission );
+            if ( is_array( $permissionedTask ) && !CRM_Utils_System::isNull( $permissionedTask ) ) {
+                $tasks += $permissionedTask;
+            }
+            
+            $this->add('select', 'task'   , ts('Actions:') . ' '    , $tasks    );  
+
+            $this->add('submit', $this->_actionButtonName, ts('Go'), 
+                       array( 'class' => 'form-submit', 
+                              'onclick' => "return checkPerformAction('mark_x', '".$this->getName()."', 0);" ) ); 
+            
+            $this->add('submit', $this->_printButtonName, ts('Print'), 
+                       array( 'class' => 'form-submit', 
+                              'onclick' => "return checkPerformAction('mark_x', '".$this->getName()."', 1);" ) ); 
+            
+            // need to perform tasks on all or selected items ? using radio_ts(task selection) for it 
+            $this->addElement('radio', 'radio_ts', null, '', 'ts_sel', array( 'checked' => 'checked') ); 
+            $this->addElement('radio', 'radio_ts', null, '', 'ts_all', array( 'onchange' => $this->getName().".toggleSelect.checked = false; toggleCheckboxVals('mark_x_',this); toggleTaskAction( true );" ) );
+        }
+        
+    //add buttons 
+        $this->addButtons( array( 
+                                 array ( 'type'      => 'refresh', 
+                                         'name'      => ts('Search'), 
+                                         'isDefault' => true     ) 
+                                  )    );
+    }
+
+    
+    /**
+     * The post processing of the form gets done here.
+     * 
+     * Key things done during post processing are
+     *      - check for reset or next request. if present, skip post procesing.
+     *      - now check if user requested running a saved search, if so, then
+     *        the form values associated with the saved search are used for searching.
+     *      - if user has done a submit with new values the regular post submissing is 
+     *        done.
+     * The processing consists of using a Selector / Controller framework for getting the
+     * search results.
+     *
+     * @param
+     *
+     * @return void 
+     * @access public
+     */
+    function postProcess( ) 
+    {
+        if ( $this->_done ) {
+            return;
+        }
+        $this->_done = true;
+        
+        $this->_formValues = $this->controller->exportValues($this->_name);
+       
+        
+
+        if ( !empty( $_GET['bid'] ) ) {
+            $this->_formValues['payment_batch_number'] = $_GET['bid'];
+        }
+        $this->fixFormValues( );
+
+        require_once 'CRM/Grant/BAO/PaymentSearch.php';
+        $this->_queryParams = CRM_Grant_BAO_PaymentSearch::convertFormValues( $this->_formValues );
+        $this->set( 'formValues' , $this->_formValues  );
+        $this->set( 'queryParams', $this->_queryParams );
+        
+        $buttonName = $this->controller->getButtonName( );
+        if ( $buttonName == $this->_actionButtonName || $buttonName == $this->_printButtonName ) { 
+            // check actionName and if next, then do not repeat a search, since we are going to the next page 
+            // hack, make sure we reset the task values 
+            $stateMachine =& $this->controller->getStateMachine( );
+            $formName     =  $stateMachine->getTaskFormName( );
+            $this->controller->resetPage( $formName ); 
+            return; 
+        }
+        
+        $sortID = null;
+        if ( $this->get( CRM_Utils_Sort::SORT_ID  ) ) { 
+            $sortID = CRM_Utils_Sort::sortIDValue( $this->get( CRM_Utils_Sort::SORT_ID  ), 
+                                                   $this->get( CRM_Utils_Sort::SORT_DIRECTION ) ); 
+        } 
+      
+
+        $selector = new CRM_Grant_Selector_PaymentSearch( $this->_queryParams,
+                                                          $this->_action,
+                                                          null,
+                                                          $this->_single,
+                                                          $this->_limit,
+                                                          $this->_context );
+        
+        $selector->setKey( $this->controller->_key );
+       
+        
+        $prefix = null;
+        if ( $this->_context == 'basic' || $this->_context == 'user') {
+            $prefix = $this->_prefix;
+
+        }
+       
+        $controller = new CRM_Core_Selector_Controller($selector , 
+                                                       $this->get( CRM_Utils_Pager::PAGE_ID ), 
+                                                       $sortID, 
+                                                       CRM_Core_Action::VIEW,
+                                                       $this,
+                                                       CRM_Core_Selector_Controller::SESSION,
+                                                       $prefix);
+        
+        $controller->setEmbedded( true ); 
+        
+        $query   =& $selector->getQuery( );
+        if ( $this->_context == 'user' ) {
+            $query->setSkipPermission( true );
+        }
+        $controller->run(); 
+    }
+    
+
+    /**
+     * Set the default form values
+     *
+     * @access protected
+     * @return array the default array reference
+     */
+    function &setDefaultValues( ) 
+        {
+            return $this->_formValues;
+        }
+
+    function fixFormValues( )
+    {
+        // if this search has been forced
+        // then see if there are any get values, and if so over-ride the post values
+        // note that this means that GET over-rides POST :)
+        
+        if ( ! $this->_force ) {
+            return;
+        }
+
+        $status = CRM_Utils_Request::retrieve( 'status', 'String',
+                                               CRM_Core_DAO::$_nullObject );
+        if ( $status ) {
+            $this->_formValues['payment_status_id'] = $status;
+            $this->_defaults  ['payment_status_id'] = $status;
+        }
+
+        $cid = CRM_Utils_Request::retrieve( 'cid', 'Positive', $this );
+
+        if ( $cid ) {
+            $cid = CRM_Utils_Type::escape( $cid, 'Integer' );
+            if ( $cid > 0 ) {
+                $this->_formValues['contact_id'] = $cid;
+                
+                // also assign individual mode to the template
+                $this->_single = true;
+
+            }
+        }    
+    }
+
+    function getFormValues( ) {
+        return null;
+    }
+    
+    /**
+     * Return a descriptive name for the page, used in wizard header
+     *
+     * @return string
+     * @access public
+     */
+    public function getTitle( ) 
+    {
+        return ts( 'Search Grant Payments' );
+    } 
+
+    function run( ) 
+    {
+        $action = CRM_Utils_Request::retrieve('action', 'String',
+                                              $this, false, 0 );
+        
+        if ( $action & CRM_Core_Action::VIEW ) { 
+            $this->view( $action); 
+        } else if ( $action & ( CRM_Core_Action::UPDATE | CRM_Core_Action::ADD | CRM_Core_Action::DELETE ) ) {
+            $this->edit( $action);
+        } else {
+            $this->browse( ); 
+        }
+        $this->assign('action', $action);
+        return parent::run( );
+    }
+}
+
diff --git a/CRM/Grant/Form/PaymentTask.php b/CRM/Grant/Form/PaymentTask.php
new file mode 100755
index 0000000..9754a03
--- /dev/null
+++ b/CRM/Grant/Form/PaymentTask.php
@@ -0,0 +1,170 @@
+<?php
+
+/*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.1                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*/
+
+/**
+ *
+ * @package CRM
+ * @copyright CiviCRM LLC (c) 2004-2011
+ * $Id$
+ *
+ */
+
+require_once 'CRM/Core/SelectValues.php';
+require_once 'CRM/Core/Form.php';
+require_once 'CRM/Grant/PaymentTask.php';
+require_once 'CRM/Contact/BAO/Query.php';
+/**
+ * This class generates task actions for CiviEvent
+ * 
+ */
+class CRM_Grant_Form_PaymentTask extends CRM_Core_Form
+{
+  /**
+   * the task being performed
+   *
+   * @var int
+   */
+  protected $_task;
+
+  /**
+   * The additional clause that we restrict the search with
+   *
+   * @var string
+   */
+  protected $_componentClause = null;
+
+  /**
+   * The array that holds all the component ids
+   *
+   * @var array
+   */
+  protected $_componentIds;
+
+  /**
+   * The array that holds all the grant ids
+   *
+   * @var array
+   */
+  protected $_grantIds;
+
+  /**
+   * build all the data structures needed to build the form
+   *
+   * @param
+   * @return void
+   * @access public
+   */
+  function preProcess( ) 
+  {
+    self::preProcessCommon( $this );
+  }
+
+  static function preProcessCommon( &$form, $useTable = false )
+  {
+    $form->_grantIds = array();
+        
+    if ( !CRM_Utils_Array::value( 'prid', $_GET  ) ) {
+      $values = $form->controller->exportValues( 'PaymentSearch' );
+    }
+
+    $form->_task = CRM_Utils_Array::value( 'task', $values );
+    $grantPaymentTasks = CRM_Grant_PaymentTask::tasks();
+    if ( !empty( $form->_task ) ) {
+      $form->assign( 'taskName', $grantPaymentTasks[$form->_task] );
+    }
+    $ids = array();
+    if ( CRM_Utils_Array::value( 'radio_ts', $values ) == 'ts_sel' ) {
+      foreach ( $values as $name => $value ) {
+        if ( substr( $name, 0, CRM_Core_Form::CB_PREFIX_LEN ) == CRM_Core_Form::CB_PREFIX ) {
+          $ids[] = substr( $name, CRM_Core_Form::CB_PREFIX_LEN );
+        }
+      }
+    } else {
+      $queryParams =  $form->get( 'queryParams' );
+      $query       = new CRM_Grant_BAO_PaymentSearch( $queryParams, null, null, false, false, 
+                                                      CRM_Grant_BAO_PaymentSearch::MODE_GRANT_PAYMENT);
+           
+      $query->_distinctComponentClause = " civicrm_payment.id";
+      $query->_groupByComponentClause  = " GROUP BY civicrm_payment.id ";
+      $result = $query->searchQuery(0, 0, null);
+      while ($result->fetch()) {
+        $ids[] = $result->id;
+      }
+    }
+
+    if ( ! empty( $ids ) ) {
+      $form->_componentClause =
+        ' civicrm_payment.id IN ( ' .
+        implode( ',', $ids ) . ' ) ';
+      $form->assign( 'totalSelectedGrants', count( $ids ) );             
+    }
+        
+    $form->_grantPaymentIds = $form->_componentIds = $ids;
+
+    //set the context for redirection for any task actions
+    $qfKey = CRM_Utils_Request::retrieve( 'qfKey', 'String', $this );
+    require_once 'CRM/Utils/Rule.php';
+    $urlParams = 'force=1';
+    if ( CRM_Utils_Rule::qfKey( $qfKey ) ) $urlParams .= "&qfKey=$qfKey";
+        
+    $session = CRM_Core_Session::singleton( );
+    $session->replaceUserContext( CRM_Utils_System::url( 'civicrm/grant/payment/search', $urlParams ) );
+  }
+
+  /**
+   * Given the grant id, compute the contact id
+   * since its used for things like send email
+   */
+  public function setContactIDs( ) 
+  {
+    $this->_contactIds =& CRM_Core_DAO::getContactIDsFromComponent( $this->_grantIds,
+                                                                    'civicrm_grant' );
+  }
+
+  /**
+   * simple shell that derived classes can call to add buttons to
+   * the form with a customized title for the main Submit
+   *
+   * @param string $title title of the main button
+   * @param string $type  button type for the form after processing
+   * @return void
+   * @access public
+   */
+  function addDefaultButtons( $title, $nextType = 'next', $backType = 'back' )
+  {
+    $this->addButtons( array(
+                             array ( 'type'      => $nextType,
+                                     'name'      => $title,
+                                     'isDefault' => true   ),
+                             array ( 'type'      => $backType,
+                                     'name'      => ts('Back') ),
+                             )
+                       );
+  }
+}
+
diff --git a/CRM/Grant/Form/Search.php b/CRM/Grant/Form/Search.php
new file mode 100755
index 0000000..b0f5111
--- /dev/null
+++ b/CRM/Grant/Form/Search.php
@@ -0,0 +1,454 @@
+<?php
+
+/*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.1                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing   
+ +--------------------------------------------------------------------+
+*/
+
+/**
+ *
+ * @package CRM
+ * @copyright CiviCRM LLC (c) 2004-2011
+ * $Id$
+ *
+ */
+
+/**
+ * Files required
+ */
+require_once 'CRM/Grant/PseudoConstant.php';
+require_once 'CRM/Grant/Selector/Search.php';
+require_once 'CRM/Core/Selector/Controller.php';
+require_once 'CRM/Contact/BAO/SavedSearch.php';
+
+/**
+ * This file is for civigrant search
+ */
+class CRM_Grant_Form_Search extends CRM_Core_Form
+{
+    /** 
+     * Are we forced to run a search 
+     * 
+     * @var int 
+     * @access protected 
+     */ 
+    protected $_force; 
+
+    /** 
+     * name of search button 
+     * 
+     * @var string 
+     * @access protected 
+     */ 
+    protected $_searchButtonName;
+
+    /** 
+     * name of print button 
+     * 
+     * @var string 
+     * @access protected 
+     */ 
+    protected $_printButtonName; 
+ 
+    /** 
+     * name of action button 
+     * 
+     * @var string 
+     * @access protected 
+     */ 
+    protected $_actionButtonName;
+
+    /** 
+     * form values that we will be using 
+     * 
+     * @var array 
+     * @access protected 
+     */ 
+    protected $_formValues; 
+
+    /**
+     * the params that are sent to the query
+     * 
+     * @var array 
+     * @access protected 
+     */ 
+    protected $_queryParams;
+    
+    /** 
+     * have we already done this search 
+     * 
+     * @access protected 
+     * @var boolean 
+     */ 
+    protected $_done; 
+
+    /**
+     * are we restricting ourselves to a single contact
+     *
+     * @access protected  
+     * @var boolean  
+     */  
+    protected $_single = false;
+
+    /** 
+     * are we restricting ourselves to a single contact 
+     * 
+     * @access protected   
+     * @var boolean   
+     */   
+    protected $_limit = null;
+
+    /** 
+     * what context are we being invoked from 
+     *    
+     * @access protected      
+     * @var string 
+     */      
+    protected $_context = null; 
+    
+    /** 
+     * prefix for the controller
+     * 
+     */
+    protected $_prefix = "grant_";
+
+    protected $_defaults;
+
+
+    /** 
+     * processing needed for buildForm and later 
+     * 
+     * @return void 
+     * @access public 
+     */ 
+    function preProcess( ) 
+    { 
+        /** 
+         * set the button names 
+         */   
+
+        $this->_searchButtonName = $this->getButtonName( 'refresh' ); 
+        $this->_printButtonName  = $this->getButtonName( 'next'   , 'print' ); 
+        $this->_actionButtonName = $this->getButtonName( 'next'   , 'action' ); 
+        
+        $this->_done = false;
+        $this->defaults = array( );
+        
+        /* 
+         * we allow the controller to set force/reset externally, useful when we are being 
+         * driven by the wizard framework 
+         */ 
+        $this->_reset   = CRM_Utils_Request::retrieve( 'reset', 'Boolean', CRM_Core_DAO::$_nullObject ); 
+        $this->_force   = CRM_Utils_Request::retrieve( 'force', 'Boolean',  $this, false ); 
+        $this->_limit   = CRM_Utils_Request::retrieve( 'limit', 'Positive', $this );
+        $this->_context = CRM_Utils_Request::retrieve( 'context', 'String', $this, false, 'search' );
+        
+        $this->assign( "context", $this->_context );
+        
+        // get user submitted values  
+        // get it from controller only if form has been submitted, else preProcess has set this  
+        if ( ! empty( $_POST ) ) { 
+            $this->_formValues = $this->controller->exportValues( $this->_name );  
+        } else {
+            $this->_formValues = $this->get( 'formValues' ); 
+        } 
+
+        if ( empty( $this->_formValues ) ) {
+            if ( isset( $this->_ssID ) ) {
+                $this->_formValues = CRM_Contact_BAO_SavedSearch::getFormValues( $this->_ssID );
+            }
+        }
+        
+        if ( $this->_force ) { 
+            $this->postProcess( );
+            $this->set( 'force', 0 );
+        }
+      
+        $sortID = null; 
+        if ( $this->get( CRM_Utils_Sort::SORT_ID  ) ) { 
+            $sortID = CRM_Utils_Sort::sortIDValue( $this->get( CRM_Utils_Sort::SORT_ID  ), 
+                                                   $this->get( CRM_Utils_Sort::SORT_DIRECTION ) ); 
+        } 
+
+        require_once 'CRM/Contact/BAO/Query.php';
+        $this->_queryParams = CRM_Contact_BAO_Query::convertFormValues( $this->_formValues );
+        $selector = new CRM_Grant_Selector_Search( $this->_queryParams,
+                                                    $this->_action,
+                                                    null,
+                                                    $this->_single,
+                                                    $this->_limit,
+                                                    $this->_context );
+        $prefix = null;
+        if ( $this->_context == 'user' ) {
+            $prefix = $this->_prefix;
+        }
+
+        $this->assign( "{$prefix}limit", $this->_limit );
+        $this->assign( "{$prefix}single", $this->_single );
+  
+        $controller = new CRM_Core_Selector_Controller($selector ,  
+                                                        $this->get( CRM_Utils_Pager::PAGE_ID ),  
+                                                        $sortID,  
+                                                        CRM_Core_Action::VIEW, 
+                                                        $this, 
+                                                        CRM_Core_Selector_Controller::TRANSFER,
+                                                        $prefix);
+        $controller->setEmbedded( true ); 
+        $controller->moveFromSessionToTemplate(); 
+        
+        $this->assign( 'summary', $this->get( 'summary' ) );
+    }
+    
+    /**
+     * Build the form
+     *
+     * @access public
+     * @return void
+ */
+    function buildQuickForm( ) 
+    {
+        $this->addElement('text', 'sort_name', ts('Name or Email'), CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact', 'sort_name') );
+        
+        require_once 'CRM/Grant/BAO/Query.php';
+        CRM_Grant_BAO_Query::buildSearchForm( $this );
+
+        /* 
+         * add form checkboxes for each row. This is needed out here to conform to QF protocol 
+         * of all elements being declared in builQuickForm 
+         */ 
+
+        $rows = $this->get( 'rows' );
+        if ( is_array( $rows ) ) {
+            if ( !$this->_single ) {
+                $this->addElement( 'checkbox', 'toggleSelect', null, null, array( 'onchange' => "toggleTaskAction( true ); return toggleCheckboxVals('mark_x_',this);" ) ); 
+                foreach ($rows as $row) { 
+                    $this->addElement( 'checkbox', CRM_Utils_Array::value( 'checkbox', $row ), 
+                                       null, null, 
+                                       array( 'onclick' => " toggleTaskAction( true ); return checkSelectedBox('" . CRM_Utils_Array::value( 'checkbox', $row ) . "');" )
+                                       ); 
+                    $grant_id = $row['grant_id'];
+                }
+            }
+
+            $total = $cancel = 0;
+
+            require_once "CRM/Core/Permission.php";
+            $permission = CRM_Core_Permission::getPermission( );
+
+            require_once 'CRM/Grant/Task.php';
+            $tasks = array( '' => ts('- actions -') );
+            $permissionedTask = CRM_Grant_Task::permissionedTaskTitles( $permission );
+            if ( is_array( $permissionedTask ) && !CRM_Utils_System::isNull( $permissionedTask ) ) {
+                $tasks += $permissionedTask;
+            }
+            
+            $this->add('select', 'task'   , ts('Actions:') . ' '    , $tasks    ); 
+            $this->add('submit', $this->_actionButtonName, ts('Go'), 
+                       array( 'class' => 'form-submit', 
+                              'onclick' => "return if (checkPerformAction('mark_x', '".$this->getName()."', 0));" ) ); 
+            
+            $this->addFormRule( array( 'CRM_Grant_Form_Search', 'formRule' ), $this );
+            $this->add('submit', $this->_printButtonName, ts('Print'), 
+                       array( 'class' => 'form-submit', 
+                              'onclick' => "return checkPerformAction('mark_x', '".$this->getName()."', 1);" ) ); 
+            
+            // need to perform tasks on all or selected items ? using radio_ts(task selection) for it 
+            $this->addElement('radio', 'radio_ts', null, '', 'ts_sel', array( 'checked' => 'checked') ); 
+            $this->addElement('radio', 'radio_ts', null, '', 'ts_all', array( 'onchange' => $this->getName().".toggleSelect.checked = false; toggleCheckboxVals('mark_x_',this); toggleTaskAction( true );" ) );
+        }
+        
+        // add buttons 
+        $this->addButtons( array( 
+                                 array ( 'type'      => 'refresh', 
+                                         'name'      => ts('Search'), 
+                                         'isDefault' => true     ) 
+                                 )    );
+    }
+
+    
+    /**
+     * The post processing of the form gets done here.
+     *
+     * Key things done during post processing are
+     *      - check for reset or next request. if present, skip post procesing.
+     *      - now check if user requested running a saved search, if so, then
+     *        the form values associated with the saved search are used for searching.
+     *      - if user has done a submit with new values the regular post submissing is 
+     *        done.
+     * The processing consists of using a Selector / Controller framework for getting the
+     * search results.
+     *
+     * @param
+     *
+     * @return void 
+     * @access public
+     */
+    function postProcess( ) 
+    {
+        if ( $this->_done ) {
+            return;
+        }
+   
+        $this->_done = true;
+        
+        $this->_formValues = $this->controller->exportValues($this->_name);
+        $this->fixFormValues( );
+
+        if ( isset( $this->_ssID ) && empty( $_POST ) ) {
+            // if we are editing / running a saved search and the form has not been posted
+            $this->_formValues = CRM_Contact_BAO_SavedSearch::getFormValues( $this->_ssID );
+        }
+           
+        require_once 'CRM/Contact/BAO/Query.php';
+        $this->_queryParams = CRM_Contact_BAO_Query::convertFormValues( $this->_formValues );
+        
+        $this->set( 'formValues' , $this->_formValues  );
+        $this->set( 'queryParams', $this->_queryParams );
+        $buttonName = $this->controller->getButtonName( );
+        if ( $buttonName == $this->_actionButtonName || $buttonName == $this->_printButtonName ) { 
+            // check actionName and if next, then do not repeat a search, since we are going to the next page 
+            
+            // hack, make sure we reset the task values 
+            $stateMachine =& $this->controller->getStateMachine( );
+            
+            $formName     =  $stateMachine->getTaskFormName( ); 
+            $this->controller->resetPage( $formName ); 
+            return; 
+        }
+        
+        $sortID = null; 
+        if ( $this->get( CRM_Utils_Sort::SORT_ID  ) ) { 
+            $sortID = CRM_Utils_Sort::sortIDValue( $this->get( CRM_Utils_Sort::SORT_ID  ), 
+                                                   $this->get( CRM_Utils_Sort::SORT_DIRECTION ) ); 
+        } 
+      
+        require_once 'CRM/Contact/BAO/Query.php';
+
+        $selector = new CRM_Grant_Selector_Search( $this->_queryParams,
+                                                   $this->_action,
+                                                   null,
+                                                   $this->_single,
+                                                   $this->_limit,
+                                                   $this->_context );
+        $selector->setKey( $this->controller->_key );
+        
+        $prefix = null;
+        if ( $this->_context == 'basic' || $this->_context == 'user') {
+            $prefix = $this->_prefix;
+        }
+             
+        
+        $controller = new CRM_Core_Selector_Controller($selector , 
+                                                        $this->get( CRM_Utils_Pager::PAGE_ID ), 
+                                                        $sortID, 
+                                                        CRM_Core_Action::VIEW,
+                                                        $this,
+                                                        CRM_Core_Selector_Controller::SESSION,
+                                                        $prefix);
+        $controller->setEmbedded( true );
+        
+        $query   =& $selector->getQuery( );
+        if ( $this->_context == 'user' ) {
+            $query->setSkipPermission( true );
+        }
+        $controller->run(); 
+        
+    }
+    
+    static function formRule( $fields, $files, $self ) {  
+      $errors = array( );
+      require_once 'CRM/Grant/BAO/Grant.php';
+      if(isset($fields['task']) && $fields['task'] == '5') {
+        foreach( $fields as $fieldKey => $fieldValue ) {
+          if( strstr( $fieldKey, 'mark_x_' ) ) {
+            $grantID = ltrim( $fieldKey, 'mark_x_' );
+            $grantDetails = CRM_Grant_BAO_Grant::getGrants( array( 'id' => $grantID ) );
+            if( ! $grantDetails[$grantID]['amount_granted'] ) {
+              $errors['task'] = ts('Payments are only possible when there is an amount owing.');
+              break;
+            }
+          }
+        }
+      }
+      return $errors;
+    }
+    
+
+    /**
+     * Set the default form values
+     *
+     * @access protected
+     * @return array the default array reference
+     */
+    function &setDefaultValues( ) 
+    {
+        return $this->_formValues;
+    }
+
+    function fixFormValues( )
+    {
+        // if this search has been forced
+        // then see if there are any get values, and if so over-ride the post values
+        // note that this means that GET over-rides POST :)
+        
+        if ( ! $this->_force ) {
+            return;
+        }
+
+        $status = CRM_Utils_Request::retrieve( 'status', 'String',
+                                               CRM_Core_DAO::$_nullObject );
+        if ( $status ) {
+            $this->_formValues['grant_status_id'] = $status;
+            $this->_defaults  ['grant_status_id'] = $status;
+        }
+
+        $cid = CRM_Utils_Request::retrieve( 'cid', 'Positive', $this );
+
+        if ( $cid ) {
+            $cid = CRM_Utils_Type::escape( $cid, 'Integer' );
+            if ( $cid > 0 ) {
+                $this->_formValues['contact_id'] = $cid;
+                
+                // also assign individual mode to the template
+                $this->_single = true;
+            }
+        }
+    }
+
+    function getFormValues( ) {
+        return null;
+    }
+
+    /**
+     * Return a descriptive name for the page, used in wizard header
+     *
+     * @return string
+     * @access public
+     */
+    public function getTitle( ) 
+    {
+        return ts( 'Find Grants' );
+    }
+}
+
diff --git a/CRM/Grant/Form/Search.php~ b/CRM/Grant/Form/Search.php~
new file mode 100755
index 0000000..b0f5111
--- /dev/null
+++ b/CRM/Grant/Form/Search.php~
@@ -0,0 +1,454 @@
+<?php
+
+/*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.1                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing   
+ +--------------------------------------------------------------------+
+*/
+
+/**
+ *
+ * @package CRM
+ * @copyright CiviCRM LLC (c) 2004-2011
+ * $Id$
+ *
+ */
+
+/**
+ * Files required
+ */
+require_once 'CRM/Grant/PseudoConstant.php';
+require_once 'CRM/Grant/Selector/Search.php';
+require_once 'CRM/Core/Selector/Controller.php';
+require_once 'CRM/Contact/BAO/SavedSearch.php';
+
+/**
+ * This file is for civigrant search
+ */
+class CRM_Grant_Form_Search extends CRM_Core_Form
+{
+    /** 
+     * Are we forced to run a search 
+     * 
+     * @var int 
+     * @access protected 
+     */ 
+    protected $_force; 
+
+    /** 
+     * name of search button 
+     * 
+     * @var string 
+     * @access protected 
+     */ 
+    protected $_searchButtonName;
+
+    /** 
+     * name of print button 
+     * 
+     * @var string 
+     * @access protected 
+     */ 
+    protected $_printButtonName; 
+ 
+    /** 
+     * name of action button 
+     * 
+     * @var string 
+     * @access protected 
+     */ 
+    protected $_actionButtonName;
+
+    /** 
+     * form values that we will be using 
+     * 
+     * @var array 
+     * @access protected 
+     */ 
+    protected $_formValues; 
+
+    /**
+     * the params that are sent to the query
+     * 
+     * @var array 
+     * @access protected 
+     */ 
+    protected $_queryParams;
+    
+    /** 
+     * have we already done this search 
+     * 
+     * @access protected 
+     * @var boolean 
+     */ 
+    protected $_done; 
+
+    /**
+     * are we restricting ourselves to a single contact
+     *
+     * @access protected  
+     * @var boolean  
+     */  
+    protected $_single = false;
+
+    /** 
+     * are we restricting ourselves to a single contact 
+     * 
+     * @access protected   
+     * @var boolean   
+     */   
+    protected $_limit = null;
+
+    /** 
+     * what context are we being invoked from 
+     *    
+     * @access protected      
+     * @var string 
+     */      
+    protected $_context = null; 
+    
+    /** 
+     * prefix for the controller
+     * 
+     */
+    protected $_prefix = "grant_";
+
+    protected $_defaults;
+
+
+    /** 
+     * processing needed for buildForm and later 
+     * 
+     * @return void 
+     * @access public 
+     */ 
+    function preProcess( ) 
+    { 
+        /** 
+         * set the button names 
+         */   
+
+        $this->_searchButtonName = $this->getButtonName( 'refresh' ); 
+        $this->_printButtonName  = $this->getButtonName( 'next'   , 'print' ); 
+        $this->_actionButtonName = $this->getButtonName( 'next'   , 'action' ); 
+        
+        $this->_done = false;
+        $this->defaults = array( );
+        
+        /* 
+         * we allow the controller to set force/reset externally, useful when we are being 
+         * driven by the wizard framework 
+         */ 
+        $this->_reset   = CRM_Utils_Request::retrieve( 'reset', 'Boolean', CRM_Core_DAO::$_nullObject ); 
+        $this->_force   = CRM_Utils_Request::retrieve( 'force', 'Boolean',  $this, false ); 
+        $this->_limit   = CRM_Utils_Request::retrieve( 'limit', 'Positive', $this );
+        $this->_context = CRM_Utils_Request::retrieve( 'context', 'String', $this, false, 'search' );
+        
+        $this->assign( "context", $this->_context );
+        
+        // get user submitted values  
+        // get it from controller only if form has been submitted, else preProcess has set this  
+        if ( ! empty( $_POST ) ) { 
+            $this->_formValues = $this->controller->exportValues( $this->_name );  
+        } else {
+            $this->_formValues = $this->get( 'formValues' ); 
+        } 
+
+        if ( empty( $this->_formValues ) ) {
+            if ( isset( $this->_ssID ) ) {
+                $this->_formValues = CRM_Contact_BAO_SavedSearch::getFormValues( $this->_ssID );
+            }
+        }
+        
+        if ( $this->_force ) { 
+            $this->postProcess( );
+            $this->set( 'force', 0 );
+        }
+      
+        $sortID = null; 
+        if ( $this->get( CRM_Utils_Sort::SORT_ID  ) ) { 
+            $sortID = CRM_Utils_Sort::sortIDValue( $this->get( CRM_Utils_Sort::SORT_ID  ), 
+                                                   $this->get( CRM_Utils_Sort::SORT_DIRECTION ) ); 
+        } 
+
+        require_once 'CRM/Contact/BAO/Query.php';
+        $this->_queryParams = CRM_Contact_BAO_Query::convertFormValues( $this->_formValues );
+        $selector = new CRM_Grant_Selector_Search( $this->_queryParams,
+                                                    $this->_action,
+                                                    null,
+                                                    $this->_single,
+                                                    $this->_limit,
+                                                    $this->_context );
+        $prefix = null;
+        if ( $this->_context == 'user' ) {
+            $prefix = $this->_prefix;
+        }
+
+        $this->assign( "{$prefix}limit", $this->_limit );
+        $this->assign( "{$prefix}single", $this->_single );
+  
+        $controller = new CRM_Core_Selector_Controller($selector ,  
+                                                        $this->get( CRM_Utils_Pager::PAGE_ID ),  
+                                                        $sortID,  
+                                                        CRM_Core_Action::VIEW, 
+                                                        $this, 
+                                                        CRM_Core_Selector_Controller::TRANSFER,
+                                                        $prefix);
+        $controller->setEmbedded( true ); 
+        $controller->moveFromSessionToTemplate(); 
+        
+        $this->assign( 'summary', $this->get( 'summary' ) );
+    }
+    
+    /**
+     * Build the form
+     *
+     * @access public
+     * @return void
+ */
+    function buildQuickForm( ) 
+    {
+        $this->addElement('text', 'sort_name', ts('Name or Email'), CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact', 'sort_name') );
+        
+        require_once 'CRM/Grant/BAO/Query.php';
+        CRM_Grant_BAO_Query::buildSearchForm( $this );
+
+        /* 
+         * add form checkboxes for each row. This is needed out here to conform to QF protocol 
+         * of all elements being declared in builQuickForm 
+         */ 
+
+        $rows = $this->get( 'rows' );
+        if ( is_array( $rows ) ) {
+            if ( !$this->_single ) {
+                $this->addElement( 'checkbox', 'toggleSelect', null, null, array( 'onchange' => "toggleTaskAction( true ); return toggleCheckboxVals('mark_x_',this);" ) ); 
+                foreach ($rows as $row) { 
+                    $this->addElement( 'checkbox', CRM_Utils_Array::value( 'checkbox', $row ), 
+                                       null, null, 
+                                       array( 'onclick' => " toggleTaskAction( true ); return checkSelectedBox('" . CRM_Utils_Array::value( 'checkbox', $row ) . "');" )
+                                       ); 
+                    $grant_id = $row['grant_id'];
+                }
+            }
+
+            $total = $cancel = 0;
+
+            require_once "CRM/Core/Permission.php";
+            $permission = CRM_Core_Permission::getPermission( );
+
+            require_once 'CRM/Grant/Task.php';
+            $tasks = array( '' => ts('- actions -') );
+            $permissionedTask = CRM_Grant_Task::permissionedTaskTitles( $permission );
+            if ( is_array( $permissionedTask ) && !CRM_Utils_System::isNull( $permissionedTask ) ) {
+                $tasks += $permissionedTask;
+            }
+            
+            $this->add('select', 'task'   , ts('Actions:') . ' '    , $tasks    ); 
+            $this->add('submit', $this->_actionButtonName, ts('Go'), 
+                       array( 'class' => 'form-submit', 
+                              'onclick' => "return if (checkPerformAction('mark_x', '".$this->getName()."', 0));" ) ); 
+            
+            $this->addFormRule( array( 'CRM_Grant_Form_Search', 'formRule' ), $this );
+            $this->add('submit', $this->_printButtonName, ts('Print'), 
+                       array( 'class' => 'form-submit', 
+                              'onclick' => "return checkPerformAction('mark_x', '".$this->getName()."', 1);" ) ); 
+            
+            // need to perform tasks on all or selected items ? using radio_ts(task selection) for it 
+            $this->addElement('radio', 'radio_ts', null, '', 'ts_sel', array( 'checked' => 'checked') ); 
+            $this->addElement('radio', 'radio_ts', null, '', 'ts_all', array( 'onchange' => $this->getName().".toggleSelect.checked = false; toggleCheckboxVals('mark_x_',this); toggleTaskAction( true );" ) );
+        }
+        
+        // add buttons 
+        $this->addButtons( array( 
+                                 array ( 'type'      => 'refresh', 
+                                         'name'      => ts('Search'), 
+                                         'isDefault' => true     ) 
+                                 )    );
+    }
+
+    
+    /**
+     * The post processing of the form gets done here.
+     *
+     * Key things done during post processing are
+     *      - check for reset or next request. if present, skip post procesing.
+     *      - now check if user requested running a saved search, if so, then
+     *        the form values associated with the saved search are used for searching.
+     *      - if user has done a submit with new values the regular post submissing is 
+     *        done.
+     * The processing consists of using a Selector / Controller framework for getting the
+     * search results.
+     *
+     * @param
+     *
+     * @return void 
+     * @access public
+     */
+    function postProcess( ) 
+    {
+        if ( $this->_done ) {
+            return;
+        }
+   
+        $this->_done = true;
+        
+        $this->_formValues = $this->controller->exportValues($this->_name);
+        $this->fixFormValues( );
+
+        if ( isset( $this->_ssID ) && empty( $_POST ) ) {
+            // if we are editing / running a saved search and the form has not been posted
+            $this->_formValues = CRM_Contact_BAO_SavedSearch::getFormValues( $this->_ssID );
+        }
+           
+        require_once 'CRM/Contact/BAO/Query.php';
+        $this->_queryParams = CRM_Contact_BAO_Query::convertFormValues( $this->_formValues );
+        
+        $this->set( 'formValues' , $this->_formValues  );
+        $this->set( 'queryParams', $this->_queryParams );
+        $buttonName = $this->controller->getButtonName( );
+        if ( $buttonName == $this->_actionButtonName || $buttonName == $this->_printButtonName ) { 
+            // check actionName and if next, then do not repeat a search, since we are going to the next page 
+            
+            // hack, make sure we reset the task values 
+            $stateMachine =& $this->controller->getStateMachine( );
+            
+            $formName     =  $stateMachine->getTaskFormName( ); 
+            $this->controller->resetPage( $formName ); 
+            return; 
+        }
+        
+        $sortID = null; 
+        if ( $this->get( CRM_Utils_Sort::SORT_ID  ) ) { 
+            $sortID = CRM_Utils_Sort::sortIDValue( $this->get( CRM_Utils_Sort::SORT_ID  ), 
+                                                   $this->get( CRM_Utils_Sort::SORT_DIRECTION ) ); 
+        } 
+      
+        require_once 'CRM/Contact/BAO/Query.php';
+
+        $selector = new CRM_Grant_Selector_Search( $this->_queryParams,
+                                                   $this->_action,
+                                                   null,
+                                                   $this->_single,
+                                                   $this->_limit,
+                                                   $this->_context );
+        $selector->setKey( $this->controller->_key );
+        
+        $prefix = null;
+        if ( $this->_context == 'basic' || $this->_context == 'user') {
+            $prefix = $this->_prefix;
+        }
+             
+        
+        $controller = new CRM_Core_Selector_Controller($selector , 
+                                                        $this->get( CRM_Utils_Pager::PAGE_ID ), 
+                                                        $sortID, 
+                                                        CRM_Core_Action::VIEW,
+                                                        $this,
+                                                        CRM_Core_Selector_Controller::SESSION,
+                                                        $prefix);
+        $controller->setEmbedded( true );
+        
+        $query   =& $selector->getQuery( );
+        if ( $this->_context == 'user' ) {
+            $query->setSkipPermission( true );
+        }
+        $controller->run(); 
+        
+    }
+    
+    static function formRule( $fields, $files, $self ) {  
+      $errors = array( );
+      require_once 'CRM/Grant/BAO/Grant.php';
+      if(isset($fields['task']) && $fields['task'] == '5') {
+        foreach( $fields as $fieldKey => $fieldValue ) {
+          if( strstr( $fieldKey, 'mark_x_' ) ) {
+            $grantID = ltrim( $fieldKey, 'mark_x_' );
+            $grantDetails = CRM_Grant_BAO_Grant::getGrants( array( 'id' => $grantID ) );
+            if( ! $grantDetails[$grantID]['amount_granted'] ) {
+              $errors['task'] = ts('Payments are only possible when there is an amount owing.');
+              break;
+            }
+          }
+        }
+      }
+      return $errors;
+    }
+    
+
+    /**
+     * Set the default form values
+     *
+     * @access protected
+     * @return array the default array reference
+     */
+    function &setDefaultValues( ) 
+    {
+        return $this->_formValues;
+    }
+
+    function fixFormValues( )
+    {
+        // if this search has been forced
+        // then see if there are any get values, and if so over-ride the post values
+        // note that this means that GET over-rides POST :)
+        
+        if ( ! $this->_force ) {
+            return;
+        }
+
+        $status = CRM_Utils_Request::retrieve( 'status', 'String',
+                                               CRM_Core_DAO::$_nullObject );
+        if ( $status ) {
+            $this->_formValues['grant_status_id'] = $status;
+            $this->_defaults  ['grant_status_id'] = $status;
+        }
+
+        $cid = CRM_Utils_Request::retrieve( 'cid', 'Positive', $this );
+
+        if ( $cid ) {
+            $cid = CRM_Utils_Type::escape( $cid, 'Integer' );
+            if ( $cid > 0 ) {
+                $this->_formValues['contact_id'] = $cid;
+                
+                // also assign individual mode to the template
+                $this->_single = true;
+            }
+        }
+    }
+
+    function getFormValues( ) {
+        return null;
+    }
+
+    /**
+     * Return a descriptive name for the page, used in wizard header
+     *
+     * @return string
+     * @access public
+     */
+    public function getTitle( ) 
+    {
+        return ts( 'Find Grants' );
+    }
+}
+
diff --git a/CRM/Grant/Form/Task/Cancel.php b/CRM/Grant/Form/Task/Cancel.php
new file mode 100755
index 0000000..3a6c74d
--- /dev/null
+++ b/CRM/Grant/Form/Task/Cancel.php
@@ -0,0 +1,119 @@
+<?php
+
+/*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.1                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*/
+
+/**
+ *
+ * @package CRM
+ * @copyright CiviCRM LLC (c) 2004-2011
+ * $Id$
+ *
+ */
+
+require_once 'CRM/Grant/Form/PaymentTask.php';
+require_once 'CRM/Core/OptionGroup.php';
+
+/**
+ * This class provides the functionality to delete a group of
+ * participations. This class provides functionality for the actual
+ * deletion.
+ */
+class CRM_Grant_Form_Task_Cancel extends CRM_Grant_Form_PaymentTask 
+{
+    /**
+     * Are we operating in "single mode", i.e. deleting one
+     * specific participation?
+     *
+     * @var boolean
+     */
+    protected $_single = false;
+
+    /**
+     * build all the data structures needed to build the form
+     *
+     * @return void
+     * @access public
+     */
+    function preProcess( ) 
+    {
+        parent::preProcess( );
+
+        //check permission for delete.
+        if ( !CRM_Core_Permission::checkActionPermission( 'CiviGrant', CRM_Core_Action::DELETE ) ) {
+            CRM_Core_Error::fatal( ts( 'You do not have permission to access this page' ) );  
+        }
+    }
+
+    /**
+     * Build the form
+     *
+     * @access public
+     * @return void
+     */
+    function buildQuickForm( ) 
+    {
+        $this->addDefaultButtons( ts( 'Cancel Grants' ), 'done' );
+    }
+
+    /**
+     * process the form after the input has been submitted and validated
+     *
+     * @access public
+     * @return None
+     */
+    public function postProcess( ) 
+    {
+      $deletedGrantPayments = 0;
+      require_once 'CRM/Grant/DAO/EntityPayment.php';
+      require_once 'CRM/Grant/BAO/GrantPayment.php';
+      require_once 'CRM/Grant/BAO/EntityPayment.php';
+      foreach ( $this->_grantPaymentIds as $paymentId ) {
+        $entityDAO =& new CRM_Grant_DAO_EntityPayment();
+        $entityDAO->payment_id = $paymentId;
+        $entityDAO->find();
+        
+        while( $entityDAO->fetch() ) {
+          CRM_Grant_BAO_EntityPayment::del( $entityDAO->id );
+          $grantDAO =& new CRM_Grant_DAO_Grant();
+          $grantDAO->id        = $entityDAO->entity_id;
+          $grantDAO->status_id = CRM_Core_OptionGroup::getValue( 'grant_status', 'Approved', 'name' );
+          $grantDAO->save();
+        }
+        if ( CRM_Grant_BAO_GrantPayment::del( $paymentId ) ) {
+          $deletedGrantPayments++;
+        }
+      }
+
+      $status = array(
+                      ts( 'Cancel Grant Payments(s): %1',        array( 1 => $deletedGrantPayments ) ),
+                      ts( 'Total Selected Grant Payments(s): %1', array( 1 => count($this->_grantPaymentIds ) ) ),
+                      );
+      CRM_Core_Session::setStatus( $status );
+    }
+}
+
+
diff --git a/CRM/Grant/Form/Task/GrantPayment.php b/CRM/Grant/Form/Task/GrantPayment.php
new file mode 100755
index 0000000..5d0b43d
--- /dev/null
+++ b/CRM/Grant/Form/Task/GrantPayment.php
@@ -0,0 +1,383 @@
+<?php
+
+/*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.0                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*/
+
+/**
+ *
+ * @package CRM
+ * @copyright CiviCRM LLC (c) 2004-2011
+ * $Id$
+ *
+ */
+
+require_once 'CRM/Core/Form.php';
+require_once 'CRM/Utils/Rule.php';
+require_once 'CRM/Grant/BAO/GrantProgram.php';
+require_once 'CRM/Grant/BAO/Grant.php';
+require_once 'CRM/Grant/DAO/Grant.php';
+require_once "CRM/Core/DAO/EntityFile.php";
+require_once 'CRM/Core/BAO/File.php';
+require_once 'CRM/Grant/BAO/GrantPayment.php';
+require_once 'CRM/Activity/BAO/Activity.php';
+require_once 'CRM/Grant/Form/Task.php';
+require_once 'CRM/Core/OptionGroup.php';
+require_once 'CRM/Utils/Money.php';
+/**
+ * This class generates form components for Payments
+ * 
+ */    
+class CRM_Grant_Form_Task_GrantPayment extends CRM_Grant_Form_Task
+{
+    
+  protected $_id     = null;
+  protected $_fields = null;
+  function preProcess( ) {
+    parent::preProcess( ); 
+    $this->_action     = CRM_Utils_Request::retrieve('action', 'String', $this );
+    $this->_prid = CRM_Utils_Request::retrieve('prid', 'Positive', $this );
+    if ( $this->_prid ) {
+      $session = CRM_Core_Session::singleton();
+      $url = CRM_Utils_System::url('civicrm/grant/payment/search', '_qf_PaymentSearch_display=true&qfKey='.CRM_Utils_Request::retrieve('prid', 'Positive', $this ));
+      $session->pushUserContext( $url );
+    }
+  }
+    
+  function setDefaultValues( ) 
+  {
+    $defaults = array();
+    $paymentNumbers = CRM_Grant_BAO_GrantPayment::getMaxPayementBatchNumber( );
+    $defaults['payment_date'] = strftime("%m/%d/%Y", strtotime( date('Y/m/d') ));
+    $defaults['payment_number'] = $paymentNumbers['payment_number'] + 1;
+    $defaults['payment_batch_number'] = $paymentNumbers['payment_batch_number'] + 1;
+
+    return $defaults;
+  }
+  /**
+   * Function to build the form
+   *
+   * @return None
+   * @access public
+   */
+  public function buildQuickForm( $check = false ) 
+  {
+    parent::buildQuickForm( );
+    if ( $this->_action & CRM_Core_Action::DELETE ) {
+            
+      $this->addButtons( array(
+                               array ( 'type'      => 'next',
+                                       'name'      => ts('Delete'),
+                                       'isDefault' => true   ),
+                                     
+                               array ( 'type'      => 'cancel',
+                                       'name'      => ts('Cancel') ),
+                               )
+                         );
+      return;
+    }
+
+    $this->applyFilter('__ALL__','trim');
+    $attributes = CRM_Core_DAO::getAttribute( 'CRM_Grant_DAO_GrantProgram' );
+        
+    $this->_contributionTypes = CRM_Grant_BAO_GrantProgram::contributionTypes();
+    $this->add('select', 'contribution_type_id',  ts( 'From account' ),
+               array( '' => ts( '- select -' ) ) + $this->_contributionTypes , true);
+
+    $this->add( 'text', 'payment_batch_number', ts( 'Payment Batch number' ),
+                $attributes['label'], true );
+
+    $this->add( 'text', 'payment_number', ts( 'Starting cheque number' ),
+                $attributes['label'], true );
+        
+    $this->addDate( 'payment_date', ts('Payment date to appear on cheques'), false, array( 'formatType' => 'custom') );
+    $buttonName = "Print Checks";
+    if ( $this->_prid ) {
+      $buttonName = "Reprint Checks";
+    }
+    $this->addButtons(array( 
+                            array ( 'type'      => 'upload',
+                                    'name'      => ts($buttonName), 
+                                    'isDefault' => true   ),
+                            array ( 'type'      => 'next',
+                                    'name'      => ts('Export to CSV'),), 
+                            array ( 'type'      => 'cancel', 
+                                    'name'      => ts('Cancel') ), 
+                             ) 
+                      );
+    $this->addFormRule( array( 'CRM_Grant_Form_Task_GrantPayment', 'formRule' ), $this );
+        
+  }
+
+  public function formRule( $params, $files, $self ) 
+  {
+    $errors = array( ); 
+    $date  = date('m/d/Y', mktime(0, 0, 0, date("m")-6  , date("d")+1, date("Y")) );
+    if( strtotime($params['payment_date']  < strtotime($date) ) )
+      $errors['payment_date'] = ts( 'Payments may not be back-dated more than 6 months.' );
+         
+    if ( ! CRM_Utils_Rule::integer($params['payment_number'] ) )
+      $errors['payment_number'] = ts( "'{$params['payment_number']}' is not integer value." );
+
+    if ( ! CRM_Utils_Rule::integer($params['payment_batch_number'] ) )
+      $errors['payment_batch_number'] = ts( "'{$params['payment_batch_number']}' is not integer value." );
+
+    if ( $params['payment_number'] < 1 )
+      $errors['payment_number'] = ts( "Please enter valid payment number." );
+
+    if ( $params['payment_batch_number'] < 1 )
+      $errors['payment_batch_number'] = ts( "Please enter valid payment batch number." );
+
+    if ( CRM_Utils_Rule::integer( $params['payment_number'] ) )
+      if ( CRM_Grant_BAO_GrantPayment::getPaymentNumber( $params['payment_number'] ) ) 
+        $errors['payment_number'] = ts( "Payment number already exists." );
+
+    if ( CRM_Utils_Rule::integer( $params['payment_batch_number'] ) )
+      if (  CRM_Grant_BAO_GrantPayment::getPaymentBatchNumber( $params['payment_batch_number'] ) ) 
+        $errors['payment_batch_number'] = ts( "Payment batch number already exists." );
+
+    return empty($errors) ? true : $errors;
+  }
+  /**
+   * Function to process the form
+   *
+   * @access public
+   * @return None
+   */
+  public function postProcess() 
+  {
+    $details = $allGrants =array();
+    CRM_Utils_System::flushCache( 'CRM_Grant_DAO_GrantPayment' );
+    $values  = $this->controller->exportValues( $this->_name );
+    $makePdf = true;
+    foreach ( $_POST as $buttonKey => $buttonValue ) {
+      if ( $buttonKey == '_qf_GrantPayment_next' ) {
+        $makePdf = false;
+      }
+    }
+    $batchNumaber = $values['payment_batch_number'];
+    $this->_approvedGrants = $this->get( 'approvedGrants' );
+        
+    if ( $this->_prid ) {
+      $query = "SELECT cp.id as pid, cg.amount_granted as total_amount, cp.currency, cp.payment_reason, cp.contact_id as id, cep.entity_id as grant_id FROM civicrm_payment as cp LEFT JOIN civicrm_entity_payment as cep ON cep.payment_id = cp.id LEFT JOIN civicrm_grant as cg ON cg.id = cep.entity_id WHERE cp.id IN (".$this->_prid.")";
+    } else {
+      $query = "SELECT id as grant_id, amount_granted as total_amount, currency, grant_program_id, grant_type_id, contact_id as id FROM civicrm_grant WHERE id IN (".implode(', ', array_keys($this->_approvedGrants) ).")";
+
+    }
+    $dao = CRM_Grant_DAO_Grant::executeQuery($query);
+        
+    
+    while( $dao->fetch() ) {  
+      if ( !empty( $payment_details[$dao->id] ) ) {
+        $payment_details[$dao->id] .= '</td></tr><tr><td width="15%" >'.date("Y-m-d", strtotime($values['payment_date'])).'</td><td width="15%" >'.$dao->grant_id.'</td><td width="50%" >'.CRM_Grant_BAO_GrantProgram::getDisplayName( $dao->id ).'</td><td width="20%" >CAD :'.CRM_Utils_Money::format( $dao->total_amount,null, null,false );
+
+
+      } else {
+        $payment_details[$dao->id] = date("Y-m-d", strtotime($values['payment_date'])).'</td><td width="15%" >'.$dao->grant_id.'</td><td width="50%" >'.CRM_Grant_BAO_GrantProgram::getDisplayName( $dao->id ).'</td><td width="20%" >CAD :'.CRM_Utils_Money::format( $dao->total_amount,null, null,false );
+      }
+
+      if ( !empty( $details[$dao->id]['total_amount'] ) ) {
+        $details[$dao->id]['total_amount']  = $details[$dao->id]['total_amount'] + $dao->total_amount;
+      } else {
+        $details[$dao->id]['total_amount']  = $dao->total_amount;
+      }
+      $details[$dao->id]['currency']        = $dao->currency;
+      
+      $contactGrants[$dao->grant_id] = $dao->id;
+
+      if ( !$this->_prid ) {
+        $grantProgramSql = "SELECT is_auto_email FROM civicrm_grant_program WHERE id  = ".$dao->grant_program_id;
+        $grantProgramDao = CRM_Grant_DAO_GrantProgram::executeQuery( $grantProgramSql );
+        while( $grantProgramDao->fetch() ) {
+          $mailParams[$dao->grant_id]['is_auto_email']  = $grantProgramDao->is_auto_email;
+        }
+        $mailParams[$dao->grant_id]['amount_total']     = $dao->total_amount;
+        $mailParams[$dao->grant_id]['grant_type_id']    = $dao->grant_type_id;
+        $mailParams[$dao->grant_id]['grant_program_id'] = $dao->grant_program_id;
+        $grantContctId[$dao->grant_id] = $dao->id;
+        $gProgram = CRM_Grant_BAO_Grant::getGrantPrograms( $dao->grant_program_id );
+        if( !empty( $gProgram ) ) {
+          $details[$dao->id]['grant_program_id'][$gProgram[$dao->grant_program_id]] = $gProgram[$dao->grant_program_id];
+        }
+      } else {
+        $details[$dao->id]['payment_reason'][$dao->payment_reason]   = $dao->payment_reason;
+      }
+    }
+    $totalAmount = 0;
+    foreach ( $details as $id => $value ) {
+      
+      $grantPayment[$id]['contact_id'] = $id;
+      $grantPayment[$id]['contribution_type_id'] = $values['contribution_type_id'];
+      $grantPayment[$id]['payment_batch_number'] = $values['payment_batch_number'];
+      $grantPayment[$id]['payment_number'      ] = $values['payment_number'];
+      $grantPayment[$id]['payment_date'        ] = date("Y-m-d", strtotime($values['payment_date']));
+      $grantPayment[$id]['payment_created_date'] = date('Y-m-d');
+      $grantPayment[$id]['payable_to_name'     ] = CRM_Grant_BAO_GrantProgram::getDisplayName( $id );
+      $grantPayment[$id]['payable_to_address'  ] = CRM_Utils_Array::value( 'address', CRM_Grant_BAO_GrantProgram::getAddress( $id ) );
+      $grantPayment[$id]['amount'              ] = $details[$id]['total_amount'];
+      $grantPayment[$id]['currency'            ] = $details[$id]['currency'];
+      $grantPayment[$id]['payment_status_id'   ] = 1;
+      if ( $this->_prid ) {
+        $grantPayment[$id]['payment_reason'     ]  = implode(', ',  $details[$id]['payment_reason']);
+        $grantPayment[$id]['replaces_payment_id']  = $this->_prid;
+        $grantPayment[$id]['payment_status_id'   ] = CRM_Core_OptionGroup::getValue( 'grant_payment_status', 'Reprinted', 'name' );
+      } else {
+        $grantPayment[$id]['payment_reason'     ] = implode(', ',  $details[$id]['grant_program_id']);
+        $grantPayment[$id]['replaces_payment_id'] = 'NULL';
+      }
+      if ( $makePdf ) {
+        $grantPayment[$id]['payment_details'] = $payment_details[$id];
+      }
+      $values['payment_number']++;
+      $totalAmount += $details[$id]['total_amount'];
+    } 
+    
+    foreach ( $grantPayment as $grantKey => $values ) {
+      $row = array();
+      $grantValues = $values;
+      if ( $this->_prid ) {
+        require_once 'CRM/Grant/DAO/GrantPayment.php';
+        $dao = new CRM_Grant_DAO_GrantPayment( );
+        $dao->id                    = $this->_prid;
+        $dao->payment_status_id     = CRM_Core_OptionGroup::getValue( 'grant_payment_status', 'Stopped', 'name' );
+        $dao->save();
+      } 
+      require_once 'CRM/Grant/Words.php';
+      $words = new CRM_Grant_Words();
+      $amountInWords = ucwords($words->convert_number_to_words( $values['amount'] ) );
+      $values['total_in_words'] = $grantValues['total_in_words'] = $amountInWords;
+      $result = CRM_Grant_BAO_GrantPayment::add( &$values, $ids = array() );
+      $grantPayment[$grantKey]['amount'] = CRM_Utils_Money::format( $values['amount'], null, null,false );
+      $contactPayments[$grantKey] = $result->id;
+      unset($grantPayment[$grantKey]['payment_status_id']);
+      if ( $makePdf ) {
+        $grantPayment[$grantKey]['payment_id'] = $grantValues['payment_id'] = $result->payment_number;
+      }
+    }
+        
+    $downloadName  = check_plain('grantPayment');
+    $downloadName .= '_'.date('Ymdhis');
+    if ( !$makePdf )  {
+      $downloadName .= '.csv';
+      $fileName = CRM_Utils_File::makeFileName( $downloadName );
+      $config = CRM_Core_Config::singleton();
+      $file_name = $config->customFileUploadDir . $fileName;
+      CRM_Grant_BAO_GrantPayment::createCSV($file_name, $grantPayment);
+    } else {
+      $downloadName .= '.pdf';
+      $fileName = CRM_Utils_File::makeFileName( $downloadName );
+      $fileName = CRM_Grant_BAO_GrantPayment::makePDF($fileName, $grantPayment );
+    }
+    $this->assign( 'date', date('Y-m-d'));
+    $this->assign( 'time', date('H:i:s'));
+    $this->assign( 'account_name',CRM_Core_DAO::getFieldValue( 'CRM_Contribute_DAO_ContributionType', $values['contribution_type_id'], 'name' ) );
+    $this->assign( 'batch_number', $values['payment_batch_number']);
+    $this->assign( 'contact',CRM_Core_DAO::getFieldValue( 'CRM_Contact_DAO_Contact', $_SESSION[ 'CiviCRM' ][ 'userID' ], 'display_name' ) );
+    $this->assign( 'grantPayment', $grantPayment );
+    $this->assign( 'total_payments', count($grantPayment) );
+    $this->assign( 'total_amount' , CRM_Utils_Money::format( $totalAmount, null, null,false ) );
+    $this->assign( 'domain_name', CRM_Core_DAO::getFieldValue( 'CRM_Core_DAO_Domain', CRM_Core_Config::domainID( ) , 'name' ) );
+    
+    $checkRegisterFile = check_plain('CheckRegister');
+    $checkRegisterFile .= '.pdf';
+    $checkFile = CRM_Utils_File::makeFileName( $checkRegisterFile );
+    $checkRegister = CRM_Grant_BAO_GrantPayment::makeReport( $checkFile, $grantPayment );
+    
+    $fileDAO =& new CRM_Core_DAO_File();
+    $fileDAO->uri           = $fileName;
+    if ( $makePdf ) {
+      $fileDAO->mime_type = 'application/pdf';
+    } else {
+      $fileDAO->mime_type = 'text/x-csv';
+    }
+    $fileDAO->upload_date   = date('Ymdhis'); 
+    $fileDAO->save();
+    $grantPaymentFile = $fileDAO->id;
+    
+    $entityFileDAO =& new CRM_Core_DAO_EntityFile();
+    $entityFileDAO->entity_table = 'civicrm_contact';
+    $entityFileDAO->entity_id    = $_SESSION[ 'CiviCRM' ][ 'userID' ];
+    $entityFileDAO->file_id      = $grantPaymentFile;
+    $entityFileDAO->save();
+    
+    $fileDAO->uri           = $checkFile;
+    $fileDAO->upload_date   = date('Ymdhis'); 
+    $fileDAO->save();
+    $grantPaymentCheckFile = $fileDAO->id;
+    
+    $entityFileDAO =& new CRM_Core_DAO_EntityFile();
+    $entityFileDAO->entity_table = 'civicrm_contact';
+    $entityFileDAO->entity_id    = $_SESSION[ 'CiviCRM' ][ 'userID' ];
+    $entityFileDAO->file_id      = $grantPaymentCheckFile;
+    $entityFileDAO->save(); 
+
+    $params = array( 
+                    'source_contact_id'    => $_SESSION[ 'CiviCRM' ][ 'userID' ],
+                    'activity_type_id'     => key(CRM_Core_OptionGroup::values( 'activity_type', false, false, false, 'AND v.label = "Grant Payment"' , 'value' )),
+                    'assignee_contact_id'  => $_SESSION[ 'CiviCRM' ][ 'userID' ],
+                    'subject'              => "Grant Payment",
+                    'activity_date_time'   => date('Ymdhis'),
+                    'status_id'            => CRM_Core_OptionGroup::getValue( 'activity_status', 'Completed', 'name' ),
+                    'priority_id'          => 2,
+                    'details'              => "<a href=".CRM_Utils_System::url( 'civicrm/file', 'reset=1&id='.$grantPaymentFile.'&eid='.$_SESSION[ 'CiviCRM' ][ 'userID' ].'').">".$downloadName."</a></br><a href=".CRM_Utils_System::url( 'civicrm/file', 'reset=1&id='.$grantPaymentCheckFile.'&eid='.$_SESSION[ 'CiviCRM' ][ 'userID' ].'').">".$checkRegisterFile."</a>",
+                     );
+    CRM_Activity_BAO_Activity::create( $params );
+    
+    require_once 'CRM/Grant/DAO/EntityPayment.php';
+    if ( $this->_prid ) {
+      foreach( $contactGrants as $grantId => $contact ) {
+        $entityDAO =& new CRM_Grant_DAO_EntityPayment();
+        $entityDAO->entity_table = 'civicrm_grant';
+        $entityDAO->entity_id    = $grantId;
+        $entityDAO->payment_id   = $contactPayments[$contact];
+        $entityDAO->save();
+      }
+      CRM_Core_Session::setStatus( "Selected payment stopped and reprinted successfully.");
+    } else { 
+      foreach ( $this->_approvedGrants as $grantId => $status ) {
+        $grantDAO =& new CRM_Grant_DAO_Grant();
+        $grantDAO->id        = $grantId;
+        $grantDAO->status_id = CRM_Core_OptionGroup::getValue( 'grant_status', 'Paid', 'name' );
+        $grantDAO->save();
+        $entityDAO =& new CRM_Grant_DAO_EntityPayment();
+        $entityDAO->entity_table = 'civicrm_grant';
+        $entityDAO->entity_id    = $grantId;
+        $entityDAO->payment_id   = $contactPayments[$contactGrants[$grantId]];
+        $entityDAO->save();
+        $grantStatus = CRM_Core_OptionGroup::values( 'grant_status' );
+        $grantType   = CRM_Core_OptionGroup::values( 'grant_type' );
+        $grantPrograms = CRM_Grant_BAO_Grant::getGrantPrograms();
+        $this->assign( 'grant_type', $grantType[$mailParams[$grantId]['grant_type_id']] );
+        $this->assign( 'grant_programs', $grantPrograms[$mailParams[$grantId]['grant_program_id']] );
+        $this->assign( 'grant_status', 'Paid' );
+        $this->assign( 'params', $mailParams[$grantId] );
+        CRM_Grant_BAO_Grant::sendMail( $grantContctId[$grantId], $mailParams[$grantId], 'Paid' );
+      }
+      CRM_Core_Session::setStatus( "Created ".count($details)." payments to pay for ".count($this->_approvedGrants)." grants to ".count($details)." applicants." );
+    }
+    CRM_Utils_System::redirect(CRM_Utils_System::url( 'civicrm/grant/payment/search', 'reset=1&bid='.$batchNumaber.'&download='.$fileName.'&force=1'));
+        
+  }
+}
\ No newline at end of file
diff --git a/CRM/Grant/Form/Task/Pay.php b/CRM/Grant/Form/Task/Pay.php
new file mode 100755
index 0000000..3c32002
--- /dev/null
+++ b/CRM/Grant/Form/Task/Pay.php
@@ -0,0 +1,149 @@
+<?php
+
+/*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.1                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*/
+
+/**
+ *
+ * @package CRM
+ * @copyright CiviCRM LLC (c) 2004-2011
+ * $Id$
+ *
+ */
+
+require_once 'CRM/Grant/Form/Task.php';
+
+/**
+ * This class provides the functionality to delete a group of
+ * participations. This class provides functionality for the actual
+ * deletion.
+ */
+class CRM_Grant_Form_Task_Pay extends CRM_Grant_Form_Task 
+{
+    /**
+     * Are we operating in "single mode", i.e. deleting one
+     * specific participation?
+     *
+     * @var boolean
+     */
+    protected $_single = false;
+
+    /**
+     * build all the data structures needed to build the form
+     *
+     * @return void
+     * @access public
+     */
+    function preProcess( ) 
+    {
+        parent::preProcess( );
+
+        //check permission for delete.
+        if ( !CRM_Core_Permission::checkActionPermission( 'CiviGrant', CRM_Core_Action::PAY ) ) {
+            CRM_Core_Error::fatal( ts( 'You do not have permission to access this page' ) );  
+        }
+        require_once "CRM/Core/PseudoConstant.php";
+        require_once 'CRM/Core/OptionGroup.php';
+        $grantStatus = CRM_Core_OptionGroup::values( 'grant_status' );
+        $grantStatus =  array_flip($grantStatus);
+        
+        $paidGrants = $approvedGrants = array();
+        CRM_Core_PseudoConstant::populate( &$paidGrants, 'CRM_Grant_DAO_Grant', true, 'status_id', false, " id in (".implode ( ', ' , $this->_grantIds ).") AND status_id = {$grantStatus['Paid']}" );
+        CRM_Core_PseudoConstant::populate( &$approvedGrants, 'CRM_Grant_DAO_Grant', true, 'status_id', false, " id in (".implode ( ', ' , $this->_grantIds ).") AND status_id = {$grantStatus['Approved']}" );
+        
+        $this->_paidGrants = $paidGrants;
+        $this->_notApproved = count($this->_grantIds) - count( $this->_paidGrants ) - count( $approvedGrants );
+
+        foreach ( $approvedGrants as $key => $value ) {
+            $grantProgram = new CRM_Grant_DAO_Grant( );
+            $grantArray =  array( 'id' => $key );
+            $grantProgram->copyValues( $grantArray );
+            $grantProgram->find( true );
+            $currencyDetails[$grantProgram->contact_id][$grantProgram->currency] = $key;
+        }
+        //$this->_currency = $currencyDetails;
+        $curency = 0;
+        if ( !empty( $currencyDetails ) ) {
+            foreach ( $currencyDetails as $key => $value ) {
+                if ( count($value) > 1 ) {
+                    foreach ( $value as $unsetKey => $unsetVal ) {
+                        unset( $approvedGrants[$unsetVal] );
+                        $curency++;
+                    }
+                }
+            }
+            $this->_curency = $curency;
+        }
+        $this->_approvedGrants = $approvedGrants;
+    }
+
+    /**
+     * Build the form
+     *
+     * @access public
+     * @return void
+     */
+    function buildQuickForm( ) 
+    {
+        if ( count($this->_approvedGrants) ) {
+            $this->assign( 'paid', count( $this->_paidGrants ) );
+            $this->assign( 'approved', count( $this->_approvedGrants ) );
+            $this->assign( 'total', count( $this->_grantIds ) );
+            $this->assign( 'notApproved', $this->_notApproved );
+            $this->assign( 'multipleCurrency', $this->_curency );
+            
+            $this->addButtons( array(
+                                 array ( 'type'      => 'next',
+                                         'name'      => ts('Continue >>'),
+                                         'spacing'   => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
+                                         'isDefault' => true   ),
+                                 array ( 'type'      => 'cancel',
+                                         'name'      => ts('Cancel') ),
+                                 )
+                           );
+        } else {
+             $this->addButtons(array( 
+                                    array ( 'type'      => 'cancel', 
+                                            'name'      => ts('Cancel') ), 
+                                    ) 
+                              );
+        }
+    }
+
+    /**
+     * process the form after the input has been submitted and validated
+     *
+     * @access public
+     * @return None
+     */
+    public function postProcess( ) 
+    {
+        $this->set( 'approvedGrants', $this->_approvedGrants );
+        $this->controller->resetPage( 'GrantPayment' );
+    }
+}
+
+
diff --git a/CRM/Grant/Form/Task/Reprint.php b/CRM/Grant/Form/Task/Reprint.php
new file mode 100755
index 0000000..9bd002b
--- /dev/null
+++ b/CRM/Grant/Form/Task/Reprint.php
@@ -0,0 +1,319 @@
+<?php
+
+/*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.1                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*/
+
+/**
+ *
+ * @package CRM
+ * @copyright CiviCRM LLC (c) 2004-2011
+ * $Id$
+ *
+ */
+
+require_once 'CRM/Grant/Form/PaymentTask.php';
+require_once 'CRM/Grant/BAO/GrantProgram.php';
+require_once 'CRM/Grant/BAO/EntityPayment.php';
+require_once 'CRM/Grant/BAO/GrantPayment.php';
+require_once 'CRM/Grant/BAO/Grant.php';
+require_once 'CRM/Utils/Money.php';
+require_once 'CRM/Core/DAO/EntityFile.php';
+require_once 'CRM/Core/BAO/File.php';
+
+/**
+ * This class provides the functionality to delete a group of
+ * participations. This class provides functionality for the actual
+ * deletion.
+ */
+class CRM_Grant_Form_Task_Reprint extends CRM_Grant_Form_PaymentTask
+{
+  /**
+   * Are we operating in "single mode", i.e. deleting one
+   * specific participation?
+   *
+   * @var boolean
+   */
+  protected $_single = false;
+
+  /**
+   * build all the data structures needed to build the form
+   *
+   * @return void
+   * @access public
+   */
+  function preProcess( ) 
+  {
+    parent::preProcess( );
+        
+    if ( !CRM_Core_Permission::checkActionPermission( 'CiviGrant', CRM_Core_Action::PAY ) ) {
+      CRM_Core_Error::fatal( ts( 'You do not have permission to access this page' ) );
+    }
+    
+  }
+  function setDefaultValues( ) 
+  {
+    $defaults = array();
+    $paymentNumbers = CRM_Grant_BAO_GrantPayment::getMaxPayementBatchNumber( );
+    $defaults['payment_date'] = strftime("%m/%d/%Y", strtotime( date('Y/m/d') ));
+    $defaults['payment_number'] = $paymentNumbers['payment_number'] + 1;
+    $defaults['payment_batch_number'] = $paymentNumbers['payment_batch_number'] + 1;
+
+    return $defaults;
+  }
+  /**
+   * Build the form
+   *
+   * @access public
+   * @return void
+   */
+  function buildQuickForm( ) 
+  { 
+    require_once 'CRM/Core/OptionGroup.php';
+    $validStatus = array( 'Printed', 'Reprinted');
+    $paymentStatus = CRM_Core_OptionGroup::values( 'grant_payment_status' );
+    foreach( $paymentStatus as $statusKey => $status ) {
+      if(in_array( $status , $validStatus) ) {
+        unset( $paymentStatus[$statusKey] );
+      }
+    }
+    $selectedPayments = count($this->_grantPaymentIds);
+    $this->assign( 'total', $selectedPayments );
+    foreach ( $this->_grantPaymentIds as $key => $paymentId ) {
+      $paymentDAO =& new CRM_Grant_DAO_GrantPayment();
+      $paymentDAO->id = $paymentId; 
+      $paymentDAO->find(true);
+      if( array_key_exists( $paymentDAO->payment_status_id, $paymentStatus ) ) {
+        unset($this->_grantPaymentIds[$key]);
+      }
+    }
+    $reprinted = count($this->_grantPaymentIds);
+    $this->assign( 'stopped', $selectedPayments - $reprinted );
+    $this->assign( 'reprinted', $reprinted );
+    
+    if ( count($this->_grantPaymentIds ) ) {
+      $this->assign( 'payments', 1 );
+      $this->applyFilter('__ALL__','trim');
+      $attributes = CRM_Core_DAO::getAttribute( 'CRM_Grant_DAO_GrantProgram' );
+    
+      $this->_contributionTypes = CRM_Grant_BAO_GrantProgram::contributionTypes();
+      $this->add('select', 'contribution_type_id',  ts( 'From account' ),
+                 array( '' => ts( '- select -' ) ) + $this->_contributionTypes , true);
+
+      $this->add( 'text', 'payment_batch_number', ts( 'Payment Batch number' ),
+                  $attributes['label'], true );
+
+      $this->add( 'text', 'payment_number', ts( 'Starting cheque number' ),
+                  $attributes['label'], true );
+        
+      $this->addDate( 'payment_date', ts('Payment date to appear on cheques'), false, array( 'formatType' => 'custom') );
+        
+      $this->addButtons(array( 
+                              array ( 'type'      => 'upload',
+                                      'name'      => ts('Reprint Checks'), 
+                                      'isDefault' => true   ),
+                              array ( 'type'      => 'next',
+                                      'name'      => ts('Export to CSV'),), 
+                              array ( 'type'      => 'cancel', 
+                                      'name'      => ts('Cancel') ), 
+                               ) 
+                        );
+    } else {
+      $this->addButtons(array( 
+                              array ( 'type'      => 'cancel', 
+                                      'name'      => ts('Cancel') ), 
+                               ) 
+                        );
+    }
+  }
+
+  /**
+   * process the form after the input has been submitted and validated
+   *
+   * @access public
+   * @return None
+   */
+  public function postProcess( ) 
+  { 
+    $values  = $this->controller->exportValues( $this->_name );
+    $makePdf = true;
+    foreach ( $_POST as $buttonKey => $buttonValue ) {
+      if ( $buttonKey == '_qf_Reprint_next' ) {
+        $makePdf = false;
+      }
+    }
+    $totalAmount = 0;
+    foreach ( $this->_grantPaymentIds as $paymentId ) {
+        
+      $paymentDAO =& new CRM_Grant_DAO_GrantPayment(); 
+      $paymentDAO->id = $paymentId; 
+      $paymentDAO->payment_status_id    = CRM_Core_OptionGroup::getValue( 'grant_payment_status', 'Stopped', 'name' );
+      $paymentDAO->save();
+      $paymentDAO =& new CRM_Grant_DAO_GrantPayment();
+      $paymentDAO->id = $paymentId; 
+      $paymentDAO->find(true);
+      
+      $payment['payment_batch_number'] = $values['payment_batch_number'];
+      $payment['contribution_type_id'] = $values['contribution_type_id']; 
+      $payment['payment_number']       = $values['payment_number'];
+      $payment['contact_id']           = $paymentDAO->contact_id; 
+      $payment['payment_created_date'] = date('m/d/Y');
+      $payment['payment_date']         = date("Y-m-d", strtotime($values['payment_date']));
+      $payment['payable_to_name']      = $paymentDAO->payable_to_name;
+      $payment['payable_to_address']   = $paymentDAO->payable_to_address; 
+      $payment['amount']               = $paymentDAO->amount;
+      $payment['currency']             = $paymentDAO->currency; 
+      $payment['payment_reason']       = $paymentDAO->payment_reason;
+      $payment['payment_status_id']    = CRM_Core_OptionGroup::getValue( 'grant_payment_status', 'Reprinted', 'name' );
+      $payment['replaces_payment_id']  = $paymentId;
+      
+      $result = CRM_Grant_BAO_GrantPayment::add( &$payment, $ids = array() );
+      
+      $newPaymentId = $result->id;
+        
+      $entityDAO =& new CRM_Grant_DAO_EntityPayment();
+      $entityDAO->payment_id = $paymentId;
+      $entityDAO->find();
+      
+      while( $entityDAO->fetch() ) {
+        $newEntityDAO =& new CRM_Grant_DAO_EntityPayment();
+        //$newEntityDAO->find( true );
+        $newEntityDAO->payment_id   = $newPaymentId;
+        $newEntityDAO->entity_table = 'civicrm_grant';
+        $newEntityDAO->entity_id    = $entityDAO->entity_id;
+        $newEntityDAO->save();
+        $grantDAO =& new CRM_Grant_DAO_Grant();
+        $grantDAO->id = $entityDAO->entity_id;
+        $grantDAO->find(true);
+        
+        if ( !empty( $payment_details[$newEntityDAO->payment_id] ) ) {
+          $payment_details[$newEntityDAO->payment_id] .= '</td></tr><tr><td width="15%" >'.date("Y-m-d", strtotime($values['payment_date'])).'</td><td width="15%" >'.$entityDAO->entity_id.'</td><td width="50%" >'.CRM_Grant_BAO_GrantProgram::getDisplayName( $result->contact_id ).'</td><td width="20%" >CAD :'.CRM_Utils_Money::format( $grantDAO->amount_granted,null, null,false );
+        } else {
+          $payment_details[$newEntityDAO->payment_id] = date("Y-m-d", strtotime($values['payment_date'])).'</td><td width="15%" >'.$entityDAO->entity_id.'</td><td width="50%" >'.CRM_Grant_BAO_GrantProgram::getDisplayName( $result->contact_id ).'</td><td width="20%" >CAD :'.CRM_Utils_Money::format( $grantDAO->amount_granted,null, null,false );
+        }
+      }
+      
+      $grantPayment[$newEntityDAO->payment_id]['contact_id']           = $result->contact_id;
+      $grantPayment[$newEntityDAO->payment_id]['contribution_type_id'] = $values['contribution_type_id'];
+      $grantPayment[$newEntityDAO->payment_id]['payment_batch_number'] = $values['payment_batch_number'];
+      $grantPayment[$newEntityDAO->payment_id]['payment_number'      ] = $values['payment_number'];
+      $grantPayment[$newEntityDAO->payment_id]['payment_date'        ] = date("Y-m-d", strtotime( $values['payment_date']));
+      $grantPayment[$newEntityDAO->payment_id]['payment_created_date'] = date('Y-m-d');
+      $grantPayment[$newEntityDAO->payment_id]['payable_to_name'     ] = CRM_Grant_BAO_GrantProgram::getDisplayName( $result->contact_id );
+      $grantPayment[$newEntityDAO->payment_id]['payable_to_address'  ] = CRM_Utils_Array::value( 'address', CRM_Grant_BAO_GrantProgram::getAddress( $result->contact_id ) );
+      $grantPayment[$newEntityDAO->payment_id]['amount'              ] = CRM_Utils_Money::format( $result->amount,null, null,false ) ;
+      $grantPayment[$newEntityDAO->payment_id]['currency'            ] = $result->currency;
+      $grantPayment[$newEntityDAO->payment_id]['payment_status_id'   ] = 3;
+      $grantPayment[$newEntityDAO->payment_id]['payment_reason'     ]  = $result->payment_reason;
+      $grantPayment[$newEntityDAO->payment_id]['replaces_payment_id']  = $result->replaces_payment_id;
+      
+      if ( $makePdf ) {
+        $grantPayment[$newEntityDAO->payment_id]['payment_details'] = $payment_details[$newEntityDAO->payment_id];
+        $grantPayment[$newEntityDAO->payment_id]['payment_id']      = $values['payment_number'];
+      } else {
+        unset($grantPayment[$newEntityDAO->payment_id]['payment_status_id']);
+      }
+      $values['payment_number']++;
+      $totalAmount += $result->amount;
+    }
+  
+    require_once 'CRM/Grant/Form/Task/GrantPayment.php';
+    
+    $downloadName  = check_plain('grantPayment');
+    $downloadName .= '_'.date('Ymdhis');
+    $this->assign( 'date', date('Y-m-d'));
+    $this->assign( 'time', date('H:i:s'));
+    $this->assign( 'account_name',CRM_Core_DAO::getFieldValue( 'CRM_Contribute_DAO_ContributionType', $values['contribution_type_id'], 'name' ) );
+    $this->assign( 'batch_number', $values['payment_batch_number']);
+    $this->assign( 'contact',CRM_Core_DAO::getFieldValue( 'CRM_Contact_DAO_Contact', $_SESSION[ 'CiviCRM' ][ 'userID' ], 'display_name' ) );
+    $this->assign( 'grantPayment', $grantPayment );
+    $this->assign( 'total_payments', count($grantPayment) );
+    $this->assign( 'total_amount' , CRM_Utils_Money::format( $totalAmount, null, null,false ) );
+    $this->assign( 'domain_name', CRM_Core_DAO::getFieldValue( 'CRM_Core_DAO_Domain', CRM_Core_Config::domainID( ) , 'name' ) );
+                   
+    if( !$makePdf ) {
+      $downloadName .= '.csv';
+      $fileName = CRM_Utils_File::makeFileName( $downloadName );
+      $config = CRM_Core_Config::singleton();
+      $file_name = $config->customFileUploadDir . $fileName;
+      CRM_Grant_BAO_GrantPayment::createCSV( $file_name, $grantPayment ); 
+    } else {
+      $downloadName .= '.pdf';
+      $fileName = CRM_Utils_File::makeFileName( $downloadName );
+      $fileName = CRM_Grant_BAO_GrantPayment::makePDF( $fileName, $grantPayment );
+    }
+    $checkRegisterFile = check_plain('CheckRegister');
+    $checkRegisterFile .= '_'.date('Ymdhis');
+    $checkRegisterFile .= '.pdf';
+    $checkFile = CRM_Utils_File::makeFileName( $checkRegisterFile );
+    $checkRegister = CRM_Grant_BAO_GrantPayment::makeReport($checkFile, $grantPayment );
+   
+    $fileDAO =& new CRM_Core_DAO_File();
+    $fileDAO->uri           = $fileName;
+    if ( $makePdf ) {
+      $fileDAO->mime_type = 'application/pdf';
+    } else {
+      $fileDAO->mime_type = 'text/x-csv';
+    }
+    $fileDAO->upload_date   = date('Ymdhis'); 
+    $fileDAO->save();
+    $grantPaymentFile = $fileDAO->id;
+    
+    $entityFileDAO =& new CRM_Core_DAO_EntityFile();
+    $entityFileDAO->entity_table = 'civicrm_contact';
+    $entityFileDAO->entity_id    = $_SESSION[ 'CiviCRM' ][ 'userID' ];
+    $entityFileDAO->file_id      = $grantPaymentFile;
+    $entityFileDAO->save();
+    
+    $fileDAO =& new CRM_Core_DAO_File();
+    $fileDAO->uri           = $checkFile;
+    $fileDAO->mime_type     = 'application/pdf';
+    $fileDAO->upload_date   = date('Ymdhis'); 
+    $fileDAO->save();
+    $grantPaymentCheckFile = $fileDAO->id;
+    
+    $entityFileDAO =& new CRM_Core_DAO_EntityFile();
+    $entityFileDAO->entity_table = 'civicrm_contact';
+    $entityFileDAO->entity_id    = $_SESSION[ 'CiviCRM' ][ 'userID' ];
+    $entityFileDAO->file_id      = $grantPaymentCheckFile;
+    $entityFileDAO->save(); 
+
+    $params = array( 
+                    'source_contact_id'    => $_SESSION[ 'CiviCRM' ][ 'userID' ],
+                    'activity_type_id'     => key(CRM_Core_OptionGroup::values( 'activity_type', false, false, false, 'AND v.label = "Grant Payment"' , 'value' )),
+                    'assignee_contact_id'  => $_SESSION[ 'CiviCRM' ][ 'userID' ],
+                    'subject'              => "Grant Payment",
+                    'activity_date_time'   => date('Ymdhis'),
+                    'status_id'            => CRM_Core_OptionGroup::getValue( 'activity_status','Completed','name' ),
+                    'priority_id'          => 2,
+                    'details'              => "<a href=".CRM_Utils_System::url( 'civicrm/file', 'reset=1&id='.$grantPaymentFile.'&eid='.$_SESSION[ 'CiviCRM' ][ 'userID' ].'').">".$downloadName."</a></br><a href=".CRM_Utils_System::url( 'civicrm/file', 'reset=1&id='.$grantPaymentCheckFile.'&eid='.$_SESSION[ 'CiviCRM' ][ 'userID' ].'').">".$checkRegisterFile."</a>",
+                     );
+    CRM_Activity_BAO_Activity::create( $params );
+    CRM_Core_Session::setStatus( "Selected payment stopped and reprinted successfully.");
+    CRM_Utils_System::redirect(CRM_Utils_System::url( 'civicrm/grant/payment/search', 'reset=1&bid='.$values['payment_batch_number'].'&download='.$fileName.'&force=1'));
+  }
+}
+
+
diff --git a/CRM/Grant/Form/Task/SearchTaskHookSample.php b/CRM/Grant/Form/Task/SearchTaskHookSample.php
new file mode 100755
index 0000000..475eed6
--- /dev/null
+++ b/CRM/Grant/Form/Task/SearchTaskHookSample.php
@@ -0,0 +1,95 @@
+<?php
+
+/*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.1                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007.                                       |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License along with this program; if not, contact CiviCRM LLC       |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*/
+
+/**
+ *
+ * @package CRM
+ * @copyright CiviCRM LLC (c) 2004-2011
+ * $Id$
+ *
+ */
+
+require_once 'CRM/Grant/Form/Task.php';
+
+/**
+ * This class provides the functionality to save a search
+ * Saved Searches are used for saving frequently used queries
+ */
+class CRM_Grant_Form_Task_SearchTaskHookSample extends CRM_Grant_Form_Task 
+{
+    /**
+     * build all the data structures needed to build the form
+     *
+     * @return void
+     * @access public
+     */
+    function preProcess( ) 
+    {
+        parent::preProcess( );
+        $rows = array( );
+        // display name and grant details of all selectced contacts
+        $grantIDs = implode( ',', $this->_grantIds );      
+        
+        $query = "
+    SELECT grt.decision_date  as decision_date,
+           grt.amount_total   as amount_total,
+           grt.amount_granted as amount_granted,
+           ct.display_name    as display_name      
+      FROM civicrm_grant grt
+INNER JOIN civicrm_contact ct ON ( grt.contact_id = ct.id )       
+     WHERE grt.id IN ( $grantIDs )";
+        
+        $dao = CRM_Core_DAO::executeQuery( $query, CRM_Core_DAO::$_nullArray );
+        
+        while ( $dao->fetch( ) ) {
+            $rows[]= array(
+                           'display_name'     =>  $dao->display_name,
+                           'decision_date'    =>  $dao->decision_date,
+                           'amount_requested' =>  $dao->amount_total,
+                           'amount_granted'   =>  $dao->amount_granted
+                           
+                           );
+        }
+        $this->assign( 'rows', $rows );
+    }
+    
+    /**
+     * Function to actually build the form
+     *
+     * @return None
+     * @access public
+     */
+    public function buildQuickForm( ) 
+    {
+        $this->addButtons( array(
+                                 array ( 'type'      => 'done',
+                                         'name'      => ts('Done'),
+                                         'isDefault' => true   ),
+                                 )
+                           );
+    }
+}
\ No newline at end of file
diff --git a/CRM/Grant/Form/Task/Update.php b/CRM/Grant/Form/Task/Update.php
new file mode 100755
index 0000000..cb48e23
--- /dev/null
+++ b/CRM/Grant/Form/Task/Update.php
@@ -0,0 +1,135 @@
+<?php
+
+/*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.1                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*/
+
+/**
+ *
+ * @package CRM
+ * @copyright CiviCRM LLC (c) 2004-2011
+ * $Id$
+ *
+ */
+
+require_once 'CRM/Grant/Form/Task.php';
+
+/**
+ * This class provides the functionality to update a group of
+ * grants. This class provides functionality for the actual
+ * update.
+ */
+class CRM_Grant_Form_Task_Update extends CRM_Grant_Form_Task 
+{
+    /**
+     * build all the data structures needed to build the form
+     *
+     * @return void
+     * @access public
+     */
+    function preProcess( ) 
+    {
+        parent::preProcess( );
+
+        //check permission for update.
+        if ( !CRM_Core_Permission::checkActionPermission( 'CiviGrant', CRM_Core_Action::UPDATE ) ) {
+            CRM_Core_Error::fatal( ts( 'You do not have permission to access this page' ) );  
+        }
+    }
+
+    /**
+     * Build the form
+     *
+     * @access public
+     * @return void
+     */
+
+ 
+    function buildQuickForm( ) 
+    {
+        require_once 'CRM/Grant/PseudoConstant.php';
+        $grantStatus = CRM_Grant_PseudoConstant::grantStatus();
+        $this->addElement('select', 'status_id', ts('Grant Status'), array( '' => ts( '- select -' )  ) + $grantStatus);
+        
+        $this->addElement('radio', 'radio_ts', null, 'Other Amount', 'amount_granted' );
+
+        $this->setDefaults( array( 'radio_ts'=> 'amount_granted' ) );
+
+        $this->addElement('text', 'amount_granted', ts('Other Amount') );
+        $this->addRule('amount_granted', ts('Please enter a valid amount.'), 'money');
+
+        $this->addElement('radio', 'radio_ts', null, 'Amount Allocated', 'amount_total' );
+
+        $this->addDate( 'decision_date', ts('Grant Decision'), false, array( 'formatType' => 'custom') );
+
+        //$this->assign( 'elements', array( 'status_id', 'other_amount', 'amount_total', 'decision_date' ) );
+        $this->assign( 'totalSelectedGrants', count($this->_grantIds) );
+
+        $this->addDefaultButtons( ts( 'Update Grants' ), 'done' );
+    }
+
+    /**
+     * process the form after the input has been submitted and validated
+     *
+     * @access public
+     * @return None
+     */
+    public function postProcess( ) 
+    {
+        $updatedGrants = 0;
+
+        // get the submitted form values.  
+        $params = $this->controller->exportValues( $this->_name );
+        if ( $params['radio_ts'] == 'amount_total' ) {
+            unset($params['granted_amount']);
+        }
+        $qfKey = $params['qfKey'];
+        foreach ( $params as $key => $value ) {
+            if ( $value == '' || $key == 'qfKey' || $key == 'radio_ts' ) {
+                unset( $params[$key] );
+            }
+        }
+
+        if ( ! empty( $params ) ) {
+            require_once 'CRM/Grant/BAO/Grant.php';
+            foreach ( $params as $key => $value ) {
+                $values[$key] = $value;
+            }
+            foreach ( $this->_grantIds as $grantId ) {
+                $ids['grant'] = $grantId;
+                
+                CRM_Grant_BAO_Grant::add( $values, $ids );
+                $updatedGrants++;
+            }
+        }
+        
+        $status = array(
+                        ts( 'Updated Grant(s): %1',        array( 1 => $updatedGrants ) ),
+                        ts( 'Total Selected Grant(s): %1', array( 1 => count($this->_grantIds ) ) ),
+                        );
+        CRM_Core_Session::setStatus( $status );
+        CRM_Utils_System::redirect( CRM_Utils_System::url( 'civicrm/grant/search', 'force=1&qfKey=' . $qfKey ) );
+    }
+}
diff --git a/CRM/Grant/Info.php b/CRM/Grant/Info.php
new file mode 100755
index 0000000..c382c41
--- /dev/null
+++ b/CRM/Grant/Info.php
@@ -0,0 +1,125 @@
+<?php
+
+/*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.1                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*/
+
+require_once 'CRM/Core/Component/Info.php';
+
+/**
+ * This class introduces component to the system and provides all the 
+ * information about it. It needs to extend CRM_Core_Component_Info
+ * abstract class.
+ *
+ * @package CRM
+ * @copyright CiviCRM LLC (c) 2004-2011
+ * $Id$
+ *
+ */
+class CRM_Grant_Info extends CRM_Core_Component_Info
+{
+
+    // docs inherited from interface
+    protected $keyword = 'grant';
+
+    // docs inherited from interface
+    public function getInfo()
+    {
+        return array( 'name'                 => 'CiviGrant',
+                      'translatedName'       => ts('CiviGrant'),
+                      'title'                => 'CiviCRM Grant Management Engine',
+                      'path'                 => 'CRM_Grant_',
+                      'search'               => 1,
+                      'showActivitiesInCore' => 1 
+                      );
+    }
+
+
+    // docs inherited from interface
+    public function getPermissions()
+    {
+        return array( 'access CiviGrant', 
+                      'edit grants',
+                      'edit grant program',
+                      'delete in CiviGrant',
+                      'administer CiviGrant');
+    }
+
+    // docs inherited from interface
+    public function getUserDashboardElement()
+    {
+        // no dashboard element for this component
+        return null;
+    }
+
+    // docs inherited from interface
+    public function getUserDashboardObject()
+    {
+        // no dashboard element for this component
+        return null;
+    }
+
+    // docs inherited from interface  
+    public function registerTab()
+    {
+        return array( 'title'   => ts( 'Grants' ),
+                      'url'	=> 'grant',
+                      'weight'  => 50 );
+    }
+    
+    // docs inherited from interface  
+    public function registerAdvancedSearchPane()
+    {
+        return array( 'title'   => ts( 'Grants' ),
+                      'weight'  => 50 );
+    }    
+        
+    // docs inherited from interface    
+    public function getActivityTypes()
+    {
+        return null;
+    }
+
+    // add shortcut to Create New
+    public function creatNewShortcut( &$shortCuts ) {
+        if ( CRM_Core_Permission::check('access CiviGrant') &&
+             CRM_Core_Permission::check('edit grants') ) {
+            $shortCuts = 
+            array_merge($shortCuts, array( array( 'path'  => 'civicrm/grant/add',
+                                                  'query' => "reset=1&action=add&context=standalone",
+                                                  'ref'   => 'new-grant',
+                                                  'title' => ts('Grant') ) ));
+        }
+
+        if ( CRM_Core_Permission::check('access CiviGrant') &&
+             CRM_Core_Permission::check('edit grant program') ) {
+            $shortCuts = 
+                array_merge($shortCuts, array( array( 'path'  => 'civicrm/grant_program',
+                                                      'query' => "reset=1&action=browse&id=1",
+                                                      'ref'   => 'new-grant program',
+                                                      'title' => ts('Grant Program') ) ));
+        }
+    }
+}
diff --git a/CRM/Grant/Page/DashBoard.php b/CRM/Grant/Page/DashBoard.php
new file mode 100755
index 0000000..256b11f
--- /dev/null
+++ b/CRM/Grant/Page/DashBoard.php
@@ -0,0 +1,85 @@
+<?php
+/*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.1                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*/
+
+/**
+ *
+ * @package CRM
+ * @copyright CiviCRM LLC (c) 2004-2011
+ * $Id$
+ *
+ */
+
+require_once 'CRM/Core/Page.php';
+
+/**
+ * This is page is for Grant Dashboard
+ */
+class CRM_Grant_Page_DashBoard extends CRM_Core_Page 
+{
+    /** 
+     * Heart of the viewing process. The runner gets all the meta data for 
+     * the contact and calls the appropriate type of page to view. 
+     * 
+     * @return void 
+     * @access public 
+     * 
+     */ 
+    function preProcess( ) 
+    {
+        $admin = CRM_Core_Permission::check( 'administer CiviCRM' );
+
+        require_once 'CRM/Grant/BAO/Grant.php';
+        $grantSummary = CRM_Grant_BAO_Grant::getGrantSummary( $admin );
+        
+        $this->assign( 'grantAdmin'  , $admin );
+        $this->assign( 'grantSummary' , $grantSummary);
+    }
+    
+    /** 
+     * This function is the main function that is called when the page loads, 
+     * it decides the which action has to be taken for the page. 
+     *                                                          
+     * return null        
+     * @access public 
+     */                                                          
+    function run( ) 
+    {
+        $this->preProcess( );
+        
+        $controller = new CRM_Core_Controller_Simple( 'CRM_Grant_Form_Search', ts('grants'), null );
+        $controller->setEmbedded( true ); 
+        $controller->reset( );
+        $controller->set( 'limit', 10 );
+        $controller->set( 'force', 1 );
+        $controller->set( 'context', 'dashboard' ); 
+        $controller->process( ); 
+        $controller->run( ); 
+        
+        return parent::run( );
+    }
+}
+
diff --git a/CRM/Grant/Page/GrantProgram.php b/CRM/Grant/Page/GrantProgram.php
new file mode 100755
index 0000000..6a59cf7
--- /dev/null
+++ b/CRM/Grant/Page/GrantProgram.php
@@ -0,0 +1,143 @@
+<?php
+
+/*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.0                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*/
+
+/**
+ *
+ * @package CRM
+ * @copyright CiviCRM LLC (c) 2004-2011
+ * $Id$
+ *
+ */
+
+require_once 'CRM/Core/Page.php';
+require_once 'CRM/Grant/BAO/GrantProgram.php';
+
+
+/**
+ * Page for displaying list of contribution types
+ */
+class CRM_Grant_Page_GrantProgram extends CRM_Core_Page
+{
+
+    protected $_id;
+    /**
+     * The action links that we need to display for the browse screen
+     *
+     * @var array
+     */
+    private static $_links;
+    /**
+     * Get action Links
+     *
+     * @return array (reference) of action links
+     */
+    function &links()
+        {
+            if (!(self::$_links)) {
+                self::$_links = array(
+                                      CRM_Core_Action::VIEW  => array(
+                                                                      'name'  => ts('View'),
+                                                                      'url'   => 'civicrm/grant_program',
+                                                                      'qs'    => 'action=view&id=%%id%%&reset=1',
+                                                                      'title' => ts('View Grant Program') 
+                                                                      ),
+                                      CRM_Core_Action::UPDATE  => array(
+                                                                        'name'  => ts('Edit'),
+                                                                        'url'   => 'civicrm/grant_program',
+                                                                        'qs'    => 'action=update&id=%%id%%&reset=1',
+                                                                        'title' => ts('Edit Grant Program') 
+                                                                        ),
+                                      CRM_Core_Action::DELETE  => array(
+                                                                        'name'  => ts('Delete'),
+                                                                        'url'   => 'civicrm/grant_program',
+                                                                        'qs'    => 'action=delete&id=%%id%%',
+                                                                        'title' => ts('Delete Grant Program') 
+                                                                        )
+                                      );
+            }
+            return self::$_links;
+        }
+    
+    function browse( ) {
+        
+        $grantProgram = array();
+        require_once 'CRM/Grant/DAO/GrantProgram.php';
+        $dao = new CRM_Grant_DAO_GrantProgram();
+        
+        $dao->orderBy('label');
+        $dao->find();
+        
+        while ($dao->fetch()) {
+            $grantProgram[$dao->id] = array();
+            CRM_Core_DAO::storeValues( $dao, $grantProgram[$dao->id]);
+            $action = array_sum(array_keys($this->links()));
+
+            $grantProgram[$dao->id]['action'] = CRM_Core_Action::formLink(self::links(), $action, 
+                                                                          array('id' => $dao->id));
+        }
+        require_once 'CRM/Grant/PseudoConstant.php';
+        $grantType   = CRM_Grant_PseudoConstant::grantType( );
+        $grantStatus = CRM_Grant_PseudoConstant::grantProgramStatus( );
+        foreach ( $grantProgram as $key => $value ) {
+            $grantProgram[$key]['grant_type_id'] = $grantType[CRM_Grant_BAO_GrantProgram::getOptionValue($grantProgram[$key]['grant_type_id'])];
+            $grantProgram[$key]['status_id'] = $grantStatus[CRM_Grant_BAO_GrantProgram::getOptionValue($grantProgram[$key]['status_id'])];
+        }
+        $this->assign('rows',$grantProgram );
+    }
+    
+    function run( ) 
+    {
+        $action = CRM_Utils_Request::retrieve('action', 'String',
+                                              $this, false, 0 );
+        if ( $action & CRM_Core_Action::VIEW ) { 
+            $this->view( $action); 
+        } else if ( $action & ( CRM_Core_Action::UPDATE | CRM_Core_Action::ADD | CRM_Core_Action::DELETE ) ) {
+            $this->edit( $action);
+        } else {
+            $this->browse( ); 
+        }
+        $this->assign('action', $action);
+        return parent::run( );
+    }
+
+    function edit($action)
+    {
+        $controller = new CRM_Core_Controller_Simple('CRM_Grant_Form_GrantProgram', ts(''), $action);
+        $controller->setEmbedded(true);
+        $result = $controller->process();
+        $result = $controller->run();
+    }
+
+    function view( $action ) 
+    {   
+        $controller = new CRM_Core_Controller_Simple( 'CRM_Grant_Form_GrantProgramView', ts(''), $action );
+        $controller->setEmbedded( true );  
+        $result = $controller->process();
+        $result = $controller->run();
+    }
+}
diff --git a/CRM/Grant/Page/Payment.php b/CRM/Grant/Page/Payment.php
new file mode 100755
index 0000000..4df0665
--- /dev/null
+++ b/CRM/Grant/Page/Payment.php
@@ -0,0 +1,97 @@
+<?php
+
+/*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.0                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*/
+
+/**
+ *
+ * @package CRM
+ * @copyright CiviCRM LLC (c) 2004-2011
+ * $Id$
+ *
+ */
+
+require_once 'CRM/Core/Page.php';
+require_once 'CRM/Grant/BAO/GrantProgram.php';
+
+
+/**
+ * Page for displaying list of contribution types
+ */
+class CRM_Grant_Page_Payment extends CRM_Core_Page
+{
+
+    
+    function run( ) 
+    {
+        $action = CRM_Utils_Request::retrieve('action', 'String',
+                                              $this, false, 0 );
+        if ( $action & CRM_Core_Action::VIEW ) { 
+            $this->view( $action ); 
+        } elseif ( $action & ( CRM_Core_Action::STOP) ) {
+            $this->stop( $action );
+        } elseif ( $action & ( CRM_Core_Action::REPRINT ) ) {
+            $this->reprint( $action ); 
+        } else {
+            $this->withdraw( $action ); 
+        }
+        $this->assign('action', $action);
+        return parent::run( );
+    }
+
+
+    function view( $action ) 
+    {   
+        $controller = new CRM_Core_Controller_Simple( 'CRM_Grant_Form_Payment_View', ts(''), $action );
+        $controller->setEmbedded( true );  
+        $result = $controller->process();
+        $result = $controller->run();
+    }
+
+    function stop( $action ) 
+    {   
+        $controller = new CRM_Core_Controller_Simple( 'CRM_Grant_Form_Payment_View', ts(''), $action );
+        $controller->setEmbedded( true );  
+        $result = $controller->process();
+        $result = $controller->run();
+    }
+
+    function reprint( $action ) 
+    {   
+        $controller = new CRM_Core_Controller_Simple( 'CRM_Grant_Form_Payment_View', ts(''), $action );
+        $controller->setEmbedded( true );  
+        $result = $controller->process();
+        $result = $controller->run();
+    }
+
+    function withdraw( $action ) 
+    {   
+        $controller = new CRM_Core_Controller_Simple( 'CRM_Grant_Form_Payment_View', ts(''), $action );
+        $controller->setEmbedded( true );  
+        $result = $controller->process();
+        $result = $controller->run();
+    }
+}
diff --git a/CRM/Grant/PaymentTask.php b/CRM/Grant/PaymentTask.php
new file mode 100755
index 0000000..460a2a2
--- /dev/null
+++ b/CRM/Grant/PaymentTask.php
@@ -0,0 +1,161 @@
+<?php
+
+/*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.1                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*/
+
+/**
+ *
+ * @package CRM
+ * @copyright CiviCRM LLC (c) 2004-2011
+ * $Id$
+ *
+ */
+
+/**
+ * class to represent the actions that can be performed on a group of contacts
+ * used by the search forms
+ *
+ */
+class CRM_Grant_PaymentTask
+{
+    const
+      CANCEL_PAYMENTS                     =     1,
+      REPRINT_PAYMENTS                    =     2;
+     
+    /**
+     * the task array
+     *
+     * @var array
+     * @static
+     */
+    static $_tasks = null;
+
+    /**
+     * the optional task array
+     *
+     * @var array
+     * @static
+     */
+    static $_optionalTasks = null;
+
+    /**
+     * These tasks are the core set of tasks that the user can perform
+     * on a contact / group of contacts
+     *
+     * @return array the set of tasks for a group of contacts
+     * @static
+     * @access public
+     */
+    static function &tasks( )
+    {
+        if ( !( self::$_tasks ) ) {
+            self::$_tasks = array( 1 => array( 'title'  => ts( 'Cancel Payments' ),
+                                               'class'  => 'CRM_Grant_Form_Task_Cancel',
+                                               'result' => false ),
+                                   2 => array( 'title'  => ts( 'Reprint Payments' ),
+                                               'class'  => 'CRM_Grant_Form_Task_Reprint',
+                                               'result' => false ),
+                                   
+                                   );
+        }
+        if ( !CRM_Core_Permission::check( 'cancel payments in CiviGrant' ) ) {
+            unset( self::$_tasks[1] );
+        }
+        
+        if ( !CRM_Core_Permission::check( 'edit payments in CiviGrant' ) && !CRM_Core_Permission::check( 'create payments in CiviGrant' )) {
+            unset( self::$_tasks[2] );
+        }
+        
+        require_once 'CRM/Utils/Hook.php';
+        CRM_Utils_Hook::searchTasks( 'grant', self::$_tasks );
+        asort( self::$_tasks );
+        return self::$_tasks;
+    }
+    
+    /**
+     * These tasks are the core set of task titles
+     *
+     * @return array the set of task titles 
+     * @static
+     * @access public
+     */
+    static function &taskTitles( )
+    {
+        self::tasks( );
+        $titles = array( );
+        foreach ( self::$_tasks as $id => $value ) {
+          $titles[$id] = $value['title'];
+        }      
+        return $titles;
+    }
+    
+    /**
+     * show tasks selectively based on the permission level
+     * of the user
+     *
+     * @param int $permission
+     *
+     * @return array set of tasks that are valid for the user
+     * @access public
+     */
+    static function &permissionedTaskTitles( $permission ) 
+    {
+        $tasks = array( );
+        if ( ( $permission == CRM_Core_Permission::EDIT ) 
+             || CRM_Core_Permission::check( 'edit payments in CiviGrant' ) ) {
+            $tasks = self::taskTitles( );
+        } else {
+            $tasks = array(
+                           3 => self::$_tasks[3]['title'] );
+            //CRM-4418,
+            if ( CRM_Core_Permission::check( 'cancel payments in CiviGrant' ) ) {
+                $tasks[1] = self::$_tasks[1]['title']; 
+            }
+        }
+        return $tasks;
+    }
+    
+    /**
+     * These tasks are the core set of tasks that the user can perform
+     *
+     * @param int $value
+     *
+     * @return array the set of tasks for a group of contacts
+     * @static
+     * @access public
+     */
+    static function getTask( $value ) 
+    {
+        self::tasks( );
+        if ( ! $value  || ! CRM_Utils_Array::value( $value, self::$_tasks ) ) {
+            // make the print task by default
+            $value = 2; 
+        }
+        return array( self::$_tasks[$value]['class' ],
+                      self::$_tasks[$value]['result'] );
+    }
+}
+
diff --git a/CRM/Grant/PseudoConstant.php b/CRM/Grant/PseudoConstant.php
new file mode 100755
index 0000000..4c59765
--- /dev/null
+++ b/CRM/Grant/PseudoConstant.php
@@ -0,0 +1,126 @@
+<?php
+
+/*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.1                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*/
+
+/**
+ *
+ * @package CRM
+ * @copyright CiviCRM LLC (c) 2004-2011
+ * $Id$
+ *
+ */
+
+require_once 'CRM/Core/OptionGroup.php';
+
+/**
+ * This class holds all the Pseudo constants that are specific to Grant. This avoids
+ * polluting the core class and isolates the Grant
+ */
+class CRM_Grant_PseudoConstant extends CRM_Core_PseudoConstant 
+{
+    /**
+     * Grant Status 
+     *
+     * @var array
+     * @static
+     */
+    private static $grantStatus; 
+    
+    /**
+     * grant Type
+     *
+     * @var array
+     * @static
+     */
+    private static $grantType; 
+
+
+    
+    private static $grantProgramStatus; 
+    /**
+     * Get all the n grant statuses
+     *
+     * @access public
+     * @return array - array reference of all grant statuses if any
+     * @static
+     */
+    public static function &grantStatus( $id = null )
+    {
+        if ( ! self::$grantStatus ) {
+            self::$grantStatus = array( );
+            self::$grantStatus = CRM_Core_OptionGroup::values( 'grant_status' );
+        }
+        
+        if( $id ) {
+            return self::$grantStatus[$id];
+        }
+        
+        return self::$grantStatus ;
+    }
+    
+    /**
+     * Get all the n grant types
+     *
+     * @access public
+     * @return array - array reference of all grant types if any
+     * @static
+     */
+    public static function &grantType( $id = null )
+    {
+        if ( ! self::$grantType ) {
+            self::$grantType = array( );
+            self::$grantType = CRM_Core_OptionGroup::values( 'grant_type' );
+        }
+        
+        If( $id ) {
+            return self::$grantType[$id];
+        }
+        
+        return self::$grantType ;
+    } 
+    /**
+     * Get all the n grant program statuses
+     *
+     * @access public
+     * @return array - array reference of all grant program statuses if any
+     * @static
+     */
+    public static function &grantProgramStatus( $id = null )
+    {
+        if ( ! self::$grantProgramStatus ) {
+            self::$grantProgramStatus = array( );
+            self::$grantProgramStatus = CRM_Core_OptionGroup::values( 'grant_program_status' );
+        }
+        
+        if( $id ) {
+            return self::$grantProgramStatus[$id];
+        }
+        
+        return self::$grantProgramStatus ;
+    }
+}
+
diff --git a/CRM/Grant/Selector/PaymentSearch.php b/CRM/Grant/Selector/PaymentSearch.php
new file mode 100755
index 0000000..70a5f1a
--- /dev/null
+++ b/CRM/Grant/Selector/PaymentSearch.php
@@ -0,0 +1,418 @@
+<?php
+/*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.1                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*/
+
+/**
+ *
+ * @package CRM
+ * @copyright CiviCRM LLC (c) 2004-2011
+ * $Id$
+ *
+ */
+
+require_once 'CRM/Core/Selector/Base.php';
+require_once 'CRM/Core/Selector/API.php';
+
+require_once 'CRM/Utils/Pager.php';
+require_once 'CRM/Utils/Sort.php';
+
+require_once 'CRM/Grant/BAO/PaymentSearch.php';
+
+/**
+ * This class is used to retrieve and display a range of
+ * contacts that match the given criteria (specifically for
+ * results of advanced search options.
+ *
+ */
+class CRM_Grant_Selector_PaymentSearch extends CRM_Core_Selector_Base implements CRM_Core_Selector_API 
+{
+    
+    /**
+     * This defines two actions- View and Edit.
+     *
+     * @var array
+     * @static
+     */
+    static $_links = null;
+
+    /**
+     * we use desc to remind us what that column is, name is used in the tpl
+     *
+     * @var array
+     * @static
+     */
+    static $_columnHeaders;
+
+    /**
+     * Properties of contact we're interested in displaying
+     * @var array
+     * @static
+     */
+    static $_properties = array( 'id',
+                                 'payable_to_name',
+                                 'payment_batch_number',
+                                 'payment_number',
+                                 'payment_status_id',
+                                 'payment_created_date',
+                                 'amount',
+                                 );
+
+    /** 
+     * are we restricting ourselves to a single contact 
+     * 
+     * @access protected   
+     * @var boolean   
+     */   
+    protected $_single = false;
+
+    /**  
+     * are we restricting ourselves to a single contact  
+     *  
+     * @access protected    
+     * @var boolean    
+     */    
+    protected $_limit = null;
+
+    /**
+     * what context are we being invoked from
+     *   
+     * @access protected     
+     * @var string
+     */     
+    protected $_context = null;
+
+    /**
+     * queryParams is the array returned by exportValues called on
+     * the HTML_QuickForm_Controller for that page.
+     *
+     * @var array
+     * @access protected
+     */
+    public $_queryParams; 
+
+    /**
+     * represent the type of selector
+     *
+     * @var int
+     * @access protected
+     */
+    protected $_action;
+
+    /** 
+     * The additional clause that we restrict the search with 
+     * 
+     * @var string 
+     */ 
+    protected $_grantClause = null;
+
+    /** 
+     * The query object
+     * 
+     * @var string 
+     */ 
+    protected $_query;
+
+    /**
+     * Class constructor
+     *
+     * @param array   $queryParams array of parameters for query
+     * @param int     $action - action of search basic or advanced.
+     * @param string  $grantClause if the caller wants to further restrict the search 
+     * @param boolean $single are we dealing only with one contact?
+     * @param int     $limit  how many participations do we want returned
+     *
+     * @return CRM_Contact_Selector
+     * @access public
+     */
+    function __construct(&$queryParams,
+                         $action = CRM_Core_Action::NONE,
+                         $grantClause = null,
+                         $single = false,
+                         $limit = null,
+                         $context = 'search' ) 
+    {
+        // submitted form values
+        $this->_queryParams =& $queryParams;
+        
+
+        $this->_single  = $single;
+        $this->_limit   = $limit;
+        $this->_context = $context;
+
+        $this->_grantClause = $grantClause;
+
+        // type of selector
+        $this->_action = $action;
+
+        $this->_query = new CRM_Grant_BAO_PaymentSearch( $this->_queryParams, null, null, false, false,
+                                                         CRM_Grant_BAO_PaymentSearch::MODE_GRANT_PAYMENT );
+     
+        
+        $this->_query->_distinctComponentClause = " civicrm_payment.id";
+        $this->_query->_groupByComponentClause  = " GROUP BY civicrm_payment.id";
+      
+    }//end of constructor
+
+
+    /**
+     * This method returns the links that are given for each search row.
+     * currently the links added for each row are 
+     * 
+     * - View
+     * - Edit
+     *
+     * @return array
+     * @access public
+     *
+     */
+    static function &links( $key = null )
+    {       
+        $id = CRM_Utils_Request::retrieve('id', 'Integer', $this);
+        $extraParams = ( $key ) ? "&key={$key}" : null;
+        
+        if (!(self::$_links)) {
+            self::$_links = array(
+                                  CRM_Core_Action::VIEW     => array(
+                                                                     'name'     => ts('View'),
+                                                                     'url'      => 'civicrm/grant/payment',
+                                                                     'qs'       => 'reset=1&id=%%id%%&action=view&context=%%cxt%%&selectedChild=grant'.$extraParams,
+                                                                     'title'    => ts('View Grant'),
+                                                                     ), 
+                                  CRM_Core_Action::STOP     => array(
+                                                                     'name'     => ts('Stop'),
+                                                                     'url'      => 'civicrm/grant/payment',
+                                                                     'qs'       => 'reset=1&action=stop&id=%%id%%&context=%%cxt%%'.$extraParams,
+                                                                     'title'    => ts('Edit Grant'),
+                                                                     ),
+                                  CRM_Core_Action::REPRINT  => array(
+                                                                     'name'     => ts('Reprint'),
+                                                                     'url'      => 'civicrm/grant/payment',
+                                                                     'qs'       => 'reset=1&action=reprint&id=%%id%%&context=%%cxt%%'.$extraParams,
+                                                                     'title'    => ts('Edit Grant'),
+                                                                     ),
+                                  CRM_Core_Action::WITHDRAW => array(
+                                                                     'name'     => ts('Withdraw'),
+                                                                     'url'      => 'civicrm/grant/payment',
+                                                                     'qs'       => 'reset=1&action=withdraw&id=%%id%%&context=%%cxt%%'.$extraParams,
+                                                                     'title'    => ts('Edit Grant'),
+                                                                     )
+                                  );
+            
+            self::$_links =  self::$_links  ;
+           
+        }
+       
+        
+        return self::$_links;
+    } //end of function
+        
+    /**
+     * getter for array of the parameters required for creating pager.
+     *
+     * @param 
+     * @access public
+     */
+    function getPagerParams($action, &$params) 
+    {
+        $params['status']       = ts('Grant') . ' %%StatusMessage%%';
+        $params['csvString']    = null;
+        if ( $this->_limit ) {
+            $params['rowCount']     = $this->_limit;
+        } else {
+            $params['rowCount']     = CRM_Utils_Pager::ROWCOUNT;
+        }
+
+        $params['buttonTop']    = 'PagerTopButton';
+        $params['buttonBottom'] = 'PagerBottomButton';
+    } //end of function
+
+    /**
+     * Returns total number of rows for the query.
+     *
+     * @param 
+     * @return int Total number of rows 
+     * @access public
+     */
+    function getTotalCount($action)
+    { 
+        return $this->_query->searchQuery( 0, 0, null,
+                                           true, false, 
+                                           false, false, 
+                                           false, 
+                                           $this->_grantClause );
+       
+    }
+
+    
+    /**
+     * returns all the rows in the given offset and rowCount     *
+     * @param enum   $action   the action being performed
+     * @param int    $offset   the row number to start from
+     * @param int    $rowCount the number of rows to return
+     * @param string $sort     the sql string that describes the sort order
+     * @param enum   $output   what should the result set include (web/email/csv)
+     *
+     * @return int   the total number of rows for this action
+     */
+     function &getRows($action, $offset, $rowCount, $sort, $output = null) 
+     {  
+         $result = $this->_query->searchQuery( $offset, $rowCount, $sort,
+                                               false, false, 
+                                               false, false, 
+                                               false, 
+                                               $this->_grantClause );
+         // CRM_Core_Error::debug( '$result', $result );
+         // exit;
+     
+         // process the result of the query
+         $rows = array( );
+         
+         //CRM-4418 check for view, edit, delete
+         $permissions = array( CRM_Core_Permission::VIEW );
+         if ( CRM_Core_Permission::check( 'edit grants' ) ) {
+             $permissions[] = CRM_Core_Permission::EDIT;
+         }
+         if ( CRM_Core_Permission::check( 'delete in CiviGrant' ) ) {
+             $permissions[] = CRM_Core_Permission::DELETE;
+         }
+         $mask = CRM_Core_Action::mask( $permissions ); 
+   
+        
+         while ( $result->fetch()) {
+             $row = array();
+             
+             // the columns we are interested in
+             foreach (self::$_properties as $property) {
+                 if ( isset( $result->$property ) ) {
+                     if ( $property == 'payment_status_id' ) {
+                         require_once 'CRM/Core/OptionGroup.php';
+                         $paymentStatus = CRM_Core_OptionGroup::values( 'grant_payment_status' );
+                         $row[$property] = $paymentStatus[$result->$property];
+                     } else {
+                         $row[$property] = $result->$property;
+                     }
+                 }
+             }
+             if ($this->_context == 'search') {
+               $row['checkbox'] = CRM_Core_Form::CB_PREFIX . $result->id;
+             }
+             $this->id = $result->id; 
+             $link = self::links( $this->_key);
+             if ( $result->payment_status_id == 2 || $result->payment_status_id == 4 ) {
+                unset($link[CRM_Core_Action::STOP]); 
+                unset($link[CRM_Core_Action::REPRINT]);
+                unset($link[CRM_Core_Action::WITHDRAW]);
+             }
+             
+             $row['action']   = CRM_Core_Action::formLink( $link, 
+                                                           $mask,
+                                                           array( 'id'  => $result->id,
+                                                                  'cxt' => $this->_context ) );
+
+             $rows[] = $row;
+         }
+         return $rows;
+     }
+     
+     
+     /**
+      * @return array              $qill         which contains an array of strings
+      * @access public
+      */
+     
+     // the current internationalisation is bad, but should more or less work
+     // for most of "European" languages
+     public function getQILL( )
+     { 
+         return $this->_query->qill( );
+     }
+     
+     /** 
+      * returns the column headers as an array of tuples: 
+     * (name, sortName (key to the sort array)) 
+     * 
+     * @param string $action the action being performed 
+     * @param enum   $output what should the result set include (web/email/csv) 
+     * 
+     * @return array the column headers that need to be displayed 
+     * @access public 
+     */ 
+    public function &getColumnHeaders( $action = null, $output = null ) 
+    {       
+        if ( ! isset( self::$_columnHeaders ) ) {
+            self::$_columnHeaders = array(
+                                          array('name'      => ts('Status'),
+                                                'sort'      => 'payment_status_id',
+                                                'direction' => CRM_Utils_Sort::DONTCARE,
+                                                ),
+                                          array(
+                                                'name'      => ts('Batch Number'),
+                                                'sort'      => 'payment_batch_number',
+                                                'direction' => CRM_Utils_Sort::DONTCARE,
+                                                ),
+                                          array(
+                                                'name'      => ts('Payment Number'),
+                                                'sort'      => 'payment_number',
+                                                'direction' => CRM_Utils_Sort::DONTCARE,
+                                                ),
+                                          array(
+                                                'name'      => ts('Date'),
+                                                'sort'      => 'payment_created_date',
+                                                'direction' => CRM_Utils_Sort::DONTCARE,
+                                                ),
+                                          array(
+                                                'name'      => ts('Payee name'),
+                                                'sort'      => 'payable_to_name',                                                
+                                                'direction' => CRM_Utils_Sort::DONTCARE,
+                                                ),
+                                          array(
+                                                'name'      => ts('Amount'),
+                                                'sort'      => 'amount',                                                
+                                                'direction' => CRM_Utils_Sort::DONTCARE,
+                                                ),
+                                          array('desc' => ts('Actions') ),
+                                          );
+        }
+        return self::$_columnHeaders;
+    }
+    
+    function &getQuery( ) {
+        return $this->_query;
+    }
+
+    /** 
+     * name of export file. 
+     * 
+     * @param string $output type of output 
+     * @return string name of the file 
+     */ 
+     function getExportFileName( $output = 'csv') { 
+         return ts('CiviCRM Grant Search'); 
+     } 
+
+}//end of class
+
+
diff --git a/CRM/Grant/Selector/Search.php b/CRM/Grant/Selector/Search.php
new file mode 100755
index 0000000..66b772c
--- /dev/null
+++ b/CRM/Grant/Selector/Search.php
@@ -0,0 +1,487 @@
+<?php
+/*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.1                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*/
+
+/**
+ *
+ * @package CRM
+ * @copyright CiviCRM LLC (c) 2004-2011
+ * $Id$
+ *
+ */
+
+require_once 'CRM/Core/Selector/Base.php';
+require_once 'CRM/Core/Selector/API.php';
+
+require_once 'CRM/Utils/Pager.php';
+require_once 'CRM/Utils/Sort.php';
+
+require_once 'CRM/Contact/BAO/Query.php';
+
+/**
+ * This class is used to retrieve and display a range of
+ * contacts that match the given criteria (specifically for
+ * results of advanced search options.
+ *
+ */
+class CRM_Grant_Selector_Search extends CRM_Core_Selector_Base implements CRM_Core_Selector_API 
+{
+    /**
+     * This defines two actions- View and Edit.
+     *
+     * @var array
+     * @static
+     */
+    static $_links = null;
+
+    /**
+     * we use desc to remind us what that column is, name is used in the tpl
+     *
+     * @var array
+     * @static
+     */
+    static $_columnHeaders;
+
+    /**
+     * Properties of contact we're interested in displaying
+     * @var array
+     * @static
+     */
+    static $_properties = array( 'contact_id', 
+                                 'contact_type',
+                                 'sort_name',
+                                 'grant_id',
+                                 'grant_status_id',
+                                 'grant_status',
+                                 'grant_type_id',
+                                 'grant_type',
+                                 'grant_amount_total',
+                                 'grant_amount_requested',
+                                 'grant_amount_granted',
+                                 'grant_application_received_date',
+                                 'course_type',
+                                 'course_name',
+                                 );
+
+    /** 
+     * are we restricting ourselves to a single contact 
+     * 
+     * @access protected   
+     * @var boolean   
+     */   
+    protected $_single = false;
+
+    /**  
+     * are we restricting ourselves to a single contact  
+     *  
+     * @access protected    
+     * @var boolean    
+     */    
+    protected $_limit = null;
+
+    /**
+     * what context are we being invoked from
+     *   
+     * @access protected     
+     * @var string
+     */     
+    protected $_context = null;
+
+    /**
+     * queryParams is the array returned by exportValues called on
+     * the HTML_QuickForm_Controller for that page.
+     *
+     * @var array
+     * @access protected
+     */
+    public $_queryParams; 
+
+    /**
+     * represent the type of selector
+     *
+     * @var int
+     * @access protected
+     */
+    protected $_action;
+
+    /** 
+     * The additional clause that we restrict the search with 
+     * 
+     * @var string 
+     */ 
+    protected $_grantClause = null;
+
+    /** 
+     * The query object
+     * 
+     * @var string 
+     */ 
+    protected $_query;
+
+    /**
+     * Class constructor
+     *
+     * @param array   $queryParams array of parameters for query
+     * @param int     $action - action of search basic or advanced.
+     * @param string  $grantClause if the caller wants to further restrict the search 
+     * @param boolean $single are we dealing only with one contact?
+     * @param int     $limit  how many participations do we want returned
+     *
+     * @return CRM_Contact_Selector
+     * @access public
+     */
+    function __construct(&$queryParams,
+                         $action = CRM_Core_Action::NONE,
+                         $grantClause = null,
+                         $single = false,
+                         $limit = null,
+                         $context = 'search' ) 
+    {
+        // submitted form values
+        $this->_queryParams =& $queryParams;
+        
+
+        $this->_single  = $single;
+        $this->_limit   = $limit;
+        $this->_context = $context;
+
+        $this->_grantClause = $grantClause;
+
+        // type of selector
+        $this->_action = $action;
+
+        $this->_query = new CRM_Contact_BAO_Query( $this->_queryParams, null, null, false, false,
+                                                    CRM_Contact_BAO_Query::MODE_GRANT );
+        $this->_query->_distinctComponentClause = " civicrm_grant.id";
+        $this->_query->_groupByComponentClause  = " GROUP BY civicrm_grant.id ";
+    }//end of constructor
+
+
+    /**
+     * This method returns the links that are given for each search row.
+     * currently the links added for each row are 
+     * 
+     * - View
+     * - Edit
+     *
+     * @return array
+     * @access public
+     *
+     */
+    static function &links( $key = null )
+    {       
+        $cid  = CRM_Utils_Request::retrieve('cid', 'Integer', $this);
+        $next = CRM_Utils_Request::retrieve('next', 'Integer', $this);
+        $prev = CRM_Utils_Request::retrieve('prev', 'Integer', $this);
+        $extraParams = ( $key ) ? "&key={$key}" : null;
+        
+        if (!(self::$_links)) {
+            self::$_links = array(
+                                  CRM_Core_Action::VIEW   => array(
+                                                                   'name'     => ts('View'),
+                                                                   'url'      => 'civicrm/contact/view/grant',
+                                                                   'qs'       => 'reset=1&id=%%id%%&cid=%%cid%%&action=view&context=%%cxt%%&selectedChild=grant'.$extraParams,
+                                                                   'title'    => ts('View Grant'),
+                                                                   ),
+                                  CRM_Core_Action::UPDATE => array(
+                                                                   'name'     => ts('Edit'),
+                                                                   'url'      => 'civicrm/contact/view/grant',
+                                                                   'qs'       => 'reset=1&action=update&id=%%id%%&cid=%%cid%%&context=%%cxt%%&next=%%next%%&prev=%%prev%%'.$extraParams,
+                                                                   'title'    => ts('Edit Grant'),
+                                                                  ),
+                                  );
+            
+              if ( $cid ) {
+                  $deleteExtra = ts('Are you sure you want to delete this grant?');
+                  
+                  $delLink = array( 
+                                 CRM_Core_Action::DELETE => array( 'name'  => ts('Delete'),
+                                                                   'url'   => 'civicrm/contact/view/grant',
+                                                                   'qs'    => 'action=delete&reset=1&cid=%%cid%%&id=%%id%%&selectedChild=grant'.$extraParams,
+                                                                   'extra' => 'onclick = "if (confirm(\'' . $deleteExtra . '\') ) this.href+=\'&amp;confirmed=1\'; else return false;"',
+                                                                   'title' => ts('Delete Grant')
+                                                                   )
+                                 );
+                  self::$_links =  self::$_links +  $delLink ;
+              }
+        }
+        return self::$_links;
+    } //end of function
+        
+    /**
+     * getter for array of the parameters required for creating pager.
+     *
+     * @param 
+     * @access public
+     */
+    function getPagerParams($action, &$params) 
+    {
+        $params['status']       = ts('Grant') . ' %%StatusMessage%%';
+        $params['csvString']    = null;
+        if ( $this->_limit ) {
+            $params['rowCount']     = $this->_limit;
+        } else {
+            $params['rowCount']     = CRM_Utils_Pager::ROWCOUNT;
+        }
+
+        $params['buttonTop']    = 'PagerTopButton';
+        
+        $params['buttonBottom'] = 'PagerBottomButton';
+    } //end of function
+
+    /**
+     * Returns total number of rows for the query.
+     *
+     * @param 
+     * @return int Total number of rows 
+     * @access public
+     */
+    function getTotalCount($action)
+    {
+        return $this->_query->searchQuery( 0, 0, null,
+                                           true, false, 
+                                           false, false, 
+                                           false, 
+                                           $this->_grantClause );
+    }
+
+    
+    /**
+     * returns all the rows in the given offset and rowCount     *
+     * @param enum   $action   the action being performed
+     * @param int    $offset   the row number to start from
+     * @param int    $rowCount the number of rows to return
+     * @param string $sort     the sql string that describes the sort order
+     * @param enum   $output   what should the result set include (web/email/csv)
+     *
+     * @return int   the total number of rows for this action
+     */
+     function &getRows($action, $offset, $rowCount, $sort, $output = null) 
+     {
+         $result = $this->_query->searchQuery( $offset, $rowCount, $sort,
+                                               false, false, 
+                                               false, false, 
+                                               false, 
+                                               $this->_grantClause );
+
+         // process the result of the query
+         $rows = array( );
+         
+         //CRM-4418 check for view, edit, delete
+         $permissions = array( CRM_Core_Permission::VIEW );
+         if ( CRM_Core_Permission::check( 'edit grants' ) ) {
+             $permissions[] = CRM_Core_Permission::EDIT;
+         }
+         if ( CRM_Core_Permission::check( 'delete in CiviGrant' ) ) {
+             $permissions[] = CRM_Core_Permission::DELETE;
+         }
+         $mask = CRM_Core_Action::mask( $permissions );
+         $grant = $this->_query->searchQuery( $offset, $rowCount, $sort,
+                                               false, false, 
+                                               false, false, 
+                                               false, 
+                                               $this->_grantClause );
+         while ($grant->fetch()) {
+           $grants[$grant->contact_id][$grant->id] = $grant->id;
+         }
+           
+         while ($result->fetch()) {
+           $row = array();
+           if ($result->id == CRM_Utils_Array::value('id',$_GET)) {
+             continue;
+           }
+           $prev = $next = null;
+           $foundit = false;
+           $contactGrants = $grants[$result->contact_id];
+           foreach( $contactGrants as $gKey => $gVal) {
+             if ($foundit) {
+               $next = $gKey; 
+               break;
+             }
+             if ($gKey == $result->id) {
+               $next = $gKey; 
+               if($gKey == end($contactGrants)) {
+                 reset($contactGrants);
+                 $next = key($contactGrants);
+               }
+               $foundit = true;
+             } else {
+               $prev = $gKey;
+             }
+           }
+           if(empty($prev)) {
+             $prev = end($contactGrants);
+           }
+           if ( isset( $result->course_type ) ) {
+             if ( !empty($result->course_type) ) {
+               if( $result->course_type != 'select_or_other' ) {
+                 $result->course_type = CRM_Core_DAO::singleValueQuery("SELECT civicrm_option_value.label as course_type FROM civicrm_option_value LEFT JOIN civicrm_option_group ON civicrm_option_group.id = civicrm_option_value.option_group_id  WHERE civicrm_option_value.value = {$result->course_type} AND  civicrm_option_group.name = 'course_conference_type_20120606094128'");
+               } else {
+                 $result->course_type = 'Other';
+               }
+             }
+           }
+           // the columns we are interested in
+           foreach (self::$_properties as $property) {
+             if ( isset( $result->$property ) ) {
+               $row[$property] = $result->$property;
+             }
+           }
+
+           if ($this->_context == 'search') {
+             $row['checkbox'] = CRM_Core_Form::CB_PREFIX . $result->grant_id;
+           }
+             
+           $row['action']   = CRM_Core_Action::formLink( self::links( $this->_key ), 
+                                                         $mask,
+                                                         array( 'id'   => $result->grant_id,
+                                                                'cid'  => $result->contact_id,
+                                                                'cxt'  => $this->_context,
+                                                                'prev' => $prev,
+                                                                'next' => $next) );
+             
+           require_once( 'CRM/Contact/BAO/Contact/Utils.php' );
+           $row['contact_type' ] = 
+             CRM_Contact_BAO_Contact_Utils::getImage( $result->contact_sub_type ? 
+                                                      $result->contact_sub_type : $result->contact_type ,false,$result->contact_id);
+
+           $rows[] = $row;
+          
+         }
+         return $rows;
+     }
+     
+     
+     /**
+      * @return array              $qill         which contains an array of strings
+      * @access public
+      */
+     
+     // the current internationalisation is bad, but should more or less work
+     // for most of "European" languages
+     public function getQILL( )
+     {
+         return $this->_query->qill( );
+     }
+     
+     /** 
+      * returns the column headers as an array of tuples: 
+     * (name, sortName (key to the sort array)) 
+     * 
+     * @param string $action the action being performed 
+     * @param enum   $output what should the result set include (web/email/csv) 
+     * 
+     * @return array the column headers that need to be displayed 
+     * @access public 
+     */ 
+    public function &getColumnHeaders( $action = null, $output = null ) 
+    {    
+      if ( ! isset( self::$_columnHeaders ) ) {
+        if(CRM_Utils_Array::value( 'qfKey',$_GET )) {
+          $statusHeader =  array(
+                                 array('name'      => ts('Status'),
+                                       'sort'      => 'grant_status',
+                                       'direction' => CRM_Utils_Sort::DONTCARE,
+                                       ),
+                                 );
+        } else{
+          $statusHeader =  array(
+                                 array('name'      => ts('Status'),
+                                       'sort'      => 'grant_status',
+                                       'direction' => CRM_Utils_Sort::DESCENDING,
+                                       ),
+                                 );
+        }
+          
+        self::$_columnHeaders = array(
+                                      array(
+                                            'name'      => ts('Type'),
+                                            'sort'      => 'grant_type_id',
+                                            'direction' => CRM_Utils_Sort::DONTCARE,
+                                            ),
+                                      array(
+                                            'name'      => ts('Requested'),
+                                            'sort'      => 'grant_amount_total',
+                                            'direction' => CRM_Utils_Sort::DONTCARE,
+                                            ),
+                                      array(
+                                            'name'      => ts('Granted'),
+                                            'sort'      => 'grant_amount_granted',
+                                            'direction' => CRM_Utils_Sort::DONTCARE,
+                                            ),
+                                      array(
+                                            'name'      => ts('Application Received'),
+                                            'sort'      => 'grant_application_received_date',                                                
+                                            'direction' => CRM_Utils_Sort::ASCENDING,
+                                            ),
+                                      array(
+                                            'name'      => ts('Course Name'),
+                                            'sort'      => 'course_conference_name_24',                                                
+                                            'direction' => CRM_Utils_Sort::DONTCARE,
+                                            ),
+                                      array(
+                                            'name'      => ts('Course Type'),
+                                            'sort'      => 'course_conference_type_21',                                                
+                                            'direction' => CRM_Utils_Sort::DONTCARE,
+                                            ),
+                                      array('desc' => ts('Actions') ),
+                                      );
+            
+        if ( ! $this->_single ) {
+          $pre = array( 
+                       array('desc' => ts('Contact Type') ),   
+                       array( 
+                             'name'      => ts('Name'), 
+                             'sort'      => 'sort_name', 
+                             'direction' => CRM_Utils_Sort::DONTCARE, 
+                              )
+                        );
+          self::$_columnHeaders = array_merge($pre, $statusHeader, self::$_columnHeaders);
+        } 
+        else {
+          self::$_columnHeaders = array_merge($statusHeader, self::$_columnHeaders);
+        }
+      }
+      return self::$_columnHeaders;
+    }
+    
+    function &getQuery( ) {
+        return $this->_query;
+    }
+
+    /** 
+     * name of export file. 
+     * 
+     * @param string $output type of output 
+     * @return string name of the file 
+     */ 
+     function getExportFileName( $output = 'csv') { 
+         return ts('CiviCRM Grant Search'); 
+     } 
+
+}//end of class
+
+
diff --git a/CRM/Grant/StateMachine/PaymentSearch.php b/CRM/Grant/StateMachine/PaymentSearch.php
new file mode 100755
index 0000000..d3d3299
--- /dev/null
+++ b/CRM/Grant/StateMachine/PaymentSearch.php
@@ -0,0 +1,117 @@
+<?php
+
+/*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.1                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*/
+
+/**
+ *
+ * @package CRM
+ * @copyright CiviCRM LLC (c) 2004-2011
+ * $Id$
+ *
+ */
+
+require_once 'CRM/Core/StateMachine.php';
+require_once 'CRM/Core/Action.php';
+require_once 'CRM/Grant/PaymentTask.php';
+
+class CRM_Grant_StateMachine_PaymentSearch extends CRM_Core_StateMachine
+{
+    /**
+     * The task that the wizard is currently processing
+     *
+     * @var string
+     * @protected
+     */
+    protected $_task;
+
+    /**
+     * class constructor
+     */
+    function __construct( $controller, $action = CRM_Core_Action::NONE )
+    {
+        parent::__construct( $controller, $action );
+        
+        $this->_pages = array( );
+        
+        $this->_pages['CRM_Grant_Form_PaymentSearch'] = null;
+        list( $task, $result ) = $this->taskName( $controller, 'PaymentSearch' );
+        $this->_task    = $task;
+        
+        if ( is_array( $task ) ) {
+            foreach ( $task as $t ) {
+                $this->_pages[$t] = null;
+            }
+        } else {
+            $this->_pages[$task] = null;
+        }
+
+        if ( $result ) {
+            $this->_pages['CRM_Grant_Form_Task_Result'] = null;
+        }
+        
+        $this->addSequentialPages( $this->_pages, $action );
+    }
+    
+    /**
+     * Determine the form name based on the action. This allows us
+     * to avoid using  conditional state machine, much more efficient
+     * and simpler
+     *
+     * @param CRM_Core_Controller $controller the controller object
+     *
+     * @return string the name of the form that will handle the task
+     * @access protected
+     */
+    function taskName( $controller, $formName = 'PaymentSearch' )
+    {
+        // total hack, check POST vars and then session to determine stuff
+        // fix value if print button is pressed
+        if ( CRM_Utils_Array::value( '_qf_' . $formName . '_next_print', $_POST ) ) {
+            $value = CRM_Grant_Task::PRINT_GRANTS;
+        } else {
+            $value = CRM_Utils_Array::value( 'task', $_POST );
+        }
+        if ( ! isset( $value ) ) {
+            $value = $this->_controller->get( 'task' );
+        }
+        $this->_controller->set( 'task', $value );
+        
+        return CRM_Grant_PaymentTask::getTask( $value );  
+    }
+    
+    /**
+     * return the form name of the task
+     *
+     * @return string
+     * @access public
+     */
+    function getTaskFormName( )
+    {
+        return CRM_Utils_String::getClassName( $this->_task );
+    }
+}
+
diff --git a/CRM/Grant/StateMachine/Search.php b/CRM/Grant/StateMachine/Search.php
new file mode 100755
index 0000000..e21c307
--- /dev/null
+++ b/CRM/Grant/StateMachine/Search.php
@@ -0,0 +1,117 @@
+<?php
+
+/*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.1                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*/
+
+/**
+ *
+ * @package CRM
+ * @copyright CiviCRM LLC (c) 2004-2011
+ * $Id$
+ *
+ */
+
+require_once 'CRM/Core/StateMachine.php';
+require_once 'CRM/Core/Action.php';
+require_once 'CRM/Grant/Task.php';
+
+class CRM_Grant_StateMachine_Search extends CRM_Core_StateMachine
+{
+    /**
+     * The task that the wizard is currently processing
+     *
+     * @var string
+     * @protected
+     */
+    protected $_task;
+
+    /**
+     * class constructor
+     */
+    function __construct( $controller, $action = CRM_Core_Action::NONE )
+    {
+        parent::__construct( $controller, $action );
+        
+        $this->_pages = array( );
+        
+        $this->_pages['CRM_Grant_Form_Search'] = null;
+        list( $task, $result ) = $this->taskName( $controller, 'Search' );
+        $this->_task    = $task;
+        
+        if ( is_array( $task ) ) {
+            foreach ( $task as $t ) {
+                $this->_pages[$t] = null;
+            }
+        } else {
+            $this->_pages[$task] = null;
+        }
+
+        if ( $result ) {
+            $this->_pages['CRM_Grant_Form_Task_Result'] = null;
+        }
+        
+        $this->addSequentialPages( $this->_pages, $action );
+    }
+    
+    /**
+     * Determine the form name based on the action. This allows us
+     * to avoid using  conditional state machine, much more efficient
+     * and simpler
+     *
+     * @param CRM_Core_Controller $controller the controller object
+     *
+     * @return string the name of the form that will handle the task
+     * @access protected
+     */
+    function taskName( $controller, $formName = 'Search' )
+    {
+        // total hack, check POST vars and then session to determine stuff
+        // fix value if print button is pressed
+        if ( CRM_Utils_Array::value( '_qf_' . $formName . '_next_print', $_POST ) ) {
+            $value = CRM_Grant_Task::PRINT_GRANTS;
+        } else {
+            $value = CRM_Utils_Array::value( 'task', $_POST );
+        }
+        if ( ! isset( $value ) ) {
+            $value = $this->_controller->get( 'task' );
+        }
+        $this->_controller->set( 'task', $value );
+        
+        return CRM_Grant_Task::getTask( $value );  
+    }
+    
+    /**
+     * return the form name of the task
+     *
+     * @return string
+     * @access public
+     */
+    function getTaskFormName( )
+    {
+        return CRM_Utils_String::getClassName( $this->_task );
+    }
+}
+
diff --git a/CRM/Grant/Task.php b/CRM/Grant/Task.php
new file mode 100755
index 0000000..ed7803d
--- /dev/null
+++ b/CRM/Grant/Task.php
@@ -0,0 +1,173 @@
+<?php
+
+/*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.1                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*/
+
+/**
+ *
+ * @package CRM
+ * @copyright CiviCRM LLC (c) 2004-2011
+ * $Id$
+ *
+ */
+
+/**
+ * class to represent the actions that can be performed on a group of contacts
+ * used by the search forms
+ *
+ */
+class CRM_Grant_Task
+{
+    const
+        DELETE_GRANTS                     =     1,
+        PRINT_GRANTS                      =     2,
+        EXPORT_GRANTS                     =     3, 
+        UPDATE_GRANTS                     =     4,
+        PAY_GRANTS                        =     5;
+     
+    /**
+     * the task array
+     *
+     * @var array
+     * @static
+     */
+    static $_tasks = null;
+
+    /**
+     * the optional task array
+     *
+     * @var array
+     * @static
+     */
+    static $_optionalTasks = null;
+
+    /**
+     * These tasks are the core set of tasks that the user can perform
+     * on a contact / group of contacts
+     *
+     * @return array the set of tasks for a group of contacts
+     * @static
+     * @access public
+     */
+    static function &tasks( )
+    {
+        if ( !( self::$_tasks ) ) {
+            self::$_tasks = array( 1 => array( 'title'  => ts( 'Delete Grants' ),
+                                               'class'  => 'CRM_Grant_Form_Task_Delete',
+                                               'result' => false ),
+                                   2 => array( 'title'  => ts( 'Print Grants' ),
+                                               'class'  => 'CRM_Grant_Form_Task_Print',
+                                               'result' => false ),
+                                   3 => array( 'title'  => ts( 'Export Grants' ),
+                                               'class'  => array( 'CRM_Export_Form_Select',
+                                                                  'CRM_Export_Form_Map' ),
+                                               'result' => false ),
+                                   4 => array( 'title'  => ts( 'Update Grants' ),
+                                               'class'  => 'CRM_Grant_Form_Task_Update',
+                                               'result' => false ),
+                                   5 => array( 'title'  => ts( 'Pay Grants' ),
+                                               'class'  => array( 'CRM_Grant_Form_Task_Pay',
+                                                                  'CRM_Grant_Form_Task_GrantPayment' ),
+                                               'result' => false ),
+                                   
+                                   );
+        }
+        if ( !CRM_Core_Permission::check( 'delete in CiviGrant' ) ) {
+            unset( self::$_tasks[1] );
+        }
+        require_once 'CRM/Utils/Hook.php';
+        CRM_Utils_Hook::searchTasks( 'grant', self::$_tasks );
+        asort( self::$_tasks );
+        return self::$_tasks;
+    }
+    
+    /**
+     * These tasks are the core set of task titles
+     *
+     * @return array the set of task titles 
+     * @static
+     * @access public
+     */
+    static function &taskTitles( )
+    {
+        self::tasks( );
+        $titles = array( );
+        foreach ( self::$_tasks as $id => $value ) {
+            // skip Print Grant task
+            if ( $id != 2 ) {
+                $titles[$id] = $value['title'];
+            }
+        }      
+        return $titles;
+    }
+    
+    /**
+     * show tasks selectively based on the permission level
+     * of the user
+     *
+     * @param int $permission
+     *
+     * @return array set of tasks that are valid for the user
+     * @access public
+     */
+    static function &permissionedTaskTitles( $permission ) 
+    {
+        $tasks = array( );
+        if ( ( $permission == CRM_Core_Permission::EDIT ) 
+             || CRM_Core_Permission::check( 'edit grants' ) ) {
+            $tasks = self::taskTitles( );
+        } else {
+            $tasks = array(
+                           3 => self::$_tasks[3]['title'] );
+            //CRM-4418,
+            if ( CRM_Core_Permission::check( 'delete in CiviGrant' ) ) {
+                $tasks[1] = self::$_tasks[1]['title']; 
+            }
+        }
+        return $tasks;
+    }
+    
+    /**
+     * These tasks are the core set of tasks that the user can perform
+     *
+     * @param int $value
+     *
+     * @return array the set of tasks for a group of contacts
+     * @static
+     * @access public
+     */
+    static function getTask( $value ) 
+    {
+        self::tasks( );
+        if ( ! $value  || ! CRM_Utils_Array::value( $value, self::$_tasks ) ) {
+            // make the print task by default
+            $value = 2; 
+        }
+        return array( self::$_tasks[$value]['class' ],
+                      self::$_tasks[$value]['result'] );
+    }
+}
+
diff --git a/CRM/Grant/Words.php b/CRM/Grant/Words.php
new file mode 100755
index 0000000..7c4e14f
--- /dev/null
+++ b/CRM/Grant/Words.php
@@ -0,0 +1,158 @@
+<?php
+
+/*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.1                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*/
+
+/**
+ *
+ * @package CRM
+ * @copyright CiviCRM LLC (c) 2004-2011
+ * $Id$
+ *
+ */
+
+/**
+ * class to represent the actions that can be performed on a group of contacts
+ * used by the search forms
+ *
+ */
+class CRM_Grant_Words
+{
+
+    function convert_number_to_words($number) {
+   
+        $hyphen      = '-';
+        $conjunction = ' and ';
+        $separator   = ', ';
+        $negative    = 'negative ';
+        $decimal     = ' and ';
+        $dictionary  = array(
+                             0                   => 'zero',
+                             1                   => 'one',
+                             2                   => 'two',
+                             3                   => 'three',
+                             4                   => 'four',
+                             5                   => 'five',
+                             6                   => 'six',
+                             7                   => 'seven',
+                             8                   => 'eight',
+                             9                   => 'nine',
+                             10                  => 'ten',
+                             11                  => 'eleven',
+                             12                  => 'twelve',
+                             13                  => 'thirteen',
+                             14                  => 'fourteen',
+                             15                  => 'fifteen',
+                             16                  => 'sixteen',
+                             17                  => 'seventeen',
+                             18                  => 'eighteen',
+                             19                  => 'nineteen',
+                             20                  => 'twenty',
+                             30                  => 'thirty',
+                             40                  => 'fourty',
+                             50                  => 'fifty',
+                             60                  => 'sixty',
+                             70                  => 'seventy',
+                             80                  => 'eighty',
+                             90                  => 'ninety',
+                             100                 => 'hundred',
+                             1000                => 'thousand',
+                             1000000             => 'million',
+                             1000000000          => 'billion',
+                             1000000000000       => 'trillion',
+                             1000000000000000    => 'quadrillion',
+                             1000000000000000000 => 'quintillion'
+                             );
+   
+        if (!is_numeric($number)) {
+            return false;
+        }
+   
+        if (($number >= 0 && (int) $number < 0) || (int) $number < 0 - PHP_INT_MAX) {
+            // overflow
+            trigger_error(
+                          'convert_number_to_words only accepts numbers between -' . PHP_INT_MAX . ' and ' . PHP_INT_MAX,
+                          E_USER_WARNING
+                          );
+            return false;
+        }
+
+        if ($number < 0) {
+            return $negative . convert_number_to_words(abs($number));
+        }
+   
+        $string = $fraction = null;
+   
+        if (strpos($number, '.') !== false) {
+            list($number, $fraction) = explode('.', $number);
+        }
+   
+        switch (true) {
+        case $number < 21:
+            $string = $dictionary[$number];
+            break;
+        case $number < 100:
+            $tens   = ((int) ($number / 10)) * 10;
+            $units  = $number % 10;
+            $string = $dictionary[$tens];
+            if ($units) {
+                $string .= $hyphen . $dictionary[$units];
+            }
+            break;
+        case $number < 1000:
+            $hundreds  = $number / 100;
+            $remainder = $number % 100;
+            $string = $dictionary[$hundreds] . ' ' . $dictionary[100];
+            if ($remainder) {
+                
+                $string .= $conjunction . self::convert_number_to_words(abs($remainder));
+            }
+            break;
+        default:
+            $baseUnit = pow(1000, floor(log($number, 1000)));
+            $numBaseUnits = (int) ($number / $baseUnit);
+            $remainder = $number % $baseUnit;
+            $string = self::convert_number_to_words($numBaseUnits) . ' ' . $dictionary[$baseUnit];
+            if ($remainder) {
+                $string .= $remainder < 100 ? $conjunction : $separator;
+                $string .= self::convert_number_to_words($remainder);
+            }
+            break;
+        }
+   
+        if (null !== $fraction && is_numeric($fraction)) {
+            $string .= $decimal;
+            //$words = array();
+            $string .= $fraction.'/100';
+            // foreach (str_split((string) $fraction) as $number) {
+            //     $words[] = $dictionary[$number];
+            // }
+            // $string .= implode(' ', $words);
+        }
+        return $string;
+    }
+ 
+}
\ No newline at end of file
diff --git a/CRM/Grant/xml/Menu/Grant.xml b/CRM/Grant/xml/Menu/Grant.xml
new file mode 100755
index 0000000..815ed2f
--- /dev/null
+++ b/CRM/Grant/xml/Menu/Grant.xml
@@ -0,0 +1,92 @@
+<?xml version="1.0" encoding="iso-8859-1" ?>
+
+<menu>
+  <item>
+     <path>civicrm/grant</path>
+     <title>CiviGrant Dashboard</title>
+     <page_callback>CRM_Grant_Page_DashBoard</page_callback>
+     <access_arguments>access CiviGrant</access_arguments>
+     <page_type>1</page_type>
+     <weight>1000</weight>
+     <component>CiviGrant</component>
+  </item>
+  <item>
+     <path>civicrm/grant/info</path>
+     <access_arguments>access CiviGrant</access_arguments>
+     <weight>0</weight>
+  </item>
+  <item>
+     <path>civicrm/grant/search</path>
+     <title>Find Grants</title>
+     <page_callback>CRM_Grant_Controller_Search</page_callback>
+     <access_arguments>access CiviGrant</access_arguments>
+     <page_type>1</page_type>
+     <weight>1010</weight>
+  </item>
+  <item>
+     <path>civicrm/grant/add</path>
+     <title>New Grant</title>
+     <page_callback>CRM_Grant_Page_Tab</page_callback>
+     <path_arguments>action=add</path_arguments>
+     <access_arguments>access CiviGrant</access_arguments>
+     <page_type>1</page_type>
+     <component>CiviGrant</component>
+  </item>
+  <item>
+     <path>civicrm/contact/view/grant</path>
+     <page_callback>CRM_Grant_Page_Tab</page_callback>
+     <access_arguments>access CiviGrant</access_arguments>
+  </item>
+   <item>
+     <path>civicrm/grant_program</path>
+     <title>Grant Programs</title>
+     <desc>List of grant programs which can be assigned to Grants</desc>
+     <page_callback>CRM_Grant_Page_GrantProgram</page_callback>
+     <access_arguments>edit grant program</access_arguments>
+     <page_type>1</page_type>
+     <weight>1011</weight>
+  </item> 
+  <item>
+     <path>civicrm/grant/payment</path>
+     <title>Grant Payment</title>
+     <desc>Grant Payment.</desc>
+     <page_callback>CRM_Grant_Page_Payment</page_callback>
+     <access_arguments>access CiviCRM</access_arguments>
+  </item>
+  <item>
+     <path>civicrm/grant/payment/search</path>
+     <title>Find Grant Payments</title>
+     <page_callback>CRM_Grant_Controller_PaymentSearch</page_callback>
+     <access_arguments>access CiviGrant</access_arguments>
+     <page_type>1</page_type>
+     <component>CiviGrant</component>
+  </item>   
+  <item>
+     <path>civicrm/grant/payment/reprint</path>
+     <title>Grant Payment Reprint</title>
+     <desc>Grant Payment Reprint.</desc>
+     <path_arguments>action=add</path_arguments>
+     <page_callback>CRM_Grant_Form_Task_GrantPayment</page_callback>
+     <access_arguments>access CiviGrant</access_arguments>
+  </item>  
+  <item>
+     <path>civicrm/grant_program/allocate</path>
+     <page_callback>CRM_Grant_Form_GrantProgramView::allocate</page_callback> 
+     <access_arguments>access CiviCRM</access_arguments> 
+  </item>
+  <item>
+     <path>civicrm/grant_program/finalize</path>
+     <page_callback>CRM_Grant_Form_GrantProgramView::finalize</page_callback> 
+     <access_arguments>access CiviCRM</access_arguments> 
+  </item>
+  <item>
+     <path>civicrm/grant_program/reject</path>
+     <page_callback>CRM_Grant_Form_GrantProgramView::reject</page_callback> 
+     <access_arguments>access CiviCRM</access_arguments> 
+  </item>
+  <item>
+     <path>civicrm/grant_program/processFinalization</path>
+     <page_callback>CRM_Grant_Form_GrantProgramView::processFinalization</page_callback> 
+     <access_arguments>access CiviCRM</access_arguments> 
+  </item>
+</menu>
diff --git a/grantprograms.civix.php b/grantprograms.civix.php
new file mode 100644
index 0000000..cb7f037
--- /dev/null
+++ b/grantprograms.civix.php
@@ -0,0 +1,169 @@
+<?php
+
+// AUTO-GENERATED FILE -- Civix may overwrite any changes made to this file
+
+/**
+ * (Delegated) Implementation of hook_civicrm_config
+ */
+function _grantprograms_civix_civicrm_config(&$config = NULL) {
+  static $configured = FALSE;
+  if ($configured) return;
+  $configured = TRUE;
+
+  $template =& CRM_Core_Smarty::singleton();
+
+  $extRoot = dirname( __FILE__ ) . DIRECTORY_SEPARATOR;
+  $extDir = $extRoot . 'templates';
+
+  if ( is_array( $template->template_dir ) ) {
+      array_unshift( $template->template_dir, $extDir );
+  } else {
+      $template->template_dir = array( $extDir, $template->template_dir );
+  }
+
+  $include_path = $extRoot . PATH_SEPARATOR . get_include_path( );
+  set_include_path( $include_path );
+}
+
+/**
+ * (Delegated) Implementation of hook_civicrm_xmlMenu
+ *
+ * @param $files array(string)
+ */
+function _grantprograms_civix_civicrm_xmlMenu(&$files) {
+  foreach (_grantprograms_civix_glob(__DIR__ . '/xml/Menu/*.xml') as $file) {
+    $files[] = $file;
+  }
+}
+
+/**
+ * Implementation of hook_civicrm_install
+ */
+function _grantprograms_civix_civicrm_install() {
+  _grantprograms_civix_civicrm_config();
+  if ($upgrader = _grantprograms_civix_upgrader()) {
+    return $upgrader->onInstall();
+  }
+}
+
+/**
+ * Implementation of hook_civicrm_uninstall
+ */
+function _grantprograms_civix_civicrm_uninstall() {
+  _grantprograms_civix_civicrm_config();
+  if ($upgrader = _grantprograms_civix_upgrader()) {
+    return $upgrader->onUninstall();
+  }
+}
+
+/**
+ * (Delegated) Implementation of hook_civicrm_enable
+ */
+function _grantprograms_civix_civicrm_enable() {
+  _grantprograms_civix_civicrm_config();
+  if ($upgrader = _grantprograms_civix_upgrader()) {
+    if (is_callable(array($upgrader, 'onEnable'))) {
+      return $upgrader->onEnable();
+    }
+  }
+}
+
+/**
+ * (Delegated) Implementation of hook_civicrm_disable
+ */
+function _grantprograms_civix_civicrm_disable() {
+  _grantprograms_civix_civicrm_config();
+  if ($upgrader = _grantprograms_civix_upgrader()) {
+    if (is_callable(array($upgrader, 'onDisable'))) {
+      return $upgrader->onDisable();
+    }
+  }
+}
+
+/**
+ * (Delegated) Implementation of hook_civicrm_upgrade
+ *
+ * @param $op string, the type of operation being performed; 'check' or 'enqueue'
+ * @param $queue CRM_Queue_Queue, (for 'enqueue') the modifiable list of pending up upgrade tasks
+ *
+ * @return mixed  based on op. for 'check', returns array(boolean) (TRUE if upgrades are pending)
+ *                for 'enqueue', returns void
+ */
+function _grantprograms_civix_civicrm_upgrade($op, CRM_Queue_Queue $queue = NULL) {
+  if ($upgrader = _grantprograms_civix_upgrader()) {
+    return $upgrader->onUpgrade($op, $queue);
+  }
+}
+
+function _grantprograms_civix_upgrader() {
+  if (!file_exists(__DIR__.'/CRM/Grantprograms/Upgrader.php')) {
+    return NULL;
+  } else {
+    return CRM_Grantprograms_Upgrader_Base::instance();
+  }
+}
+
+/**
+ * Search directory tree for files which match a glob pattern
+ *
+ * @param $dir string, base dir
+ * @param $pattern string, glob pattern, eg "*.txt"
+ * @return array(string)
+ */
+function _grantprograms_civix_find_files($dir, $pattern) {
+  $todos = array($dir);
+  $result = array();
+  while (!empty($todos)) {
+    $subdir = array_shift($todos);
+    foreach (_grantprograms_civix_glob("$subdir/$pattern") as $match) {
+      if (!is_dir($match)) {
+        $result[] = $match;
+      }
+    }
+    if ($dh = opendir($subdir)) {
+      while (FALSE !== ($entry = readdir($dh))) {
+        $path = $subdir . DIRECTORY_SEPARATOR . $entry;
+        if ($entry == '.' || $entry == '..') {
+        } elseif (is_dir($path)) {
+          $todos[] = $path;
+        }
+      }
+      closedir($dh);
+    }
+  }
+  return $result;
+}
+/**
+ * (Delegated) Implementation of hook_civicrm_managed
+ *
+ * Find any *.mgd.php files, merge their content, and return.
+ */
+function _grantprograms_civix_civicrm_managed(&$entities) {
+  $mgdFiles = _grantprograms_civix_find_files(__DIR__, '*.mgd.php');
+  foreach ($mgdFiles as $file) {
+    $es = include $file;
+    foreach ($es as $e) {
+      if (empty($e['module'])) {
+        $e['module'] = 'biz.jmaconsulting.grantprograms';
+      }
+      $entities[] = $e;
+    }
+  }
+}
+
+/**
+ * Glob wrapper which is guaranteed to return an array.
+ *
+ * The documentation for glob() says, "On some systems it is impossible to
+ * distinguish between empty match and an error." Anecdotally, the return
+ * result for an empty match is sometimes array() and sometimes FALSE.
+ * This wrapper provides consistency.
+ *
+ * @see http://php.net/glob
+ * @param string $pattern
+ * @return array, possibly empty
+ */
+function _grantprograms_civix_glob($pattern) {
+  $result = glob($pattern);
+  return is_array($result) ? $result : array();
+}
diff --git a/grantprograms.php b/grantprograms.php
new file mode 100644
index 0000000..798f6b7
--- /dev/null
+++ b/grantprograms.php
@@ -0,0 +1,154 @@
+<?php
+
+require_once 'grantprograms.civix.php';
+
+/**
+ * Implementation of hook_civicrm_config
+ */
+function grantprograms_civicrm_config(&$config) {
+  _grantprograms_civix_civicrm_config($config);
+}
+
+/**
+ * Implementation of hook_civicrm_xmlMenu
+ *
+ * @param $files array(string)
+ */
+function grantprograms_civicrm_xmlMenu(&$files) {
+  _grantprograms_civix_civicrm_xmlMenu($files);
+}
+
+/**
+ * Implementation of hook_civicrm_install
+ */
+function grantprograms_civicrm_install() {
+  return _grantprograms_civix_civicrm_install();
+}
+
+/**
+ * Implementation of hook_civicrm_uninstall
+ */
+function grantprograms_civicrm_uninstall() {
+  return _grantprograms_civix_civicrm_uninstall();
+}
+
+/**
+ * Implementation of hook_civicrm_enable
+ */
+function grantprograms_civicrm_enable() {
+  return _grantprograms_civix_civicrm_enable();
+}
+
+/**
+ * Implementation of hook_civicrm_disable
+ */
+function grantprograms_civicrm_disable() {
+  return _grantprograms_civix_civicrm_disable();
+}
+
+/**
+ * Implementation of hook_civicrm_upgrade
+ *
+ * @param $op string, the type of operation being performed; 'check' or 'enqueue'
+ * @param $queue CRM_Queue_Queue, (for 'enqueue') the modifiable list of pending up upgrade tasks
+ *
+ * @return mixed  based on op. for 'check', returns array(boolean) (TRUE if upgrades are pending)
+ *                for 'enqueue', returns void
+ */
+function grantprograms_civicrm_upgrade($op, CRM_Queue_Queue $queue = NULL) {
+  return _grantprograms_civix_civicrm_upgrade($op, $queue);
+}
+
+/**
+ * Implementation of hook_civicrm_managed
+ *
+ * Generate a list of entities to create/deactivate/delete when this module
+ * is installed, disabled, uninstalled.
+ */
+function grantprograms_civicrm_managed(&$entities) {
+  return _grantprograms_civix_civicrm_managed($entities);
+}
+
+
+function grantprograms_civicrm_grantAssessment( &$params ) { 
+  if ( array_key_exists('custom', $params ) ) {
+    $threeYearsBackDate = date('Y',strtotime("-1 year")).'-01-01';
+    $previousYear       = date('Y',strtotime("-1 year")).'-12-31';
+    $result = CRM_Core_DAO::executeQuery("SELECT id, contact_id, application_received_date, amount_granted, status_id FROM civicrm_grant WHERE status_id = 4 AND application_received_date >= '{$threeYearsBackDate}' AND application_received_date <= '{$previousYear}' AND contact_id = {$params['contact_id']}");
+    $grantThresholds = CRM_Core_OptionGroup::values( 'grant_thresholds' );
+    $grantThresholds = array_flip($grantThresholds);
+    if ( $result->N ) {
+      while( $result->fetch() ) {
+        if ( $result->amount_granted >= $grantThresholds['Maximum Grant'] ) {
+          //$years[$result->application_received_date] = $result->amount_granted;
+          $priority = 10;
+        } else {
+          $priority = 0;
+        }
+      }
+    } else {
+      $priority = -10;
+    }
+    
+    if( array_key_exists( 'assessment', $params ) ) {
+      if ( $params['assessment'] != 0 ) {
+        $params['assessment'] = $params['assessment'] - $priority;//- 5 * count($years) - $priority;
+      }
+    }
+  }
+}
+
+function grantprograms_civicrm_buildForm( $formName, &$form  ) {
+
+  if ($formName = 'CRM_Grant_Form_Grant'  ) {
+    if ( $form->getVar('_name') == 'Grant' ) {
+      $form->_reasonGrantRejected = CRM_Core_OptionGroup::values( 'reason_grant_rejected' );
+      $form->add('select', 'grant_rejected_reason_id',  ts( 'Reason Grant Rejected' ),
+                 array( '' => ts( '- select -' ) ) + $form->_reasonGrantRejected , false);
+
+      $form->_grantPrograms = CRM_Grant_BAO_Grant::getGrantPrograms();
+      $form->add('select', 'grant_program_id',  ts( 'Grant Programs' ),
+                 array( '' => ts( '- select -' ) ) + $form->_grantPrograms , true);
+    
+      if ( CRM_Core_Permission::check('administer CiviGrant')  ) {
+        $form->add( 'text', 'assessment', ts( 'Assessment' ) );
+      }
+    } elseif ( $form->getVar('_name') == 'Search' ) {
+      $grantPrograms = CRM_Grant_BAO_Grant::getGrantPrograms();
+      $form->add('select', 'grant_program_id',  ts( 'Grant Programs' ),
+                 array( '' => ts( '- select -' ) ) + $grantPrograms);
+      $form->add('text', 'grant_amount_total_low', ts('From'), array( 'size' => 8, 'maxlength' => 8 ) ); 
+      $form->addRule('grant_amount_total_low', ts('Please enter a valid money value (e.g. %1).', array(1 => CRM_Utils_Money::format('9.99', ' '))), 'money');
+        
+      $form->add('text', 'grant_amount_total_high', ts('To'), array( 'size' => 8, 'maxlength' => 8 ) ); 
+      $form->addRule('grant_amount_total_high', ts('Please enter a valid money value (e.g. %1).', array(1 => CRM_Utils_Money::format('99.99', ' '))), 'money');
+      $form->add('text', 'grant_assessment_low', ts('From'), array( 'size' => 9, 'maxlength' => 9 ) );
+        
+      $form->add('text', 'grant_assessment_high', ts('To'), array( 'size' => 9, 'maxlength' => 9 ) );
+    }
+  }
+  
+  if ($formName == 'CRM_Custom_Form_Field') {
+    
+    for($i = 1; $i <= $formName::NUM_OPTION; $i++) {
+      $form->add('text', 'option_description['.$i.']', 'Marks', array( 'id' => 'marks') );
+    } 
+  }
+  if( $formName == 'CRM_Custom_Form_Option'  ) {
+    $form->add('text', 'description', 'Marks', array( 'id' => 'marks') );
+  }
+}
+
+function grantprograms_civicrm_validate( $formName, &$fields, &$files, &$form ) {
+  
+  if ( $formName == 'CRM_Grant_Form_Grant' ) {
+    $errors = array();
+    require_once 'CRM/Grant/BAO/GrantProgram.php';
+    $params['grant_program_id'] = $form->_submitValues['grant_program_id'];
+    CRM_Grant_BAO_GrantProgram::retrieve( $params, $defaults);
+    if ( $defaults['remainder_amount'] < $form->_submitValues['amount_granted'] ) {
+      $errors['amount_granted'] = ts( 'You need to increase the Grant Program Total Amount' );
+    }
+  }
+  return empty($errors) ? true : $errors;
+}
\ No newline at end of file
diff --git a/info.xml b/info.xml
new file mode 100644
index 0000000..4b0735e
--- /dev/null
+++ b/info.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<extension key="biz.jmaconsulting.grantprograms" type="module">
+  <file>grantprograms</file>
+  <name>GrantProgram</name>
+  <description>GrantProgram</description>
+  <license>FIXME</license>
+  <maintainer>
+    <author>Jma Consulting</author>
+    <email>info@jmaconsulting.biz</email>
+  </maintainer>
+  <releaseDate>2013-03-13</releaseDate>
+  <version>1.0.beta1</version>
+  <develStage>beta</develStage>
+  <compatibility>
+    <ver>4.2</ver>
+  </compatibility>
+  <comments>This is a new, undeveloped module</comments>
+  <civix>
+    <namespace>CRM/Grantprograms</namespace>
+  </civix>
+</extension>
diff --git a/templates/CRM/Grant/Form/Grant.tpl b/templates/CRM/Grant/Form/Grant.tpl
new file mode 100755
index 0000000..7fc0db1
--- /dev/null
+++ b/templates/CRM/Grant/Form/Grant.tpl
@@ -0,0 +1,173 @@
+{*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.1                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*}
+{* this template is used for adding/editing/deleting grant *}
+
+{if $action eq 1 and $context ne 'standalone'}
+	<h3>{ts}New Grant{/ts}</h3>
+{elseif $action eq 2}
+	<h3>{ts}Edit Grant{/ts}</h3>
+{elseif $action eq 8}
+	<h3>{ts}Delete Grant{/ts}</h3>
+{/if}
+
+<div class="crm-block crm-form-block crm-grant-form-block">
+
+  {if $action eq 8} 
+      <div class="messages status">
+             <p><div class="icon inform-icon"></div>&nbsp;
+             {ts}Are you sure you want to delete this Grant?{/ts} {ts}This operation cannot be undone.{/ts}</p>
+             <p>{include file="CRM/Grant/Form/Task.tpl"}</p>
+      </div>
+  {else}
+
+<div class="crm-submit-buttons">{include file="CRM/common/formButtons.tpl" location="top"}</div> 	
+
+		<table class="form-layout-compressed">  
+		    {if $context eq 'standalone'}
+                {include file="CRM/Contact/Form/NewContact.tpl"}
+            {/if}
+			<tr class="crm-grant-form-block-status_id">
+			     <td class="label">{$form.status_id.label}</td>
+			     <td>{$form.status_id.html}</td>
+			</tr>
+			<tr class="crm-grant-form-block-grant_rejected_reason_id grant_rejected_reason_id">
+			     <td class="label">{$form.grant_rejected_reason_id.label}</td>
+			     <td>{$form.grant_rejected_reason_id.html}</td>
+			</tr>  
+			<tr class="crm-grant-form-block-grant_type_id">
+			     <td class="label">{$form.grant_type_id.label}</td>
+			     <td>{$form.grant_type_id.html}</td>
+			</tr>
+			<tr class="crm-grant-form-block-grant_program_id">
+			     <td class="label">{$form.grant_program_id.label}</td>
+			     <td>{$form.grant_program_id.html}</td>
+			</tr>  
+			<tr class="crm-grant-form-block-amount_total">
+			     <td class="label">{$form.amount_total.label}</td>
+			     <td>{$form.amount_total.html}</td>
+			</tr>
+			<tr class="crm-grant-form-block-amount_requested">
+			     <td class="label">{$form.amount_requested.label}</td>
+			     <td>{$form.amount_requested.html}<br />
+                	     <span class="description">{ts}Amount requested for grant in original currency (if different).{/ts}</span></td>
+		        </tr>
+			<tr class="crm-grant-form-block-assessment">
+			     <td class="label">{$form.assessment.label}</td>
+			     <td>{$form.assessment.html}</td>
+		        </tr>
+			<tr class="crm-grant-form-block-amount_granted">
+			     <td class="label">{$form.amount_granted.label}</td>
+			     <td>{$form.amount_granted.html}</td>
+		        </tr>
+
+			<tr class="crm-grant-form-block-application_received_date">
+			     <td class="label">{$form.application_received_date.label}</td>
+				<td>
+    				{if $hideCalendar neq true}
+                        {include file="CRM/common/jcalendar.tpl" elementName=application_received_date}
+                    {else}
+                        {$form.application_received_date.html|crmDate}
+                    {/if}
+				</td>
+			</tr>
+			<tr class="crm-grant-form-block-decision_date"><td class="label">{$form.decision_date.label}</td>
+			<td>{if $hideCalendar neq true}
+                    {include file="CRM/common/jcalendar.tpl" elementName=decision_date}
+                {else}
+                    {$form.decision_date.html|crmDate}
+                {/if}
+			<br />
+                <span class="description">{ts}Date on which the grant decision was finalized.{/ts}</span></td></tr>
+			<tr class="crm-grant-form-block-money_transfer_date"><td class="label">{$form.money_transfer_date.label}</td>
+				<td>{if $hideCalendar neq true}
+                        {include file="CRM/common/jcalendar.tpl" elementName=money_transfer_date}
+                    {else}
+                        {$form.money_transfer_date.html|crmDate}
+                    {/if}<br />
+                    <span class="description">{ts}Date on which the grant money was transferred.{/ts}</span></td></tr>
+			<tr class="crm-grant-form-block-grant_due_date"><td class="label">{$form.grant_due_date.label}</td>
+				<td>
+				    {if $hideCalendar neq true}
+                        {include file="CRM/common/jcalendar.tpl" elementName=grant_due_date}
+                    {else}
+                        {$form.grant_due_date.html|crmDate}
+                    {/if}
+				</td>
+			</tr>
+			<tr class="crm-grant-form-block-grant_report_received"><td class="label">{$form.grant_report_received.label}</td><td>{$form.grant_report_received.html}</td></tr>
+			<tr class="crm-grant-form-block-rationale"><td class="label">{$form.rationale.label}</td><td>{$form.rationale.html}</td></tr>
+			<tr class="crm-grant-form-block-note">
+			     <td class="label">{$form.note.label}</td>
+			     <td>{$form.note.html}</td>
+			</tr>
+
+		</table>
+		
+		<div class="crm-grant-form-block-custom_data">
+		     {include file="CRM/Custom/Form/CustomData.tpl"}
+		</div>
+		<div class="crm-grant-form-block-attachment">
+		     {include file="CRM/Form/attachment.tpl"}
+		</div>
+
+   {/if}
+<div class="crm-submit-buttons">{include file="CRM/common/formButtons.tpl" location="bottom"}</div>
+</div>
+{if $pager->_totalItems}
+<h3>{ts}Recent Grants{/ts}</h3>
+    <div class="form-item">
+        {include file="CRM/Grant/Form/Selector.tpl" context="DashBoard"}
+    </div>
+{/if}
+ <script type="text/javascript">
+    {literal}
+var total = 0;
+cj(".form-select").change(function(){
+cj(".form-select").each(function(){
+
+var name = cj(this).attr('id');
+    var customName = name.split('_');
+if ( customName[0] == 'custom' ) {
+   total += parseInt(cj('#'+name).val());
+}
+});
+});
+cj(document).ready(function(){
+if ( cj("#status_id option:selected").text() == 'Rejected') {
+  cj('.grant_rejected_reason_id').show();
+} else {
+  cj('.grant_rejected_reason_id').hide();
+}
+cj('#status_id').change(function(){
+if ( this.options[this.selectedIndex].text == 'Rejected' ) {
+  cj('.grant_rejected_reason_id').show();
+} else {
+  cj('.grant_rejected_reason_id').hide();
+}
+});
+});
+    {/literal}
+    </script>
diff --git a/templates/CRM/Grant/Form/GrantProgram.tpl b/templates/CRM/Grant/Form/GrantProgram.tpl
new file mode 100755
index 0000000..49e9c2e
--- /dev/null
+++ b/templates/CRM/Grant/Form/GrantProgram.tpl
@@ -0,0 +1,88 @@
+{*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.0                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*}
+{* this template is used for adding/editing/deleting contribution type  *}
+<h3>{if $action eq 1}{ts}New Grant Program{/ts}{elseif $action eq 2}{ts}Edit Grant Program{/ts}{elseif $action eq 4}{ts}View Grant Program{/ts}{else}{ts}Delete Grant Program{/ts}{/if}</h3>
+<div class="crm-block crm-form-block crm-contribution_type-form-block">
+   {if $action eq 4}
+    
+   {elseif $action eq 8}
+      <div class="messages status">
+          <div class="icon inform-icon"></div>    
+           {ts}Deleting a grant program cannot be undone.{/ts} {ts}Do you want to continue?{/ts}
+      </div>
+   {else}
+     <div class="crm-submit-buttons">{include file="CRM/common/formButtons.tpl" location="top"}</div>
+     <table class="form-layout-compressed">
+      <tr class="crm-grant_program-form-block-label">
+ 	  <td class="label">{$form.label.label}</td>
+	  <td class="html-adjust">{$form.label.html}</td>	
+       </tr>
+       <tr class="crm-grant_program-form-block-grant_type_id">	 
+    	  <td class="label">{$form.grant_type_id.label}</td>
+	  <td class="html-adjust">{$form.grant_type_id.html}</td>
+       </tr>
+       <tr class="crm-grant_program-form-block-total_amount">
+    	  <td class="label">{$form.total_amount.label}</td>
+	  <td class="html-adjust">{$form.total_amount.html}</td>
+       </tr>
+       <tr class="crm-grant_program-form-block-remainder_amount">
+    	  <td class="label">{$form.remainder_amount.label}</td>
+	  <td class="html-adjust">{$form.remainder_amount.html}</td>
+       </tr>
+       <tr class="crm-grant_program-form-block-contribution_type_id">
+	  <td class="label">{$form.contribution_type_id.label}</td>
+	  <td class="html-adjust">{$form.contribution_type_id.html}</td>
+       </tr>
+       <tr class="crm-grant_program-form-block-status_id">
+	  <td class="label">{$form.status_id.label}</td>
+	  <td class="html-adjust">{$form.status_id.html}</td>
+       </tr>
+       <tr class="crm-grant_program-form-block-allocation_algorithm">
+	  <td class="label">{$form.allocation_algorithm.label}</td>
+	  <td class="html-adjust">{$form.allocation_algorithm.html}</td>
+       </tr>
+       <tr class="crm-grant_program-form-block-allocation_date">
+           <td class="label">{$form.allocation_date.label}</td>
+	   <td>
+    	      {if $hideCalendar neq true}
+                 {include file="CRM/common/jcalendar.tpl" elementName=allocation_date}
+              {else}
+                 {$form.allocation_date.html|crmDate}
+              {/if}
+       	  </td>
+       </tr>
+       <tr class="crm-grant_program-form-block-is_active">	 
+          <td class="label">{$form.is_active.label}</td>
+	  <td class="html-adjust">{$form.is_active.html}</td>
+       </tr>
+       <tr class="crm-grant_program-form-block-is_auto_email">	 
+          <td class="label">{$form.is_auto_email.label}</td>
+	  <td class="html-adjust">{$form.is_auto_email.html}</td>
+       </tr>
+      </table> 
+   {/if}
+   <div class="crm-submit-buttons">{include file="CRM/common/formButtons.tpl" location="botttom"}</div>
+</div>
diff --git a/templates/CRM/Grant/Form/GrantProgramView.tpl b/templates/CRM/Grant/Form/GrantProgramView.tpl
new file mode 100755
index 0000000..45b507d
--- /dev/null
+++ b/templates/CRM/Grant/Form/GrantProgramView.tpl
@@ -0,0 +1,164 @@
+{*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.1                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*}
+{* this template is used for viewing grants *} 
+<h3>{ts}View Grant Program{/ts}</h3>
+<div class="crm-block crm-content-block crm-grant-view-block">
+    <div class="crm-submit-buttons">
+        {if call_user_func(array('CRM_Core_Permission','check'), 'edit grants')}
+            {assign var='urlParams' value="action=update&id=$id&reset=1"}
+            {if ( $context eq 'fulltext' || $context eq 'search' ) && $searchKey}
+                {assign var='urlParams' value="action=update&id=$id&reset=1"}
+            {/if}
+            <a class="button" href="{crmURL p='civicrm/grant_program' q=$urlParams}" accesskey="e"><span><div class="icon edit-icon"></div> {ts}Edit{/ts}</span></a>
+        {/if}
+        {if call_user_func(array('CRM_Core_Permission','check'), 'delete in CiviGrant')}
+    	    {assign var='urlParams' value="action=delete&id=$id&reset=1"}
+            {if ( $context eq 'fulltext' || $context eq 'search' ) && $searchKey}
+                {assign var='urlParams' value="action=delete&id=$id&reset=1"}
+            {/if}
+            <a class="button" href="{crmURL p='civicrm/grant_program' q=$urlParams}"><span><div class="icon delete-icon"></div>{ts}Delete{/ts}</span></a>
+        {/if}
+        {include file="CRM/common/formButtons.tpl" location="top"}
+    </div>
+    <table class="crm-info-panel">
+        <tr class="crm-grant-program-view-form-block-name"><td class="label">{ts}Name{/ts}</td><td class="bold">{$name}</td></tr>    
+        <tr class="crm-grant-program-view-form-block-grant_type_id"><td class="label">{ts}Grant Type{/ts}</td> <td>{$grantType}</td></tr>
+	<tr class="crm-grant-program-view-form-block-total_amount"><td class="label">{ts}Total Amount{/ts}</td> <td>{$total_amount|crmMoney}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="button" id="allocation" value="Allocate Approved (Trial)">&nbsp;<input type="button" id="finalize" value="Finalize Approved Allocations">&nbsp;<input type="button" id="reject" value="Reject Submitted and Approved Grants"> </td></tr>
+	<tr class="crm-grant-program-view-form-block-remainder_amount"><td class="label">{ts}Remainder Amount{/ts}</td> <td>{$remainder_amount|crmMoney}</td></tr>
+	<tr class="crm-grant-program-view-form-block-contribution_type_id"><td class="label">{ts}Contribution Type{/ts}</td> <td>{$contributionType}</td></tr>
+        <tr class="crm-grant-program-view-form-block-status_id"><td class="label">{ts}Grant Status{/ts}</td> <td>{$grantProgramStatus}</td></tr>
+	<tr class="crm-grant-program-view-form-block-allocation_algorithm"><td class="label">{ts}Allocation Algorithm{/ts}</td> <td>{$grantProgramAlgorithm}</td></tr>
+        <tr class="crm-grant-program-view-form-block-allocation_date"><td class="label">{ts}Allocation Date{/ts}</td> <td>{$allocation_date|crmDate}</td></tr>
+        <tr class="crm-grant-program-view-form-block-is_active"><td class="label">{ts}Enabled?{/ts}</td> <td>{if $is_active}{ts}Yes{/ts} {else}{ts}No{/ts}{/if}</td></tr>
+	<tr class="crm-grant-program-view-form-block-is_active"><td class="label">{ts}Auto Email?{/ts}</td> <td>{if $is_auto_email}{ts}Yes{/ts} {else}{ts}No{/ts}{/if}</td></tr>
+    </table>
+    {include file="CRM/Custom/Page/CustomDataView.tpl"} 
+    <div class="crm-submit-buttons">
+        {if call_user_func(array('CRM_Core_Permission','check'), 'edit grants')}
+            {assign var='urlParams' value="action=update&id=$id&reset=1"}
+	        {if ( $context eq 'fulltext' || $context eq 'search' ) && $searchKey}
+	            {assign var='urlParams' value="action=update&id=$id&reset=1"}
+	        {/if}
+            <a class="button" href="{crmURL p='civicrm/grant_program' q=$urlParams}" accesskey="e"><span><div class="icon edit-icon"></div> {ts}Edit{/ts}</span></a>
+        {/if}
+        {if call_user_func(array('CRM_Core_Permission','check'), 'delete in CiviGrant')}
+		    {assign var='urlParams' value="action=update&id=$id&reset=1"}
+	        {if ( $context eq 'fulltext' || $context eq 'search' ) && $searchKey}
+	            {assign var='urlParams' value="action=update&id=$id&reset=1"}
+	        {/if}
+            <a class="button" href="{crmURL p='civicrm/grant_program' q=$urlParams}"><span><div class="icon delete-icon"></div>{ts}Delete{/ts}</span></a>
+        {/if}
+        {include file="CRM/common/formButtons.tpl" location="bottom"}
+    </div>
+</div>
+
+
+{literal}
+<script type="text/javascript">
+cj('#allocation').click(function(){
+var r=confirm("You want to do trial allocation?");
+if (r==true)
+  {    
+     var data = 'pid={/literal}{$id}{literal}&amount={/literal}{$total_amount}{literal}&remainder_amount={/literal}{$remainder_amount}{literal}&algorithm={/literal}{$grantProgramAlgorithm}{literal}';
+     var dataURL = {/literal}"{crmURL p='civicrm/grant_program/allocate'}"{literal};
+     cj.ajax({ 
+         url: dataURL,	
+         data: data,
+         type: 'POST',
+         success: function(output) { 
+           setTimeout("location.reload(true);",1500);
+	 }
+      });
+   }
+});
+
+cj('#finalize').click(function(){
+ var confirmed = 0;
+ var totalAmounts = 0;
+ var grantedAmount = 0;
+ var data = 'pid={/literal}{$id}{literal}}&amount={/literal}{$total_amount}{literal}';
+     var dataURL = {/literal}"{crmURL p='civicrm/grant_program/finalize'}"{literal};
+     cj.ajax({ 
+         url: dataURL,	
+         data: data,
+         type: 'POST',
+         success: function(output) { 
+	 var result = eval('(' + output + ')');
+	 cj.each( result, function( index, value ) {
+alert(index);alert(value);
+	 if( index == 'confirm' ) {
+	   confirmed = value;
+	 }
+	 if( index == 'total_amount' ) {
+	   totalAmounts = value;
+	 }
+	 if( index == 'amount_granted' ) {
+	   grantedAmount = value;
+	   var data = 'amount_granted = '+value;
+	   alert(data);
+	 }
+         });
+	 alert(data);
+	 if (confirmed == 'confirm' ) {
+	    var r=confirm("Do you want finalize the award of grants for this grant program to the amounts currently allocated?");
+	    if (r==true)
+  	    { 
+	    var dataURL = {/literal}"{crmURL p='civicrm/grant_program/processFinalization'}"{literal};
+     	    cj.ajax({ 
+              url: dataURL,	
+              data: data,
+              type: 'POST',
+              success: function(output) { 
+	      setTimeout("location.reload(true);",1500);
+	      }
+	      });
+	    }
+	 } else {
+alert("The sum of the grants to be allocated ($"+grantedAmount+".00) is greater than the total amount available to be allocated by the program ($"+totalAmounts+"). Please reduce the amount granted in pending applications or increase the total amount available to be granted.");
+	  }
+	}
+   });  
+});
+cj('#reject').click(function(){
+
+var r=confirm("Do you want to reject all Pending grant applications for this Grant Program??");
+if (r==true)
+  {
+ var data = 'pid={/literal}{$id}{literal}';
+     var dataURL = {/literal}"{crmURL p='civicrm/grant_program/reject'}"{literal};
+     cj.ajax({ 
+         url: dataURL,	
+         data: data,
+         type: 'POST',
+         success: function(output) { 
+	   setTimeout("location.reload(true);",1500);
+	 }
+   });
+  }     
+});
+
+</script>
+{/literal}
\ No newline at end of file
diff --git a/templates/CRM/Grant/Form/GrantView.extra.tpl b/templates/CRM/Grant/Form/GrantView.extra.tpl
new file mode 100755
index 0000000..fc96824
--- /dev/null
+++ b/templates/CRM/Grant/Form/GrantView.extra.tpl
@@ -0,0 +1,83 @@
+{debug}{*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.2                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2012                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*}
+{* this template is used for viewing grants *}
+<h3>{ts}View Grant{/ts}</h3>
+<div class="crm-block crm-content-block crm-grant-view-block">
+    <div class="crm-submit-buttons">
+        {if call_user_func(array('CRM_Core_Permission','check'), 'edit grants')}
+            {assign var='urlParams' value="reset=1&id=$id&cid=$contactId&action=update&context=$context"}
+            {if ( $context eq 'fulltext' || $context eq 'search' ) && $searchKey}
+                {assign var='urlParams' value="reset=1&id=$id&cid=$contactId&action=update&context=$context&key=$searchKey"}
+            {/if}
+            <a class="button" href="{crmURL p='civicrm/contact/view/grant' q=$urlParams}" accesskey="e"><span><div class="icon edit-icon"></div> {ts}Edit{/ts}</span></a>
+        {/if}
+        {if call_user_func(array('CRM_Core_Permission','check'), 'delete in CiviGrant')}
+    	    {assign var='urlParams' value="reset=1&id=$id&cid=$contactId&action=delete&context=$context"}
+            {if ( $context eq 'fulltext' || $context eq 'search' ) && $searchKey}
+                {assign var='urlParams' value="reset=1&id=$id&cid=$contactId&action=delete&context=$context&key=$searchKey"}
+            {/if}
+            <a class="button" href="{crmURL p='civicrm/contact/view/grant' q=$urlParams}"><span><div class="icon delete-icon"></div>{ts}Delete{/ts}</span></a>
+        {/if}
+        {include file="CRM/common/formButtons.tpl" location="top"}
+    </div>
+    <table class="crm-info-panel">
+        <tr class="crm-grant-view-form-block-name"><td class="label">{ts}Name{/ts}</td><td class="bold">{$displayName}</td></tr>
+        <tr class="crm-grant-view-form-block-status_id"><td class="label">{ts}Grant Status{/ts}</td> <td>{$grantStatus}</td></tr>
+        <tr class="crm-grant-view-form-block-grant_type_id"><td class="label">{ts}Grant Type{/ts}</td> <td>{$grantType}</td></tr>
+        <tr class="crm-grant-view-form-block-application_received_date"><td class="label">{ts}Application Received{/ts}</td> <td>{$application_received_date|crmDate}</td></tr>
+        <tr class="crm-grant-view-form-block-decision_date"><td class="label">{ts}Grant Decision{/ts}</td> <td>{$decision_date|crmDate}</td></tr>
+        <tr class="crm-grant-view-form-block-money_transfer_date"><td class="label">{ts}Money Transferred{/ts}</td> <td>{$money_transfer_date|crmDate}</td></tr>
+        <tr class="crm-grant-view-form-block-grant_due_date"><td class="label">{ts}Grant Report Due{/ts}</td> <td>{$grant_due_date|crmDate}</td></tr>
+        <tr class="crm-grant-view-form-block-amount_total"><td class="label">{ts}Amount Requested{/ts}</td> <td>{$amount_total|crmMoney}</td></tr>
+        <tr class="crm-grant-view-form-block-amount_requested"><td class="label">{ts}Amount Requested{/ts}<br />
+                              {ts}(original currency){/ts}   </td> <td>{$amount_requested|crmMoney}</td></tr>
+        <tr class="crm-grant-view-form-block-amount_granted"><td class="label">{ts}Amount Granted{/ts}</td> <td>{$amount_granted|crmMoney}</td></tr>
+        <tr class="crm-grant-view-form-block-grant_report_received"><td class="label">{ts}Grant Report Received?{/ts}</td> <td>{if $grant_report_received}{ts}Yes{/ts} {else}{ts}No{/ts}{/if}</td></tr>
+        <tr class="crm-grant-view-form-block-rationale"><td class="label">{ts}Rationale{/ts}</td> <td>{$rationale|nl2br}</td></tr>
+        <tr class="crm-grant-view-form-block-note"><td class="label">{ts}Notes{/ts}</td> <td>{$note|nl2br}</td></tr>
+        {if $attachment}
+            <tr class="crm-grant-view-form-block-attachment"><td class="label">{ts}Attachment(s){/ts}</td><td>{$attachment}</td></tr>
+        {/if}
+    </table>
+    {include file="CRM/Custom/Page/CustomDataView.tpl"}
+    <div class="crm-submit-buttons">
+        {if call_user_func(array('CRM_Core_Permission','check'), 'edit grants')}
+            {assign var='urlParams' value="reset=1&id=$id&cid=$contactId&action=update&context=$context"}
+	        {if ( $context eq 'fulltext' || $context eq 'search' ) && $searchKey}
+	            {assign var='urlParams' value="reset=1&id=$id&cid=$contactId&action=update&context=$context&key=$searchKey"}
+	        {/if}
+            <a class="button" href="{crmURL p='civicrm/contact/view/grant' q=$urlParams}" accesskey="e"><span><div class="icon edit-icon"></div> {ts}Edit{/ts}</span></a>
+        {/if}
+        {if call_user_func(array('CRM_Core_Permission','check'), 'delete in CiviGrant')}
+		    {assign var='urlParams' value="reset=1&id=$id&cid=$contactId&action=delete&context=$context"}
+	        {if ( $context eq 'fulltext' || $context eq 'search' ) && $searchKey}
+	            {assign var='urlParams' value="reset=1&id=$id&cid=$contactId&action=delete&context=$context&key=$searchKey"}
+	        {/if}
+            <a class="button" href="{crmURL p='civicrm/contact/view/grant' q=$urlParams}"><span><div class="icon delete-icon"></div>{ts}Delete{/ts}</span></a>
+        {/if}
+        {include file="CRM/common/formButtons.tpl" location="bottom"}
+    </div>
+</div>
diff --git a/templates/CRM/Grant/Form/GrantViewaaa.php b/templates/CRM/Grant/Form/GrantViewaaa.php
new file mode 100755
index 0000000..4358652
--- /dev/null
+++ b/templates/CRM/Grant/Form/GrantViewaaa.php
@@ -0,0 +1,151 @@
+<?php
+
+/*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.1                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*/
+
+/**
+ *
+ * @package CRM
+ * @copyright CiviCRM LLC (c) 2004-2011
+ * $Id$
+ *
+ */
+
+require_once 'CRM/Core/Form.php';
+
+/**
+ * This class generates form components for processing a Grant
+ * 
+ */
+class CRM_Grant_Form_GrantView extends CRM_Core_Form
+{
+
+    /**  
+     * Function to set variables up before form is built  
+     *                                                            
+     * @return void  
+     * @access public  
+     */
+    public function preProcess( ) 
+    {
+        $this->_contactID = CRM_Utils_Request::retrieve( 'cid', 'Positive', $this );
+        $this->_id        = CRM_Utils_Request::retrieve( 'id', 'Positive', $this );
+        $context          = CRM_Utils_Request::retrieve( 'context', 'String', $this );
+        $this->assign( 'context', $context );
+        
+        $values = array( ); 
+        $params['id'] = $this->_id;
+        require_once 'CRM/Grant/BAO/Grant.php';
+        CRM_Grant_BAO_Grant::retrieve( $params, $values);
+        require_once 'CRM/Grant/PseudoConstant.php';
+        $grantType   = CRM_Grant_PseudoConstant::grantType( );
+        $grantStatus = CRM_Grant_PseudoConstant::grantStatus( );
+        $this->assign('grantType',  $grantType[$values['grant_type_id']] );
+        $this->assign('grantStatus',$grantStatus[$values['status_id']] );
+        $grantTokens = array( 'amount_total','amount_requested','amount_granted',
+                              'rationale','grant_report_received', 'application_received_date', 
+                              'decision_date', 'money_transfer_date', 'grant_due_date' );
+        if ( CRM_Core_Permission::check('administer CiviGrant')  ) {
+          $grantTokens[] = 'assessment';
+        }
+        
+        foreach ( $grantTokens as $token ) {
+            $this->assign( $token, CRM_Utils_Array::value( $token, $values ) );
+        }
+
+        if ( isset( $this->_id ) ) {
+            require_once 'CRM/Core/BAO/Note.php';
+            $noteDAO               = new CRM_Core_BAO_Note();
+            $noteDAO->entity_table = 'civicrm_grant';
+            $noteDAO->entity_id    = $this->_id;
+            if ( $noteDAO->find(true) ) {
+                $this->_noteId = $noteDAO->id;
+            }
+        }
+
+        if ( isset( $this->_noteId ) ) {
+            $this->assign( 'note', CRM_Core_DAO::getFieldValue( 'CRM_Core_DAO_Note', $this->_noteId, 'note' ) );
+        }
+
+
+        // add Grant to Recent Items
+        require_once 'CRM/Utils/Recent.php';
+        require_once 'CRM/Contact/BAO/Contact.php';
+        require_once 'CRM/Utils/Money.php';
+        $url = CRM_Utils_System::url( 'civicrm/contact/view/grant', 
+               "action=view&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home" );
+       
+        $title = CRM_Contact_BAO_Contact::displayName($values['contact_id'] ) . ' - ' . ts('Grant') . ': ' .
+                 CRM_Utils_Money::format( $values['amount_total'] ) . ' (' . 
+                 $grantType[$values['grant_type_id']] . ')';
+
+        $recentOther = array( );
+        if ( CRM_Core_Permission::checkActionPermission( 'CiviGrant', CRM_Core_Action::UPDATE ) ) {
+            $recentOther['editUrl'] = CRM_Utils_System::url( 'civicrm/contact/view/grant', 
+                                                             "action=update&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home" );
+        }
+        if ( CRM_Core_Permission::checkActionPermission( 'CiviGrant', CRM_Core_Action::DELETE ) ) {
+            $recentOther['deleteUrl'] = CRM_Utils_System::url( 'civicrm/contact/view/grant', 
+                                                               "action=delete&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home" );
+        }
+        CRM_Utils_Recent::add( $title,
+                               $url,
+                               $values['id'],
+                               'Grant',
+                               $values['contact_id'],
+                               null,
+                               $recentOther );
+
+        require_once 'CRM/Core/BAO/File.php';
+        $attachment = CRM_Core_BAO_File::attachmentInfo( 'civicrm_grant',
+                                                         $this->_id );
+        $this->assign( 'attachment', $attachment );
+        
+        $groupTree = CRM_Core_BAO_CustomGroup::getTree( "Grant", $this, $this->_id, 0 );
+        CRM_Core_BAO_CustomGroup::buildCustomDataView( $this, $groupTree ); 
+
+        $this->assign( 'id', $this->_id );
+    }
+
+    /**
+     * Function to build the form
+     *
+     * @return None
+     * @access public
+     */
+    public function buildQuickForm( ) 
+    {
+        $this->addButtons(array(  
+                                array ( 'type'      => 'cancel',  
+                                        'name'      => ts('Done'),  
+                                        'spacing'   => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',  
+                                        'isDefault' => true   )
+                                )
+                          );
+    }
+
+
+}
\ No newline at end of file
diff --git a/templates/CRM/Grant/Form/Payment/View.tpl b/templates/CRM/Grant/Form/Payment/View.tpl
new file mode 100755
index 0000000..eaec958
--- /dev/null
+++ b/templates/CRM/Grant/Form/Payment/View.tpl
@@ -0,0 +1,96 @@
+{*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.1                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*}
+{* this template is used for viewing grants *}
+{if $action eq 4}
+<h3>{ts}View Payment{/ts}</h3>
+<div class="crm-block crm-content-block crm-grant-view-block">
+    <div class="crm-submit-buttons">
+        {include file="CRM/common/formButtons.tpl" location="top"}
+    </div>
+    <table class="crm-info-panel">
+        <tr class="crm-grant-view-form-block-name"><td class="label">{ts}Payment Number{/ts}</td><td class="bold">{$payment_number}</td></tr> 
+        <tr class="crm-grant-view-form-block-grant_type_id"><td class="label">{ts}Batch Number{/ts}</td> <td>{$payment_batch_number}</td></tr>   
+        <tr class="crm-grant-view-form-block-status_id"><td class="label">{ts}Payment Status{/ts}</td> <td>{$payment_status_id}</td></tr>
+        <tr class="crm-grant-view-form-block-application_received_date"><td class="label">{ts}Payment Created Date{/ts}</td> <td>{$payment_created_date|crmDate}</td></tr>
+        <tr class="crm-grant-view-form-block-decision_date"><td class="label">{ts}Payment Date{/ts}</td> <td>{$payment_date|crmDate}</td></tr>
+        <tr class="crm-grant-view-form-block-rationale"><td class="label">{ts}Payee Name{/ts}</td> <td>{$payable_to_name}</td></tr>
+	<tr class="crm-grant-view-form-block-rationale"><td class="label">{ts}Payee Address{/ts}</td> <td>{$payable_to_address}</td></tr>
+        <tr class="crm-grant-view-form-block-amount_requested"><td class="label">{ts}Amount{/ts}</td> <td>{$amount|crmMoney}</td></tr>
+        <tr class="crm-grant-view-form-block-note"><td class="label">{ts}Payment Reason{/ts}</td> <td>{$payment_reason}</td></tr>
+    </table>
+    {include file="CRM/Custom/Page/CustomDataView.tpl"} 
+    <div class="crm-submit-buttons">
+        {include file="CRM/common/formButtons.tpl" location="bottom"}
+    </div>
+</div>
+{elseif $action eq 524288 }
+<h3>{ts}Stop Payment{/ts}</h3>
+<div class="crm-block crm-content-block crm-grant-view-block">  
+     <div class="messages status">
+          <div class="icon inform-icon"></div>    
+           {ts}Do you want to record that a Stop payment request has been made with bank on this payment?{/ts}
+      </div>
+   <div class="crm-submit-buttons">
+        {include file="CRM/common/formButtons.tpl" location="bottom"}
+    </div>
+</div>
+
+
+{elseif $action eq 1048576 }
+<h3>{ts}Reprint Payment{/ts}</h3>
+<div class="crm-block crm-content-block crm-grant-view-block">
+    <div class="crm-submit-buttons">
+        {include file="CRM/common/formButtons.tpl" location="top"}
+    </div>
+    <table class="crm-info-panel">
+        <tr class="crm-grant-view-form-block-name"><td class="label">{ts}Payment Number{/ts}</td><td class="bold">{$payment_number}</td></tr> 
+        <tr class="crm-grant-view-form-block-grant_type_id"><td class="label">{ts}Batch Number{/ts}</td> <td>{$payment_batch_number}</td></tr>   
+        <tr class="crm-grant-view-form-block-status_id"><td class="label">{ts}Payment Status{/ts}</td> <td>{$payment_status_id}</td></tr>
+        <tr class="crm-grant-view-form-block-application_received_date"><td class="label">{ts}Payment Created Date{/ts}</td> <td>{$payment_created_date|crmDate}</td></tr>
+        <tr class="crm-grant-view-form-block-decision_date"><td class="label">{ts}Payment Date{/ts}</td> <td>{$payment_date|crmDate}</td></tr>
+        <tr class="crm-grant-view-form-block-rationale"><td class="label">{ts}Payee Name{/ts}</td> <td>{$payable_to_name}</td></tr>
+	<tr class="crm-grant-view-form-block-rationale"><td class="label">{ts}Payee Address{/ts}</td> <td>{$payable_to_address}</td></tr>
+        <tr class="crm-grant-view-form-block-amount_requested"><td class="label">{ts}Amount{/ts}</td> <td>{$amount|crmMoney}</td></tr>
+        <tr class="crm-grant-view-form-block-note"><td class="label">{ts}Payment Reason{/ts}</td> <td>{$payment_reason}</td></tr>
+	<tr class="crm-grant-view-form-block-note"><td class="label">{ts}Repaces Payment Id{/ts}</td> <td>{$replaces_payment_id}</td></tr>
+    </table> 
+    <div class="crm-submit-buttons">
+        {include file="CRM/common/formButtons.tpl" location="bottom"}
+    </div>
+</div>
+{elseif $action eq 2097152 }
+<h3>{ts}Withdraw Payment{/ts}</h3>
+
+<div class="crm-block crm-content-block crm-grant-view-block">  
+     <div class="messages status">
+          <div class="icon inform-icon"></div>    
+           {ts}Do you want to record that this cheque will not be cashed, e.g. it has been destroyed or is stale dated?{/ts}
+      </div>
+   <div class="crm-submit-buttons">
+        {include file="CRM/common/formButtons.tpl" location="bottom"}
+    </div>
+</div>	
+{/if}
diff --git a/templates/CRM/Grant/Form/PaymentSearch.tpl b/templates/CRM/Grant/Form/PaymentSearch.tpl
new file mode 100755
index 0000000..b0e039e
--- /dev/null
+++ b/templates/CRM/Grant/Form/PaymentSearch.tpl
@@ -0,0 +1,113 @@
+{*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.1                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*}
+
+<div class="crm-block crm-form-block crm-search-form-block">
+	<div class="crm-accordion-wrapper crm-member_search_form-accordion {if $rows}crm-accordion-closed{else}crm-accordion-open{/if}">
+	 <div class="crm-accordion-header crm-master-accordion-header">
+	    <div class="icon crm-accordion-pointer"></div> 
+	    {ts}Edit Search Criteria{/ts}
+ 	 </div><!-- /.crm-accordion-header -->
+	<div class="crm-accordion-body">
+	    {strip}
+        <div id="help">
+            {ts}Use this form to find Grant Payment(s) by Payee name , Status, Batch Number, Payment Number , etc .{/ts}
+        </div>
+        <table class="form-layout">
+            <tr>
+               <td class="font-size12pt" colspan="4">
+                    {$form.payable_to_name.label}&nbsp;&nbsp;{$form.payable_to_name.html|crmReplace:class:'twenty'}&nbsp;&nbsp;&nbsp;{$form.buttons.html}<br />
+               </td>       
+            </tr>
+            <tr>
+	       <td colspan="2">
+                    {$form.payment_status_id.label}&nbsp;&nbsp;
+                    {$form.payment_status_id.html}
+               </td>
+               <td colspan="2">
+                    {$form.payment_batch_number.label}&nbsp;&nbsp;
+                    {$form.payment_batch_number.html}
+               </td>
+               <td colspan="2">
+                    {$form.payment_number.label}&nbsp;&nbsp;
+                    {$form.payment_number.html} 
+               </td>
+             </tr>
+	     	<tr> 
+		<td colspan="2">
+		{$form.payment_created_date_low.label}&nbsp;&nbsp;
+        	{include file="CRM/common/jcalendar.tpl" elementName=payment_created_date_low}
+		</td>
+	       <td colspan="2">
+                    {$form.payment_created_date_high.label}&nbsp;&nbsp;
+                    {include file="CRM/common/jcalendar.tpl" elementName=payment_created_date_high}
+               </td>
+               <td colspan="2">
+                    {$form.amount.label}&nbsp;&nbsp;
+                    {$form.amount.html}
+               </td>
+             </tr>    
+        </table>
+        {/strip}
+    </div><!-- /.crm-accordion-body -->
+  </div><!-- /.crm-accordion-wrapper -->
+</div><!-- /.crm-form-block -->
+<div class="crm-content-block">
+{if $rowsEmpty}
+    <div class="crm-results-block crm-results-block-empty">
+        {include file="CRM/Grant/Form/Search/EmptyResults.tpl"}
+    </div>
+{/if}
+{if $rows}
+    {* Search request has returned 1 or more matching rows. Display results and collapse the search criteria fieldset. *}    
+	<div class="crm-results-block">
+        {* This section handles form elements for action task select and submit *}
+        <div class="crm-search-tasks">
+            {include file="CRM/Grant/Form/Task/paymentResultTask.tpl"}
+        </div>
+        {* This section displays the rows along and includes the paging controls *}
+        <div class="crm-search-results">
+            {include file="CRM/Grant/Form/PaymentSelector.tpl" context="Search"}
+       </div>
+    </div><!-- /.crm-results-block -->
+{/if}
+</div><!-- /.crm-content-block -->
+{if $download}
+<div id ="download"> 
+<a href={$download} class="download" "style="text-decoration: none;" >Download</a>
+</div>
+{/if}
+{literal}
+<script type="text/javascript">
+var download = "{/literal}{$download}{literal}";
+if ( download ) {
+cj("#download").hide();
+window.location.href = cj(".download").attr('href');
+}
+cj(function() {	
+   cj().crmaccordions(); 
+});
+</script>
+{/literal}
diff --git a/templates/CRM/Grant/Form/PaymentSelector.tpl b/templates/CRM/Grant/Form/PaymentSelector.tpl
new file mode 100755
index 0000000..f4a1ef8
--- /dev/null
+++ b/templates/CRM/Grant/Form/PaymentSelector.tpl
@@ -0,0 +1,87 @@
+{*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.1                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*}
+{if $context EQ 'Search'}
+    {include file="CRM/common/pager.tpl" location="top"}
+{/if}
+{strip}
+<table class="selector">
+  <thead class="sticky">
+  <tr class="columnheader">
+  {if ! $single and $context eq 'Search' }
+     <th scope="col" title="Select Rows">{$form.toggleSelect.html}</th> 
+  {/if}
+  {foreach from=$columnHeaders item=header}
+    <th scope="col">
+    {if $header.sort}
+      {assign var='key' value=$header.sort}
+      {$sort->_response.$key.link}
+    {else}
+      {$header.name}
+    {/if}
+    </th>
+  {/foreach}
+  </tr>
+  </thead>
+
+  {counter start=0 skip=1 print=false}
+  {foreach from=$rows item=row}  
+  <tr id='crm-payment_{$row.id}' class="{cycle values="odd-row,even-row"} crm-grant crm-grant_status-{$row.payment_status_id}">
+
+ {if !$single }  
+     {if $context eq 'Search' }       
+        {assign var=cbName value=$row.checkbox}
+        <td>{$form.$cbName.html}</td> 
+     {/if} 
+  {/if}
+    <td class="crm-grant-grant_status">{$row.payment_status_id}</td>
+    <td class="crm-grant-grant_type">{$row.payment_batch_number}</td> 
+    <td class="crm-grant-grant_type">{$row.payment_number}</td>
+    <td class="right crm-grant-grant_money_transfer_date">{$row.payment_created_date|truncate:10:''|crmDate}</td>
+    <td class="crm-grant-grant_status">{$row.payable_to_name}</td>
+    <td class="right crm-grant-grant_amount_total">{$row.amount|crmMoney}</td>
+    <td>{$row.action|replace:'xx':$row.grant_id}</td>
+   </tr>
+  {/foreach}
+
+{if ($context EQ 'dashboard') AND $pager->_totalItems GT $limit}
+  <tr class="even-row">
+    <td colspan="9"><a href="{crmURL p='civicrm/grant/search' q='reset=1&force=1'}">&raquo; {ts}List more Grants{/ts}...</a></td></tr>
+  </tr>	
+{/if}
+</table>
+{/strip}
+
+{if $context EQ 'Search'}
+ <script type="text/javascript">
+ {* this function is called to change the color of selected row(s) *}
+    var fname = "{$form.formName}";	
+    on_load_init_checkboxes(fname);
+ </script>
+{/if}
+
+{if $context EQ 'Search'}
+    {include file="CRM/common/pager.tpl" location="bottom"}
+{/if}
diff --git a/templates/CRM/Grant/Form/PaymentTask.tpl b/templates/CRM/Grant/Form/PaymentTask.tpl
new file mode 100755
index 0000000..d245dd6
--- /dev/null
+++ b/templates/CRM/Grant/Form/PaymentTask.tpl
@@ -0,0 +1,42 @@
+{*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.1                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*}
+{if $totalSelectedGrants}
+    {ts 1=$totalSelectedGrants}Number of selected grant paments: %1{/ts}
+{/if}
+{if $rows } 
+<div class="form-item">
+<table width="30%">
+  <tr class="columnheader">
+    <td>{ts}Name{/ts}</td>
+  </tr>
+{foreach from=$rows item=row}
+<tr class="{cycle values="odd-row,even-row"}">
+<td>{$row.displayName}</td>
+</tr>
+{/foreach}
+</table>
+</div>
+{/if}
diff --git a/templates/CRM/Grant/Form/Search.tpl b/templates/CRM/Grant/Form/Search.tpl
new file mode 100755
index 0000000..3bdc6aa
--- /dev/null
+++ b/templates/CRM/Grant/Form/Search.tpl
@@ -0,0 +1,80 @@
+{*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.1                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*}
+
+<div class="crm-block crm-form-block crm-search-form-block">
+	<div class="crm-accordion-wrapper crm-member_search_form-accordion {if $rows}crm-accordion-closed{else}crm-accordion-open{/if}">
+	 <div class="crm-accordion-header crm-master-accordion-header">
+	    <div class="icon crm-accordion-pointer"></div> 
+	    {ts}Edit Search Criteria{/ts}
+ 	 </div><!-- /.crm-accordion-header -->
+	<div class="crm-accordion-body">
+	    {strip}
+        <div id="help">
+            {ts}Use this form to find Grant(s) by Contact name, Grant Status, Grant Type, Total Amount , etc .{/ts}
+        </div>
+        <table class="form-layout">
+            <tr>
+               <td class="font-size12pt" colspan="3">
+                    {$form.sort_name.label}&nbsp;&nbsp;{$form.sort_name.html|crmReplace:class:'twenty'}&nbsp;&nbsp;&nbsp;{$form.buttons.html}<br />
+               </td>       
+            </tr>
+
+        {include file="CRM/Grant/Form/Search/Common.tpl"}
+
+        </table>
+        {/strip}
+    </div><!-- /.crm-accordion-body -->
+  </div><!-- /.crm-accordion-wrapper -->
+</div><!-- /.crm-form-block -->
+
+<div class="crm-content-block">
+{if $rowsEmpty}
+    <div class="crm-results-block crm-results-block-empty">
+        {include file="CRM/Grant/Form/Search/EmptyResults.tpl"}
+    </div>
+{/if}
+
+{if $rows}
+    {* Search request has returned 1 or more matching rows. Display results and collapse the search criteria fieldset. *}    
+	<div class="crm-results-block">
+        {* This section handles form elements for action task select and submit *}
+        <div class="crm-search-tasks">
+            {include file="CRM/common/searchResultTasks.tpl"}
+        </div>
+        {* This section displays the rows along and includes the paging controls *}
+        <div class="crm-search-results">
+            {include file="CRM/Grant/Form/Selector.tpl" context="Search"}
+       </div>
+    </div><!-- /.crm-results-block -->
+{/if}
+</div><!-- /.crm-content-block -->
+{literal}
+<script type="text/javascript">
+cj(function() {
+   cj().crmaccordions(); 
+});
+</script>
+{/literal}
diff --git a/templates/CRM/Grant/Form/Search/Common.tpl b/templates/CRM/Grant/Form/Search/Common.tpl
new file mode 100755
index 0000000..0c2e364
--- /dev/null
+++ b/templates/CRM/Grant/Form/Search/Common.tpl
@@ -0,0 +1,117 @@
+{*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.1                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*}
+<tr>
+    <td>
+        {$form.grant_report_received.label}<br />
+        {$form.grant_report_received.html}
+    </td>
+    <td>
+        {$form.grant_status_id.label}<br />
+        {$form.grant_status_id.html}
+    </td>
+    <td>
+        {$form.grant_type_id.label}<br />
+        {$form.grant_type_id.html} 
+    </td>
+    <td>
+        {$form.grant_program_id.label}<br />
+        {$form.grant_program_id.html} 
+    </td>
+</tr>
+<tr>
+    <td colspan = "2"><label>{ts}Assessment{/ts}</label> <br />
+        {$form.grant_assessment_low.label}
+        {$form.grant_assessment_low.html} &nbsp;
+	 {$form.grant_assessment_high.label}
+        {$form.grant_assessment_high.html}
+    </td>
+</tr>
+<tr>
+    <td colspan = "2"><label>{ts}Amount Allocated{/ts}</label> <br />
+        {$form.grant_amount_total_low.label}
+        {$form.grant_amount_total_low.html}
+	 {$form.grant_amount_total_high.label}
+        {$form.grant_amount_total_high.html}
+    </td>
+</tr>
+<tr>
+    <td colspan = "2"><label>{ts}Amount Granted{/ts}</label> <br />
+        {$form.grant_amount_low.label}
+        {$form.grant_amount_low.html}
+	 {$form.grant_amount_high.label}
+        {$form.grant_amount_high.html}
+    </td>
+</tr>
+<tr>
+    <td>
+        {$form.grant_application_received_date_low.label}<br />
+        {include file="CRM/common/jcalendar.tpl" elementName=grant_application_received_date_low}
+    </td>
+    <td colspan="2">
+        {$form.grant_application_received_date_high.label}<br />
+        {include file="CRM/common/jcalendar.tpl" elementName=grant_application_received_date_high}
+        &nbsp;{$form.grant_application_received_notset.html}&nbsp;&nbsp;{ts}Date is not set{/ts}
+    </td>          
+</tr>
+<tr>
+    <td>
+        {$form.grant_decision_date_low.label}<br />
+        {include file="CRM/common/jcalendar.tpl" elementName=grant_decision_date_low}
+    </td>
+    <td colspan="2">
+        {$form.grant_decision_date_high.label}<br /> 
+        {include file="CRM/common/jcalendar.tpl" elementName=grant_decision_date_high}
+        &nbsp;{$form.grant_decision_date_notset.html}&nbsp;&nbsp;{ts}Date is not set{/ts}
+    </td>          
+</tr>
+<tr>
+    <td> 
+        {$form.grant_money_transfer_date_low.label}<br /> 
+        {include file="CRM/common/jcalendar.tpl" elementName=grant_money_transfer_date_low}
+    </td>
+    <td colspan="2">                 
+        {$form.grant_money_transfer_date_high.label}<br /> 
+        {include file="CRM/common/jcalendar.tpl" elementName=grant_money_transfer_date_high}
+        &nbsp;{$form.grant_money_transfer_date_notset.html}&nbsp;&nbsp;{ts}Date is not set{/ts}
+    </td>          
+</tr>
+<tr>
+    <td>
+        {$form.grant_due_date_low.label}<br />
+        {include file="CRM/common/jcalendar.tpl" elementName=grant_due_date_low}
+    </td>
+    <td colspan="2">
+        {$form.grant_due_date_high.label}<br />
+        {include file="CRM/common/jcalendar.tpl" elementName=grant_due_date_high}
+        &nbsp;{$form.grant_due_date_notset.html}&nbsp;&nbsp;{ts}Date is not set{/ts}
+    </td>          
+</tr>
+{if $grantGroupTree}
+<tr>
+    <td colspan="3">
+    {include file="CRM/Custom/Form/Search.tpl" groupTree=$grantGroupTree showHideLinks=false}</td>
+</tr>
+{/if}
diff --git a/templates/CRM/Grant/Form/Search/Payment.tpl b/templates/CRM/Grant/Form/Search/Payment.tpl
new file mode 100755
index 0000000..0c2e364
--- /dev/null
+++ b/templates/CRM/Grant/Form/Search/Payment.tpl
@@ -0,0 +1,117 @@
+{*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.1                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*}
+<tr>
+    <td>
+        {$form.grant_report_received.label}<br />
+        {$form.grant_report_received.html}
+    </td>
+    <td>
+        {$form.grant_status_id.label}<br />
+        {$form.grant_status_id.html}
+    </td>
+    <td>
+        {$form.grant_type_id.label}<br />
+        {$form.grant_type_id.html} 
+    </td>
+    <td>
+        {$form.grant_program_id.label}<br />
+        {$form.grant_program_id.html} 
+    </td>
+</tr>
+<tr>
+    <td colspan = "2"><label>{ts}Assessment{/ts}</label> <br />
+        {$form.grant_assessment_low.label}
+        {$form.grant_assessment_low.html} &nbsp;
+	 {$form.grant_assessment_high.label}
+        {$form.grant_assessment_high.html}
+    </td>
+</tr>
+<tr>
+    <td colspan = "2"><label>{ts}Amount Allocated{/ts}</label> <br />
+        {$form.grant_amount_total_low.label}
+        {$form.grant_amount_total_low.html}
+	 {$form.grant_amount_total_high.label}
+        {$form.grant_amount_total_high.html}
+    </td>
+</tr>
+<tr>
+    <td colspan = "2"><label>{ts}Amount Granted{/ts}</label> <br />
+        {$form.grant_amount_low.label}
+        {$form.grant_amount_low.html}
+	 {$form.grant_amount_high.label}
+        {$form.grant_amount_high.html}
+    </td>
+</tr>
+<tr>
+    <td>
+        {$form.grant_application_received_date_low.label}<br />
+        {include file="CRM/common/jcalendar.tpl" elementName=grant_application_received_date_low}
+    </td>
+    <td colspan="2">
+        {$form.grant_application_received_date_high.label}<br />
+        {include file="CRM/common/jcalendar.tpl" elementName=grant_application_received_date_high}
+        &nbsp;{$form.grant_application_received_notset.html}&nbsp;&nbsp;{ts}Date is not set{/ts}
+    </td>          
+</tr>
+<tr>
+    <td>
+        {$form.grant_decision_date_low.label}<br />
+        {include file="CRM/common/jcalendar.tpl" elementName=grant_decision_date_low}
+    </td>
+    <td colspan="2">
+        {$form.grant_decision_date_high.label}<br /> 
+        {include file="CRM/common/jcalendar.tpl" elementName=grant_decision_date_high}
+        &nbsp;{$form.grant_decision_date_notset.html}&nbsp;&nbsp;{ts}Date is not set{/ts}
+    </td>          
+</tr>
+<tr>
+    <td> 
+        {$form.grant_money_transfer_date_low.label}<br /> 
+        {include file="CRM/common/jcalendar.tpl" elementName=grant_money_transfer_date_low}
+    </td>
+    <td colspan="2">                 
+        {$form.grant_money_transfer_date_high.label}<br /> 
+        {include file="CRM/common/jcalendar.tpl" elementName=grant_money_transfer_date_high}
+        &nbsp;{$form.grant_money_transfer_date_notset.html}&nbsp;&nbsp;{ts}Date is not set{/ts}
+    </td>          
+</tr>
+<tr>
+    <td>
+        {$form.grant_due_date_low.label}<br />
+        {include file="CRM/common/jcalendar.tpl" elementName=grant_due_date_low}
+    </td>
+    <td colspan="2">
+        {$form.grant_due_date_high.label}<br />
+        {include file="CRM/common/jcalendar.tpl" elementName=grant_due_date_high}
+        &nbsp;{$form.grant_due_date_notset.html}&nbsp;&nbsp;{ts}Date is not set{/ts}
+    </td>          
+</tr>
+{if $grantGroupTree}
+<tr>
+    <td colspan="3">
+    {include file="CRM/Custom/Form/Search.tpl" groupTree=$grantGroupTree showHideLinks=false}</td>
+</tr>
+{/if}
diff --git a/templates/CRM/Grant/Form/Selector.tpl b/templates/CRM/Grant/Form/Selector.tpl
new file mode 100755
index 0000000..04294fd
--- /dev/null
+++ b/templates/CRM/Grant/Form/Selector.tpl
@@ -0,0 +1,91 @@
+{*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.1                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*}
+{if $context EQ 'Search'}
+    {include file="CRM/common/pager.tpl" location="top"}
+{/if}
+
+{strip}
+<table class="selector">
+  <thead class="sticky">
+  <tr class="columnheader">
+  {if ! $single and $context eq 'Search' }
+     <th scope="col" title="Select Rows">{$form.toggleSelect.html}</th> 
+  {/if}
+  {foreach from=$columnHeaders item=header}
+    <th scope="col">
+    {if $header.sort}
+      {assign var='key' value=$header.sort}
+      {$sort->_response.$key.link}
+    {else}
+      {$header.name}
+    {/if}
+    </th>
+  {/foreach}
+  </tr>
+  </thead>
+
+  {counter start=0 skip=1 print=false}
+  {foreach from=$rows item=row}  
+  <tr id='crm-grant_{$row.grant_id}' class="{cycle values="odd-row,even-row"} crm-grant crm-grant_status-{$row.grant_status_id}">
+
+  {if !$single }  
+     {if $context eq 'Search' }       
+        {assign var=cbName value=$row.checkbox}
+        <td>{$form.$cbName.html}</td> 
+     {/if} 
+    <td>{$row.contact_type}</td>	
+    <td><a href="{crmURL p='civicrm/contact/view' q="reset=1&cid=`$row.contact_id`"}">{$row.sort_name}</a></td> 
+  {/if}
+    <td class="crm-grant-grant_status">{$row.grant_status}</td>
+    <td class="crm-grant-grant_type">{$row.grant_type}</td>
+    <td class="right crm-grant-grant_amount_total">{$row.grant_amount_total|crmMoney}</td>
+    <td class="right crm-grant-grant_amount_granted">{$row.grant_amount_granted|crmMoney}</td>
+    <td class="right crm-grant-grant_application_received_date">{$row.grant_application_received_date|truncate:10:''|crmDate}</td>
+    <td class="right crm-grant-grant_course_name">{$row.course_name}</td>
+    <td class="crm-grant-grant_course_type">{$row.course_type}</td>
+    <td>{$row.action|replace:'xx':$row.grant_id}</td>
+   </tr>
+  {/foreach}
+
+{if ($context EQ 'dashboard') AND $pager->_totalItems GT $limit}
+  <tr class="even-row">
+    <td colspan="9"><a href="{crmURL p='civicrm/grant/search' q='reset=1&force=1'}">&raquo; {ts}List more Grants{/ts}...</a></td></tr>
+  </tr>
+{/if}
+</table>
+{/strip}
+
+{if $context EQ 'Search'}
+ <script type="text/javascript">
+ {* this function is called to change the color of selected row(s) *}
+    var fname = "{$form.formName}";	
+    on_load_init_checkboxes(fname);
+ </script>
+{/if}
+
+{if $context EQ 'Search'}
+    {include file="CRM/common/pager.tpl" location="bottom"}
+{/if}
diff --git a/templates/CRM/Grant/Form/Task.tpl b/templates/CRM/Grant/Form/Task.tpl
new file mode 100755
index 0000000..09b002b
--- /dev/null
+++ b/templates/CRM/Grant/Form/Task.tpl
@@ -0,0 +1,42 @@
+{*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.1                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*}
+{if $totalSelectedGrants}
+    {ts 1=$totalSelectedGrants}Number of selected grants: %1{/ts}
+{/if}
+{if $rows } 
+<div class="form-item">
+<table width="30%">
+  <tr class="columnheader">
+    <td>{ts}Name{/ts}</td>
+  </tr>
+{foreach from=$rows item=row}
+<tr class="{cycle values="odd-row,even-row"}">
+<td>{$row.displayName}</td>
+</tr>
+{/foreach}
+</table>
+</div>
+{/if}
diff --git a/templates/CRM/Grant/Form/Task/Cancel.tpl b/templates/CRM/Grant/Form/Task/Cancel.tpl
new file mode 100755
index 0000000..d9de77c
--- /dev/null
+++ b/templates/CRM/Grant/Form/Task/Cancel.tpl
@@ -0,0 +1,32 @@
+{*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.1                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*}
+{* Confirmation of Grant Payment Cancel  *}
+<div class="messages status">
+        <p><div class="icon inform-icon"></div>&nbsp;
+        {ts}Are you sure you want to cancel the selected Grant Payments? This cancel operation cannot be undone and will delete all transactions associated with these grant payments.{/ts}</p>
+        <p>{include file="CRM/Grant/Form/PaymentTask.tpl"}</p>
+</div>
+<div class="crm-submit-buttons">{include file="CRM/common/formButtons.tpl"}</div>
diff --git a/templates/CRM/Grant/Form/Task/GrantPayment.tpl b/templates/CRM/Grant/Form/Task/GrantPayment.tpl
new file mode 100755
index 0000000..2a06735
--- /dev/null
+++ b/templates/CRM/Grant/Form/Task/GrantPayment.tpl
@@ -0,0 +1,61 @@
+{*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.0                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*}
+
+{* this template is used for adding/editing/deleting contribution type  *}
+<h3>{ts}Pay Grants{/ts}</h3>
+<div class="crm-block crm-form-block crm-contribution_type-form-block">
+     <div class="crm-submit-buttons">{include file="CRM/common/formButtons.tpl" location="top"}</div>
+     <table class="form-layout-compressed">
+       <tr class="crm-grant_payment-form-block-contribution_type_id">
+	  <td class="label">{$form.contribution_type_id.label}</td>
+	  <td class="html-adjust">{$form.contribution_type_id.html}</td>
+       </tr>
+       <tr class="crm-grant_payment-form-block-payment_batch_number">
+ 	  <td class="label">{$form.payment_batch_number.label}</td>
+	  <td class="html-adjust">{$form.payment_batch_number.html}</td>	
+       </tr>
+       <tr class="crm-grant_payment-form-block-payment_number">
+ 	  <td class="label">{$form.payment_number.label}</td>
+	  <td class="html-adjust">{$form.payment_number.html}</td>	
+       </tr>
+       <tr class="crm-grant_payment-form-block-payment_date">
+           <td class="label">{$form.payment_date.label}</td>
+	   <td>
+    	      {if $hideCalendar neq true}
+                 {include file="CRM/common/jcalendar.tpl" elementName=payment_date}
+              {else}
+                 {$form.payment_date.html|crmDate}
+              {/if}
+       	  </td>
+       </tr>
+       <tr class="crm-grant_payment-form-block-csv">
+ 	  <td class="label">{$form.download_file.label}</td>
+	  <td class="html-adjust">{$form.download_file.html}</td>	
+       </tr>
+      </table> 
+ 
+   <div class="crm-submit-buttons">{include file="CRM/common/formButtons.tpl" location="botttom"}</div>
+</div>
diff --git a/templates/CRM/Grant/Form/Task/Pay.tpl b/templates/CRM/Grant/Form/Task/Pay.tpl
new file mode 100755
index 0000000..d96c310
--- /dev/null
+++ b/templates/CRM/Grant/Form/Task/Pay.tpl
@@ -0,0 +1,38 @@
+{*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.1                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*}
+{* Confirmation of Grant pay  *}
+{if $approved}
+<div class="messages status">
+        <p><div class="icon inform-icon"></div>&nbsp;
+        {ts}'{$paid} of the {$total} selected grants have already been paid. {$notApproved} of the {$total} selected grants are not approved. {if $multipleCurrency } {$multipleCurrency} of {$total} grants have different currency of same user. {/if} Would you like to proceed to paying the {$approved} approved but unpaid grants?'{/ts}</p>
+</div>
+{else if}
+<div class="messages status">
+        <p><div class="icon inform-icon"></div>&nbsp;
+        {ts}Please select at least one grant that has been approved and not been paid.{/ts}</p>
+</div>
+{/if}
+<div class="crm-submit-buttons">{include file="CRM/common/formButtons.tpl"}</div>
diff --git a/templates/CRM/Grant/Form/Task/Reprint.tpl b/templates/CRM/Grant/Form/Task/Reprint.tpl
new file mode 100755
index 0000000..6d63aab
--- /dev/null
+++ b/templates/CRM/Grant/Form/Task/Reprint.tpl
@@ -0,0 +1,73 @@
+{*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.1                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*}
+{* Confirmation of Grant pay  *}
+{if $payments}
+<div class="messages status">
+        <p><div class="icon inform-icon"></div>&nbsp;
+        {ts}'{$stopped} of the {$total} selected grant payments have already been stopped. {$reprinted} of the {$total} selected grant payments are printed or reprinted.{/ts}</p>
+</div>
+<h3>{ts}Reprint Payments{/ts}</h3>
+<div class="crm-block crm-form-block crm-contribution_type-form-block">
+     <div class="crm-submit-buttons">{include file="CRM/common/formButtons.tpl" location="top"}</div>
+     <table class="form-layout-compressed">
+       <tr class="crm-grant_payment-form-block-contribution_type_id">
+	  <td class="label">{$form.contribution_type_id.label}</td>
+	  <td class="html-adjust">{$form.contribution_type_id.html}</td>
+       </tr>
+       <tr class="crm-grant_payment-form-block-payment_batch_number">
+ 	  <td class="label">{$form.payment_batch_number.label}</td>
+	  <td class="html-adjust">{$form.payment_batch_number.html}</td>	
+       </tr>
+       <tr class="crm-grant_payment-form-block-payment_number">
+ 	  <td class="label">{$form.payment_number.label}</td>
+	  <td class="html-adjust">{$form.payment_number.html}</td>	
+       </tr>
+       <tr class="crm-grant_payment-form-block-payment_date">
+           <td class="label">{$form.payment_date.label}</td>
+	   <td>
+    	      {if $hideCalendar neq true}
+                 {include file="CRM/common/jcalendar.tpl" elementName=payment_date}
+              {else}
+                 {$form.payment_date.html|crmDate}
+              {/if}
+       	  </td>
+       </tr>
+       <tr class="crm-grant_payment-form-block-csv">
+ 	  <td class="label">{$form.download_file.label}</td>
+	  <td class="html-adjust">{$form.download_file.html}</td>	
+       </tr>
+      </table> 
+ 
+   <div class="crm-submit-buttons">{include file="CRM/common/formButtons.tpl" location="botttom"}</div>
+</div>
+
+{else if}
+<div class="messages status">
+        <p><div class="icon inform-icon"></div>&nbsp;
+        {ts}Please select at least one grant payment that has been printed or reprinted.{/ts}</p>
+</div>
+<div class="crm-submit-buttons">{include file="CRM/common/formButtons.tpl"}</div>
+{/if}
diff --git a/templates/CRM/Grant/Form/Task/Update.tpl b/templates/CRM/Grant/Form/Task/Update.tpl
new file mode 100755
index 0000000..925fc47
--- /dev/null
+++ b/templates/CRM/Grant/Form/Task/Update.tpl
@@ -0,0 +1,73 @@
+{*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.1                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*}
+{* Update Grants *} 
+<div class="crm-block crm-form-block crm-grants-update-form-block">
+    <p>{ts}Enter values for the fields you wish to update. Leave fields blank to preserve existing values.{/ts}</p>
+    <table class="form-layout-compressed">
+        {* Loop through all defined search criteria fields (defined in the buildForm() function). *}
+
+    <tr class="crm-contact-custom-search-form-row-status_id">
+       <td class="label">{$form.status_id.label}</td>
+       <td>{$form.status_id.html}</td>
+    </tr>
+    <tr class="crm-contact-custom-search-form-row-radio_ts">
+       <td class="label">{$form.radio_ts.amount_granted.label}</td>
+       <td>{$form.radio_ts.amount_granted.html}</td>
+    </tr>
+    <tr class="crm-contact-custom-search-form-row-radio_ts">
+       <td class="label"></td>
+       <td>{$form.amount_granted.html}</td>
+    </tr>
+    <tr class="crm-contact-custom-search-form-row-radio_ts">
+       <td class="label">{$form.radio_ts.amount_total.label}</td>
+       <td>{$form.radio_ts.amount_total.html}</td>
+    </tr>
+
+    <tr class="crm-contact-custom-search-form-row-decision_date">
+       <td class="label">{$form.decision_date.label}</td>
+       <td>{include file="CRM/common/jcalendar.tpl" elementName=decision_date}<br />
+       <span class="description">{ts}Date on which the grant decision was finalized.{/ts}</span></td>
+    </tr>
+    </table>
+    <p>{ts 1=$totalSelectedGrants}Number of selected grants: %1{/ts}</p>
+    <div class="crm-submit-buttons">{include file="CRM/common/formButtons.tpl" location="bottom"}</div>
+</div><!-- /.crm-form-block -->
+
+
+<script type="text/javascript">
+    {literal} 
+
+cj("#CIVICRM_QFID_amount_total_4").click(function() {
+   cj("#amount_total").show();
+   cj("#amount_granted").hide();
+   cj("#amount_granted").val(null);
+});
+
+cj("#CIVICRM_QFID_amount_granted_2").click(function() {
+   cj("#amount_granted").show();
+});
+    {/literal}
+</script>
\ No newline at end of file
diff --git a/templates/CRM/Grant/Form/Task/paymentResultTask.tpl b/templates/CRM/Grant/Form/Task/paymentResultTask.tpl
new file mode 100755
index 0000000..5de092c
--- /dev/null
+++ b/templates/CRM/Grant/Form/Task/paymentResultTask.tpl
@@ -0,0 +1,80 @@
+{*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.1                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*}
+{* Form elements for displaying and running action tasks on search results for all component searches. *}
+<div id="search-status">
+  <table class="form-layout-compressed">
+  <tr>
+    <td class="font-size12pt" style="width: 40%;">
+    {if $savedSearch.name}{$savedSearch.name} ({ts}smart group{/ts}) - {/if}
+    {ts count=$pager->_totalItems plural='%count Results'}%count Result{/ts}{if $selectorLabel}&nbsp;-&nbsp;{$selectorLabel}{/if}
+    {if $context == 'Event' && $participantCount && ( $pager->_totalItems ne $participantCount ) }
+        <br />{ts}Actual participant count{/ts} : {$participantCount} {help id="id-actual_participant_count" file="CRM/Event/Form/Search/Results.hlp"} &nbsp;
+    {/if}
+    </td>
+    <td>
+        {* Search criteria are passed to tpl in the $qill array *}
+        {if $qill}
+            {include file="CRM/common/displaySearchCriteria.tpl"}
+        {/if}
+    </td>
+  </tr>
+{if $context == 'Contribution'}
+  <tr>
+    <td colspan="2">
+{include file="CRM/Contribute/Page/ContributionTotals.tpl"}
+    </td>
+  </tr>
+{/if}
+{if !$hideTask }
+  <tr>
+    <td class="font-size11pt"> {ts}Select Records{/ts}:</td>
+    <td class="nowrap">
+        {$form.radio_ts.ts_all.html} {ts count=$pager->_totalItems plural='All %count records'}The found record{/ts} &nbsp; {if $pager->_totalItems > 1} {$form.radio_ts.ts_sel.html} {ts}Selected records only{/ts} {/if}
+    </td>
+  </tr>
+
+  <tr>
+    <td colspan="2">
+    {if $printButtonName}
+       {$form.$printButtonName.html} &nbsp; &nbsp;
+    {else}
+       {$form._qf_PaymentSearch_next_print.html} &nbsp; &nbsp;
+     {/if}
+     {$form.task.html}
+    {if $actionButtonName}
+       {$form.$actionButtonName.html} &nbsp; &nbsp;
+    {else}
+     {$form._qf_PaymentSearch_next_action.html} 
+   {/if}
+    </td>
+  </tr>{/if}
+  </table>
+</div>
+{literal}
+<script type="text/javascript">
+
+</script>
+{/literal}
diff --git a/templates/CRM/Grant/Page/DashBoard.tpl b/templates/CRM/Grant/Page/DashBoard.tpl
new file mode 100755
index 0000000..4e15fa7
--- /dev/null
+++ b/templates/CRM/Grant/Page/DashBoard.tpl
@@ -0,0 +1,69 @@
+{*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.1                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*}
+{* CiviGrant DashBoard (launch page) *}
+<div id="help" class="solid-border-bottom">
+    {capture assign=findContactURL}{crmURL p="civicrm/contact/search/basic" q="reset=1"}{/capture}
+    <p>{ts 1=$findContactURL }CiviGrant allows you to input and track grants to Organizations, Individuals or Households. The grantee must first be entered as a contact in CiviCRM. Use <a href='%1'>Find Contacts</a> to see if there's already a record for the grantee. Once you've located or created the contact record, click <strong>View</strong> to go to their summary page, select the <strong>Grants</strong> tab and click <strong>New Grant</strong>.{/ts}
+    </p>
+</div>
+<h3>{ts}Grants Summary{/ts}</h3>
+<div class="description">
+    {capture assign=findGrantsURL}{crmURL p="civicrm/grant/search" q="reset=1"}{/capture}
+    <p>{ts 1=$findGrantsURL}This table provides a summary of <strong>Grant Totals</strong>, and includes shortcuts to view the Grant details for these commonly used search periods. Click the Grant Status to see a list of Contacts for that grant status. To run your own customized searches - click <a href='%1'>Find Grants</a>. You can search by Contact Name, Amount, Grant type and a variety of other criteria.{/ts}
+    </p>
+</div>
+
+{if $grantSummary.total_grants}
+You have {$grantSummary.total_grants} grant(s) registered in your database.
+<table class="report">
+<tr class="columnheader-dark">
+    <th scope="col">{ts}Grant status{/ts}</th>
+    <th scope="col">{ts}Number of grants{/ts}</th>
+</tr>
+
+{foreach from=$grantSummary.per_status item=status key=id}
+<tr>
+    <td><a href="{crmURL p="civicrm/grant/search" q="reset=1&status=`$id`&force=1"}">{$status.label}</a></td>
+    <td><a href="{crmURL p="civicrm/grant/search" q="reset=1&status=`$id`&force=1"}">{$status.total}</a></td>
+</tr>
+{/foreach}
+<tr class="columnfooter">
+    <td>{ts}TOTAL{/ts}:</td>
+    <td>{$grantSummary.total_grants}</td>
+</tr>
+</table>
+{else}
+{ts}You have no Grants registered in your database.{/ts}
+{/if}
+
+
+{if $pager->_totalItems}
+    
+    <h3>{ts}Recent Grants{/ts}</h3>
+    <div class="form-item">
+        {include file="CRM/Grant/Form/Selector.tpl" context="DashBoard"}
+    </div>
+{/if}
diff --git a/templates/CRM/Grant/Page/GrantProgram.tpl b/templates/CRM/Grant/Page/GrantProgram.tpl
new file mode 100755
index 0000000..1ae3700
--- /dev/null
+++ b/templates/CRM/Grant/Page/GrantProgram.tpl
@@ -0,0 +1,82 @@
+{*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.0                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*}
+
+{if $action eq 1 or $action eq 2 or $action eq 8}
+   {include file="CRM/Grant/Form/GrantProgram.tpl"}
+{elseif $action eq 4}
+   {include file="CRM/Grant/Form/GrantProgramView.tpl"}
+{else}
+{if $rows}
+<div id="ltype">
+<p></p>
+    <div class="form-item">
+    {if $action ne 1 and $action ne 2}
+	    <div class="action-link">
+    	<a href="{crmURL q="action=add&reset=1"}" id="grant_program" class="button"><span><div class="icon add-icon"></div>{ts}Add Grant Program{/ts}</span></a>
+        </div>
+        {/if}
+        {strip}
+        <table cellpadding="0" cellspacing="0" border="0">
+           <thead class="sticky">
+            <th>{ts}Name{/ts}</th>
+            <th>{ts}Type{/ts}</th>
+            <th>{ts}Description{/ts}</th>
+            <th>{ts}Total{/ts}</th>
+            <th>{ts}Status{/ts}</th>
+	    <th>{ts}Allocation Date{/ts}</th>
+	    <th>{ts}Enabled?{/ts}</th>	
+            <th></th>
+          </thead>
+         {foreach from=$rows item=row}
+        <tr id="row_{$row.id}"class="{cycle values="odd-row,even-row"} {$row.class}{if NOT $row.is_active} disabled{/if}">
+	        <td>{$row.label}</td>	
+	        <td>{$row.grant_type_id}</td>
+            	<td>{$row.description}</td>
+	        <td>{$row.total_amount}</td>
+	        <td>{$row.status_id}</td>
+		<td>{$row.allocation_date|truncate:10:''|crmDate}</td>
+	        <td>{if $row.is_active}{ts}Yes{/ts}{else}{ts}No{/ts}{/if}</td>
+	        <td>{$row.action|replace:'xx':$row.id}</td>
+        </tr>
+        {/foreach}
+         </table>
+        {/strip}
+
+        {if $action ne 1 and $action ne 2}
+	    <div class="action-link">
+    	<a href="{crmURL q="action=add&reset=1"}" id="grant_program" class="button"><span><div class="icon add-icon"></div>{ts}Add Grant Program{/ts}</span></a>
+        </div>
+        {/if}
+    </div>
+</div>
+{else}
+    <div class="messages status">
+        <div class="icon inform-icon"></div>
+        {capture assign=crmURL}{crmURL q="action=add&reset=1"}{/capture}
+        {ts 1=$crmURL}There are no Grant Programs entered. You can <a href='%1'>add one</a>.{/ts}
+    </div>    
+{/if}
+{/if}
\ No newline at end of file
diff --git a/templates/CRM/Grant/Page/Payment.tpl b/templates/CRM/Grant/Page/Payment.tpl
new file mode 100755
index 0000000..ae00bf5
--- /dev/null
+++ b/templates/CRM/Grant/Page/Payment.tpl
@@ -0,0 +1,28 @@
+{*
+ +--------------------------------------------------------------------+
+ | CiviCRM version 4.1                                                |
+ +--------------------------------------------------------------------+
+ | Copyright CiviCRM LLC (c) 2004-2011                                |
+ +--------------------------------------------------------------------+
+ | This file is a part of CiviCRM.                                    |
+ |                                                                    |
+ | CiviCRM is free software; you can copy, modify, and distribute it  |
+ | under the terms of the GNU Affero General Public License           |
+ | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
+ |                                                                    |
+ | CiviCRM is distributed in the hope that it will be useful, but     |
+ | WITHOUT ANY WARRANTY; without even the implied warranty of         |
+ | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
+ | See the GNU Affero General Public License for more details.        |
+ |                                                                    |
+ | You should have received a copy of the GNU Affero General Public   |
+ | License and the CiviCRM Licensing Exception along                  |
+ | with this program; if not, contact CiviCRM LLC                     |
+ | at info[AT]civicrm[DOT]org. If you have questions about the        |
+ | GNU Affero General Public License or the licensing of CiviCRM,     |
+ | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ +--------------------------------------------------------------------+
+*}
+{if $action eq 4 or $action eq 524288 or $action eq 1048576 or $action eq 2097152 }
+        {include file="CRM/Grant/Form/Payment/View.tpl"}
+{/if}
diff --git a/xml/Menu/grantprograms.xml b/xml/Menu/grantprograms.xml
new file mode 100755
index 0000000..79f2c26
--- /dev/null
+++ b/xml/Menu/grantprograms.xml
@@ -0,0 +1,55 @@
+<?xml version="1.0" encoding="iso-8859-1" ?>
+<menu>
+ <item>
+     <path>civicrm/grant_program</path>
+     <title>Grant Programs</title>
+     <desc>List of grant programs which can be assigned to Grants</desc>
+     <page_callback>CRM_Grant_Page_GrantProgram</page_callback>
+     <access_arguments>edit grant program</access_arguments>
+     <page_type>1</page_type>
+     <weight>1011</weight>
+  </item> 
+  <item>
+     <path>civicrm/grant/payment</path>
+     <title>Grant Payment</title>
+     <desc>Grant Payment.</desc>
+     <page_callback>CRM_Grant_Page_Payment</page_callback>
+     <access_arguments>access CiviCRM</access_arguments>
+  </item>
+  <item>
+     <path>civicrm/grant/payment/search</path>
+     <title>Find Grant Payments</title>
+     <page_callback>CRM_Grant_Controller_PaymentSearch</page_callback>
+     <access_arguments>access CiviGrant</access_arguments>
+     <page_type>1</page_type>
+     <component>CiviGrant</component>
+  </item>   
+  <item>
+     <path>civicrm/grant/payment/reprint</path>
+     <title>Grant Payment Reprint</title>
+     <desc>Grant Payment Reprint.</desc>
+     <path_arguments>action=add</path_arguments>
+     <page_callback>CRM_Grant_Form_Task_GrantPayment</page_callback>
+     <access_arguments>access CiviGrant</access_arguments>
+  </item>  
+  <item>
+     <path>civicrm/grant_program/allocate</path>
+     <page_callback>CRM_Grant_Form_GrantProgramView::allocate</page_callback> 
+     <access_arguments>access CiviCRM</access_arguments> 
+  </item>
+  <item>
+     <path>civicrm/grant_program/finalize</path>
+     <page_callback>CRM_Grant_Form_GrantProgramView::finalize</page_callback> 
+     <access_arguments>access CiviCRM</access_arguments> 
+  </item>
+  <item>
+     <path>civicrm/grant_program/reject</path>
+     <page_callback>CRM_Grant_Form_GrantProgramView::reject</page_callback> 
+     <access_arguments>access CiviCRM</access_arguments> 
+  </item>
+  <item>
+     <path>civicrm/grant_program/processFinalization</path>
+     <page_callback>CRM_Grant_Form_GrantProgramView::processFinalization</page_callback> 
+     <access_arguments>access CiviCRM</access_arguments> 
+  </item>
+</menu>
-- 
GitLab