← Back to team overview

dhis2-devs team mailing list archive

[Merge] lp:~sis-ma/dhis2/SISMA-80 into lp:dhis2

 

Leandro Soares has proposed merging lp:~sis-ma/dhis2/SISMA-80 into lp:dhis2.

Requested reviews:
  DHIS 2 core developers (dhis2-devs-core)

For more details, see:
https://code.launchpad.net/~sis-ma/dhis2/SISMA-80/+merge/186327

Changes to allow user metadata import.

Modified files for helping merge:

dhis-2\dhis-api\src\main\java\org\hisp\dhis\common\SharingUtils.java
dhis-2\dhis-api\src\main\java\org\hisp\dhis\user\User.java
dhis-2\dhis-api\src\main\java\org\hisp\dhis\user\UserCredentials.java
dhis-2\dhis-api\src\main\java\org\hisp\dhis\mapping\MapView.java
dhis-2\dhis-services\dhis-service-dxf2\src\main\java\org\hisp\dhis\dxf2\metadata\ExchangeClasses.java
dhis-2\dhis-services\dhis-service-dxf2\src\main\java\org\hisp\dhis\dxf2\DefaultIdentifiableObjectImporter.java
dhis-2\dhis-services\dhis-service-core\src\main\java\org\hisp\dhis\startup\TableAlteror.java
dhis-2\dhis-services\dhis-service-core\src\main\resources\org\hisp\dhis\user\hibernate\UserCredentials.hbm.xml
-- 
The attached diff has been truncated due to its size.
https://code.launchpad.net/~sis-ma/dhis2/SISMA-80/+merge/186327
Your team DHIS 2 developers is subscribed to branch lp:dhis2.
=== modified file 'dhis-2/dhis-api/src/main/java/org/hisp/dhis/aggregation/AggregatedDataValueService.java'
=== modified file 'dhis-2/dhis-api/src/main/java/org/hisp/dhis/aggregation/AggregatedDataValueStore.java'
=== modified file 'dhis-2/dhis-api/src/main/java/org/hisp/dhis/caseaggregation/CaseAggregationCondition.java'
--- dhis-2/dhis-api/src/main/java/org/hisp/dhis/caseaggregation/CaseAggregationCondition.java	2013-09-11 15:26:20 +0000
+++ dhis-2/dhis-api/src/main/java/org/hisp/dhis/caseaggregation/CaseAggregationCondition.java	2013-09-18 14:05:25 +0000
@@ -67,6 +67,10 @@
     public static String OBJECT_ORGUNIT_COMPLETE_PROGRAM_STAGE = "PSIC";
     public static String OBJECT_PROGRAM_PROPERTY_INCIDENT_DATE = "dateOfIncident";
     public static String OBJECT_PROGRAM_PROPERTY_ENROLLEMENT_DATE = "enrollmentDate";
+<<<<<<< TREE
+=======
+
+>>>>>>> MERGE-SOURCE
     public static String OBJECT_PROGRAM_PROPERTY_REPORT_DATE_DATE = "executionDate";
 
     public static String MINUS_OPERATOR = "DATEDIFF";
@@ -79,6 +83,7 @@
         + OBJECT_PATIENT_ATTRIBUTE + "|" + OBJECT_PATIENT_PROPERTY + "|" + OBJECT_PROGRAM_PROPERTY + ")"
         + SEPARATOR_OBJECT + "([a-zA-Z0-9@#\\- ]+[" + SEPARATOR_ID + "[a-zA-Z0-9]*]*)" + "\\]";
 
+<<<<<<< TREE
     public static final String dataelementRegExp = MINUS_OPERATOR + "{1}\\s*\\(\\s*(\\["
         + OBJECT_PROGRAM_STAGE_DATAELEMENT + SEPARATOR_OBJECT + "([0-9]+" + SEPARATOR_ID + "[0-9]+" + SEPARATOR_ID
         + "[0-9]+)+\\])\\s*(,)+\\s*(" + OBJECT_PROGRAM_PROPERTY_INCIDENT_DATE + "|"
@@ -88,6 +93,12 @@
         + OBJECT_PROGRAM_STAGE_DATAELEMENT + SEPARATOR_OBJECT + "([0-9]+" + SEPARATOR_ID + "[0-9]+" + SEPARATOR_ID
         + "[0-9]+)+\\])\\s*(,)\\s*(\\[" + OBJECT_PROGRAM_STAGE_DATAELEMENT + SEPARATOR_OBJECT + "([0-9]+"
         + SEPARATOR_ID + "[0-9]+" + SEPARATOR_ID + "[0-9]+)+\\])\\s*\\)\\s*(>=|<=|!=|>|<|=){1}\\s*([0-9]+)";
+=======
+    public static final String dataelementRegExp = MINUS_OPERATOR + "{1}\\s*\\(\\s*(\\["
+        + OBJECT_PROGRAM_STAGE_DATAELEMENT + SEPARATOR_OBJECT + "([0-9]+" + SEPARATOR_ID + "[0-9]+" + SEPARATOR_ID
+        + "[0-9]+)+\\])\\s*(,)+\\s*(" + OBJECT_PROGRAM_PROPERTY_INCIDENT_DATE + "|"
+        + OBJECT_PROGRAM_PROPERTY_REPORT_DATE_DATE + "|" + OBJECT_PROGRAM_PROPERTY_ENROLLEMENT_DATE + ")+\\s*\\)\\s*";
+>>>>>>> MERGE-SOURCE
 
     // -------------------------------------------------------------------------
     // Fields

=== modified file 'dhis-2/dhis-api/src/main/java/org/hisp/dhis/common/BaseAnalyticalObject.java'
=== modified file 'dhis-2/dhis-api/src/main/java/org/hisp/dhis/common/DimensionalObjectUtils.java'
=== modified file 'dhis-2/dhis-api/src/main/java/org/hisp/dhis/dataanalysis/DataAnalysisStore.java'
=== modified file 'dhis-2/dhis-api/src/main/java/org/hisp/dhis/dataelement/DataElementCategoryService.java'
=== modified file 'dhis-2/dhis-api/src/main/java/org/hisp/dhis/dataelement/DataElementOperand.java'
=== modified file 'dhis-2/dhis-api/src/main/java/org/hisp/dhis/dataset/DataSet.java'
--- dhis-2/dhis-api/src/main/java/org/hisp/dhis/dataset/DataSet.java	2013-08-23 15:56:19 +0000
+++ dhis-2/dhis-api/src/main/java/org/hisp/dhis/dataset/DataSet.java	2013-09-18 14:05:25 +0000
@@ -72,7 +72,7 @@
     public static final String TYPE_SECTION_MULTIORG = "multiorg_section";
 
     public static final int NO_EXPIRY = 0;
-
+    
     /**
      * Determines if a de-serialized file is compatible with this class.
      */

=== modified file 'dhis-2/dhis-api/src/main/java/org/hisp/dhis/mapping/MappingService.java'
=== modified file 'dhis-2/dhis-api/src/main/java/org/hisp/dhis/patient/PatientIdentifierTypeService.java'
=== modified file 'dhis-2/dhis-api/src/main/java/org/hisp/dhis/report/ReportService.java'
=== modified file 'dhis-2/dhis-api/src/main/java/org/hisp/dhis/setting/SystemSettingManager.java'
=== modified file 'dhis-2/dhis-services/dhis-service-administration/src/main/java/org/hisp/dhis/resourcetable/jdbc/JdbcResourceTableStore.java'
=== modified file 'dhis-2/dhis-services/dhis-service-analytics/src/main/java/org/hisp/dhis/analytics/AnalyticsService.java'
=== modified file 'dhis-2/dhis-services/dhis-service-analytics/src/main/java/org/hisp/dhis/analytics/DataQueryParams.java'
--- dhis-2/dhis-services/dhis-service-analytics/src/main/java/org/hisp/dhis/analytics/DataQueryParams.java	2013-08-31 18:07:17 +0000
+++ dhis-2/dhis-services/dhis-service-analytics/src/main/java/org/hisp/dhis/analytics/DataQueryParams.java	2013-09-18 14:05:25 +0000
@@ -96,7 +96,11 @@
     public static final List<String> DATA_DIMS = Arrays.asList( INDICATOR_DIM_ID, DATAELEMENT_DIM_ID, DATAELEMENT_OPERAND_ID, DATASET_DIM_ID );
     public static final List<String> FIXED_DIMS = Arrays.asList( DATA_X_DIM_ID, INDICATOR_DIM_ID, DATAELEMENT_DIM_ID, DATASET_DIM_ID, PERIOD_DIM_ID, ORGUNIT_DIM_ID );
     
+<<<<<<< TREE
     public static final int MAX_DIM_OPT_PERM = 50000;
+=======
+    public static final int MAX_DIM_OPT_PERM = 20000;
+>>>>>>> MERGE-SOURCE
 
     private static final List<DimensionType> COMPLETENESS_DIMENSION_TYPES = Arrays.asList( DATASET, ORGANISATIONUNIT, ORGANISATIONUNIT_GROUPSET );
     

=== modified file 'dhis-2/dhis-services/dhis-service-analytics/src/main/java/org/hisp/dhis/analytics/data/DefaultAnalyticsService.java'
--- dhis-2/dhis-services/dhis-service-analytics/src/main/java/org/hisp/dhis/analytics/data/DefaultAnalyticsService.java	2013-08-23 16:05:01 +0000
+++ dhis-2/dhis-services/dhis-service-analytics/src/main/java/org/hisp/dhis/analytics/data/DefaultAnalyticsService.java	2013-09-18 14:05:25 +0000
@@ -182,6 +182,9 @@
 
     @Autowired
     private CurrentUserService currentUserService;
+    
+    @Autowired
+    private DataElementOperandService operandService;
 
     public void setCurrentUserService( CurrentUserService currentUserService )
     {

=== modified file 'dhis-2/dhis-services/dhis-service-analytics/src/main/java/org/hisp/dhis/analytics/table/JdbcAnalyticsTableManager.java'
=== modified file 'dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/aggregation/DefaultAggregatedDataValueService.java'
=== modified file 'dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/aggregation/jdbc/JdbcAggregatedDataValueStore.java'
=== modified file 'dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/appmanager/DefaultAppManagerService.java'
=== modified file 'dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/common/DefaultDimensionService.java'
=== modified file 'dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/common/IdentityPopulator.java'
--- dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/common/IdentityPopulator.java	2013-09-13 07:40:23 +0000
+++ dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/common/IdentityPopulator.java	2013-09-18 14:05:25 +0000
@@ -28,6 +28,12 @@
  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
+<<<<<<< TREE
+=======
+import java.util.Map;
+import java.util.UUID;
+
+>>>>>>> MERGE-SOURCE
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 import org.hisp.dhis.system.startup.AbstractStartupRoutine;
@@ -56,6 +62,10 @@
         "maplegendset", "maplayer", "section", "optionset", "program", "programinstance", "programstage", "programstageinstance",
         "patient", "patientidentifier"
     };
+    
+    private static final Map<String, String> TABLE_ID_MAP = DimensionalObjectUtils.asMap( 
+        "dataelementcategoryoption", "categoryoptionid",
+        "dataelementcategory", "categoryid" );
 
     private static final Map<String, String> TABLE_ID_MAP = DimensionalObjectUtils.asMap(
         "dataelementcategoryoption", "categoryoptionid",
@@ -139,9 +149,15 @@
             }
             catch ( Exception ex )
             {
+<<<<<<< TREE
                 log.error( "Problem updating: " + table + ", id column: " + getIdColumn( table ), ex );
 
                 throw ex;
+=======
+                log.error( "Problem updating: " + table + ", id column: " + getIdColumn( table ), ex );
+                
+                throw ex;
+>>>>>>> MERGE-SOURCE
             }
         }
 
@@ -161,6 +177,11 @@
         return TABLE_ID_MAP.containsKey( table ) ? TABLE_ID_MAP.get( table ) : (table + "id");
     }
 
+    private String getIdColumn( String table )
+    {
+        return TABLE_ID_MAP.containsKey( table ) ? TABLE_ID_MAP.get( table ) : ( table + "id" );        
+    }
+    
     private void createUidConstraints()
     {
         for ( String table : tables )

=== modified file 'dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataelement/DefaultDataElementCategoryService.java'
=== modified file 'dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataentryform/hibernate/HibernateDataEntryFormStore.java'
=== modified file 'dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/datavalue/hibernate/HibernateDataValueStore.java'
=== modified file 'dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/expression/DefaultExpressionService.java'
=== modified file 'dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/mapping/DefaultMappingService.java'
=== modified file 'dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/organisationunit/hibernate/HibernateOrganisationUnitLevelStore.java'
=== modified file 'dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/startup/TableAlteror.java'
--- dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/startup/TableAlteror.java	2013-09-17 16:29:29 +0000
+++ dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/startup/TableAlteror.java	2013-09-18 14:05:25 +0000
@@ -619,6 +619,7 @@
         executeSql( "ALTER TABLE dataelement ALTER COLUMN domaintype SET NOT NULL" );
         executeSql( "update dataelementcategory set datadimension = false where datadimension is null" );
         
+<<<<<<< TREE
 	executeSql( "UPDATE dataset SET dataelementdecoration=false WHERE dataelementdecoration is null" );
 
         executeSql( "alter table validationrulegroup rename column validationgroupid to validationrulegroupid" );
@@ -637,6 +638,11 @@
 
         upgradeMapViewsToAnalyticalObject();
         
+=======
+        executeSql( "alter table validationrulegroup rename column validationgroupid to validationrulegroupid" );
+        executeSql( "alter table sqlview rename column viewid to sqlviewid" );
+        
+>>>>>>> MERGE-SOURCE
         log.info( "Tables updated" );
     }
 

=== modified file 'dhis-2/dhis-services/dhis-service-core/src/main/resources/META-INF/dhis/beans.xml'
=== modified file 'dhis-2/dhis-services/dhis-service-core/src/main/resources/org/hisp/dhis/datavalue/hibernate/DataValue.hbm.xml'
=== modified file 'dhis-2/dhis-services/dhis-service-core/src/test/java/org/hisp/dhis/expression/ExpressionServiceTest.java'
=== modified file 'dhis-2/dhis-services/dhis-service-core/src/test/java/org/hisp/dhis/organisationunit/OrganisationUnitServiceTest.java'
--- dhis-2/dhis-services/dhis-service-core/src/test/java/org/hisp/dhis/organisationunit/OrganisationUnitServiceTest.java	2013-08-23 16:05:01 +0000
+++ dhis-2/dhis-services/dhis-service-core/src/test/java/org/hisp/dhis/organisationunit/OrganisationUnitServiceTest.java	2013-09-18 14:05:25 +0000
@@ -845,18 +845,35 @@
         assertNull( organisationUnitService.getOrganisationUnitLevel( idA ) );
         assertNull( organisationUnitService.getOrganisationUnitLevel( idB ) );
     }
-
-    @Test
-    public void getMaxLevels()
-    {
-        assertEquals( 0, organisationUnitService.getMaxOfOrganisationUnitLevels() );
-
-        OrganisationUnitLevel levelA = new OrganisationUnitLevel( 1, "National" );
-        OrganisationUnitLevel levelB = new OrganisationUnitLevel( 2, "District" );
-
-        organisationUnitService.addOrganisationUnitLevel( levelA );
-        organisationUnitService.addOrganisationUnitLevel( levelB );
-
-        assertEquals( 2, organisationUnitService.getMaxOfOrganisationUnitLevels() );
-    }
+<<<<<<< TREE
+
+    @Test
+    public void getMaxLevels()
+    {
+        assertEquals( 0, organisationUnitService.getMaxOfOrganisationUnitLevels() );
+
+        OrganisationUnitLevel levelA = new OrganisationUnitLevel( 1, "National" );
+        OrganisationUnitLevel levelB = new OrganisationUnitLevel( 2, "District" );
+
+        organisationUnitService.addOrganisationUnitLevel( levelA );
+        organisationUnitService.addOrganisationUnitLevel( levelB );
+
+        assertEquals( 2, organisationUnitService.getMaxOfOrganisationUnitLevels() );
+    }
+=======
+    
+    @Test
+    public void getMaxLevels()
+    {
+        assertEquals( 0, organisationUnitService.getMaxOfOrganisationUnitLevels() );
+
+        OrganisationUnitLevel levelA = new OrganisationUnitLevel( 1, "National" );
+        OrganisationUnitLevel levelB = new OrganisationUnitLevel( 2, "District" );
+
+        organisationUnitService.addOrganisationUnitLevel( levelA );
+        organisationUnitService.addOrganisationUnitLevel( levelB );
+
+        assertEquals( 2, organisationUnitService.getMaxOfOrganisationUnitLevels() );
+    }
+>>>>>>> MERGE-SOURCE
 }

=== modified file 'dhis-2/dhis-services/dhis-service-dxf2/pom.xml'
--- dhis-2/dhis-services/dhis-service-dxf2/pom.xml	2013-08-22 13:19:57 +0000
+++ dhis-2/dhis-services/dhis-service-dxf2/pom.xml	2013-09-18 14:05:25 +0000
@@ -30,6 +30,7 @@
       <groupId>org.hisp.dhis</groupId>
       <artifactId>dhis-service-i18n</artifactId>
     </dependency>
+<<<<<<< TREE
     
     <dependency>
       <groupId>net.sourceforge.javacsv</groupId>
@@ -39,6 +40,24 @@
       <groupId>com.lowagie</groupId>
       <artifactId>itext</artifactId>
     </dependency>
+=======
+    <dependency>
+      <groupId>org.hisp.dhis</groupId>
+      <artifactId>dhis-support-system</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>org.hisp.dhis</groupId>
+      <artifactId>dhis-support-test</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>org.hisp.dhis</groupId>
+      <artifactId>dhis-support-xml</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>net.sourceforge.javacsv</groupId>
+      <artifactId>javacsv</artifactId>
+    </dependency>
+>>>>>>> MERGE-SOURCE
     <dependency>
       <groupId>com.fasterxml.jackson.core</groupId>
       <artifactId>jackson-core</artifactId>

=== modified file 'dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/datavalue/StreamingCsvDataValue.java'
=== modified file 'dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/datavalueset/DataValueSetService.java'
=== modified file 'dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/datavalueset/DefaultDataValueSetService.java'
=== modified file 'dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/datavalueset/SpringDataValueSetStore.java'
=== modified file 'dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/datavalueset/StreamingCsvDataValueSet.java'
=== modified file 'dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/datavalueset/StreamingDataValueSet.java'
=== modified file 'dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/Options.java'
=== modified file 'dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/metadata/importers/DefaultIdentifiableObjectImporter.java'
=== modified file 'dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/pdfform/DefaultPdfDataEntryFormService.java'
--- dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/pdfform/DefaultPdfDataEntryFormService.java	2013-08-23 16:05:01 +0000
+++ dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/pdfform/DefaultPdfDataEntryFormService.java	2013-09-18 14:05:25 +0000
@@ -183,11 +183,19 @@
             document.add( mainTable );
 
 
+<<<<<<< TREE
             document.add( Chunk.NEWLINE );             
             document.add( Chunk.NEWLINE );
             
             insertSaveAsButton( document, writer, PdfDataEntryFormUtil.LABELCODE_BUTTON_SAVEAS, dataSet.getDisplayName() );
              
+=======
+            //document.add( Chunk.NEWLINE );             
+            //document.add( Chunk.NEWLINE );
+            
+            //insertSaveAsButton( document, writer, PdfDataEntryFormUtil.LABELCODE_BUTTON_SAVEAS, dataSet.getDisplayName() );
+             
+>>>>>>> MERGE-SOURCE
         }
     }
 

=== modified file 'dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/pdfform/PdfDataEntryFormService.java'
=== modified file 'dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/pdfform/PdfDataEntryFormUtil.java'
--- dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/pdfform/PdfDataEntryFormUtil.java	2013-08-23 16:05:01 +0000
+++ dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/pdfform/PdfDataEntryFormUtil.java	2013-09-18 14:05:25 +0000
@@ -51,9 +51,16 @@
 import com.lowagie.text.pdf.PdfPCell;
 import com.lowagie.text.pdf.PdfReader;
 
-/**
- * @author James Chang
- */
+<<<<<<< TREE
+/**
+ * @author James Chang
+ */
+=======
+/**
+ * @author James Chang
+ */
+
+>>>>>>> MERGE-SOURCE
 public class PdfDataEntryFormUtil
 {
     public static final int DATATYPE_DATASET = 0;
@@ -145,7 +152,16 @@
         }
     }
 
-    public static PdfPCell getPdfPCell( boolean hasBorder )
+<<<<<<< TREE
+    public static PdfPCell getPdfPCell( boolean hasBorder )
+=======
+//  public static PdfPCell getPdfPCell( float minHeight )
+//  {
+//      return getPdfPCell( minHeight, CELL_COLUMN_TYPE_LABEL );
+//  }
+
+    public static PdfPCell getPdfPCell( boolean hasBorder )
+>>>>>>> MERGE-SOURCE
     {
         return getPdfPCell( CELL_MIN_HEIGHT_DEFAULT, CELL_COLUMN_TYPE_ENTRYFIELD, hasBorder );
     }

=== modified file 'dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/pdfform/PdfFieldCell.java'
--- dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/pdfform/PdfFieldCell.java	2013-08-23 16:05:01 +0000
+++ dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/pdfform/PdfFieldCell.java	2013-09-18 14:05:25 +0000
@@ -28,6 +28,8 @@
  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
+import java.util.Locale;
+
 import com.lowagie.text.Element;
 import com.lowagie.text.Phrase;
 import com.lowagie.text.Rectangle;

=== modified file 'dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/pdfform/PdfFormFontSettings.java'
=== modified file 'dhis-2/dhis-services/dhis-service-dxf2/src/test/java/org/hisp/dhis/dxf2/datavalueset/DataValueSetServiceTest.java'
=== modified file 'dhis-2/dhis-services/dhis-service-importexport/src/main/java/org/hisp/dhis/importexport/dhis14/file/rowhandler/DataElementRowHandler.java'
=== modified file 'dhis-2/dhis-services/dhis-service-importexport/src/main/java/org/hisp/dhis/importexport/dhis14/xml/converter/DataElementConverter.java'
=== modified file 'dhis-2/dhis-services/dhis-service-mapgeneration/pom.xml'
=== added file 'dhis-2/dhis-services/dhis-service-mapgeneration/src/main/java/org/hisp/dhis/mapgeneration/GeoToolsMap.java.OTHER'
--- dhis-2/dhis-services/dhis-service-mapgeneration/src/main/java/org/hisp/dhis/mapgeneration/GeoToolsMap.java.OTHER	1970-01-01 00:00:00 +0000
+++ dhis-2/dhis-services/dhis-service-mapgeneration/src/main/java/org/hisp/dhis/mapgeneration/GeoToolsMap.java.OTHER	2013-09-18 14:05:25 +0000
@@ -0,0 +1,296 @@
+package org.hisp.dhis.mapgeneration;
+
+/*
+ * Copyright (c) 2004-2012, University of Oslo
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ * * Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright notice,
+ *   this list of conditions and the following disclaimer in the documentation
+ *   and/or other materials provided with the distribution.
+ * * Neither the name of the HISP project nor the names of its contributors may
+ *   be used to endorse or promote products derived from this software without
+ *   specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+import java.awt.Color;
+import java.awt.Graphics2D;
+import java.awt.Rectangle;
+import java.awt.RenderingHints;
+import java.awt.image.BufferedImage;
+import java.util.LinkedList;
+import java.util.List;
+
+import org.geotools.data.DataUtilities;
+import org.geotools.data.simple.SimpleFeatureCollection;
+import org.geotools.feature.FeatureCollections;
+import org.geotools.feature.SchemaException;
+import org.geotools.feature.simple.SimpleFeatureBuilder;
+import org.geotools.geometry.jts.ReferencedEnvelope;
+import org.geotools.map.FeatureLayer;
+import org.geotools.map.Layer;
+import org.geotools.map.MapContent;
+import org.geotools.renderer.GTRenderer;
+import org.geotools.renderer.lite.StreamingRenderer;
+import org.geotools.styling.SLD;
+import org.geotools.styling.Style;
+import org.opengis.feature.simple.SimpleFeature;
+import org.opengis.feature.simple.SimpleFeatureType;
+
+import com.vividsolutions.jts.geom.Geometry;
+import com.vividsolutions.jts.geom.MultiPolygon;
+import com.vividsolutions.jts.geom.Point;
+import com.vividsolutions.jts.geom.Polygon;
+
+/**
+ * This class can be used to render map objects onto a map image. The projection
+ * is transformed automatically to "EPSG 3785".
+ * 
+ * @author Kjetil Andresen <kjetand@xxxxxxxxxx>
+ * @author Olai Solheim <olais@xxxxxxxxxx>
+ */
+public class GeoToolsMap
+    extends InternalMap
+{
+    // The flat list of map objects in this map.
+    private List<GeoToolsMapObject> mapObjects;
+
+    /**
+     * Creates an empty map.
+     */
+    public GeoToolsMap()
+    {
+        this.mapObjects = new LinkedList<GeoToolsMapObject>();
+    }
+
+    /**
+     * Creates a map with the given initial map layer.
+     * 
+     * @param layer the initial map layer
+     */
+    public GeoToolsMap( InternalMapLayer layer )
+    {
+        this.mapObjects = new LinkedList<GeoToolsMapObject>();
+        this.addMapLayer( layer );
+    }
+
+    /**
+     * Creates a map with the given initial map layers.
+     * 
+     * @param layers the list of initial map layers
+     */
+    public GeoToolsMap( List<InternalMapLayer> layers )
+    {
+        this.mapObjects = new LinkedList<GeoToolsMapObject>();
+        this.addAllMapLayers( layers );
+    }
+
+    /**
+     * Adds a map object to this map.
+     * 
+     * @param mapObject the map object
+     */
+    public void addMapObject( GeoToolsMapObject mapObject )
+    {
+        this.mapObjects.add( mapObject );
+    }
+
+    /**
+     * Adds all map objects contained in the list.
+     * 
+     * @param mapObjects the list of map objects
+     */
+    public void addMapObjects( List<GeoToolsMapObject> mapObjects )
+    {
+        this.mapObjects.addAll( mapObjects );
+    }
+
+    // -------------------------------------------------------------------------
+    // InternalMap implementation
+    // -------------------------------------------------------------------------
+
+    public void addMapLayer( InternalMapLayer layer )
+    {
+        for ( InternalMapObject mapObject : layer.getAllMapObjects() )
+        {
+            this.addMapObject( (GeoToolsMapObject) mapObject );
+        }
+    }
+
+    public void addAllMapLayers( List<InternalMapLayer> layers )
+    {
+        for ( InternalMapLayer layer : layers )
+        {
+            for ( InternalMapObject mapObject : layer.getAllMapObjects() )
+            {
+                this.addMapObject( (GeoToolsMapObject) mapObject );
+            }
+        }
+    }
+
+    public BufferedImage render()
+    {
+        return render( DEFAULT_MAP_WIDTH );
+    }
+
+    public BufferedImage render( int imageWidth )
+    {
+        MapContent map = new MapContent();
+
+        // Convert map objects to features, and add them to the map
+        for ( GeoToolsMapObject mapObject : mapObjects )
+        {
+            try
+            {
+                map.addLayer( createFeatureLayerFromMapObject( mapObject ) );
+            }
+            catch ( SchemaException ex )
+            {
+                throw new RuntimeException( "Could not add map object: " + mapObject.toString() + ": " + ex.getMessage() );
+            }
+        }
+
+        // Create a renderer for this map
+        GTRenderer renderer = new StreamingRenderer();
+        renderer.setMapContent( map );
+
+        // Calculate image height
+        // TODO Might want to add a margin of say 25 pixels surrounding the map
+        ReferencedEnvelope mapBounds = map.getMaxBounds();
+        double imageHeightFactor = mapBounds.getSpan( 1 ) / mapBounds.getSpan( 0 );
+        Rectangle imageBounds = new Rectangle( 0, 0, imageWidth, (int) Math.ceil( imageWidth * imageHeightFactor ) );
+
+        // Create an image and get the graphics context from it
+        BufferedImage image = new BufferedImage( imageBounds.width, imageBounds.height, BufferedImage.TYPE_INT_ARGB );
+        Graphics2D g = (Graphics2D) image.getGraphics();
+
+        // Draw a background if the background color is specified
+        // NOTE It will be transparent otherwise, which is desired
+        if ( backgroundColor != null )
+        {
+            g.setColor( backgroundColor );
+            g.fill( imageBounds );
+        }
+
+        // Enable anti-aliasing if specified
+        if ( isAntiAliasingEnabled )
+        {
+            g.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
+        }
+        else
+        {
+            g.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF );
+        }
+
+        // Render the map
+        renderer.paint( g, imageBounds, mapBounds );
+
+        map.dispose();
+        
+        return image;
+    }
+
+    // -------------------------------------------------------------------------
+    // Internal
+    // -------------------------------------------------------------------------
+
+    /**
+     * Creates a feature layer based on a map object.
+     */
+    private Layer createFeatureLayerFromMapObject( GeoToolsMapObject mapObject )
+        throws SchemaException
+    {
+        SimpleFeatureType featureType;
+        SimpleFeatureBuilder featureBuilder;
+        SimpleFeature feature;
+        SimpleFeatureCollection featureCollection;
+        Style style = null;
+
+        featureType = createFeatureType( mapObject.getGeometry() );
+        featureBuilder = new SimpleFeatureBuilder( featureType );
+        featureBuilder.add( mapObject.getGeometry() );
+        feature = featureBuilder.buildFeature( null );
+
+        featureCollection = FeatureCollections.newCollection();
+        featureCollection.add( feature );
+
+        // Create style for this map object
+        if ( mapObject.getGeometry() instanceof Point )
+        {
+            style = SLD.createPointStyle( "Circle", mapObject.getStrokeColor(), mapObject.getFillColor(),
+                mapObject.getFillOpacity(), mapObject.getRadius() );
+        }
+        else if ( mapObject.getGeometry() instanceof Polygon || mapObject.getGeometry() instanceof MultiPolygon )
+        {
+            style = SLD.createPolygonStyle( mapObject.getStrokeColor(), mapObject.getFillColor(),
+                mapObject.getFillOpacity() );
+        }
+        else
+        {
+            style = SLD.createSimpleStyle( featureType );
+        }
+
+        return new FeatureLayer( featureCollection, style );
+    }
+
+    /**
+     * Creates a feature type for a GeoTools geometric primitive.
+     */
+    private SimpleFeatureType createFeatureType( Geometry geom )
+        throws SchemaException
+    {
+        String type = "";
+
+        if ( geom instanceof Point )
+        {
+            type = "Point";
+        }
+        else if ( geom instanceof Polygon )
+        {
+            type = "Polygon";
+        }
+        else if ( geom instanceof MultiPolygon )
+        {
+            type = "MultiPolygon";
+        }
+        else
+        {
+            throw new IllegalArgumentException();
+        }
+
+        return DataUtilities.createType( "geometries", "geometry:" + type + ":srid=3785" );
+    }
+
+    /**
+     * Creates an image with text indicating an error.
+     */
+    @SuppressWarnings( "unused" )
+    private BufferedImage createErrorImage( String error )
+    {
+        String str = "Error creating map image: " + error;
+        BufferedImage image = new BufferedImage( 500, 25, BufferedImage.TYPE_INT_RGB );
+        Graphics2D g = (Graphics2D) image.createGraphics();
+
+        g.setColor( Color.WHITE );
+        g.fill( new Rectangle( 500, 25 ) );
+
+        g.setColor( Color.RED );
+        g.drawString( str, 1, 12 );
+
+        return image;
+    }
+}

=== modified file 'dhis-2/dhis-services/dhis-service-mapgeneration/src/main/java/org/hisp/dhis/mapgeneration/GeoToolsMapGenerationService.java'
--- dhis-2/dhis-services/dhis-service-mapgeneration/src/main/java/org/hisp/dhis/mapgeneration/GeoToolsMapGenerationService.java	2013-09-17 16:22:09 +0000
+++ dhis-2/dhis-services/dhis-service-mapgeneration/src/main/java/org/hisp/dhis/mapgeneration/GeoToolsMapGenerationService.java	2013-09-18 14:05:25 +0000
@@ -28,14 +28,20 @@
  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
+import static org.hisp.dhis.common.NameableObjectUtils.getList;
+
 import java.awt.Color;
 import java.awt.Graphics;
 import java.awt.image.BufferedImage;
 import java.util.ArrayList;
 import java.util.Collection;
+<<<<<<< TREE
 import java.util.Collections;
 import java.util.HashMap;
 import java.util.List;
+=======
+import java.util.List;
+>>>>>>> MERGE-SOURCE
 
 import org.apache.commons.lang.StringUtils;
 import org.hisp.dhis.analytics.AnalyticsService;
@@ -159,13 +165,18 @@
 
     private InternalMapLayer getSingleInternalMapLayer( MapView mapView )
     {
+<<<<<<< TREE
         if ( mapView == null )
         {
             return null;
         }
+=======
+        Assert.isTrue( mapView != null );
+>>>>>>> MERGE-SOURCE
 
         boolean isIndicator = MapView.VALUE_TYPE_INDICATOR.equals( mapView.getValueType() );
 
+<<<<<<< TREE
         List<OrganisationUnit> atLevels = new ArrayList<OrganisationUnit>();
         List<OrganisationUnit> inGroups = new ArrayList<OrganisationUnit>();
         
@@ -197,6 +208,43 @@
         Collection<MapValue> mapValues = getMapValues( grid );
 
         if ( mapValues.isEmpty() )
+=======
+        List<OrganisationUnit> organisationUnits = new ArrayList<OrganisationUnit>( organisationUnitService.
+            getOrganisationUnitsAtLevel( mapView.getOrganisationUnitLevel().getLevel(), mapView.getParentOrganisationUnit() ) );
+
+        DataQueryParams params = new DataQueryParams();
+        
+        if ( mapView.getIndicator() != null )
+        {
+            params.setIndicators( getList( mapView.getIndicator() ) );
+        }
+        else if ( mapView.getDataElement() != null )
+        {
+            params.setDataElements( getList( mapView.getDataElement() ) );
+        }
+        
+        //TODO operands
+
+        params.setOrganisationUnits( organisationUnits );
+        params.setFilterPeriods( getList( mapView.getPeriod() ) );
+        
+        Grid grid = analyticsService.getAggregatedDataValues( params );
+        
+        Collection<MapValue> mapValues = new ArrayList<MapValue>();
+
+        for ( List<Object> row : grid.getRows() )
+        {
+            if ( row != null && row.size() >= 3 )
+            {
+                String ou = (String) row.get( 1 );
+                Double value = (Double) row.get( 2 );
+                
+                mapValues.add( new MapValue( ou, value ) );
+            }
+        }
+                
+        if ( mapValues.isEmpty() )
+>>>>>>> MERGE-SOURCE
         {
             return null;
         }
@@ -243,7 +291,11 @@
         for ( MapValue mapValue : mapValues )
         {
             // Get the org unit for this map value
+<<<<<<< TREE
             OrganisationUnit orgUnit = uidOuMap.get( mapValue.getOu() );
+=======
+            OrganisationUnit orgUnit = organisationUnitService.getOrganisationUnit( mapValue.getOu() );
+>>>>>>> MERGE-SOURCE
             
             if ( orgUnit != null && orgUnit.hasCoordinates() && orgUnit.hasFeatureType() )
             {
@@ -266,6 +318,7 @@
         return mapLayer;
     }
 
+<<<<<<< TREE
     /**
      * Creates a list of aggregated map values.
      */
@@ -289,6 +342,10 @@
     
     private InternalMapObject buildSingleGeoToolsMapObjectForMapLayer( InternalMapLayer mapLayer,
         double mapValue, OrganisationUnit orgUnit )
+=======
+    private GeoToolsMapObject buildSingleGeoToolsMapObjectForMapLayer( InternalMapLayer mapLayer,
+        double mapValue, OrganisationUnit orgUnit )
+>>>>>>> MERGE-SOURCE
     {
         // Create and setup an internal map object
         InternalMapObject mapObject = new InternalMapObject();

=== modified file 'dhis-2/dhis-services/dhis-service-mapgeneration/src/main/java/org/hisp/dhis/mapgeneration/MapValue.java'
--- dhis-2/dhis-services/dhis-service-mapgeneration/src/main/java/org/hisp/dhis/mapgeneration/MapValue.java	2013-08-23 16:05:01 +0000
+++ dhis-2/dhis-services/dhis-service-mapgeneration/src/main/java/org/hisp/dhis/mapgeneration/MapValue.java	2013-09-18 14:05:25 +0000
@@ -1,3 +1,4 @@
+<<<<<<< TREE
 package org.hisp.dhis.mapgeneration;
 
 /*
@@ -60,3 +61,39 @@
         this.value = value;
     }
 }
+=======
+package org.hisp.dhis.mapgeneration;
+
+public class MapValue
+{
+    private String ou;
+    
+    private double value;
+
+    public MapValue( String ou, double value )
+    {
+        this.ou = ou;
+        this.value = value;
+    }
+
+    public String getOu()
+    {
+        return ou;
+    }
+
+    public void setOu( String ou )
+    {
+        this.ou = ou;
+    }
+
+    public double getValue()
+    {
+        return value;
+    }
+
+    public void setValue( double value )
+    {
+        this.value = value;
+    }
+}
+>>>>>>> MERGE-SOURCE

=== added directory 'dhis-2/dhis-services/dhis-service-patient/src/main/java/org/hisp/dhis/caseaggregation'
=== added directory 'dhis-2/dhis-services/dhis-service-patient/src/main/java/org/hisp/dhis/caseaggregation/jdbc'
=== added file 'dhis-2/dhis-services/dhis-service-patient/src/main/java/org/hisp/dhis/caseaggregation/jdbc/JdbcCaseAggregationConditionManager.java.OTHER'
--- dhis-2/dhis-services/dhis-service-patient/src/main/java/org/hisp/dhis/caseaggregation/jdbc/JdbcCaseAggregationConditionManager.java.OTHER	1970-01-01 00:00:00 +0000
+++ dhis-2/dhis-services/dhis-service-patient/src/main/java/org/hisp/dhis/caseaggregation/jdbc/JdbcCaseAggregationConditionManager.java.OTHER	2013-09-18 14:05:25 +0000
@@ -0,0 +1,1096 @@
+/*
+ * Copyright (c) 2004-2012, University of Oslo
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ * * Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright notice,
+ *   this list of conditions and the following disclaimer in the documentation
+ *   and/or other materials provided with the distribution.
+ * * Neither the name of the HISP project nor the names of its contributors may
+ *   be used to endorse or promote products derived from this software without
+ *   specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+package org.hisp.dhis.caseaggregation.jdbc;
+
+import static org.hisp.dhis.caseaggregation.CaseAggregationCondition.OBJECT_ORGUNIT_COMPLETE_PROGRAM_STAGE;
+import static org.hisp.dhis.caseaggregation.CaseAggregationCondition.OBJECT_PATIENT;
+import static org.hisp.dhis.caseaggregation.CaseAggregationCondition.OBJECT_PATIENT_ATTRIBUTE;
+import static org.hisp.dhis.caseaggregation.CaseAggregationCondition.OBJECT_PATIENT_PROGRAM_STAGE_PROPERTY;
+import static org.hisp.dhis.caseaggregation.CaseAggregationCondition.OBJECT_PATIENT_PROPERTY;
+import static org.hisp.dhis.caseaggregation.CaseAggregationCondition.OBJECT_PROGRAM;
+import static org.hisp.dhis.caseaggregation.CaseAggregationCondition.OBJECT_PROGRAM_PROPERTY;
+import static org.hisp.dhis.caseaggregation.CaseAggregationCondition.OBJECT_PROGRAM_STAGE;
+import static org.hisp.dhis.caseaggregation.CaseAggregationCondition.OBJECT_PROGRAM_STAGE_DATAELEMENT;
+import static org.hisp.dhis.caseaggregation.CaseAggregationCondition.OBJECT_PROGRAM_STAGE_PROPERTY;
+import static org.hisp.dhis.caseaggregation.CaseAggregationCondition.SEPARATOR_ID;
+import static org.hisp.dhis.caseaggregation.CaseAggregationCondition.SEPARATOR_OBJECT;
+import static org.hisp.dhis.patient.scheduling.CaseAggregateConditionSchedulingManager.TASK_AGGREGATE_QUERY_BUILDER_LAST_12_MONTH;
+import static org.hisp.dhis.patient.scheduling.CaseAggregateConditionSchedulingManager.TASK_AGGREGATE_QUERY_BUILDER_LAST_3_MONTH;
+import static org.hisp.dhis.patient.scheduling.CaseAggregateConditionSchedulingManager.TASK_AGGREGATE_QUERY_BUILDER_LAST_6_MONTH;
+import static org.hisp.dhis.patient.scheduling.CaseAggregateConditionSchedulingManager.TASK_AGGREGATE_QUERY_BUILDER_LAST_MONTH;
+
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.Calendar;
+import java.util.Collection;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.Future;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.hisp.dhis.caseaggregation.CaseAggregateSchedule;
+import org.hisp.dhis.caseaggregation.CaseAggregationCondition;
+import org.hisp.dhis.caseaggregation.CaseAggregationConditionManager;
+import org.hisp.dhis.common.Grid;
+import org.hisp.dhis.common.GridHeader;
+import org.hisp.dhis.dataelement.DataElement;
+import org.hisp.dhis.dataelement.DataElementService;
+import org.hisp.dhis.i18n.I18n;
+import org.hisp.dhis.i18n.I18nFormat;
+import org.hisp.dhis.jdbc.StatementBuilder;
+import org.hisp.dhis.organisationunit.OrganisationUnit;
+import org.hisp.dhis.period.CalendarPeriodType;
+import org.hisp.dhis.period.Period;
+import org.hisp.dhis.period.PeriodType;
+import org.hisp.dhis.system.grid.ListGrid;
+import org.hisp.dhis.system.util.DateUtils;
+import org.hisp.dhis.system.util.TextUtils;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.jdbc.core.RowMapper;
+import org.springframework.jdbc.support.rowset.SqlRowSet;
+import org.springframework.scheduling.annotation.Async;
+
+/**
+ * @author Chau Thu Tran
+ */
+public class JdbcCaseAggregationConditionManager
+    implements CaseAggregationConditionManager
+{
+    private final String IS_NULL = "is null";
+
+    private final String PROPERTY_AGE = "age";
+
+    private final String IN_CONDITION_GET_ALL = "*";
+
+    private final String IN_CONDITION_START_SIGN = "@";
+
+    private final String IN_CONDITION_END_SIGN = "#";
+
+    private final String IN_CONDITION_COUNT_X_TIMES = "COUNT";
+
+    public static final String STORED_BY_DHIS_SYSTEM = "DHIS-System";
+
+    // -------------------------------------------------------------------------
+    // Dependency
+    // -------------------------------------------------------------------------
+
+    private JdbcTemplate jdbcTemplate;
+
+    public void setJdbcTemplate( JdbcTemplate jdbcTemplate )
+    {
+        this.jdbcTemplate = jdbcTemplate;
+    }
+
+    private StatementBuilder statementBuilder;
+
+    public void setStatementBuilder( StatementBuilder statementBuilder )
+    {
+        this.statementBuilder = statementBuilder;
+    }
+
+    private DataElementService dataElementService;
+
+    public void setDataElementService( DataElementService dataElementService )
+    {
+        this.dataElementService = dataElementService;
+    }
+
+    // -------------------------------------------------------------------------
+    // Implementation Methods
+    // -------------------------------------------------------------------------
+
+    @Override
+    public List<Integer> executeSQL( String sql )
+    {
+        try
+        {
+            List<Integer> patientIds = jdbcTemplate.query( sql, new RowMapper<Integer>()
+            {
+                public Integer mapRow( ResultSet rs, int rowNum )
+                    throws SQLException
+                {
+                    return rs.getInt( 1 );
+                }
+            } );
+
+            return patientIds;
+        }
+        catch ( Exception ex )
+        {
+            ex.printStackTrace();
+            return null;
+        }
+    }
+
+    @Async
+    public Future<?> aggregate( ConcurrentLinkedQueue<CaseAggregateSchedule> caseAggregateSchedule, String taskStrategy )
+    {
+        taskLoop: while ( true )
+        {
+            CaseAggregateSchedule dataSet = caseAggregateSchedule.poll();
+
+            if ( dataSet == null )
+            {
+                break taskLoop;
+            }
+
+            Collection<Period> periods = getPeriods( dataSet.getPeriodTypeName(), taskStrategy );
+
+            runAggregate( null, dataSet, periods );
+        }
+
+        return null;
+    }
+
+    public Grid getAggregateValue( CaseAggregationCondition caseAggregationCondition, Collection<Integer> orgunitIds,
+        Period period, I18nFormat format, I18n i18n )
+    {
+        Collection<Integer> _orgunitIds = getServiceOrgunit( DateUtils.getMediumDateString( period.getStartDate() ),
+            DateUtils.getMediumDateString( period.getEndDate() ) );
+        _orgunitIds.retainAll( orgunitIds );
+
+        if ( _orgunitIds.size() > 0 )
+        {
+            Grid grid = new ListGrid();
+            grid.setTitle( caseAggregationCondition.getDisplayName() );
+            grid.setSubtitle( format.formatPeriod( period ) );
+
+            grid.addHeader( new GridHeader( i18n.getString( "dataelementid" ), true, true ) );
+            grid.addHeader( new GridHeader( i18n.getString( "categoryoptioncomboid" ), true, true ) );
+            grid.addHeader( new GridHeader( i18n.getString( "periodid" ), true, true ) );
+            grid.addHeader( new GridHeader( i18n.getString( "organisationunitid" ), true, true ) );
+            grid.addHeader( new GridHeader( i18n.getString( "comment" ), true, true ) );
+            grid.addHeader( new GridHeader( i18n.getString( "dataelementname" ), false, true ) );
+            grid.addHeader( new GridHeader( i18n.getString( "categoryoptioncomboname" ), false, true ) );
+            grid.addHeader( new GridHeader( i18n.getString( "organisationunitname" ), false, true ) );
+            grid.addHeader( new GridHeader( i18n.getString( "value" ), false, true ) );
+
+            Integer deSumId = (caseAggregationCondition.getDeSum() == null) ? null : caseAggregationCondition
+                .getDeSum().getId();
+            String sql = parseExpressionToSql( false, caseAggregationCondition.getAggregationExpression(),
+                caseAggregationCondition.getOperator(), caseAggregationCondition.getAggregationDataElement().getId(),
+                caseAggregationCondition.getAggregationDataElement().getDisplayName(), caseAggregationCondition
+                    .getOptionCombo().getId(), caseAggregationCondition.getOptionCombo().getDisplayName(), deSumId,
+                _orgunitIds, period );
+
+            SqlRowSet rs = jdbcTemplate.queryForRowSet( sql );
+            grid.addRows( rs );
+
+            return grid;
+        }
+
+        return null;
+    }
+
+    @Override
+    public Grid getAggregateValueDetails( CaseAggregationCondition aggregationCondition, OrganisationUnit orgunit,
+        Period period, I18nFormat format, I18n i18n )
+    {
+        Grid grid = new ListGrid();
+        grid.setTitle( orgunit.getName() + " - " + aggregationCondition.getDisplayName() );
+        grid.setSubtitle( format.formatPeriod( period ) );
+
+        String sql = parseExpressionDetailsToSql( aggregationCondition.getAggregationExpression(),
+            aggregationCondition.getOperator(), orgunit.getId(), period );
+
+        SqlRowSet rs = jdbcTemplate.queryForRowSet( sql );
+
+        for ( String colName : rs.getMetaData().getColumnNames() )
+        {
+            grid.addHeader( new GridHeader( i18n.getString( colName ), false, true ) );
+        }
+
+        grid.addRows( rs );
+
+        return grid;
+    }
+
+    /**
+     * Insert data elements into database directly
+     * 
+     */
+    public void insertAggregateValue( CaseAggregationCondition caseAggregationCondition,
+        Collection<Integer> orgunitIds, Period period )
+    {
+        Integer deSumId = (caseAggregationCondition.getDeSum() == null) ? null : caseAggregationCondition.getDeSum()
+            .getId();
+
+        insertAggregateValue( caseAggregationCondition.getAggregationExpression(),
+            caseAggregationCondition.getOperator(), caseAggregationCondition.getAggregationDataElement().getId(),
+            caseAggregationCondition.getOptionCombo().getId(), deSumId, orgunitIds, period );
+    }
+
+    private void insertAggregateValue( String expression, String operator, Integer dataElementId,
+        Integer optionComboId, Integer deSumId, Collection<Integer> orgunitIds, Period period )
+    {
+        // Delete all data value from this period which created from DHIS-system
+        // after to run Aggregate Query Builder
+
+        String periodtypeSql = "select periodtypeid from periodtype where name='" + period.getPeriodType().getName()
+            + "'";
+        int periodTypeId = jdbcTemplate.queryForObject( periodtypeSql, Integer.class );
+
+        String periodSql = "select periodid from period where periodtypeid=" + periodTypeId + " and startdate='"
+            + DateUtils.getMediumDateString( period.getStartDate() ) + "' and enddate='"
+            + DateUtils.getMediumDateString( period.getEndDate() ) + "'";
+
+        SqlRowSet rs = jdbcTemplate.queryForRowSet( periodSql );
+
+        int periodid = 0;
+        if ( rs.next() )
+        {
+            periodid = rs.getInt( "periodid" );
+        }
+
+        if ( periodid == 0 )
+        {
+            String insertSql = "insert into period (periodtypeid,startdate,enddate) " + " VALUES " + "("
+                + period.getPeriodType().getId() + ",'" + DateUtils.getMediumDateString( period.getStartDate() )
+                + "','" + DateUtils.getMediumDateString( period.getEndDate() ) + "' )";
+            jdbcTemplate.execute( insertSql );
+
+            period.setId( jdbcTemplate.queryForObject( insertSql, Integer.class ) );
+        }
+        else
+        {
+            period.setId( periodid );
+
+            String deleteDataValueSql = "delete from datavalue where dataelementid=" + dataElementId
+                + " and categoryoptioncomboid=" + optionComboId + " and sourceid in ("
+                + TextUtils.getCommaDelimitedString( orgunitIds ) + ") and periodid=" + periodid + "";
+
+            jdbcTemplate.execute( deleteDataValueSql );
+        }
+
+        // insert data elements into database directly
+
+        String sql = parseExpressionToSql( true, expression, operator, dataElementId, "dataelementname", optionComboId,
+            "optionComboname", deSumId, orgunitIds, period );
+
+        jdbcTemplate.execute( sql );
+    }
+
+    public String parseExpressionToSql( boolean isInsert, String caseExpression, String operator,
+        Integer aggregateDeId, String aggregateDeName, Integer optionComboId, String optionComboName, Integer deSumId,
+        Collection<Integer> orgunitIds, Period period )
+    {
+        String sql = "SELECT '" + aggregateDeId + "' as dataelementid, '" + optionComboId
+            + "' as categoryoptioncomboid, ou.organisationunitid as sourceid, '" + period.getId() + "' as periodid,'"
+            + CaseAggregationCondition.AUTO_STORED_BY + "' as comment, ";
+
+        if ( isInsert )
+        {
+            sql = "INSERT INTO datavalue (dataelementid, categoryoptioncomboid, sourceid, periodid, comment, value)"
+                + sql;
+        }
+        else
+        {
+            sql += "'" + period.getIsoDate() + "' as periodIsoDate,'" + aggregateDeName + "' as dataelementname, '"
+                + optionComboName + "' as categoryoptioncomboname, ou.name as organisationunitname, ";
+        }
+
+        if ( operator.equals( CaseAggregationCondition.AGGRERATION_COUNT )
+            || operator.equals( CaseAggregationCondition.AGGRERATION_SUM ) )
+        {
+            if ( hasOrgunitProgramStageCompleted( caseExpression ) )
+            {
+                sql += createSQL( caseExpression, operator, orgunitIds,
+                    DateUtils.getMediumDateString( period.getStartDate() ),
+                    DateUtils.getMediumDateString( period.getEndDate() ) );
+            }
+            else
+            {
+                if ( operator.equals( CaseAggregationCondition.AGGRERATION_COUNT ) )
+                {
+                    sql += " count (distinct(pi.patientid) ) as value ";
+                }
+                else
+                {
+                    sql += " count (psi.programinstanceid ) as value ";
+                }
+
+                sql += "FROM programstageinstance as psi ";
+                boolean hasPatients = hasPatientCriteria( caseExpression );
+                boolean hasProgramInstances = hasProgramInstanceCriteria( caseExpression );
+
+                if ( hasPatients )
+                {
+                    sql += "INNER JOIN programinstance as pi ON pi.programinstanceid = psi.programinstanceid ";
+                    sql += "INNER JOIN patient p on p.patientid=pi.patientid  ";
+                }
+                else if ( (hasProgramInstances && !hasPatients)
+                    || operator.equals( CaseAggregationCondition.AGGRERATION_COUNT ) )
+                {
+                    sql += "INNER JOIN programinstance as pi ON pi.programinstanceid = psi.programinstanceid ";
+                }
+                sql += "INNER JOIN organisationunit ou on ou.organisationunitid=psi.organisationunitid WHERE "
+                    + createSQL( caseExpression, operator, orgunitIds,
+                        DateUtils.getMediumDateString( period.getStartDate() ),
+                        DateUtils.getMediumDateString( period.getEndDate() ) );
+
+                sql += "GROUP BY ou.organisationunitid, ou.name";
+            }
+        }
+        else
+        {
+            sql += " " + operator + "( cast( pdv.value as DOUBLE PRECISION ) ) ";
+            sql += "FROM patientdatavalue pdv ";
+            sql += "    INNER JOIN programstageinstance psi  ";
+            sql += "            ON psi.programstageinstanceid = pdv.programstageinstanceid ";
+            sql += "    INNER JOIN organisationunit ou ";
+            sql += "            ON ou.organisationunitid=psi.organisationunitid ";
+            sql += "WHERE executiondate >='" + DateUtils.getMediumDateString( period.getStartDate() ) + "'  ";
+            sql += "    AND executiondate <='" + DateUtils.getMediumDateString( period.getEndDate() )
+                + "' AND pdv.dataelementid=" + deSumId;
+
+            if ( caseExpression != null && !caseExpression.isEmpty() )
+            {
+                sql += " AND "
+                    + createSQL( caseExpression, operator, orgunitIds,
+                        DateUtils.getMediumDateString( period.getStartDate() ),
+                        DateUtils.getMediumDateString( period.getEndDate() ) );
+            }
+
+            sql += "GROUP BY ou.organisationunitid, ou.name";
+
+        }
+
+        sql = sql.replaceAll( "COMBINE", "" );
+
+        return sql;
+    }
+
+    @Override
+    public String parseExpressionDetailsToSql( String caseExpression, String operator, Integer orgunitId, Period period )
+    {
+        String sql = "SELECT ";
+
+        boolean hasPatients = hasPatientCriteria( caseExpression );
+        boolean hasProgramInstances = hasProgramInstanceCriteria( caseExpression );
+        boolean hasDataelement = hasDataelementCriteria( caseExpression );
+
+        Collection<Integer> orgunitIds = new HashSet<Integer>();
+        orgunitIds.add( orgunitId );
+
+        if ( hasOrgunitProgramStageCompleted( caseExpression ) )
+        {
+            sql += "ou.name "
+                + createSQL( caseExpression, operator, orgunitIds,
+                    DateUtils.getMediumDateString( period.getStartDate() ),
+                    DateUtils.getMediumDateString( period.getEndDate() ) );
+        }
+        else if ( hasPatients || operator.equals( CaseAggregationCondition.AGGRERATION_COUNT ) )
+        {
+            sql += "p.firstName, p.middleName, p.lastName, p.gender, p.birthDate, p.phoneNumber, ";
+        }
+        else if ( hasDataelement )
+        {
+            sql += "pdv.value,";
+        }
+
+        sql += "pgs.name as program_stage, psi.executiondate as report_date ";
+
+        sql += "FROM programstageinstance as psi ";
+        sql += "INNER JOIN programstage as pgs ON pgs.programstageid = psi.programstageid ";
+        if ( hasDataelement )
+        {
+            sql += "INNER JOIN patientdatavalue as pdv ON psi.programstageinstanceid = pdv.programstageinstanceid ";
+        }
+
+        if ( hasPatients || operator.equals( CaseAggregationCondition.AGGRERATION_COUNT ) )
+        {
+            sql += "INNER JOIN programinstance as pi ON pi.programinstanceid = psi.programinstanceid ";
+            sql += "INNER JOIN patient p on p.patientid=pi.patientid  ";
+        }
+        else if ( (hasProgramInstances && !hasPatients) || operator.equals( CaseAggregationCondition.AGGRERATION_COUNT ) )
+        {
+            sql += "INNER JOIN programinstance as pi ON pi.programinstanceid = psi.programinstanceid ";
+        }
+        sql += "INNER JOIN organisationunit ou on ou.organisationunitid=psi.organisationunitid WHERE "
+            + createSQL( caseExpression, operator, orgunitIds, DateUtils.getMediumDateString( period.getStartDate() ),
+                DateUtils.getMediumDateString( period.getEndDate() ) );
+
+        sql = sql.replaceAll( "COMBINE", "" );
+
+        return sql;
+    }
+
+    // -------------------------------------------------------------------------
+    // Supportive methods
+    // -------------------------------------------------------------------------
+
+    /**
+     * Aggregate data values for the dataset by periods with a organisation unit
+     * list
+     * 
+     */
+    private void runAggregate( Collection<Integer> orgunitIds, CaseAggregateSchedule dataSet, Collection<Period> periods )
+    {
+        String sql = "select caseaggregationconditionid, aggregationdataelementid, optioncomboid, "
+            + " cagg.aggregationexpression as caseexpression, cagg.operator as caseoperator, cagg.desum as desumid "
+            + "     from caseaggregationcondition cagg inner join datasetmembers dm "
+            + "             on cagg.aggregationdataelementid=dm.dataelementid inner join dataset ds "
+            + "             on ds.datasetid = dm.datasetid inner join periodtype pt "
+            + "             on pt.periodtypeid=ds.periodtypeid inner join dataelement de "
+            + "             on de.dataelementid=dm.dataelementid where ds.datasetid = " + dataSet.getDataSetId();
+
+        SqlRowSet rs = jdbcTemplate.queryForRowSet( sql );
+
+        while ( rs.next() )
+        {
+            for ( Period period : periods )
+            {
+                // -------------------------------------------------------------
+                // Get formula, agg-dataelement and option-combo
+                // -------------------------------------------------------------
+
+                int dataelementId = rs.getInt( "aggregationdataelementid" );
+                int optionComboId = rs.getInt( "optioncomboid" );
+                String caseExpression = rs.getString( "caseexpression" );
+                String caseOperator = rs.getString( "caseoperator" );
+                int deSumId = rs.getInt( "desumid" );
+
+                Collection<Integer> _orgunitIds = getServiceOrgunit(
+                    DateUtils.getMediumDateString( period.getStartDate() ),
+                    DateUtils.getMediumDateString( period.getEndDate() ) );
+
+                if ( orgunitIds == null )
+                {
+                    orgunitIds = new HashSet<Integer>();
+                    orgunitIds.addAll( _orgunitIds );
+                }
+                else
+                {
+                    orgunitIds.retainAll( _orgunitIds );
+                }
+
+                // ---------------------------------------------------------------------
+                // Aggregation
+                // ---------------------------------------------------------------------
+
+                if ( _orgunitIds.size() > 0 )
+                {
+                    insertAggregateValue( caseExpression, caseOperator, dataelementId, optionComboId, deSumId,
+                        orgunitIds, period );
+                }
+            }
+
+        }
+    }
+
+    /**
+     * Generate period list based on period Type and taskStrategy option
+     * 
+     * @param periodTypeName The name of period type
+     * @param taskStrategy Specify how to get period list based on period type
+     *        of each dataset. There are four options, include last month, last
+     *        3 month, last 6 month and last 12 month
+     * 
+     */
+    private Collection<Period> getPeriods( String periodTypeName, String taskStrategy )
+    {
+        Calendar calStartDate = Calendar.getInstance();
+
+        if ( TASK_AGGREGATE_QUERY_BUILDER_LAST_MONTH.equals( taskStrategy ) )
+        {
+            calStartDate.add( Calendar.MONTH, -1 );
+        }
+        else if ( TASK_AGGREGATE_QUERY_BUILDER_LAST_3_MONTH.equals( taskStrategy ) )
+        {
+            calStartDate.add( Calendar.MONTH, -3 );
+        }
+        else if ( TASK_AGGREGATE_QUERY_BUILDER_LAST_6_MONTH.equals( taskStrategy ) )
+        {
+            calStartDate.add( Calendar.MONTH, -6 );
+        }
+        else if ( TASK_AGGREGATE_QUERY_BUILDER_LAST_12_MONTH.equals( taskStrategy ) )
+        {
+            calStartDate.add( Calendar.MONTH, -12 );
+        }
+
+        Date startDate = calStartDate.getTime();
+
+        Calendar calEndDate = Calendar.getInstance();
+
+        Date endDate = calEndDate.getTime();
+
+        CalendarPeriodType periodType = (CalendarPeriodType) PeriodType.getPeriodTypeByName( periodTypeName );
+        String sql = "select periodtypeid from periodtype where name='" + periodTypeName + "'";
+        int periodTypeId = jdbcTemplate.queryForObject( sql, Integer.class );
+
+        Collection<Period> periods = periodType.generatePeriods( startDate, endDate );
+
+        for ( Period period : periods )
+        {
+            String start = DateUtils.getMediumDateString( period.getStartDate() );
+            String end = DateUtils.getMediumDateString( period.getEndDate() );
+
+            sql = "select periodid from period where periodtypeid=" + periodTypeId + " and startdate='" + start
+                + "' and enddate='" + end + "'";
+            Integer periodid = null;
+            SqlRowSet rs = jdbcTemplate.queryForRowSet( sql );
+            if ( rs.next() )
+            {
+                periodid = rs.getInt( "periodid" );
+            }
+
+            if ( periodid == null )
+            {
+                String insertSql = "insert into period (periodtypeid,startdate,enddate) " + " VALUES " + "("
+                    + periodTypeId + ",'" + start + "','" + end + "' )";
+                jdbcTemplate.execute( insertSql );
+
+                period.setId( jdbcTemplate.queryForObject( sql, Integer.class ) );
+            }
+            else
+            {
+                period.setId( periodid );
+            }
+        }
+
+        return periods;
+    }
+
+    /**
+     * Return standard SQL from query builder formula
+     * 
+     * @param caseExpression The query builder expression
+     * @param operator There are six operators, includes Number of persons,
+     *        Number of visits, Sum, Average, Minimum and Maximum of data
+     *        element values.
+     * @param deType Aggregate Data element type
+     * @param orgunitIds The ids of organisation units where to aggregate data
+     *        value
+     * @param startDate Start date
+     * @param endDate End date
+     */
+    private String createSQL( String caseExpression, String operator, Collection<Integer> orgunitIds, String startDate,
+        String endDate )
+    {
+        boolean orgunitCompletedProgramStage = false;
+
+        StringBuffer sqlResult = new StringBuffer();
+
+        String sqlOrgunitCompleted = "";
+
+        // Get minus(date, date) out from the expression and run them later
+
+        Map<Integer, String> minusSQLMap = new HashMap<Integer, String>();
+        int idx = 0;
+        Pattern patternMinus = Pattern.compile( CaseAggregationCondition.dataelementRegExp );
+        Matcher matcherMinus = patternMinus.matcher( caseExpression );
+        while ( matcherMinus.find() )
+        {
+            String[] ids = matcherMinus.group( 2 ).split( SEPARATOR_ID );
+
+            minusSQLMap.put(
+                idx,
+                getConditionForMinusDataElement( orgunitIds, Integer.parseInt( ids[1] ), Integer.parseInt( ids[2] ),
+                    matcherMinus.group( 4 ), startDate, endDate ) );
+
+            caseExpression = caseExpression.replace( matcherMinus.group( 0 ), CaseAggregationCondition.MINUS_OPERATOR
+                + "_" + idx );
+
+            idx++;
+        }
+
+        // Run nornal expression
+        String[] expression = caseExpression.split( "(AND|OR)" );
+        caseExpression = caseExpression.replaceAll( "AND", " ) AND " );
+        caseExpression = caseExpression.replaceAll( "OR", " ) OR " );
+
+        // ---------------------------------------------------------------------
+        // parse expressions
+        // ---------------------------------------------------------------------
+
+        Pattern patternCondition = Pattern.compile( CaseAggregationCondition.regExp );
+
+        Matcher matcherCondition = patternCondition.matcher( caseExpression );
+
+        String condition = "";
+
+        int index = 0;
+        while ( matcherCondition.find() )
+        {
+            String match = matcherCondition.group();
+
+            match = match.replaceAll( "[\\[\\]]", "" );
+
+            String[] info = match.split( SEPARATOR_OBJECT );
+            if ( info[0].equalsIgnoreCase( OBJECT_PATIENT ) )
+            {
+                condition = getConditionForPatient( orgunitIds, operator, startDate, endDate );
+            }
+            else if ( info[0].equalsIgnoreCase( OBJECT_PATIENT_PROPERTY ) )
+            {
+                String propertyName = info[1];
+                condition = getConditionForPatientProperty( propertyName, operator, startDate, endDate );
+            }
+            else if ( info[0].equalsIgnoreCase( OBJECT_PATIENT_ATTRIBUTE ) )
+            {
+                int attributeId = Integer.parseInt( info[1] );
+                condition = getConditionForPatientAttribute( attributeId, orgunitIds );
+                condition += ")";
+            }
+            else if ( info[0].equalsIgnoreCase( OBJECT_PROGRAM_STAGE_DATAELEMENT ) )
+            {
+                String[] ids = info[1].split( SEPARATOR_ID );
+
+                int programId = Integer.parseInt( ids[0] );
+                String programStageId = ids[1];
+                int dataElementId = Integer.parseInt( ids[2] );
+
+                String compareValue = expression[index].replace( "[" + match + "]", "" ).trim();
+
+                boolean isExist = compareValue.equals( IS_NULL ) ? false : true;
+                condition = getConditionForDataElement( isExist, programId, programStageId, dataElementId, orgunitIds,
+                    startDate, endDate );
+            }
+
+            else if ( info[0].equalsIgnoreCase( OBJECT_PROGRAM_PROPERTY ) )
+            {
+                condition = getConditionForProgramProperty( operator, startDate, endDate, info[1] );
+            }
+            else if ( info[0].equalsIgnoreCase( OBJECT_PROGRAM ) )
+            {
+                String[] ids = info[1].split( SEPARATOR_ID );
+                condition = getConditionForProgram( ids[0], operator, orgunitIds, startDate, endDate );
+                if ( ids.length > 1 )
+                {
+                    condition += ids[1];
+                }
+            }
+            else if ( info[0].equalsIgnoreCase( OBJECT_PROGRAM_STAGE ) )
+            {
+                String[] ids = info[1].split( SEPARATOR_ID );
+                if ( ids.length == 2 && ids[1].equals( IN_CONDITION_COUNT_X_TIMES ) )
+                {
+                    condition = getConditionForCountProgramStage( ids[0], operator, orgunitIds, startDate, endDate );
+                }
+                else
+                {
+                    condition = getConditionForProgramStage( ids[0], operator, orgunitIds, startDate, endDate );
+                }
+            }
+            else if ( info[0].equalsIgnoreCase( OBJECT_PROGRAM_STAGE_PROPERTY ) )
+            {
+                condition = getConditionForProgramStageProperty( info[1], operator, orgunitIds, startDate, endDate );
+            }
+            else if ( info[0].equalsIgnoreCase( OBJECT_PATIENT_PROGRAM_STAGE_PROPERTY ) )
+            {
+                condition = getConditionForPatientProgramStageProperty( info[1], operator, startDate, endDate );
+            }
+            else if ( info[0].equalsIgnoreCase( OBJECT_ORGUNIT_COMPLETE_PROGRAM_STAGE ) )
+            {
+                sqlOrgunitCompleted += getConditionForOrgunitProgramStageCompleted( info[1], operator, orgunitIds,
+                    startDate, endDate, orgunitCompletedProgramStage );
+                orgunitCompletedProgramStage = true;
+            }
+
+            matcherCondition.appendReplacement( sqlResult, condition );
+
+            index++;
+        }
+
+        matcherCondition.appendTail( sqlResult );
+
+        if ( !sqlOrgunitCompleted.isEmpty() )
+        {
+            sqlOrgunitCompleted = sqlOrgunitCompleted.substring( 0, sqlOrgunitCompleted.length() - 2 );
+        }
+
+        sqlResult.append( sqlOrgunitCompleted );
+
+        String sql = sqlResult.toString();
+
+        sql = sql.replaceAll( IN_CONDITION_START_SIGN, "(" );
+        sql = sql.replaceAll( IN_CONDITION_END_SIGN, ")" );
+        sql = sql.replaceAll( IS_NULL, " " );
+
+        for ( int key = 0; key < idx; key++ )
+        {
+            sql = sql.replace( CaseAggregationCondition.MINUS_OPERATOR + "_" + key, minusSQLMap.get( key ) );
+        }
+
+        return sql + " ) ";
+
+    }
+
+    /**
+     * Return standard SQL of the expression to compare data value as null
+     * 
+     */
+    private String getConditionForDataElement( boolean isExist, int programId, String programStageId,
+        int dataElementId, Collection<Integer> orgunitIds, String startDate, String endDate )
+    {
+        String keyExist = (isExist == true) ? "EXISTS" : "NOT EXISTS";
+
+        String sql = " " + keyExist + " ( SELECT * "
+            + "FROM patientdatavalue _pdv inner join programstageinstance _psi "
+            + "ON _pdv.programstageinstanceid=_psi.programstageinstanceid JOIN programinstance _pi "
+            + "ON _pi.programinstanceid=_psi.programinstanceid "
+            + "WHERE psi.programstageinstanceid=_pdv.programstageinstanceid AND _pdv.dataelementid=" + dataElementId
+            + "  AND _psi.organisationunitid in (" + TextUtils.getCommaDelimitedString( orgunitIds ) + ")  "
+            + "AND _pi.programid = " + programId + " AND _psi.executionDate>='" + startDate
+            + "' AND _psi.executionDate <= '" + endDate + "' ";
+
+        if ( !programStageId.equals( IN_CONDITION_GET_ALL ) )
+        {
+            sql += " AND _psi.programstageid = " + programStageId;
+        }
+
+        if ( isExist )
+        {
+            DataElement dataElement = dataElementService.getDataElement( dataElementId );
+            if ( dataElement.getType().equals( DataElement.VALUE_TYPE_INT ) )
+            {
+                sql += " AND ( cast( _pdv.value as " + statementBuilder.getDoubleColumnType() + " )  ) ";
+            }
+            else
+            {
+                sql += " AND _pdv.value ";
+            }
+        }
+
+        return sql;
+    }
+
+    /**
+     * Return standard SQL of a dynamic patient-attribute expression. E.g [CA:1]
+     * 
+     */
+    private String getConditionForPatientAttribute( int attributeId, Collection<Integer> orgunitIds )
+    {
+        String sql = " EXISTS ( SELECT * " + "FROM patientattributevalue _pav "
+            + "WHERE _pav.patientid = pi.patientid " + "and _pav.patientattributeid=" + attributeId
+            + "  AND p.organisationunitid in (" + TextUtils.getCommaDelimitedString( orgunitIds ) + ") AND _pav.value ";
+
+        return sql;
+    }
+
+    /**
+     * Return standard SQL of the expression which is used for calculating total
+     * of person registration
+     * 
+     */
+    private String getConditionForPatient( Collection<Integer> orgunitIds, String operator, String startDate,
+        String endDate )
+    {
+        String sql = " EXISTS ( SELECT * " + "FROM patient _p " + "WHERE _p.patientid = pi.patientid "
+            + "AND _p.registrationdate>='" + startDate + "' AND _p.registrationdate<='" + endDate + "' "
+            + "AND p.organisationunitid in (" + TextUtils.getCommaDelimitedString( orgunitIds ) + ") ";
+
+        return sql;
+    }
+
+    /**
+     * Return standard SQL of the patient-fixed-attribute expression. E.g
+     * [CP:gender]
+     * 
+     */
+    private String getConditionForPatientProperty( String propertyName, String operator, String startDate,
+        String endDate )
+    {
+        String sql = " EXISTS (SELECT * FROM patient _p WHERE _p.patientid = pi.patientid AND ";
+
+        if ( propertyName.equals( PROPERTY_AGE ) )
+        {
+            sql += "DATE(registrationdate) - DATE(birthdate) ";
+        }
+        else
+        {
+            sql += propertyName + " ";
+        }
+
+        return sql;
+    }
+
+    /**
+     * Return standard SQL of the program-property expression. E.g
+     * [PC:executionDate]
+     * 
+     */
+    private String getConditionForPatientProgramStageProperty( String propertyName, String operator, String startDate,
+        String endDate )
+    {
+        String sql = " EXISTS ( SELECT * from programstageinstance _psi "
+            + "WHERE _psi.programstageinstanceid=psi.programstageinstanceid AND _psi.executionDate>='" + startDate
+            + "' and _psi.executionDate<='" + endDate + "' and " + propertyName;
+
+        return sql;
+    }
+
+    /**
+     * Return standard SQL of the program expression. E.g
+     * [PP:DATE@enrollmentdate#-DATE@dateofincident#] for geting the number of
+     * days between date of enrollment and date of incident.
+     * 
+     */
+    private String getConditionForProgramProperty( String operator, String startDate, String endDate, String property )
+    {
+        String sql = " EXISTS ( SELECT * FROM programinstance as _pi WHERE psi.programinstanceid=_pi.programsinstanceid AND "
+            + "_pi.enrollmentdate>='"
+            + startDate
+            + "' "
+            + "AND _pi.enrollmentdate<='"
+            + endDate
+            + "'  AND "
+            + property
+            + " ";
+
+        return sql;
+    }
+
+    /**
+     * Return standard SQL to retrieve the number of persons enrolled into the
+     * program. E.g [PG:1]
+     * 
+     */
+    private String getConditionForProgram( String programId, String operator, Collection<Integer> orgunitIds,
+        String startDate, String endDate )
+    {
+        String sql = " EXISTS ( SELECT * FROM programinstance as _pi "
+            + "inner join programstageinstance _psi on _pi.programinstanceid=_psi.programinstanceid "
+            + "WHERE psi.programstageinstanceid=_psi.programstageinstanceid AND _pi.programid=" + programId + " "
+            + " AND _psi.organisationunitid in (" + TextUtils.getCommaDelimitedString( orgunitIds )
+            + ") AND _pi.enrollmentdate >= '" + startDate + "' AND _pi.enrollmentdate <= '" + endDate + "' ";
+
+        return sql;
+    }
+
+    /**
+     * Return standard SQL to retrieve the number of visits a program-stage. E.g
+     * [PS:1]
+     * 
+     */
+    private String getConditionForProgramStage( String programStageId, String operator, Collection<Integer> orgunitIds,
+        String startDate, String endDate )
+    {
+        String sql = " EXISTS ( SELECT * FROM programinstance as _pi INNER JOIN programstageinstance _psi "
+            + "ON _pi.programinstanceid = _psi.programinstanceid WHERE _psi.programstageinstanceid=psi.programstageinstanceid "
+            + "AND _psi.programstageid=" + programStageId + " AND _psi.executiondate >= '" + startDate
+            + "' AND _psi.executiondate <= '" + endDate + "' AND _psi.organisationunitid in ("
+            + TextUtils.getCommaDelimitedString( orgunitIds ) + ")  ";
+
+        return sql;
+    }
+
+    /**
+     * Return standard SQL to retrieve the x-time of a person visited one
+     * program-stage. E.g a mother came to a hospital 3th time for third
+     * trimester.
+     * 
+     */
+    private String getConditionForCountProgramStage( String programStageId, String operator,
+        Collection<Integer> orgunitIds, String startDate, String endDate )
+    {
+        String sql = " EXISTS ( SELECT * FROM programstageinstance as _psi "
+            + "WHERE psi.programstageinstanceid=_psi.programstageinstanceid AND _psi.organisationunitid in ("
+            + TextUtils.getCommaDelimitedString( orgunitIds ) + ") and _psi.programstageid = " + programStageId + " "
+            + "AND _psi.executionDate >= '" + startDate + "' AND _psi.executionDate <= '" + endDate + "' "
+            + "GROUP BY _psi.programinstanceid,_psi.programstageinstanceid "
+            + "HAVING count(_psi.programstageinstanceid) ";
+
+        return sql;
+
+    }
+
+    /**
+     * Return standard SQL to retrieve the number of days between report-date
+     * and due-date. E.g [PSP:DATE@executionDate#-DATE@dueDate#]
+     * 
+     */
+    private String getConditionForProgramStageProperty( String property, String operator,
+        Collection<Integer> orgunitIds, String startDate, String endDate )
+    {
+        String sql = " EXISTS ( SELECT * FROM programstageinstance _psi "
+            + "WHERE psi.programstageinstanceid=_psi.programstageinstanceid AND _psi.executiondate >= '" + startDate
+            + "' AND _psi.executiondate <= '" + endDate + "' AND _psi.organisationunitid in ("
+            + TextUtils.getCommaDelimitedString( orgunitIds ) + ") AND " + property + " ";
+
+        return sql;
+    }
+
+    /**
+     * Return standard SQL to retrieve the number of children orgunits has all
+     * program-stage-instance completed and due-date. E.g [PSIC:1]
+     * 
+     * @flag True if there are many stages in the expression
+     * 
+     */
+    private String getConditionForOrgunitProgramStageCompleted( String programStageId, String operator,
+        Collection<Integer> orgunitIds, String startDate, String endDate, boolean flag )
+    {
+        String sql = "";
+        if ( !flag )
+        {
+            sql = " '1' FROM organisationunit ou WHERE ou.organisationunitid in ("
+                + TextUtils.getCommaDelimitedString( orgunitIds ) + ")  ";
+        }
+
+        sql += " AND EXISTS ( SELECT programstageinstanceid FROM programstageinstance _psi "
+            + " WHERE _psi.organisationunitid=ou.organisationunitid AND _psi.programstageid = " + programStageId
+            + " AND _psi.completed=true AND _psi.executiondate >= '" + startDate + "' AND _psi.executiondate <= '"
+            + endDate + "' ) ";
+
+        return sql;
+    }
+
+    private String getConditionForMinusDataElement( Collection<Integer> orgunitIds, Integer programStageId,
+        Integer dataElementId, String compareSide, String startDate, String endDate )
+    {
+        return " EXISTS ( SELECT * FROM patientdatavalue _pdv inner join programstageinstance _psi "
+            + "                         ON _pdv.programstageinstanceid=_psi.programstageinstanceid "
+            + "                 JOIN programinstance _pi ON _pi.programinstanceid=_psi.programinstanceid "
+            + "           WHERE psi.programstageinstanceid=_pdv.programstageinstanceid "
+            + "                  AND _pdv.dataelementid=" + dataElementId
+            + "                 AND _psi.organisationunitid in (" + TextUtils.getCommaDelimitedString( orgunitIds )
+            + ") " + "                 AND _psi.programstageid = " + programStageId + " AND _psi.executionDate>='"
+            + startDate + "' AND _psi.executionDate <= '" + endDate + "' "
+            + "                 AND ( DATE(_pdv.value) - DATE(" + compareSide + ") ) ";
+    }
+
+    /**
+     * Return the Ids of organisation units which patients registered or events
+     * happened.
+     * 
+     */
+    private Collection<Integer> getServiceOrgunit( String startDate, String endDate )
+    {
+        String sql = "(select organisationunitid from programstageinstance where executiondate>= '" + startDate
+            + "' and executiondate<='" + endDate + "')";
+        sql += " UNION ";
+        sql += "( select distinct organisationunitid from patient where registrationdate>='" + startDate
+            + "' and registrationdate<='" + endDate + "')";
+
+        Collection<Integer> orgunitIds = new HashSet<Integer>();
+        orgunitIds = jdbcTemplate.query( sql, new RowMapper<Integer>()
+        {
+            public Integer mapRow( ResultSet rs, int rowNum )
+                throws SQLException
+            {
+                return rs.getInt( 1 );
+            }
+        } );
+
+        return orgunitIds;
+    }
+
+    public boolean hasOrgunitProgramStageCompleted( String expresstion )
+    {
+        Pattern pattern = Pattern.compile( CaseAggregationCondition.regExp );
+        Matcher matcher = pattern.matcher( expresstion );
+        while ( matcher.find() )
+        {
+            String match = matcher.group();
+
+            match = match.replaceAll( "[\\[\\]]", "" );
+
+            String[] info = match.split( SEPARATOR_OBJECT );
+
+            if ( info[0].equalsIgnoreCase( CaseAggregationCondition.OBJECT_ORGUNIT_COMPLETE_PROGRAM_STAGE ) )
+            {
+                return true;
+            }
+        }
+
+        return false;
+    }
+
+    public boolean hasPatientCriteria( String expresstion )
+    {
+        Pattern pattern = Pattern.compile( CaseAggregationCondition.regExp );
+        Matcher matcher = pattern.matcher( expresstion );
+        while ( matcher.find() )
+        {
+            String match = matcher.group();
+
+            match = match.replaceAll( "[\\[\\]]", "" );
+
+            String[] info = match.split( SEPARATOR_OBJECT );
+
+            if ( info[0].equalsIgnoreCase( CaseAggregationCondition.OBJECT_PATIENT )
+                || info[0].equalsIgnoreCase( CaseAggregationCondition.OBJECT_PATIENT_PROPERTY ) )
+            {
+                return true;
+            }
+        }
+
+        return false;
+    }
+
+    public boolean hasProgramInstanceCriteria( String expresstion )
+    {
+        Pattern pattern = Pattern.compile( CaseAggregationCondition.regExp );
+        Matcher matcher = pattern.matcher( expresstion );
+        while ( matcher.find() )
+        {
+            String match = matcher.group();
+
+            match = match.replaceAll( "[\\[\\]]", "" );
+
+            String[] info = match.split( SEPARATOR_OBJECT );
+
+            if ( info[0].equalsIgnoreCase( CaseAggregationCondition.OBJECT_PROGRAM_PROPERTY )
+                || info[0].equalsIgnoreCase( CaseAggregationCondition.OBJECT_PROGRAM )
+                || info[0].equalsIgnoreCase( CaseAggregationCondition.OBJECT_PROGRAM_STAGE ) )
+            {
+                return true;
+            }
+        }
+
+        return false;
+    }
+
+    public boolean hasDataelementCriteria( String expresstion )
+    {
+        Pattern pattern = Pattern.compile( CaseAggregationCondition.regExp );
+        Matcher matcher = pattern.matcher( expresstion );
+        while ( matcher.find() )
+        {
+            String match = matcher.group();
+
+            match = match.replaceAll( "[\\[\\]]", "" );
+
+            String[] info = match.split( SEPARATOR_OBJECT );
+
+            if ( info[0].equalsIgnoreCase( CaseAggregationCondition.OBJECT_PROGRAM_STAGE_DATAELEMENT ) )
+            {
+                return true;
+            }
+        }
+
+        return false;
+    }
+
+}

=== modified file 'dhis-2/dhis-services/dhis-service-patient/src/main/java/org/hisp/dhis/patient/DefaultPatientIdentifierTypeService.java'
=== modified file 'dhis-2/dhis-services/dhis-service-patient/src/main/java/org/hisp/dhis/patient/DefaultPatientRegistrationFormService.java'
=== modified file 'dhis-2/dhis-services/dhis-service-patient/src/main/java/org/hisp/dhis/patient/startup/TableAlteror.java'
--- dhis-2/dhis-services/dhis-service-patient/src/main/java/org/hisp/dhis/patient/startup/TableAlteror.java	2013-09-18 03:49:35 +0000
+++ dhis-2/dhis-services/dhis-service-patient/src/main/java/org/hisp/dhis/patient/startup/TableAlteror.java	2013-09-18 14:05:25 +0000
@@ -217,6 +217,7 @@
         executeSql( "ALTER TABLE program ALTER COLUMN dateofenrollmentdescription DROP NOT NULL" );
         executeSql( "UPDATE program SET displayOnAllOrgunit=true where displayOnAllOrgunit is null" );
         executeSql( "UPDATE program SET useFormNameDataElement=true where useFormNameDataElement is null" );
+<<<<<<< TREE
         executeSql( "ALTER TABLE caseaggregationcondition ALTER COLUMN aggregationexpression TYPE varchar(1000)" );
         executeSql( "update patientattribute set displayonvisitschedule = false where displayonvisitschedule is null" );
         executeSql( "update program set useBirthDateAsIncidentDate = false where useBirthDateAsIncidentDate is null" );
@@ -241,6 +242,9 @@
         executeSql( "alter table patient drop column lastname" );
 
         executeSql( "DROP TABLE patient_programs" );
+=======
+        executeSql( "ALTER TABLE caseaggregationcondition ALTER COLUMN aggregationexpression TYPE varchar(1000)");
+>>>>>>> MERGE-SOURCE
     }
 
     // -------------------------------------------------------------------------

=== added directory 'dhis-2/dhis-services/dhis-service-patient/src/main/java/org/hisp/dhis/program'
=== renamed directory 'dhis-2/dhis-services/dhis-service-patient/src/main/java/org/hisp/dhis/program' => 'dhis-2/dhis-services/dhis-service-patient/src/main/java/org/hisp/dhis/program.moved'
=== added file 'dhis-2/dhis-services/dhis-service-patient/src/main/java/org/hisp/dhis/program/DefaultProgramInstanceService.java'
--- dhis-2/dhis-services/dhis-service-patient/src/main/java/org/hisp/dhis/program/DefaultProgramInstanceService.java	1970-01-01 00:00:00 +0000
+++ dhis-2/dhis-services/dhis-service-patient/src/main/java/org/hisp/dhis/program/DefaultProgramInstanceService.java	2013-09-18 14:05:25 +0000
@@ -0,0 +1,571 @@
+/*
+ * Copyright (c) 2004-2009, University of Oslo
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ * * Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright notice,
+ *   this list of conditions and the following disclaimer in the documentation
+ *   and/or other materials provided with the distribution.
+ * * Neither the name of the HISP project nor the names of its contributors may
+ *   be used to endorse or promote products derived from this software without
+ *   specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+package org.hisp.dhis.program;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Date;
+import java.util.Iterator;
+import java.util.List;
+
+import org.hisp.dhis.common.Grid;
+import org.hisp.dhis.common.GridHeader;
+import org.hisp.dhis.dataelement.DataElement;
+import org.hisp.dhis.i18n.I18n;
+import org.hisp.dhis.i18n.I18nFormat;
+import org.hisp.dhis.organisationunit.OrganisationUnit;
+import org.hisp.dhis.patient.Patient;
+import org.hisp.dhis.patient.PatientAttribute;
+import org.hisp.dhis.patient.PatientIdentifier;
+import org.hisp.dhis.patient.PatientIdentifierType;
+import org.hisp.dhis.patient.PatientReminder;
+import org.hisp.dhis.patientattributevalue.PatientAttributeValue;
+import org.hisp.dhis.patientattributevalue.PatientAttributeValueService;
+import org.hisp.dhis.patientcomment.PatientComment;
+import org.hisp.dhis.patientdatavalue.PatientDataValue;
+import org.hisp.dhis.patientdatavalue.PatientDataValueService;
+import org.hisp.dhis.sms.outbound.OutboundSms;
+import org.hisp.dhis.system.grid.ListGrid;
+import org.springframework.transaction.annotation.Transactional;
+
+/**
+ * @author Abyot Asalefew
+ * @version $Id$
+ */
+@Transactional
+public class DefaultProgramInstanceService
+    implements ProgramInstanceService
+{
+    // -------------------------------------------------------------------------
+    // Dependencies
+    // -------------------------------------------------------------------------
+
+    private ProgramInstanceStore programInstanceStore;
+
+    public void setProgramInstanceStore( ProgramInstanceStore programInstanceStore )
+    {
+        this.programInstanceStore = programInstanceStore;
+    }
+
+    private PatientAttributeValueService patientAttributeValueService;
+
+    public void setPatientAttributeValueService( PatientAttributeValueService patientAttributeValueService )
+    {
+        this.patientAttributeValueService = patientAttributeValueService;
+    }
+
+    private PatientDataValueService patientDataValueService;
+
+    public void setPatientDataValueService( PatientDataValueService patientDataValueService )
+    {
+        this.patientDataValueService = patientDataValueService;
+    }
+
+    private ProgramService programService;
+
+    public void setProgramService( ProgramService programService )
+    {
+        this.programService = programService;
+    }
+
+    // -------------------------------------------------------------------------
+    // Implementation methods
+    // -------------------------------------------------------------------------
+
+    public int addProgramInstance( ProgramInstance programInstance )
+    {
+        return programInstanceStore.save( programInstance );
+    }
+
+    public void deleteProgramInstance( ProgramInstance programInstance )
+    {
+        programInstanceStore.delete( programInstance );
+    }
+
+    public Collection<ProgramInstance> getAllProgramInstances()
+    {
+        return programInstanceStore.getAll();
+    }
+
+    public ProgramInstance getProgramInstance( int id )
+    {
+        return programInstanceStore.get( id );
+    }
+
+    public Collection<ProgramInstance> getProgramInstances( Integer status )
+    {
+        return programInstanceStore.get( status );
+    }
+
+    public void updateProgramInstance( ProgramInstance programInstance )
+    {
+        programInstanceStore.update( programInstance );
+    }
+
+    public Collection<ProgramInstance> getProgramInstances( Program program )
+    {
+        return programInstanceStore.get( program );
+    }
+
+    public Collection<ProgramInstance> getProgramInstances( Collection<Program> programs )
+    {
+        return programInstanceStore.get( programs );
+    }
+
+    public Collection<ProgramInstance> getProgramInstances( Collection<Program> programs, Integer status )
+    {
+        return programInstanceStore.get( programs, status );
+    }
+
+    public Collection<ProgramInstance> getProgramInstances( Program program, Integer status )
+    {
+        return programInstanceStore.get( program, status );
+    }
+
+    public Collection<ProgramInstance> getProgramInstances( Patient patient )
+    {
+        return programInstanceStore.get( patient );
+    }
+
+    public Collection<ProgramInstance> getProgramInstances( Patient patient, Integer status )
+    {
+        return programInstanceStore.get( patient, status );
+    }
+
+    public Collection<ProgramInstance> getProgramInstances( Patient patient, Program program )
+    {
+        return programInstanceStore.get( patient, program );
+    }
+
+    public Collection<ProgramInstance> getProgramInstances( Patient patient, Program program, Integer status )
+    {
+        return programInstanceStore.get( patient, program, status );
+    }
+
+    public Collection<ProgramInstance> getProgramInstances( Program program, OrganisationUnit organisationUnit )
+    {
+        return programInstanceStore.get( program, organisationUnit );
+    }
+
+    public Collection<ProgramInstance> getProgramInstances( Program program, OrganisationUnit organisationUnit,
+        int min, int max )
+    {
+        return programInstanceStore.get( program, organisationUnit, min, max );
+    }
+
+    public Collection<ProgramInstance> getProgramInstances( Program program, OrganisationUnit organisationUnit,
+        Date startDate, Date endDate )
+    {
+        return programInstanceStore.get( program, organisationUnit, startDate, endDate );
+    }
+
+    public Collection<ProgramInstance> getProgramInstances( Program program, Collection<Integer> orgunitIds,
+        Date startDate, Date endDate, int min, int max )
+    {
+        return programInstanceStore.get( program, orgunitIds, startDate, endDate, min, max );
+    }
+
+    public int countProgramInstances( Program program, OrganisationUnit organisationUnit )
+    {
+        return programInstanceStore.count( program, organisationUnit );
+    }
+
+    public int countProgramInstances( Program program, Collection<Integer> orgunitIds, Date startDate, Date endDate )
+    {
+        return programInstanceStore.count( program, orgunitIds, startDate, endDate );
+    }
+
+    public List<Grid> getProgramInstanceReport( Patient patient, I18n i18n, I18nFormat format )
+    {
+        List<Grid> grids = new ArrayList<Grid>();
+
+        // ---------------------------------------------------------------------
+        // Get registered personal patient data
+        // ---------------------------------------------------------------------
+
+        Grid attrGrid = new ListGrid();
+
+        if ( patient.getFirstName() == null && patient.getMiddleName() == null && patient.getLastName() == null )
+        {
+            attrGrid.setTitle( "" );
+        }
+        else
+        {
+            attrGrid.setTitle( patient.getFullName() );
+        }
+        attrGrid.setSubtitle( "" );
+
+        attrGrid.addHeader( new GridHeader( i18n.getString( "name" ), false, true ) );
+        attrGrid.addHeader( new GridHeader( i18n.getString( "value" ), false, true ) );
+        attrGrid.addHeader( new GridHeader( "", true, false ) );
+
+        // ---------------------------------------------------------------------
+        // Add fixed attribues
+        // ---------------------------------------------------------------------
+
+        if ( patient.getGender() != null )
+        {
+            attrGrid.addRow();
+            attrGrid.addValue( i18n.getString( "gender" ) );
+            attrGrid.addValue( i18n.getString( patient.getGender() ) );
+        }
+
+        if ( patient.getBirthDate() != null )
+        {
+            attrGrid.addRow();
+            attrGrid.addValue( i18n.getString( "date_of_birth" ) );
+            attrGrid.addValue( format.formatDate( patient.getBirthDate() ) );
+
+            attrGrid.addRow();
+            attrGrid.addValue( i18n.getString( "age" ) );
+            attrGrid.addValue( patient.getAge() );
+        }
+
+        if ( patient.getDobType() != null )
+        {
+            attrGrid.addRow();
+            attrGrid.addValue( i18n.getString( "dob_type" ) );
+            attrGrid.addValue( i18n.getString( patient.getDobType() + "" ) );
+        }
+
+        attrGrid.addRow();
+        attrGrid.addValue( i18n.getString( "phoneNumber" ) );
+        attrGrid
+            .addValue( (patient.getPhoneNumber() == null || patient.getPhoneNumber().isEmpty()) ? PatientAttributeValue.UNKNOWN
+                : patient.getPhoneNumber() );
+
+        // ---------------------------------------------------------------------
+        // Add dynamic attribues
+        // ---------------------------------------------------------------------
+
+        Collection<Program> programs = programService
+            .getProgramsByCurrentUser( Program.MULTIPLE_EVENTS_WITH_REGISTRATION );
+        programs.addAll( programService.getProgramsByCurrentUser( Program.SINGLE_EVENT_WITH_REGISTRATION ) );
+
+        Collection<PatientAttributeValue> attributeValues = patientAttributeValueService
+            .getPatientAttributeValues( patient );
+        Iterator<PatientAttributeValue> iterAttribute = attributeValues.iterator();
+
+        for ( Program program : programs )
+        {
+            Collection<PatientAttribute> atttributes = program.getPatientAttributes();
+            while ( iterAttribute.hasNext() )
+            {
+                PatientAttributeValue attributeValue = iterAttribute.next();
+                if ( !atttributes.contains( attributeValue.getPatientAttribute() ) )
+                {
+                    iterAttribute.remove();
+                }
+            }
+        }
+
+        for ( PatientAttributeValue attributeValue : attributeValues )
+        {
+            attrGrid.addRow();
+            attrGrid.addValue( attributeValue.getPatientAttribute().getDisplayName() );
+            String value = attributeValue.getValue();
+            if ( attributeValue.getPatientAttribute().getValueType().equals( PatientAttribute.TYPE_BOOL ) )
+            {
+                value = i18n.getString( value );
+            }
+
+            attrGrid.addValue( value );
+        }
+
+        // ---------------------------------------------------------------------
+        // Add identifier
+        // ---------------------------------------------------------------------
+
+        Collection<PatientIdentifier> identifiers = patient.getIdentifiers();
+        Iterator<PatientIdentifier> iterIdentifier = identifiers.iterator();
+
+        for ( Program program : programs )
+        {
+            Collection<PatientIdentifierType> identifierTypes = program.getPatientIdentifierTypes();
+            while ( iterIdentifier.hasNext() )
+            {
+                PatientIdentifier identifier = iterIdentifier.next();
+                if ( !identifierTypes.contains( identifier.getIdentifierType() ) )
+                {
+                    iterIdentifier.remove();
+                }
+            }
+        }
+
+        for ( PatientIdentifier identifier : identifiers )
+        {
+            attrGrid.addRow();
+            PatientIdentifierType idType = identifier.getIdentifierType();
+            if ( idType != null )
+            {
+                attrGrid.addValue( idType.getName() );
+            }
+            else
+            {
+                attrGrid.addValue( i18n.getString( "system_identifier" ) );
+
+            }
+            attrGrid.addValue( identifier.getIdentifier() );
+        }
+
+        grids.add( attrGrid );
+
+        // ---------------------------------------------------------------------
+        // Get all program data registered
+        // ---------------------------------------------------------------------
+
+        Collection<ProgramInstance> programInstances = getProgramInstances( patient );
+
+        if ( programInstances.size() > 0 )
+        {
+            for ( ProgramInstance programInstance : programInstances )
+            {
+                if ( programs.contains( programInstance.getProgram() ) )
+                {
+                    Grid gridProgram = getProgramInstanceReport( programInstance, i18n, format );
+
+                    grids.add( gridProgram );
+                }
+            }
+        }
+
+        return grids;
+    }
+
+    public Grid getProgramInstanceReport( ProgramInstance programInstance, I18n i18n, I18nFormat format )
+    {
+        Grid grid = new ListGrid();
+
+        // ---------------------------------------------------------------------
+        // Get all program data registered
+        // ---------------------------------------------------------------------
+
+        grid.setTitle( programInstance.getProgram().getName() );
+        grid.setSubtitle( "" );
+
+        // ---------------------------------------------------------------------
+        // Headers
+        // ---------------------------------------------------------------------
+
+        grid.addHeader( new GridHeader( "", false, false ) );
+        grid.addHeader( new GridHeader( "", false, false ) );
+
+        // ---------------------------------------------------------------------
+        // Grids for program-stage-instance
+        // ---------------------------------------------------------------------
+
+        grid.addRow();
+        grid.addValue( programInstance.getProgram().getDateOfEnrollmentDescription() );
+        grid.addValue( format.formatDate( programInstance.getEnrollmentDate() ) );
+
+        // Get patient-identifiers which belong to the program
+
+        Patient patient = programInstance.getPatient();
+
+        Collection<PatientIdentifierType> identifierTypes = programInstance.getProgram().getPatientIdentifierTypes();
+
+        Collection<PatientIdentifier> identifiers = patient.getIdentifiers();
+
+        if ( identifierTypes != null && identifiers.size() > 0 )
+        {
+            for ( PatientIdentifierType identifierType : identifierTypes )
+            {
+                for ( PatientIdentifier identifier : identifiers )
+                {
+                    if ( identifier.getIdentifierType().equals( identifierType ) )
+                    {
+                        grid.addRow();
+                        grid.addValue( identifierType.getDisplayName() );
+                        grid.addValue( identifier.getIdentifier() );
+                    }
+                }
+            }
+        }
+
+        // Get patient-attribute-values which belong to the program
+
+        Collection<PatientAttribute> attrtibutes = programInstance.getProgram().getPatientAttributes();
+        for ( PatientAttribute attrtibute : attrtibutes )
+        {
+            PatientAttributeValue attributeValue = patientAttributeValueService.getPatientAttributeValue( patient,
+                attrtibute );
+            if ( attributeValue != null )
+            {
+                grid.addRow();
+                grid.addValue( attrtibute.getDisplayName() );
+                grid.addValue( attributeValue.getValue() );
+            }
+        }
+
+        PatientComment patientComment = programInstance.getPatientComment();
+        if ( patientComment != null )
+        {
+            grid.addRow();
+            grid.addValue( i18n.getString( "comment" ) + " " + i18n.getString( "on" ) + " "
+                + format.formatDateTime( patientComment.getCreatedDate() ) );
+            grid.addValue( patientComment.getCommentText() );
+        }
+
+        // Get sms of the program-instance
+
+        List<OutboundSms> messasges = programInstance.getOutboundSms();
+
+        for ( OutboundSms messasge : messasges )
+        {
+            grid.addRow();
+            grid.addValue( i18n.getString( "message" ) + " " + i18n.getString( "on" ) + " "
+                + format.formatDateTime( messasge.getDate() ) );
+            grid.addValue( messasge.getMessage() );
+        }
+
+        // Program-instance attributes
+
+        if ( programInstance.getProgram().getDisplayIncidentDate() != null
+            && programInstance.getProgram().getDisplayIncidentDate() )
+        {
+            grid.addRow();
+            grid.addValue( programInstance.getProgram().getDateOfIncidentDescription() );
+            grid.addValue( format.formatDate( programInstance.getDateOfIncident() ) );
+        }
+
+        getProgramStageInstancesReport( grid, programInstance, format, i18n );
+
+        return grid;
+    }
+
+    public int countProgramInstancesByStatus( Integer status, Program program, Collection<Integer> orgunitIds,
+        Date startDate, Date endDate )
+    {
+        return programInstanceStore.countByStatus( status, program, orgunitIds, startDate, endDate );
+    }
+
+    public Collection<ProgramInstance> getProgramInstancesByStatus( Integer status, Program program,
+        Collection<Integer> orgunitIds, Date startDate, Date endDate )
+    {
+        return programInstanceStore.getByStatus( status, program, orgunitIds, startDate, endDate );
+    }
+
+    public void removeProgramEnrollment( ProgramInstance programInstance )
+    {
+        programInstanceStore.removeProgramEnrollment( programInstance );
+    }
+
+    public Collection<SchedulingProgramObject> getSendMesssageEvents()
+    {
+        Collection<SchedulingProgramObject> result = programInstanceStore
+            .getSendMesssageEvents( PatientReminder.ENROLLEMENT_DATE_TO_COMPARE );
+
+        result.addAll( programInstanceStore.getSendMesssageEvents( PatientReminder.INCIDENT_DATE_TO_COMPARE ) );
+
+        return result;
+    }
+
+    // -------------------------------------------------------------------------
+    // due-date && report-date
+    // -------------------------------------------------------------------------
+
+    private void getProgramStageInstancesReport( Grid grid, ProgramInstance programInstance, I18nFormat format,
+        I18n i18n )
+    {
+        Collection<ProgramStageInstance> programStageInstances = programInstance.getProgramStageInstances();
+
+        for ( ProgramStageInstance programStageInstance : programStageInstances )
+        {
+            grid.addRow();
+            grid.addValue( "" );
+            grid.addValue( "" );
+
+            grid.addRow();
+            grid.addValue( programStageInstance.getProgramStage().getName() );
+            grid.addValue( "" );
+
+            // -----------------------------------------------------------------
+            // due-date && report-date
+            // -----------------------------------------------------------------
+
+            grid.addRow();
+            grid.addValue( i18n.getString( "due_date" ) );
+            grid.addValue( format.formatDate( programStageInstance.getDueDate() ) );
+
+            if ( programStageInstance.getExecutionDate() != null )
+            {
+                grid.addRow();
+                grid.addValue( programStageInstance.getProgramStage().getReportDateDescription() );
+                grid.addValue( format.formatDate( programStageInstance.getExecutionDate() ) );
+            }
+
+            // Comments
+
+            List<PatientComment> comments = new ArrayList<PatientComment>( programStageInstance.getPatientComments() );
+
+            for ( PatientComment comment : comments )
+            {
+                grid.addRow();
+                grid.addValue( i18n.getString( "comment" ) + " " + i18n.getString( "on" ) + " "
+                    + format.formatDateTime( comment.getCreatedDate() ) );
+                grid.addValue( comment.getCommentText() );
+            }
+
+            // SMS messages
+
+            List<OutboundSms> messasges = programStageInstance.getOutboundSms();
+
+            for ( OutboundSms messasge : messasges )
+            {
+                grid.addRow();
+                grid.addValue( i18n.getString( "messsage" ) + " " + i18n.getString( "on" ) + " "
+                    + format.formatDateTime( messasge.getDate() ) );
+                grid.addValue( messasge.getMessage() );
+            }
+
+            // -----------------------------------------------------------------
+            // Values
+            // -----------------------------------------------------------------
+
+            Collection<PatientDataValue> patientDataValues = patientDataValueService
+                .getPatientDataValues( programStageInstance );
+
+            for ( PatientDataValue patientDataValue : patientDataValues )
+            {
+                DataElement dataElement = patientDataValue.getDataElement();
+
+                grid.addRow();
+                grid.addValue( dataElement.getFormNameFallback() );
+
+                if ( dataElement.getType().equals( DataElement.VALUE_TYPE_BOOL ) )
+                {
+                    grid.addValue( i18n.getString( patientDataValue.getValue() ) );
+                }
+                else
+                {
+                    grid.addValue( patientDataValue.getValue() );
+                }
+            }
+        }
+    }
+
+}

=== added directory 'dhis-2/dhis-services/dhis-service-patient/src/main/java/org/hisp/dhis/program/hibernate'
=== added file 'dhis-2/dhis-services/dhis-service-patient/src/main/java/org/hisp/dhis/program/hibernate/HibernateProgramStageInstanceStore.java'
--- dhis-2/dhis-services/dhis-service-patient/src/main/java/org/hisp/dhis/program/hibernate/HibernateProgramStageInstanceStore.java	1970-01-01 00:00:00 +0000
+++ dhis-2/dhis-services/dhis-service-patient/src/main/java/org/hisp/dhis/program/hibernate/HibernateProgramStageInstanceStore.java	2013-09-18 14:05:25 +0000
@@ -0,0 +1,2393 @@
+/*
+ * Copyright (c) 2004-2009, University of Oslo
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ * * Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright notice,
+ *   this list of conditions and the following disclaimer in the documentation
+ *   and/or other materials provided with the distribution.
+ * * Neither the name of the HISP project nor the names of its contributors may
+ *   be used to endorse or promote products derived from this software without
+ *   specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+package org.hisp.dhis.program.hibernate;
+
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Types;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Collection;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.hibernate.Criteria;
+import org.hibernate.Query;
+import org.hibernate.criterion.Order;
+import org.hibernate.criterion.Projections;
+import org.hibernate.criterion.Restrictions;
+import org.hisp.dhis.common.Grid;
+import org.hisp.dhis.common.GridHeader;
+import org.hisp.dhis.dataelement.DataElement;
+import org.hisp.dhis.dataelement.DataElementService;
+import org.hisp.dhis.hibernate.HibernateGenericStore;
+import org.hisp.dhis.i18n.I18n;
+import org.hisp.dhis.i18n.I18nFormat;
+import org.hisp.dhis.jdbc.StatementBuilder;
+import org.hisp.dhis.organisationunit.OrganisationUnit;
+import org.hisp.dhis.organisationunit.OrganisationUnitLevel;
+import org.hisp.dhis.organisationunit.OrganisationUnitService;
+import org.hisp.dhis.patient.Patient;
+import org.hisp.dhis.patient.PatientAudit;
+import org.hisp.dhis.patient.PatientAuditService;
+import org.hisp.dhis.patient.PatientReminder;
+import org.hisp.dhis.patient.PatientService;
+import org.hisp.dhis.patientreport.PatientAggregateReport;
+import org.hisp.dhis.patientreport.TabularReportColumn;
+import org.hisp.dhis.period.Period;
+import org.hisp.dhis.period.PeriodType;
+import org.hisp.dhis.program.Program;
+import org.hisp.dhis.program.ProgramInstance;
+import org.hisp.dhis.program.ProgramInstanceService;
+import org.hisp.dhis.program.ProgramStage;
+import org.hisp.dhis.program.ProgramStageInstance;
+import org.hisp.dhis.program.ProgramStageInstanceStore;
+import org.hisp.dhis.program.SchedulingProgramObject;
+import org.hisp.dhis.sms.outbound.OutboundSms;
+import org.hisp.dhis.system.grid.GridUtils;
+import org.hisp.dhis.system.grid.ListGrid;
+import org.hisp.dhis.system.util.DateUtils;
+import org.hisp.dhis.system.util.TextUtils;
+import org.hisp.dhis.user.CurrentUserService;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.jdbc.core.RowMapper;
+import org.springframework.jdbc.support.rowset.SqlRowSet;
+
+/**
+ * @author Abyot Asalefew
+ */
+public class HibernateProgramStageInstanceStore
+    extends HibernateGenericStore<ProgramStageInstance>
+    implements ProgramStageInstanceStore
+{
+    // -------------------------------------------------------------------------
+    // Dependency
+    // -------------------------------------------------------------------------
+
+    private JdbcTemplate jdbcTemplate;
+
+    public void setJdbcTemplate( JdbcTemplate jdbcTemplate )
+    {
+        this.jdbcTemplate = jdbcTemplate;
+    }
+
+    private StatementBuilder statementBuilder;
+
+    public void setStatementBuilder( StatementBuilder statementBuilder )
+    {
+        this.statementBuilder = statementBuilder;
+    }
+
+    private DataElementService dataElementService;
+
+    public void setDataElementService( DataElementService dataElementService )
+    {
+        this.dataElementService = dataElementService;
+    }
+
+    private OrganisationUnitService organisationUnitService;
+
+    public void setOrganisationUnitService( OrganisationUnitService organisationUnitService )
+    {
+        this.organisationUnitService = organisationUnitService;
+    }
+
+    private PatientAuditService patientAuditService;
+
+    public void setPatientAuditService( PatientAuditService patientAuditService )
+    {
+        this.patientAuditService = patientAuditService;
+    }
+
+    private CurrentUserService currentUserService;
+
+    public void setCurrentUserService( CurrentUserService currentUserService )
+    {
+        this.currentUserService = currentUserService;
+    }
+
+    private PatientService patientService;
+
+    public void setPatientService( PatientService patientService )
+    {
+        this.patientService = patientService;
+    }
+
+    private ProgramInstanceService programInstanceService;
+
+    public void setProgramInstanceService( ProgramInstanceService programInstanceService )
+    {
+        this.programInstanceService = programInstanceService;
+    }
+
+    // -------------------------------------------------------------------------
+    // Implemented methods
+    // -------------------------------------------------------------------------
+
+    @SuppressWarnings( "unchecked" )
+    public ProgramStageInstance get( ProgramInstance programInstance, ProgramStage programStage )
+    {
+        List<ProgramStageInstance> list = new ArrayList<ProgramStageInstance>( getCriteria(
+            Restrictions.eq( "programInstance", programInstance ), Restrictions.eq( "programStage", programStage ) )
+            .addOrder( Order.asc( "id" ) ).list() );
+
+        return list.isEmpty() ? null : list.get( list.size() - 1 );
+    }
+
+    @SuppressWarnings( "unchecked" )
+    public Collection<ProgramStageInstance> get( ProgramStage programStage )
+    {
+        return getCriteria( Restrictions.eq( "programStage", programStage ) ).list();
+    }
+
+    @SuppressWarnings( "unchecked" )
+    public Collection<ProgramStageInstance> get( Collection<ProgramInstance> programInstances )
+    {
+        return getCriteria( Restrictions.in( "programInstance", programInstances ) ).list();
+    }
+
+    @SuppressWarnings( "unchecked" )
+    public Collection<ProgramStageInstance> get( Date dueDate )
+    {
+        return getCriteria( Restrictions.eq( "dueDate", dueDate ) ).list();
+    }
+
+    @SuppressWarnings( "unchecked" )
+    public Collection<ProgramStageInstance> get( Date dueDate, Boolean completed )
+    {
+        return getCriteria( Restrictions.eq( "dueDate", dueDate ), Restrictions.eq( "completed", completed ) ).list();
+    }
+
+    @SuppressWarnings( "unchecked" )
+    public Collection<ProgramStageInstance> get( Date startDate, Date endDate )
+    {
+        return (getCriteria( Restrictions.ge( "dueDate", startDate ), Restrictions.le( "dueDate", endDate ) )).list();
+    }
+
+    @SuppressWarnings( "unchecked" )
+    public Collection<ProgramStageInstance> get( Date startDate, Date endDate, Boolean completed )
+    {
+        return (getCriteria( Restrictions.ge( "dueDate", startDate ), Restrictions.le( "dueDate", endDate ),
+            Restrictions.eq( "completed", completed ) )).list();
+    }
+
+    @SuppressWarnings( "unchecked" )
+    public List<ProgramStageInstance> get( OrganisationUnit unit, Date after, Date before, Boolean completed )
+    {
+        String hql = "from ProgramStageInstance psi where psi.organisationUnit = :unit";
+
+        if ( after != null )
+        {
+            hql += " and dueDate >= :after";
+        }
+
+        if ( before != null )
+        {
+            hql += " and dueDate <= :before";
+        }
+
+        if ( completed != null )
+        {
+            hql += " and completed = :completed";
+        }
+
+        Query q = getQuery( hql ).setEntity( "unit", unit );
+
+        if ( after != null )
+        {
+            q.setDate( "after", after );
+        }
+
+        if ( before != null )
+        {
+            q.setDate( "before", before );
+        }
+
+        if ( completed != null )
+        {
+            q.setBoolean( "completed", completed );
+        }
+
+        return q.list();
+    }
+
+    @SuppressWarnings( "unchecked" )
+    public List<ProgramStageInstance> get( Patient patient, Boolean completed )
+    {
+        String hql = "from ProgramStageInstance where programInstance.patient = :patient and completed = :completed";
+
+        return getQuery( hql ).setEntity( "patient", patient ).setBoolean( "completed", completed ).list();
+    }
+
+    @SuppressWarnings( "unchecked" )
+    public List<ProgramStageInstance> get( ProgramStage programStage, OrganisationUnit orgunit, Date startDate,
+        Date endDate, int min, int max )
+    {
+        return getCriteria( Restrictions.eq( "programStage", programStage ),
+            Restrictions.eq( "organisationUnit", orgunit ), Restrictions.between( "dueDate", startDate, endDate ) )
+            .setFirstResult( min ).setMaxResults( max ).list();
+    }
+
+    @Override
+    public Grid getTabularReport( Boolean anonynousEntryForm, ProgramStage programStage,
+        Map<Integer, OrganisationUnitLevel> orgUnitLevelMap, Collection<Integer> orgUnits,
+        List<TabularReportColumn> columns, int level, int maxLevel, Date startDate, Date endDate, boolean descOrder,
+        Boolean completed, Boolean accessPrivateInfo, Boolean displayOrgunitCode, Integer min, Integer max, I18n i18n )
+    {
+        // ---------------------------------------------------------------------
+        // Headers cols
+        // ---------------------------------------------------------------------
+
+        Grid grid = new ListGrid();
+        grid.setTitle( programStage.getDisplayName() );
+        grid.setSubtitle( i18n.getString( "from" ) + " " + DateUtils.getMediumDateString( startDate ) + " "
+            + i18n.getString( "to" ) + " " + DateUtils.getMediumDateString( endDate ) );
+
+        grid.addHeader( new GridHeader( "id", true, true ) );
+        grid.addHeader( new GridHeader( programStage.getReportDateDescription(), false, true ) );
+
+        if ( anonynousEntryForm == null || !anonynousEntryForm )
+        {
+            for ( int i = level; i <= maxLevel; i++ )
+            {
+                String name = orgUnitLevelMap.containsKey( i ) ? orgUnitLevelMap.get( i ).getName() : "Level " + i;
+                grid.addHeader( new GridHeader( name, false, true ) );
+            }
+        }
+
+        if ( displayOrgunitCode != null && displayOrgunitCode )
+        {
+            grid.addHeader( new GridHeader( i18n.getString( "orgunit_code" ), false, true ) );
+        }
+
+        Collection<String> deKeys = new HashSet<String>();
+        for ( TabularReportColumn column : columns )
+        {
+            if ( !column.isMeta() )
+            {
+                String deKey = "element_" + column.getIdentifier();
+                if ( !deKeys.contains( deKey ) )
+                {
+                    grid.addHeader( new GridHeader( column.getName(), column.isHidden(), true ) );
+                    deKeys.add( deKey );
+                }
+            }
+        }
+
+        grid.addHeader( new GridHeader( "Complete", true, true ) );
+        grid.addHeader( new GridHeader( "PatientId", true, true ) );
+
+        // ---------------------------------------------------------------------
+        // Get SQL and build grid
+        // ---------------------------------------------------------------------
+
+        String sql = getTabularReportSql( anonynousEntryForm, false, programStage, columns, orgUnits, level, maxLevel,
+            startDate, endDate, descOrder, completed, accessPrivateInfo, displayOrgunitCode, min, max );
+
+        SqlRowSet rowSet = jdbcTemplate.queryForRowSet( sql );
+
+        GridUtils.addRows( grid, rowSet );
+
+        // Save PatientAudit
+
+        if ( accessPrivateInfo != null && accessPrivateInfo )
+        {
+            long millisInDay = 60 * 60 * 24 * 1000;
+            long currentTime = new Date().getTime();
+            long dateOnly = (currentTime / millisInDay) * millisInDay;
+            Date date = new Date( dateOnly );
+            String visitor = currentUserService.getCurrentUsername();
+
+            List<Map<String, Object>> rows = jdbcTemplate.queryForList( sql );
+
+            if ( rows != null && !rows.isEmpty() )
+            {
+                for ( Map<String, Object> row : rows )
+                {
+                    Integer patientId = (Integer) row.get( "patientid" );
+
+                    PatientAudit patientAudit = patientAuditService.getPatientAudit( patientId, visitor, date,
+                        PatientAudit.MODULE_TABULAR_REPORT );
+                    if ( patientAudit == null )
+                    {
+                        Patient patient = patientService.getPatient( patientId );
+                        patientAudit = new PatientAudit( patient, visitor, date, PatientAudit.MODULE_TABULAR_REPORT );
+                        patientAuditService.savePatientAudit( patientAudit );
+                    }
+                }
+            }
+        }
+
+        return grid;
+    }
+
+    public int getTabularReportCount( Boolean anonynousEntryForm, ProgramStage programStage,
+        List<TabularReportColumn> columns, Collection<Integer> organisationUnits, int level, int maxLevel,
+        Date startDate, Date endDate, Boolean completed )
+    {
+        String sql = getTabularReportSql( anonynousEntryForm, true, programStage, columns, organisationUnits, level,
+            maxLevel, startDate, endDate, false, completed, null, null, null, null );
+
+        return jdbcTemplate.queryForObject( sql, Integer.class );
+    }
+
+    public void removeEmptyEvents( ProgramStage programStage, OrganisationUnit organisationUnit )
+    {
+        String sql = "delete from programstageinstance where programstageid=" + programStage.getId()
+            + " and organisationunitid=" + organisationUnit.getId() + " and programstageinstanceid not in "
+            + "(select pdv.programstageinstanceid from patientdatavalue pdv )";
+        jdbcTemplate.execute( sql );
+    }
+
+    @Override
+    public void update( Collection<Integer> programStageInstanceIds, OutboundSms outboundSms )
+    {
+        for ( Integer programStageInstanceId : programStageInstanceIds )
+        {
+            if ( programStageInstanceId != null && programStageInstanceId != 0 )
+            {
+                ProgramStageInstance programStageInstance = get( programStageInstanceId );
+
+                List<OutboundSms> outboundSmsList = programStageInstance.getOutboundSms();
+
+                if ( outboundSmsList == null )
+                {
+                    outboundSmsList = new ArrayList<OutboundSms>();
+                }
+
+                outboundSmsList.add( outboundSms );
+                programStageInstance.setOutboundSms( outboundSmsList );
+                update( programStageInstance );
+            }
+        }
+    }
+
+    public Collection<SchedulingProgramObject> getSendMesssageEvents()
+    {
+        String sql = "select psi.programstageinstanceid, p.phonenumber, prm.templatemessage, p.firstname, p.middlename, p.lastname, org.name as orgunitName "
+            + ",pg.name as programName, ps.name as programStageName, psi.duedate,(DATE(now()) - DATE(psi.duedate) ) as days_since_due_date,psi.duedate "
+            + "from patient p INNER JOIN programinstance pi "
+            + "     ON p.patientid=pi.patientid "
+            + " INNER JOIN programstageinstance psi  "
+            + "     ON psi.programinstanceid=pi.programinstanceid "
+            + " INNER JOIN program pg  "
+            + "     ON pg.programid=pi.programid "
+            + " INNER JOIN programstage ps  "
+            + "     ON ps.programstageid=psi.programstageid "
+            + " INNER JOIN organisationunit org  "
+            + "     ON org.organisationunitid = p.organisationunitid "
+            + " INNER JOIN patientreminder prm  "
+            + "     ON prm.programstageid = ps.programstageid "
+            + "WHERE pi.status="
+            + ProgramInstance.STATUS_ACTIVE
+            + "     and p.phonenumber is not NULL and p.phonenumber != '' "
+            + "     and prm.templatemessage is not NULL and prm.templatemessage != '' "
+            + "     and pg.type=1 and prm.daysallowedsendmessage is not null  "
+            + "     and psi.executiondate is null "
+            + "     and (  DATE(now()) - DATE(psi.duedate) ) = prm.daysallowedsendmessage ";
+
+        SqlRowSet rs = jdbcTemplate.queryForRowSet( sql );
+
+        int cols = rs.getMetaData().getColumnCount();
+
+        Collection<SchedulingProgramObject> schedulingProgramObjects = new HashSet<SchedulingProgramObject>();
+
+        while ( rs.next() )
+        {
+            String message = "";
+            for ( int i = 1; i <= cols; i++ )
+            {
+                message = rs.getString( "templatemessage" );
+                String patientName = rs.getString( "firstName" );
+                String organisationunitName = rs.getString( "orgunitName" );
+                String programName = rs.getString( "programName" );
+                String programStageName = rs.getString( "programStageName" );
+                String daysSinceDueDate = rs.getString( "days_since_due_date" );
+                String dueDate = rs.getString( "duedate" ).split( " " )[0];// just
+                                                                           // get
+                                                                           // date,
+                                                                           // remove
+                                                                           // timestamp
+
+                message = message.replace( PatientReminder.TEMPLATE_MESSSAGE_PATIENT_NAME, patientName );
+                message = message.replace( PatientReminder.TEMPLATE_MESSSAGE_PROGRAM_NAME, programName );
+                message = message.replace( PatientReminder.TEMPLATE_MESSSAGE_PROGAM_STAGE_NAME, programStageName );
+                message = message.replace( PatientReminder.TEMPLATE_MESSSAGE_DUE_DATE, dueDate );
+                message = message.replace( PatientReminder.TEMPLATE_MESSSAGE_ORGUNIT_NAME, organisationunitName );
+                message = message.replace( PatientReminder.TEMPLATE_MESSSAGE_DAYS_SINCE_DUE_DATE, daysSinceDueDate );
+            }
+
+            SchedulingProgramObject schedulingProgramObject = new SchedulingProgramObject();
+            schedulingProgramObject.setProgramStageInstanceId( rs.getInt( "programstageinstanceid" ) );
+            schedulingProgramObject.setPhoneNumber( rs.getString( "phonenumber" ) );
+            schedulingProgramObject.setMessage( message );
+
+            schedulingProgramObjects.add( schedulingProgramObject );
+        }
+
+        return schedulingProgramObjects;
+    }
+
+    public int getStatisticalProgramStageReport( ProgramStage programStage, Collection<Integer> orgunitIds,
+        Date startDate, Date endDate, int status )
+    {
+        Criteria criteria = getStatisticalProgramStageCriteria( programStage, orgunitIds, startDate, endDate, status );
+
+        Number rs = (Number) criteria.setProjection( Projections.rowCount() ).uniqueResult();
+
+        return rs != null ? rs.intValue() : 0;
+    }
+
+    @SuppressWarnings( "unchecked" )
+    public List<ProgramStageInstance> getStatisticalProgramStageDetailsReport( ProgramStage programStage,
+        Collection<Integer> orgunitIds, Date startDate, Date endDate, int status, Integer min, Integer max )
+    {
+        Criteria criteria = getStatisticalProgramStageCriteria( programStage, orgunitIds, startDate, endDate, status );
+
+        if ( min != null && max != null )
+        {
+            criteria.setFirstResult( min );
+            criteria.setMaxResults( max );
+        }
+
+        return criteria.list();
+    }
+
+    public Grid getAggregateReport( int position, ProgramStage programStage, Collection<Integer> orgunitIds,
+        String facilityLB, Integer deGroupBy, Integer deSum, Map<Integer, Collection<String>> deFilters,
+        List<Period> periods, String aggregateType, Integer limit, Boolean useCompletedEvents, Boolean displayTotals,
+        Boolean useFormNameDataElement, I18nFormat format, I18n i18n )
+    {
+        String sql = "";
+        String filterSQL = filterSQLStatement( deFilters );
+
+        Grid grid = new ListGrid();
+        grid.setTitle( programStage.getProgram().getDisplayName() );
+
+        // ---------------------------------------------------------------------
+        // Set Sub-title is filter value
+        // ---------------------------------------------------------------------
+
+        String subTitle = " ";
+        if ( deSum != null )
+        {
+            DataElement dataElement = dataElementService.getDataElement( deSum );
+            String dename = dataElement.getDisplayName();
+            if ( useFormNameDataElement != null || useFormNameDataElement )
+            {
+                dename = dataElement.getFormNameFallback();
+            }
+            subTitle = i18n.getString( "group_by" ) + ": " + dename + "; ";
+        }
+
+        // Filter is only one orgunit
+        
+        if ( position == PatientAggregateReport.POSITION_ROW_PERIOD_COLUMN_DATA )
+        {
+            String orgunitName = organisationUnitService.getOrganisationUnit( orgunitIds.iterator().next() )
+                .getDisplayName();
+            
+            grid.setSubtitle( subTitle + i18n.getString( "orgunit" ) + ": " + orgunitName );
+        }
+        // Filter is only one period
+        else if ( position == PatientAggregateReport.POSITION_ROW_ORGUNIT
+            || position == PatientAggregateReport.POSITION_ROW_ORGUNIT_COLUMN_DATA
+            || position == PatientAggregateReport.POSITION_ROW_DATA_COLUMN_ORGUNIT
+            || position == PatientAggregateReport.POSITION_ROW_DATA )
+        {
+
+            Period period = periods.iterator().next();
+            String periodName = "";
+            if ( period.getPeriodType() != null )
+            {
+                periodName += format.formatPeriod( period );
+            }
+            else
+            {
+                String startDate = format.formatDate( period.getStartDate() );
+                String endDate = format.formatDate( period.getEndDate() );
+                periodName += startDate + " -> " + endDate;
+            }
+            
+            grid.setSubtitle( subTitle + i18n.getString( "period" ) + ": " + periodName );
+        }
+        else
+        {
+            // Orgunit filter description
+            String filterOrgunitDes = "";
+            if ( position == PatientAggregateReport.POSITION_ROW_DATA_COLUMN_PERIOD
+                || position == PatientAggregateReport.POSITION_ROW_PERIOD
+                || position == PatientAggregateReport.POSITION_ROW_DATA )
+            {
+                filterOrgunitDes = getFilterOrgunitDescription( orgunitIds );
+
+                if ( !filterOrgunitDes.isEmpty() )
+                {
+                    filterOrgunitDes = i18n.getString( "orgunit" ) + ": " + filterOrgunitDes + "; ";
+                }
+            }
+
+            // Period filter description
+            String filterPeriodDes = "";
+            if ( position == PatientAggregateReport.POSITION_ROW_ORGUNIT
+                || position == PatientAggregateReport.POSITION_ROW_ORGUNIT_COLUMN_DATA
+                || position == PatientAggregateReport.POSITION_ROW_DATA
+                || position == PatientAggregateReport.POSITION_ROW_DATA_COLUMN_ORGUNIT )
+            {
+                filterPeriodDes = getFilterPeriodDescription( periods, format );
+
+                if ( !filterPeriodDes.isEmpty() )
+                {
+                    filterPeriodDes = i18n.getString( "period" ) + ": " + filterPeriodDes + "; ";
+                }
+            }
+
+            // Data filter description
+            String filterDataDes = getFilterDataDescription( deFilters );
+            if ( !filterDataDes.isEmpty() )
+            {
+                filterDataDes = "; " + i18n.getString( "data_filter" ) + ": " + filterDataDes;
+            }
+            
+            subTitle += filterOrgunitDes + filterPeriodDes + filterDataDes;
+            if ( subTitle.isEmpty() )
+            {
+                grid.setSubtitle( i18n.getString( "filter" ) + ": [" + i18n.getString( "none" ) + "]" );
+            }
+            else
+            {
+                grid.setSubtitle( subTitle );
+            }
+        }
+        
+        // ---------------------------------------------------------------------
+        // Get SQL and build grid
+        // ---------------------------------------------------------------------
+
+        // Type = 1
+        if ( position == PatientAggregateReport.POSITION_ROW_ORGUNIT_COLUMN_PERIOD )
+        {
+            sql = getAggregateReportSQL12( programStage, orgunitIds, facilityLB, filterSQL, deGroupBy, deSum, periods,
+                aggregateType, limit, useCompletedEvents, format );
+        }
+        // Type = 2
+        if ( position == PatientAggregateReport.POSITION_ROW_PERIOD_COLUMN_ORGUNIT )
+        {
+            // ---------------------------------------------------------------------
+            // Get SQL and build grid
+            // ---------------------------------------------------------------------
+
+            sql = getAggregateReportSQL12( programStage, orgunitIds, facilityLB, filterSQL, deGroupBy, deSum, periods,
+                aggregateType, limit, useCompletedEvents, format );
+
+        }
+        // Type = 3
+        else if ( position == PatientAggregateReport.POSITION_ROW_ORGUNIT_ROW_PERIOD )
+        {
+            sql = getAggregateReportSQL3( position, programStage, orgunitIds, facilityLB, filterSQL, deGroupBy, deSum,
+                periods, aggregateType, limit, useCompletedEvents, format );
+        }
+        // Type = 4
+        else if ( position == PatientAggregateReport.POSITION_ROW_PERIOD )
+        {
+            sql = getAggregateReportSQL4( position, programStage, orgunitIds, facilityLB, filterSQL, deGroupBy, deSum,
+                periods, aggregateType, limit, useCompletedEvents, format );
+        }
+        // type = 5
+        else if ( position == PatientAggregateReport.POSITION_ROW_ORGUNIT )
+        {
+            sql = getAggregateReportSQL5( position, programStage, orgunitIds, facilityLB, filterSQL, deGroupBy, deSum,
+                periods.iterator().next(), aggregateType, limit, useCompletedEvents, format );
+        }
+
+        // Type = 9 && With group-by
+        else if ( position == PatientAggregateReport.POSITION_ROW_DATA_COLUMN_PERIOD && deGroupBy != null )
+        {
+            sql = getAggregateReportSQL9( programStage, orgunitIds.iterator().next(), facilityLB, filterSQL, deGroupBy,
+                deSum, periods, aggregateType, limit, useCompletedEvents, useFormNameDataElement, format );
+        }
+
+        // Type = 6 && With group-by
+        else if ( position == PatientAggregateReport.POSITION_ROW_PERIOD_COLUMN_DATA && deGroupBy != null )
+        {
+            sql = getAggregateReportSQL6( programStage, orgunitIds.iterator().next(), facilityLB, filterSQL, deGroupBy,
+                deSum, periods, aggregateType, limit, useCompletedEvents, format );
+        }
+
+        // Type = 6-9 && NOT group-by
+        else if ( (position == PatientAggregateReport.POSITION_ROW_PERIOD_COLUMN_DATA || position == PatientAggregateReport.POSITION_ROW_DATA_COLUMN_PERIOD)
+            && deGroupBy == null )
+        {
+            sql = getAggregateReportSQL6WithoutGroup( programStage, orgunitIds.iterator().next(), facilityLB,
+                filterSQL, deSum, periods, aggregateType, limit, useCompletedEvents, format );
+        }
+
+        // Type = 7 && Group-by
+        else if ( (position == PatientAggregateReport.POSITION_ROW_ORGUNIT_COLUMN_DATA || position == PatientAggregateReport.POSITION_ROW_DATA_COLUMN_ORGUNIT)
+            && deGroupBy != null )
+        {
+            sql = getAggregateReportSQL7( programStage, orgunitIds, facilityLB, filterSQL, deGroupBy, deSum, periods
+                .iterator().next(), aggregateType, limit, useCompletedEvents, format );
+        }
+
+        // Type = 7 && NOT group-by
+        else if ( (position == PatientAggregateReport.POSITION_ROW_ORGUNIT_COLUMN_DATA || position == PatientAggregateReport.POSITION_ROW_DATA_COLUMN_ORGUNIT)
+            && deGroupBy == null )
+        {
+            sql = getAggregateReportSQL7WithoutGroup( programStage, orgunitIds, facilityLB, filterSQL, deSum, periods
+                .iterator().next(), aggregateType, limit, useCompletedEvents, format );
+        }
+
+        // type = 8 && With group-by
+        else if ( position == PatientAggregateReport.POSITION_ROW_DATA )
+        {
+            sql = getAggregateReportSQL8( programStage, orgunitIds, facilityLB, filterSQL, deGroupBy, periods
+                .iterator().next(), aggregateType, limit, useCompletedEvents, format );
+        }
+
+        if ( !sql.isEmpty() )
+        {
+            SqlRowSet rowSet = jdbcTemplate.queryForRowSet( sql );
+
+            // Type ==2 && ==9 && ==10
+            if ( position == PatientAggregateReport.POSITION_ROW_PERIOD_COLUMN_ORGUNIT
+                || position == PatientAggregateReport.POSITION_ROW_DATA_COLUMN_ORGUNIT
+                || (position == PatientAggregateReport.POSITION_ROW_DATA_COLUMN_PERIOD && deGroupBy == null) )
+            {
+                pivotTable( grid, rowSet, displayTotals, i18n, format );
+            }
+            else
+            {
+                fillDataInGrid( grid, rowSet, displayTotals, i18n, format );
+            }
+        }
+
+        return grid;
+    }
+
+    public int getOverDueCount( ProgramStage programStage, Collection<Integer> orgunitIds, Date startDate, Date endDate )
+    {
+        Calendar yesterday = Calendar.getInstance();
+        yesterday.add( Calendar.DATE, -1 );
+        PeriodType.clearTimeOfDay( yesterday );
+        Date now = yesterday.getTime();
+
+        if ( endDate.before( now ) )
+        {
+            now = endDate;
+        }
+
+        Criteria criteria = getCriteria();
+        criteria.createAlias( "programInstance", "programInstance" );
+        criteria.createAlias( "programInstance.patient", "patient" );
+        criteria.createAlias( "patient.organisationUnit", "regOrgunit" );
+        criteria.add( Restrictions.eq( "programStage", programStage ) );
+        criteria.add( Restrictions.isNull( "programInstance.endDate" ) );
+        criteria.add( Restrictions.isNull( "executionDate" ) );
+        criteria.add( Restrictions.between( "dueDate", startDate, now ) );
+        criteria.add( Restrictions.in( "regOrgunit.id", orgunitIds ) );
+        criteria.setProjection( Projections.rowCount() ).uniqueResult();
+
+        Number rs = (Number) criteria.setProjection( Projections.rowCount() ).uniqueResult();
+
+        return rs != null ? rs.intValue() : 0;
+    }
+
+    @SuppressWarnings( "unchecked" )
+    public Collection<ProgramStageInstance> get( Program program, Collection<Integer> orgunitIds, Date startDate,
+        Date endDate, Boolean completed )
+    {
+        return getCriteria( program, orgunitIds, startDate, endDate, completed ).list();
+    }
+
+    public int count( Program program, Collection<Integer> orgunitIds, Date startDate, Date endDate, Boolean completed )
+    {
+        Number rs = (Number) getCriteria( program, orgunitIds, startDate, endDate, completed ).setProjection(
+            Projections.rowCount() ).uniqueResult();
+
+        return rs != null ? rs.intValue() : 0;
+    }
+
+    public int count( ProgramStage programStage, Collection<Integer> orgunitIds, Date startDate, Date endDate,
+        Boolean completed )
+    {
+        Number rs = (Number) getCriteria( programStage, orgunitIds, startDate, endDate, completed ).setProjection(
+            Projections.rowCount() ).uniqueResult();
+
+        return rs != null ? rs.intValue() : 0;
+    }
+
+    public Grid getCompleteness( OrganisationUnit orgunit, Program program, String startDate, String endDate, I18n i18n )
+    {
+        String sql = "SELECT ou.name as orgunit, ps.name as events, psi.completeduser as user_name, count(psi.programstageinstanceid) as number_of_events "
+            + "         FROM programstageinstance psi INNER JOIN programstage ps "
+            + "                         ON psi.programstageid = ps.programstageid "
+            + "                 INNER JOIN organisationunit ou "
+            + "                         ON ou.organisationunitid=psi.organisationunitid"
+            + "                 INNER JOIN program pg "
+            + "                         ON pg.programid = ps.programid "
+            + "         WHERE ou.parentid = "
+            + orgunit.getId()
+            + "                 AND pg.programid = "
+            + program.getId()
+            + "         GROUP BY ou.name, ps.name, psi.completeduser, psi.completeddate, psi.completed "
+            + "         HAVING psi.completeddate >= '"
+            + startDate
+            + "'                AND psi.completeddate <= '"
+            + endDate
+            + "' "
+            + "                 AND psi.completed=true "
+            + "         ORDER BY ou.name, ps.name, psi.completeduser";
+
+        SqlRowSet rs = jdbcTemplate.queryForRowSet( sql );
+
+        // Create column with Total column
+
+        Grid grid = new ListGrid();
+
+        grid.setTitle( program.getDisplayName() );
+        grid.setSubtitle( i18n.getString( "from" ) + " " + startDate + " " + i18n.getString( "to" ) + " " + endDate );
+
+        int cols = rs.getMetaData().getColumnCount();
+
+        for ( int i = 1; i <= cols; i++ )
+        {
+            grid.addHeader( new GridHeader( i18n.getString( rs.getMetaData().getColumnLabel( i ) ), false, false ) );
+        }
+
+        GridUtils.addRows( grid, rs );
+
+        return grid;
+    }
+
+    // -------------------------------------------------------------------------
+    // Supportive methods
+    // -------------------------------------------------------------------------
+
+    private Criteria getCriteria( Program program, Collection<Integer> orgunitIds, Date startDate, Date endDate,
+        Boolean completed )
+    {
+        Criteria criteria = getCriteria();
+        criteria.createAlias( "programInstance", "programInstance" );
+        criteria.add( Restrictions.eq( "programInstance.program", program ) );
+
+        if ( completed == null )
+        {
+            criteria.add( Restrictions.between( "programInstance.enrollmentDate", startDate, endDate ) );
+        }
+        else
+        {
+            if ( completed )
+            {
+                criteria.add( Restrictions.and( Restrictions.eq( "completed", true ),
+                    Restrictions.between( "executionDate", startDate, endDate ),
+                    Restrictions.in( "organisationUnit.id", orgunitIds ) ) );
+            }
+            else
+            {
+                criteria.createAlias( "programInstance.patient", "patient" );
+                criteria.createAlias( "patient.organisationUnit", "regOrgunit" );
+                criteria.add( Restrictions.or( Restrictions.and( Restrictions.isNull( "executionDate" ),
+                    Restrictions.between( "dueDate", startDate, endDate ),
+                    Restrictions.in( "regOrgunit.id", orgunitIds ) ), Restrictions.and(
+                    Restrictions.eq( "completed", false ), Restrictions.isNotNull( "executionDate" ),
+                    Restrictions.between( "executionDate", startDate, endDate ),
+                    Restrictions.in( "organisationUnit.id", orgunitIds ) ) ) );
+            }
+        }
+
+        return criteria;
+    }
+
+    private Criteria getCriteria( ProgramStage programStage, Collection<Integer> orgunitIds, Date startDate,
+        Date endDate, Boolean completed )
+    {
+        Criteria criteria = getCriteria();
+        criteria.createAlias( "programInstance", "programInstance" );
+        criteria.add( Restrictions.eq( "programStage", programStage ) );
+
+        if ( completed == null )
+        {
+            criteria.createAlias( "programInstance.patient", "patient" );
+            criteria.createAlias( "patient.organisationUnit", "regOrgunit" );
+            criteria.add( Restrictions.or( Restrictions.and( Restrictions.eq( "completed", true ),
+                Restrictions.between( "executionDate", startDate, endDate ),
+                Restrictions.in( "organisationUnit.id", orgunitIds ) ), Restrictions.and(
+                Restrictions.eq( "completed", false ), Restrictions.isNotNull( "executionDate" ),
+                Restrictions.between( "executionDate", startDate, endDate ),
+                Restrictions.in( "organisationUnit.id", orgunitIds ) ),
+                Restrictions.and( Restrictions.eq( "completed", false ), Restrictions.isNull( "executionDate" ),
+                    Restrictions.between( "dueDate", startDate, endDate ),
+                    Restrictions.in( "regOrgunit.id", orgunitIds ) ), Restrictions.and(
+                    Restrictions.eq( "status", ProgramStageInstance.SKIPPED_STATUS ),
+                    Restrictions.between( "dueDate", startDate, endDate ),
+                    Restrictions.in( "regOrgunit.id", orgunitIds ) ) ) );
+        }
+        else
+        {
+            if ( completed )
+            {
+                criteria.add( Restrictions.and( Restrictions.eq( "completed", true ),
+                    Restrictions.between( "executionDate", startDate, endDate ),
+                    Restrictions.in( "organisationUnit.id", orgunitIds ) ) );
+            }
+            else
+            {
+                criteria.createAlias( "programInstance.patient", "patient" );
+                criteria.createAlias( "patient.organisationUnit", "regOrgunit" );
+                criteria.add( Restrictions.and( Restrictions.eq( "completed", false ),
+                    Restrictions.isNotNull( "executionDate" ),
+                    Restrictions.between( "executionDate", startDate, endDate ),
+                    Restrictions.in( "organisationUnit.id", orgunitIds ) ) );
+            }
+        }
+
+        return criteria;
+    }
+
+    private String getTabularReportSql( Boolean anonynousEntryForm, boolean count, ProgramStage programStage,
+        List<TabularReportColumn> columns, Collection<Integer> orgUnits, int level, int maxLevel, Date startDate,
+        Date endDate, Boolean descOrder, Boolean completed, Boolean accessPrivateInfo, Boolean displayOrgunitCode,
+        Integer min, Integer max )
+    {
+        Set<String> deKeys = new HashSet<String>();
+        String selector = count ? "count(*) " : "* ";
+
+        String sql = "select " + selector + "from ( select DISTINCT psi.programstageinstanceid, psi.executiondate,";
+        String where = "";
+        String operator = "where ";
+
+        if ( anonynousEntryForm == null || !anonynousEntryForm )
+        {
+            for ( int i = level; i <= maxLevel; i++ )
+            {
+                sql += "(select name from organisationunit where organisationunitid=ous.idlevel" + i + ") as level_"
+                    + i + ",";
+            }
+        }
+
+        if ( displayOrgunitCode != null && displayOrgunitCode )
+        {
+            sql += "(select code from organisationunit where organisationunitid=psi.organisationunitid ) as code_,";
+        }
+
+        for ( TabularReportColumn column : columns )
+        {
+            if ( column.isFixedAttribute() )
+            {
+                sql += "p." + column.getIdentifier() + ",";
+
+                if ( column.hasQuery() )
+                {
+                    if ( column.isDateType() )
+                    {
+                        where += operator + column.getIdentifier() + " " + column.getOperator() + " "
+                            + column.getQuery() + " ";
+                    }
+                    else
+                    {
+                        where += operator + "lower(" + column.getIdentifier() + ") " + column.getOperator() + " "
+                            + column.getQuery() + " ";
+                    }
+                    operator = "and ";
+                }
+            }
+            else if ( column.isIdentifierType() )
+            {
+                String deKey = "identifier_" + column.getIdentifier();
+                if ( !deKeys.contains( deKey ) )
+                {
+                    sql += "(select identifier from patientidentifier where patientid=p.patientid and patientidentifiertypeid="
+                        + column.getIdentifier() + ") as identifier_" + column.getIdentifier() + ",";
+                }
+
+                if ( column.hasQuery() )
+                {
+                    if ( column.isDateType() )
+                    {
+                        where += operator + "identifier_" + column.getIdentifier() + " " + column.getOperator() + " "
+                            + column.getQuery() + " ";
+                    }
+                    else
+                    {
+                        where += operator + "lower(identifier_" + column.getIdentifier() + ") " + column.getOperator()
+                            + " " + column.getQuery() + " ";
+                    }
+                    operator = "and ";
+                }
+            }
+            else if ( column.isDynamicAttribute() )
+            {
+                String deKey = "attribute_" + column.getIdentifier();
+                if ( !deKeys.contains( deKey ) )
+                {
+                    sql += "(select value from patientattributevalue where patientid=p.patientid and patientattributeid="
+                        + column.getIdentifier() + ") as attribute_" + column.getIdentifier() + ",";
+                }
+
+                if ( column.hasQuery() )
+                {
+                    if ( column.isDateType() )
+                    {
+                        where += operator + "attribute_" + column.getIdentifier() + " " + column.getOperator() + " "
+                            + column.getQuery() + " ";
+                    }
+                    else
+                    {
+                        where += operator + "lower(attribute_" + column.getIdentifier() + ") " + column.getOperator()
+                            + " " + column.getQuery() + " ";
+                    }
+                    operator = "and ";
+                }
+            }
+            if ( column.isNumberDataElement() )
+            {
+                String deKey = "element_" + column.getIdentifier();
+                if ( !deKeys.contains( deKey ) )
+                {
+                    sql += "(select cast( value as "
+                        + statementBuilder.getDoubleColumnType()
+                        + " ) from patientdatavalue where programstageinstanceid=psi.programstageinstanceid and dataelementid="
+                        + column.getIdentifier() + ") as element_" + column.getIdentifier() + ",";
+                    deKeys.add( deKey );
+                }
+
+                if ( column.hasQuery() )
+                {
+                    where += operator + "element_" + column.getIdentifier() + " " + column.getOperator() + " "
+                        + column.getQuery() + " ";
+                    operator = "and ";
+                }
+            }
+            else if ( column.isDataElement() )
+            {
+                String deKey = "element_" + column.getIdentifier();
+                if ( !deKeys.contains( deKey ) )
+                {
+                    sql += "(select value from patientdatavalue where programstageinstanceid=psi.programstageinstanceid and dataelementid="
+                        + column.getIdentifier() + ") as element_" + column.getIdentifier() + ",";
+                    deKeys.add( deKey );
+                }
+
+                if ( column.hasQuery() )
+                {
+                    if ( column.isDateType() )
+                    {
+                        where += operator + "element_" + column.getIdentifier() + " " + column.getOperator() + " "
+                            + column.getQuery() + " ";
+                    }
+                    else
+                    {
+                        where += operator + "lower(element_" + column.getIdentifier() + ") " + column.getOperator()
+                            + " " + column.getQuery() + " ";
+                    }
+                    operator = "and ";
+                }
+            }
+        }
+
+        sql += " psi.completed ";
+        if ( accessPrivateInfo != null && accessPrivateInfo )
+        {
+            sql += ", p.patientid ";
+        }
+
+        sql += "from programstageinstance psi ";
+        sql += "left join programinstance pi on (psi.programinstanceid=pi.programinstanceid) ";
+        sql += "left join patient p on (pi.patientid=p.patientid) ";
+        sql += "join organisationunit ou on (ou.organisationunitid=psi.organisationunitid) ";
+
+        if ( anonynousEntryForm == null || !anonynousEntryForm )
+        {
+            sql += "join _orgunitstructure ous on (psi.organisationunitid=ous.organisationunitid) ";
+        }
+
+        sql += "where psi.programstageid=" + programStage.getId() + " ";
+
+        if ( startDate != null && endDate != null )
+        {
+            String sDate = DateUtils.getMediumDateString( startDate );
+            String eDate = DateUtils.getMediumDateString( endDate );
+
+            sql += "and psi.executiondate >= '" + sDate + "' ";
+            sql += "and psi.executiondate <= '" + eDate + "' ";
+        }
+
+        if ( orgUnits != null )
+        {
+            sql += "and ou.organisationunitid in (" + TextUtils.getCommaDelimitedString( orgUnits ) + ") ";
+        }
+        if ( completed != null )
+        {
+            sql += "and psi.completed=" + completed + " ";
+        }
+
+        sql += "order by ";
+
+        if ( anonynousEntryForm == null || !anonynousEntryForm )
+        {
+            for ( int i = level; i <= maxLevel; i++ )
+            {
+                sql += "level_" + i + ",";
+            }
+        }
+
+        sql += "psi.executiondate ";
+        sql += (descOrder == null || descOrder) ? "desc " : "";
+        sql += ") as tabular ";
+        sql += where; // filters
+        sql = sql.substring( 0, sql.length() - 1 ) + " "; // Remove last comma
+        sql += (min != null && max != null) ? statementBuilder.limitRecord( min, max ) : "";
+
+        return sql;
+    }
+
+    private Criteria getStatisticalProgramStageCriteria( ProgramStage programStage, Collection<Integer> orgunitIds,
+        Date startDate, Date endDate, int status )
+    {
+        Criteria criteria = getCriteria( Restrictions.eq( "programStage", programStage ),
+            Restrictions.isNull( "programInstance.endDate" ) );
+        criteria.createAlias( "programInstance", "programInstance" );
+        criteria.createAlias( "programInstance.patient", "patient" );
+        criteria.createAlias( "patient.organisationUnit", "regOrgunit" );
+        criteria.add( Restrictions.in( "regOrgunit.id", orgunitIds ) );
+
+        switch ( status )
+        {
+        case ProgramStageInstance.COMPLETED_STATUS:
+            criteria.add( Restrictions.eq( "completed", true ) );
+            criteria.add( Restrictions.between( "executionDate", startDate, endDate ) );
+            break;
+        case ProgramStageInstance.VISITED_STATUS:
+            criteria.add( Restrictions.eq( "completed", false ) );
+            criteria.add( Restrictions.between( "executionDate", startDate, endDate ) );
+            break;
+        case ProgramStageInstance.FUTURE_VISIT_STATUS:
+            criteria.add( Restrictions.between( "programInstance.enrollmentDate", startDate, endDate ) );
+            criteria.add( Restrictions.isNull( "executionDate" ) );
+            criteria.add( Restrictions.ge( "dueDate", new Date() ) );
+            break;
+        case ProgramStageInstance.LATE_VISIT_STATUS:
+            criteria.add( Restrictions.between( "programInstance.enrollmentDate", startDate, endDate ) );
+            criteria.add( Restrictions.isNull( "executionDate" ) );
+            criteria.add( Restrictions.lt( "dueDate", new Date() ) );
+            break;
+        default:
+            break;
+        }
+
+        return criteria;
+    }
+
+    /**
+     * Aggregate report Position Orgunit Rows - Period Columns - Data Filter
+     * Aggregate report Position Orgunit Columns - Period Rows - Data Filter
+     * This result is not included orgunits without any data
+     * 
+     **/
+    private String getAggregateReportSQL12( ProgramStage programStage, Collection<Integer> roots, String facilityLB,
+        String filterSQL, Integer deGroupBy, Integer deSum, Collection<Period> periods, String aggregateType,
+        Integer limit, Boolean useCompletedEvents, I18nFormat format )
+    {
+        String sql = "";
+
+        // orgunit
+        for ( Integer root : roots )
+        {
+            sql += " (SELECT ";
+
+            sql += "( SELECT ou.name FROM organisationunit ou ";
+            sql += "WHERE ou.organisationunitid=" + root + " ) as orgunit, ";
+
+            Collection<Integer> allOrgunitIds = getOrganisationUnits( root, facilityLB );
+
+            // -- period
+            for ( Period period : periods )
+            {
+                String periodName = "";
+                String startDate = format.formatDate( period.getStartDate() );
+                String endDate = format.formatDate( period.getEndDate() );
+                if ( period.getPeriodType() != null )
+                {
+                    periodName = format.formatPeriod( period );
+                }
+                else
+                {
+                    periodName = startDate + " -> " + endDate;
+                }
+
+                Collection<Integer> orgunitIds = getServiceOrgunit( allOrgunitIds, period );
+
+                if ( orgunitIds.size() == 0 )
+                {
+                    sql += "(SELECT 0  ";
+                }
+                else
+                {
+                    if ( aggregateType.equals( PatientAggregateReport.AGGREGATE_TYPE_COUNT ) )
+                    {
+                        sql += "(SELECT count(DISTINCT psi_1.programstageinstanceid) ";
+                    }
+                    else
+                    {
+                        sql += "(SELECT " + aggregateType + "( cast( value as "
+                            + statementBuilder.getDoubleColumnType() + " )) ";
+                    }
+                    sql += "FROM programstageinstance psi_1 ";
+                    sql += "        JOIN patientdatavalue pdv_1 ";
+                    sql += "                ON psi_1.programstageinstanceid=pdv_1.programstageinstanceid ";
+                    sql += "WHERE ";
+                    sql += "     psi_1.organisationunitid in ( " + TextUtils.getCommaDelimitedString( orgunitIds )
+                        + " )  AND ";
+                    sql += "     psi_1.executiondate >= '" + startDate + "' AND ";
+                    sql += "     psi_1.executiondate <= '" + endDate + "' AND ";
+                    if ( deSum != null )
+                    {
+                        sql += " dataelementid=" + deSum + " AND ";
+                    }
+                    if ( useCompletedEvents != null )
+                    {
+                        sql += " AND psi_1.completed = " + useCompletedEvents + " AND ";
+                    }
+                    if ( deGroupBy != null )
+                    {
+                        sql += "(SELECT value from patientdatavalue ";
+                        sql += "WHERE programstageinstanceid=psi_1.programstageinstanceid AND ";
+                        sql += "      dataelementid=" + deGroupBy + ") is not null AND ";
+                    }
+                    sql += "     psi_1.programstageid=" + programStage.getId() + " ";
+                    sql += filterSQL + "LIMIT 1 ) ";
+                }
+
+                sql += " as \"" + periodName + "\" ,";
+            }
+            // -- end period
+
+            sql = sql.substring( 0, sql.length() - 1 ) + " ";
+            sql += " ) ) ";
+            sql += " UNION ";
+        }
+        sql = sql.substring( 0, sql.length() - 10 );
+        sql += " ORDER BY orgunit asc ";
+        if ( limit != null )
+        {
+            sql += "LIMIT " + limit;
+        }
+
+        return sql;
+    }
+
+    /**
+     * Aggregate report Position Orgunit Rows - Period Rows - Data Filter
+     * 
+     **/
+    private String getAggregateReportSQL3( int position, ProgramStage programStage, Collection<Integer> roots,
+        String facilityLB, String filterSQL, Integer deGroupBy, Integer deSum, Collection<Period> periods,
+        String aggregateType, Integer limit, Boolean useCompletedEvents, I18nFormat format )
+    {
+        String sql = "";
+
+        for ( Integer root : roots )
+        {
+            Collection<Integer> allOrgunitIds = getOrganisationUnits( root, facilityLB );
+
+            for ( Period period : periods )
+            {
+                String periodName = "";
+                String startDate = format.formatDate( period.getStartDate() );
+                String endDate = format.formatDate( period.getEndDate() );
+                if ( period.getPeriodType() != null )
+                {
+                    periodName = format.formatPeriod( period );
+                }
+                else
+                {
+                    periodName = startDate + " -> " + endDate;
+                }
+
+                sql += "( SELECT ";
+                sql += "( SELECT ou.name FROM organisationunit ou WHERE organisationunitid=" + root + " ) as orgunit, ";
+                sql += "'" + periodName + "' as period, ";
+
+                Collection<Integer> orgunitIds = getServiceOrgunit( allOrgunitIds, period );
+
+                if ( orgunitIds.size() == 0 )
+                {
+                    sql += "(SELECT 0 ";
+                }
+                else
+                {
+                    if ( aggregateType.equals( PatientAggregateReport.AGGREGATE_TYPE_COUNT ) )
+                    {
+                        sql += "(SELECT count(DISTINCT psi_1.programstageinstanceid) ";
+                    }
+                    else
+                    {
+                        sql += "(SELECT " + aggregateType + "( cast( value as DOUBLE PRECISION )) ";
+                    }
+                    sql += "FROM ";
+                    sql += "   patientdatavalue pdv_1 JOIN programstageinstance psi_1 ";
+                    sql += "        ON psi_1.programstageinstanceid=pdv_1.programstageinstanceid ";
+                    sql += "   JOIN organisationunit ou on (ou.organisationunitid=psi_1.organisationunitid ) ";
+                    sql += "WHERE ";
+                    sql += "    ou.organisationunitid in ( " + TextUtils.getCommaDelimitedString( orgunitIds )
+                        + " ) AND ";
+                    sql += "    psi_1.programstageid=" + programStage.getId() + " AND ";
+                    if ( deSum != null )
+                    {
+                        sql += " dataelementid=" + deSum + " AND ";
+                    }
+                    if ( useCompletedEvents != null )
+                    {
+                        sql += " psi_1.completed = " + useCompletedEvents + " AND ";
+                    }
+                    if ( deGroupBy != null )
+                    {
+                        sql += "(SELECT value from patientdatavalue ";
+                        sql += "WHERE programstageinstanceid=psi_1.programstageinstanceid AND ";
+                        sql += "      dataelementid=" + deGroupBy + ") is not null AND ";
+                    }
+                    sql += "     psi_1.executiondate >= '" + startDate + "' AND ";
+                    sql += "     psi_1.executiondate <= '" + endDate + "' ";
+                    sql += filterSQL + " LIMIT 1 ) ";
+                }
+
+                sql += " as " + aggregateType;
+                sql += "  ) ";
+                sql += " UNION ";
+            }
+        }
+
+        sql = sql.substring( 0, sql.length() - 6 ) + " ) ";
+       
+        sql += " ORDER BY orgunit asc ";
+        if ( limit != null )
+        {
+            sql += "LIMIT " + limit;
+        }
+        
+        return sql;
+    }
+
+    /**
+     * Aggregate report Orgunit Filter - Period Rows - Data Filter
+     * 
+     **/
+    private String getAggregateReportSQL4( int position, ProgramStage programStage, Collection<Integer> roots,
+        String facilityLB, String filterSQL, Integer deGroupBy, Integer deSum, Collection<Period> periods,
+        String aggregateType, Integer limit, Boolean useCompletedEvents, I18nFormat format )
+    {
+        String sql = "";
+
+        for ( Integer root : roots )
+        {
+            Collection<Integer> allOrgunitIds = getOrganisationUnits( root, facilityLB );
+
+            for ( Period period : periods )
+            {
+                String periodName = "";
+                String startDate = format.formatDate( period.getStartDate() );
+                String endDate = format.formatDate( period.getEndDate() );
+                if ( period.getPeriodType() != null )
+                {
+                    periodName = format.formatPeriod( period );
+                }
+                else
+                {
+                    periodName = startDate + " -> " + endDate;
+                }
+
+                sql += "( SELECT ";
+                sql += "'" + periodName + "' as period, ";
+
+                Collection<Integer> orgunitIds = getServiceOrgunit( allOrgunitIds, period );
+                if ( orgunitIds.size() == 0 )
+                {
+                    sql += "(SELECT 0 ";
+                }
+                else
+                {
+                    if ( aggregateType.equals( PatientAggregateReport.AGGREGATE_TYPE_COUNT ) )
+                    {
+                        sql += "(SELECT count(DISTINCT psi_1.programstageinstanceid) ";
+                    }
+                    else
+                    {
+                        sql += "(SELECT " + aggregateType + "( cast( value as DOUBLE PRECISION )) ";
+                    }
+                    sql += "FROM ";
+                    sql += "   patientdatavalue pdv_1 JOIN programstageinstance psi_1 ";
+                    sql += "        ON psi_1.programstageinstanceid=pdv_1.programstageinstanceid ";
+                    sql += "   JOIN organisationunit ou on (ou.organisationunitid=psi_1.organisationunitid ) ";
+                    sql += "WHERE ";
+                    sql += "    ou.organisationunitid in ( " + TextUtils.getCommaDelimitedString( orgunitIds )
+                        + " ) AND ";
+                    sql += "    psi_1.programstageid=" + programStage.getId() + " AND ";
+                    if ( deSum != null )
+                    {
+                        sql += " dataelementid=" + deSum + " AND ";
+                    }
+                    if ( useCompletedEvents != null )
+                    {
+                        sql += " psi_1.completed = " + useCompletedEvents + " AND ";
+                    }
+                    if ( deGroupBy != null )
+                    {
+                        sql += "(SELECT value from patientdatavalue ";
+                        sql += "WHERE programstageinstanceid=psi_1.programstageinstanceid AND ";
+                        sql += "      dataelementid=" + deGroupBy + ") is not null AND ";
+                    }
+                    sql += "     psi_1.executiondate >= '" + startDate + "' AND ";
+                    sql += "     psi_1.executiondate <= '" + endDate + "' ";
+                    sql += filterSQL + " LIMIT 1 ";
+                }
+
+                sql += " ) as " + aggregateType;
+                sql += ") ";
+                sql += " UNION ALL ";
+
+            }
+        }
+
+        sql = sql.substring( 0, sql.length() - 10 );
+        
+        if( periods.size() > 1 )
+        
+        if ( limit != null )
+        {
+            sql += " LIMIT " + limit;
+        }
+
+        return sql;
+    }
+
+    /**
+     * Aggregate report Position Orgunit Rows -Period Filter - Data Filter
+     * 
+     **/
+    private String getAggregateReportSQL5( int position, ProgramStage programStage, Collection<Integer> roots,
+        String facilityLB, String filterSQL, Integer deGroupBy, Integer deSum, Period period, String aggregateType,
+        Integer limit, Boolean useCompletedEvents, I18nFormat format )
+    {
+        String sql = "";
+
+        for ( Integer root : roots )
+        {
+            Collection<Integer> allOrgunitIds = getOrganisationUnits( root, facilityLB );
+
+            sql += "( SELECT  ";
+            sql += "( SELECT ou.name  ";
+            sql += "FROM organisationunit ou  ";
+            sql += "WHERE ou.organisationunitid=" + root + " ) as orgunit, ";
+
+            Collection<Integer> orgunitIds = getServiceOrgunit( allOrgunitIds, period );
+            if ( orgunitIds.size() == 0 )
+            {
+                sql += "(SELECT 0 ";
+            }
+            else
+            {
+                if ( aggregateType.equals( PatientAggregateReport.AGGREGATE_TYPE_COUNT ) )
+                {
+                    sql += "(SELECT count(DISTINCT psi_1.programstageinstanceid) ";
+                }
+                else
+                {
+                    sql += "(SELECT " + aggregateType + "( cast( value as DOUBLE PRECISION )) ";
+                }
+                sql += "FROM ";
+                sql += "    patientdatavalue pdv_1 RIGHT JOIN programstageinstance psi_1 ";
+                sql += "            ON psi_1.programstageinstanceid=pdv_1.programstageinstanceid ";
+                sql += "WHERE ";
+                sql += "    psi_1.organisationunitid in ( " + TextUtils.getCommaDelimitedString( orgunitIds )
+                    + " ) AND ";
+                sql += "    psi_1.programstageid=" + programStage.getId() + " AND ";
+                sql += "    psi_1.executiondate >= '" + format.formatDate( period.getStartDate() ) + "' AND ";
+                sql += "    psi_1.executiondate <= '" + format.formatDate( period.getEndDate() ) + "' ";
+                sql += filterSQL + " ";
+                if ( deGroupBy != null )
+                {
+                    sql += " AND (SELECT value from patientdatavalue ";
+                    sql += "WHERE programstageinstanceid=psi_1.programstageinstanceid AND ";
+                    sql += "      dataelementid=" + deGroupBy + ") is not null ";
+                }
+                if ( useCompletedEvents != null )
+                {
+                    sql += " AND psi_1.completed = " + useCompletedEvents + " ";
+                }
+                if ( deSum != null )
+                {
+                    sql += " AND dataelementid=" + deSum + "  LIMIT 1 ";
+                }
+            }
+
+            sql += " ) as " + aggregateType + "  ) ";
+            sql += " UNION ";
+
+        }
+
+        sql = sql.substring( 0, sql.length() - 6 ) + " ";
+        sql += " ORDER BY orgunit asc ";
+        if ( limit != null )
+        {
+            sql += " LIMIT " + limit;
+        }
+
+        return sql;
+    }
+
+    /**
+     * Aggregate report Position Orgunit Filter - Period Rows - Data Columns
+     * with group-by
+     **/
+    private String getAggregateReportSQL6( ProgramStage programStage, Integer root, String facilityLB,
+        String filterSQL, Integer deGroupBy, Integer deSum, Collection<Period> periods, String aggregateType,
+        Integer limit, Boolean useCompletedEvents, I18nFormat format )
+    {
+        String sql = "";
+        Collection<Integer> allOrgunitIds = getOrganisationUnits( root, facilityLB );
+
+        String dataValueSql = "SELECT DISTINCT(pdv.value) ";
+        dataValueSql += "FROM patientdatavalue pdv JOIN programstageinstance psi";
+        dataValueSql += "       ON pdv.programstageinstanceid=psi.programstageinstanceid ";
+        dataValueSql += "WHERE pdv.dataelementid=" + deGroupBy + " AND ";
+        dataValueSql += "       psi.organisationunitid in ( " + TextUtils.getCommaDelimitedString( allOrgunitIds )
+            + " ) AND ";
+        dataValueSql += "       psi.programstageid=" + programStage.getId() + " AND ( ";
+        for ( Period period : periods )
+        {
+            dataValueSql += " ( psi.executiondate >= '" + format.formatDate( period.getStartDate() ) + "' AND ";
+            dataValueSql += "   psi.executiondate <= '" + format.formatDate( period.getEndDate() ) + "') OR ";
+        }
+        dataValueSql = dataValueSql.substring( 0, dataValueSql.length() - 3 );
+        dataValueSql += ") ORDER BY value asc";
+
+        Collection<String> deValues = new HashSet<String>();
+        try
+        {
+            deValues = jdbcTemplate.query( dataValueSql, new RowMapper<String>()
+            {
+                public String mapRow( ResultSet rs, int rowNum )
+                    throws SQLException
+                {
+                    return rs.getString( 1 );
+                }
+            } );
+        }
+        catch ( Exception ex )
+        {
+            ex.printStackTrace();
+        }
+
+        if ( deValues.size() > 0 )
+        {
+            for ( Period period : periods )
+            {
+                String periodName = "";
+                String startDate = format.formatDate( period.getStartDate() );
+                String endDate = format.formatDate( period.getEndDate() );
+                if ( period.getPeriodType() != null )
+                {
+                    periodName = format.formatPeriod( period );
+                }
+                else
+                {
+                    periodName = startDate + " -> " + endDate;
+                }
+
+                sql += "(SELECT DISTINCT '" + periodName + "' as period, ";
+
+                Collection<Integer> orgunitIds = getServiceOrgunit( allOrgunitIds, period );
+                if ( orgunitIds.size() == 0 )
+                {
+                    for ( String deValue : deValues )
+                    {
+                        sql += "(SELECT 0 as \"" + deValue + "\",";
+                    }
+                }
+                else
+                {
+                    for ( String deValue : deValues )
+                    {
+                        if ( aggregateType.equals( PatientAggregateReport.AGGREGATE_TYPE_COUNT ) )
+                        {
+                            sql += "(SELECT count(DISTINCT psi_1.programstageinstanceid) ";
+                        }
+                        else
+                        {
+                            sql += "(SELECT " + aggregateType + "( cast( value as DOUBLE PRECISION )) ";
+                        }
+                        sql += "FROM programstageinstance psi_1 JOIN patientdatavalue pdv_1 ";
+                        sql += "    on psi_1.programstageinstanceid = pdv_1.programstageinstanceid ";
+                        sql += "WHERE ";
+                        sql += "    psi_1.organisationunitid in ( " + TextUtils.getCommaDelimitedString( orgunitIds )
+                            + "     ) AND ";
+                        sql += "    psi_1.executiondate >= '" + startDate + "' AND ";
+                        sql += "    psi_1.executiondate <= '" + endDate + "' ";
+                        sql += filterSQL + " AND ";
+                        sql += "        (SELECT value from patientdatavalue ";
+                        sql += "        WHERE programstageinstanceid=psi_1.programstageinstanceid AND ";
+                        sql += "              dataelementid=" + deGroupBy + ") = '" + deValue + "' ";
+                        sql += "        LIMIT 1 ) as \"" + deValue + "\",";
+                    }
+                    sql = sql.substring( 0, sql.length() - 1 ) + " ";
+
+                    sql += "FROM  programstageinstance psi JOIN patientdatavalue pdv ";
+                    sql += "    on psi.programstageinstanceid = pdv.programstageinstanceid ";
+                    sql += "WHERE ";
+                    sql += "    psi.programstageid=" + programStage.getId() + " ";
+                    if ( deSum != null )
+                    {
+                        sql += " AND dataelementid=" + deSum + "  ";
+                    }
+                    if ( useCompletedEvents != null )
+                    {
+                        sql += " AND psi.completed = " + useCompletedEvents + " ";
+                    }
+                    sql += "GROUP BY dataelementid ";
+                }
+
+                sql += ") UNION ALL ";
+
+            }
+
+            sql = sql.substring( 0, sql.length() - 10 );
+
+            if ( limit != null )
+            {
+                sql += " LIMIT " + limit;
+            }
+
+        }
+
+        return sql;
+    }
+
+    /**
+     * Aggregate report Position Orgunit Filter - Period Rows - Data Columns
+     * without group-by
+     **/
+    private String getAggregateReportSQL6WithoutGroup( ProgramStage programStage, Integer root, String facilityLB,
+        String filterSQL, Integer deSum, Collection<Period> periods, String aggregateType, Integer limit,
+        Boolean useCompletedEvents, I18nFormat format )
+    {
+        String sql = "";
+
+        Collection<Integer> allOrgunitIds = getOrganisationUnits( root, facilityLB );
+
+        for ( Period period : periods )
+        {
+            String periodName = "";
+            String startDate = format.formatDate( period.getStartDate() );
+            String endDate = format.formatDate( period.getEndDate() );
+            if ( period.getPeriodType() != null )
+            {
+                periodName = format.formatPeriod( period );
+            }
+            else
+            {
+                periodName = startDate + " -> " + endDate;
+            }
+
+            sql += "(SELECT DISTINCT '" + periodName + "' as period, ";
+
+            Collection<Integer> orgunitIds = getServiceOrgunit( allOrgunitIds, period );
+            if ( orgunitIds.size() == 0 )
+            {
+                sql += "(SELECT 0 ";
+            }
+            else
+            {
+                if ( aggregateType.equals( PatientAggregateReport.AGGREGATE_TYPE_COUNT ) )
+                {
+                    sql += "(SELECT count(DISTINCT psi_1.programstageinstanceid) ";
+                }
+                else
+                {
+                    sql += "(SELECT " + aggregateType + "( cast( value as DOUBLE PRECISION )) ";
+                }
+                sql += "FROM programstageinstance psi_1 JOIN patientdatavalue pdv_1 ";
+                sql += "    on psi_1.programstageinstanceid = pdv_1.programstageinstanceid ";
+                sql += "WHERE ";
+                sql += "    psi_1.organisationunitid in ( " + TextUtils.getCommaDelimitedString( orgunitIds )
+                    + "     ) AND ";
+                sql += "    psi_1.executiondate >= '" + startDate + "' AND ";
+                sql += "    psi_1.executiondate <= '" + endDate + "' AND ";
+                sql += "    psi_1.programstageid=" + programStage.getId() + " ";
+                sql += filterSQL + "  LIMIT 1 ) as \"" + aggregateType + "\",";
+
+                sql = sql.substring( 0, sql.length() - 1 ) + " ";
+
+                sql += "FROM  programstageinstance psi JOIN patientdatavalue pdv ";
+                sql += "    on psi.programstageinstanceid = pdv.programstageinstanceid ";
+                sql += "WHERE ";
+                sql += "    psi.programstageid=" + programStage.getId() + " ";
+                if ( deSum != null )
+                {
+                    sql += " AND dataelementid=" + deSum + "  ";
+                }
+                if ( useCompletedEvents != null )
+                {
+                    sql += " AND psi.completed = " + useCompletedEvents + " ";
+                }
+                sql += "GROUP BY dataelementid ";
+            }
+
+            sql += ") UNION ALL ";
+        }
+
+        sql = sql.substring( 0, sql.length() - 10 );
+        if ( limit != null )
+        {
+            sql += " LIMIT " + limit;
+        }
+
+        return sql;
+    }
+
+    /**
+     * Aggregate report Position Orgunit Rows - Period Filter - Data Columns
+     * 
+     **/
+    private String getAggregateReportSQL7( ProgramStage programStage, Collection<Integer> roots, String facilityLB,
+        String filterSQL, Integer deGroupBy, Integer deSum, Period period, String aggregateType, Integer limit,
+        Boolean useCompletedEvents, I18nFormat format )
+    {
+        String sql = "";
+
+        Collection<Integer> allOrgunitIds = new HashSet<Integer>();
+
+        for ( Integer root : roots )
+        {
+            allOrgunitIds.addAll( getOrganisationUnits( root, facilityLB ) );
+        }
+
+        if ( allOrgunitIds.size() > 0 )
+        {
+            String dataValueSql = "SELECT DISTINCT(pdv.value) ";
+            dataValueSql += "FROM patientdatavalue pdv JOIN programstageinstance psi";
+            dataValueSql += "       ON pdv.programstageinstanceid=psi.programstageinstanceid ";
+            dataValueSql += "WHERE pdv.dataelementid=" + deGroupBy + " AND ";
+            dataValueSql += "       psi.organisationunitid in ( " + TextUtils.getCommaDelimitedString( allOrgunitIds )
+                + " ) AND ";
+            dataValueSql += "       psi.programstageid=" + programStage.getId() + " AND ( ";
+
+            dataValueSql += " ( psi.executiondate >= '" + format.formatDate( period.getStartDate() ) + "' AND ";
+            dataValueSql += "   psi.executiondate <= '" + format.formatDate( period.getEndDate() ) + "') OR ";
+
+            dataValueSql = dataValueSql.substring( 0, dataValueSql.length() - 3 );
+            dataValueSql += ") ORDER BY value asc";
+
+            Collection<String> deValues = new HashSet<String>();
+            try
+            {
+                deValues = jdbcTemplate.query( dataValueSql, new RowMapper<String>()
+                {
+                    public String mapRow( ResultSet rs, int rowNum )
+                        throws SQLException
+                    {
+                        return rs.getString( 1 );
+                    }
+                } );
+            }
+            catch ( Exception ex )
+            {
+                ex.printStackTrace();
+            }
+
+            if ( deValues.size() > 0 )
+            {
+                for ( Integer root : roots )
+                {
+                    allOrgunitIds = getOrganisationUnits( root, facilityLB );
+                    Collection<Integer> orgunitIds = getServiceOrgunit( allOrgunitIds, period );
+
+                    sql += "(SELECT ";
+                    sql += "( SELECT ou.name FROM organisationunit ou WHERE ou.organisationunitid=" + root
+                        + " ) as orgunit, ";
+                    for ( String deValue : deValues )
+                    {
+                        if ( aggregateType.equals( PatientAggregateReport.AGGREGATE_TYPE_COUNT ) )
+                        {
+                            sql += "(SELECT count(DISTINCT psi_1.programstageinstanceid) ";
+                        }
+                        else
+                        {
+                            sql += "(SELECT " + aggregateType + "( cast( value as DOUBLE PRECISION )) ";
+                        }
+                        sql += "FROM patientdatavalue pdv_1 ";
+                        sql += "        inner join programstageinstance psi_1 ";
+                        sql += "          on psi_1.programstageinstanceid = pdv_1.programstageinstanceid ";
+                        sql += "WHERE ";
+                        sql += "        psi_1.executiondate >= '" + format.formatDate( period.getStartDate() )
+                            + "' AND ";
+                        sql += "        psi_1.executiondate <= '" + format.formatDate( period.getEndDate() ) + "' AND ";
+                        sql += "        psi_1.organisationunitid in (" + TextUtils.getCommaDelimitedString( orgunitIds )
+                            + ") AND ";
+                        if ( deSum != null )
+                        {
+                            sql += " dataelementid=" + deSum + " AND ";
+                        }
+                        if ( useCompletedEvents != null )
+                        {
+                            sql += " psi_1.completed = " + useCompletedEvents + " AND ";
+                        }
+                        sql += "        psi_1.programstageid=" + programStage.getId() + " ";
+                        sql += filterSQL + " AND ";
+                        sql += "   (SELECT value FROM patientdatavalue  ";
+                        sql += "   WHERE programstageinstanceid=psi_1.programstageinstanceid AND ";
+                        sql += "     dataelementid= pdv_1.dataelementid AND ";
+                        sql += "     dataelementid=" + deGroupBy + "  ) = '" + deValue + "' ";
+                        sql += "   LIMIT 1 ) as \"" + deValue + "\",";
+                    }
+
+                    sql = sql.substring( 0, sql.length() - 1 ) + " ) ";
+                    sql += " UNION ";
+                }
+
+                sql = sql.substring( 0, sql.length() - 6 );
+                if ( limit != null )
+                {
+                    sql += " LIMIT " + limit;
+                }
+            }
+        }
+
+        return sql;
+    }
+
+    /**
+     * Aggregate report Position Orgunit Rows - Period Filter - Data Columns
+     * 
+     **/
+    private String getAggregateReportSQL7WithoutGroup( ProgramStage programStage, Collection<Integer> roots,
+        String facilityLB, String filterSQL, Integer deSum, Period period, String aggregateType, Integer limit,
+        Boolean useCompletedEvents, I18nFormat format )
+    {
+
+        String sql = "";
+
+        for ( Integer root : roots )
+        {
+            Collection<Integer> allOrgunitIds = getOrganisationUnits( root, facilityLB );
+            Collection<Integer> orgunitIds = getServiceOrgunit( allOrgunitIds, period );
+
+            if ( orgunitIds.size() > 0 )
+            {
+                sql += "(SELECT ";
+                sql += "( SELECT ou.name FROM organisationunit ou WHERE ou.organisationunitid=" + root
+                    + " ) as orgunit, ";
+
+                if ( aggregateType.equals( PatientAggregateReport.AGGREGATE_TYPE_COUNT ) )
+                {
+                    sql += "(SELECT count(DISTINCT psi_1.programstageinstanceid) ";
+                }
+                else
+                {
+                    sql += "(SELECT " + aggregateType + "( cast( value as DOUBLE PRECISION )) ";
+                }
+
+                sql += "FROM patientdatavalue pdv_1 ";
+                sql += "        inner join programstageinstance psi_1 ";
+                sql += "          on psi_1.programstageinstanceid = pdv_1.programstageinstanceid ";
+                sql += "WHERE ";
+                sql += "        psi_1.executiondate >= '" + format.formatDate( period.getStartDate() ) + "' AND ";
+                sql += "        psi_1.executiondate <= '" + format.formatDate( period.getEndDate() ) + "' AND ";
+                if ( deSum != null )
+                {
+                    sql += " dataelementid=" + deSum + " AND ";
+                }
+                if ( useCompletedEvents != null )
+                {
+                    sql += " psi_1.completed = " + useCompletedEvents + " AND ";
+                }
+                sql += "        psi_1.organisationunitid in (" + TextUtils.getCommaDelimitedString( orgunitIds )
+                    + ") AND ";
+                sql += "        psi_1.programstageid=" + programStage.getId() + " ";
+                sql += filterSQL + " LIMIT 1 ) as \"" + aggregateType + "\" ) ";
+
+                sql += " UNION ";
+            }
+        }
+
+        if ( !sql.isEmpty() )
+        {
+            sql = sql.substring( 0, sql.length() - 6 );
+            if ( limit != null )
+            {
+                sql += " LIMIT " + limit;
+            }
+        }
+
+        return sql;
+    }
+
+    /**
+     * Aggregate report Position Data Rows
+     * 
+     **/
+    private String getAggregateReportSQL8( ProgramStage programStage, Collection<Integer> roots, String facilityLB,
+        String filterSQL, Integer deGroupBy, Period period, String aggregateType, Integer limit,
+        Boolean useCompletedEvents, I18nFormat format )
+    {
+        String sql = "";
+        for ( Integer root : roots )
+        {
+            Collection<Integer> allOrgunitIds = getOrganisationUnits( root, facilityLB );
+            Collection<Integer> orgunitIds = getServiceOrgunit( allOrgunitIds, period );
+
+            if ( orgunitIds.size() > 0 )
+            {
+                sql += "(SELECT pdv_1.value, " + aggregateType + "(pdv_1.value) as \"" + aggregateType + "\" ";
+                sql += "FROM patientdatavalue pdv_1 ";
+                sql += "    JOIN programstageinstance psi_1 ";
+                sql += "            ON psi_1.programstageinstanceid = pdv_1.programstageinstanceid ";
+                sql += "WHERE ";
+                sql += " psi_1.programstageid=" + programStage.getId() + " AND ";
+                if ( useCompletedEvents != null )
+                {
+                    sql += " psi_1.completed = " + useCompletedEvents + " AND ";
+                }
+                sql += "    psi_1.executiondate >= '" + format.formatDate( period.getStartDate() ) + "' AND ";
+                sql += "    psi_1.executiondate <= '" + format.formatDate( period.getEndDate() ) + "' AND ";
+                sql += "    psi_1.organisationunitid in( " + TextUtils.getCommaDelimitedString( orgunitIds ) + " )  ";
+                if ( deGroupBy != null )
+                {
+                    sql += " AND pdv_1.dataelementid=" + deGroupBy + " ";
+                }
+                sql += filterSQL + " ";
+                sql += "GROUP BY pdv_1.value )";
+                sql += " UNION ";
+            }
+        }
+
+        if ( !sql.isEmpty() )
+        {
+            sql = sql.substring( 0, sql.length() - 6 ) + " ";
+            sql += "ORDER BY  \"" + aggregateType + "\" desc ";
+            if ( limit != null )
+            {
+                sql += " LIMIT " + limit;
+            }
+        }
+
+        return sql;
+    }
+
+    /**
+     * Aggregate report Position Orgunit Filter - Period Columns - Data Rows
+     * with group-by
+     **/
+    private String getAggregateReportSQL9( ProgramStage programStage, Integer root, String facilityLB,
+        String filterSQL, Integer deGroupBy, Integer deSum, Collection<Period> periods, String aggregateType,
+        Integer limit, Boolean useCompletedEvents, Boolean useFormNameDataElement,I18nFormat format )
+    {
+        String sql = "";
+        Collection<Integer> allOrgunitIds = getOrganisationUnits( root, facilityLB );
+
+        String dataValueSql = "SELECT DISTINCT(pdv.value) ";
+        dataValueSql += "FROM patientdatavalue pdv JOIN programstageinstance psi";
+        dataValueSql += "         ON pdv.programstageinstanceid=psi.programstageinstanceid ";
+        dataValueSql += "WHERE pdv.dataelementid=" + deGroupBy + " AND ";
+        dataValueSql += "       psi.organisationunitid in ( " + TextUtils.getCommaDelimitedString( allOrgunitIds )
+            + " ) AND ";
+        dataValueSql += "      psi.programstageid=" + programStage.getId() + " AND ( ";
+        for ( Period period : periods )
+        {
+            dataValueSql += " ( psi.executiondate >= '" + format.formatDate( period.getStartDate() ) + "' AND ";
+            dataValueSql += "   psi.executiondate <= '" + format.formatDate( period.getEndDate() ) + "') OR ";
+        }
+        dataValueSql = dataValueSql.substring( 0, dataValueSql.length() - 3 );
+        dataValueSql += ") ORDER BY value asc";
+
+        Collection<String> deValues = new HashSet<String>();
+        try
+        {
+            deValues = jdbcTemplate.query( dataValueSql, new RowMapper<String>()
+            {
+                public String mapRow( ResultSet rs, int rowNum )
+                    throws SQLException
+                {
+                    return rs.getString( 1 );
+                }
+            } );
+        }
+        catch ( Exception ex )
+        {
+            ex.printStackTrace();
+        }
+
+        String firstPeriodName = "";
+
+        DataElement dataElement = dataElementService.getDataElement( deGroupBy );
+        String groupByName = dataElement.getDisplayName();
+        if ( useFormNameDataElement != null || useFormNameDataElement )
+        {
+            groupByName = dataElement.getFormNameFallback();
+        }
+        
+        for ( String deValue : deValues )
+        {
+            sql += "(SELECT DISTINCT '" + deValue + "' as \"" + groupByName + "\", ";
+
+            for ( Period period : periods )
+            {
+                String periodName = "";
+                String startDate = format.formatDate( period.getStartDate() );
+                String endDate = format.formatDate( period.getEndDate() );
+                if ( period.getPeriodType() != null )
+                {
+                    periodName = format.formatPeriod( period );
+                }
+                else
+                {
+                    periodName = startDate + " -> " + endDate;
+                }
+
+                if ( firstPeriodName.isEmpty() )
+                {
+                    firstPeriodName = periodName;
+                }
+
+                Collection<Integer> orgunitIds = getServiceOrgunit( allOrgunitIds, period );
+                if ( orgunitIds.size() == 0 )
+                {
+                    sql += "(SELECT \'0\' ";
+                }
+                else
+                {
+                    if ( aggregateType.equals( PatientAggregateReport.AGGREGATE_TYPE_COUNT ) )
+                    {
+                        sql += "(SELECT count(DISTINCT psi_1.programstageinstanceid) ";
+                    }
+                    else
+                    {
+                        sql += "(SELECT " + aggregateType + "( cast( value as DOUBLE PRECISION )) ";
+                    }
+
+                    sql += "FROM programstageinstance psi_1 JOIN patientdatavalue pdv_1 ";
+                    sql += "    on psi_1.programstageinstanceid = pdv_1.programstageinstanceid ";
+                    sql += "WHERE ";
+                    sql += "    psi_1.organisationunitid in ( " + TextUtils.getCommaDelimitedString( orgunitIds )
+                        + "     ) AND ";
+                    sql += "    psi_1.executiondate >= '" + startDate + "' AND ";
+                    sql += "    psi_1.executiondate <= '" + endDate + "' ";
+                    sql += filterSQL + " AND ";
+                    sql += "        (SELECT value from patientdatavalue ";
+                    sql += "        WHERE programstageinstanceid=psi_1.programstageinstanceid AND ";
+                    sql += "              dataelementid=" + deGroupBy + ") = '" + deValue + "' ";
+                    if ( deSum != null )
+                    {
+                        sql += " AND dataelementid=" + deSum + " ";
+                    }
+                    if ( useCompletedEvents != null )
+                    {
+                        sql += " AND psi_1.completed = " + useCompletedEvents + " ";
+                    }
+
+                }
+                sql += ") as \"" + periodName + "\",";
+            }
+            sql = sql.substring( 0, sql.length() - 1 );
+            sql += " ) UNION ALL ";
+        }
+
+        if ( !sql.isEmpty() )
+        {
+            sql = sql.substring( 0, sql.length() - 10 );
+            if ( periods.size() == 1 )
+            {
+                sql += "ORDER BY  \"" + firstPeriodName + "\" desc ";
+            }
+
+            if ( limit != null )
+            {
+                sql += " LIMIT " + limit;
+            }
+        }
+
+        return sql;
+    }
+
+    private String filterSQLStatement( Map<Integer, Collection<String>> deFilters )
+    {
+        String filter = "";
+        if ( deFilters != null )
+        {
+            // Get filter criteria
+            Iterator<Integer> iterFilter = deFilters.keySet().iterator();
+            while ( iterFilter.hasNext() )
+            {
+                Integer id = iterFilter.next();
+                for ( String filterValue : deFilters.get( id ) )
+                {
+                    DataElement dataElement = dataElementService.getDataElement( id );
+                    int index = filterValue.indexOf( PatientAggregateReport.SEPARATE_FILTER );
+                    String operator = (filterValue.substring( 0, index ));
+                    String value = filterValue.substring( index + 1, filterValue.length() );
+                    filter += "AND (SELECT ";
+                    if ( dataElement.getType().equals( DataElement.VALUE_TYPE_INT ) )
+                    {
+                        filter += "cast(value as " + statementBuilder.getDoubleColumnType() + ") ";
+
+                    }
+                    else
+                    {
+                        filter += " value ";
+                    }
+                    filter += "FROM patientdatavalue ";
+                    filter += "WHERE programstageinstanceid=psi_1.programstageinstanceid AND ";
+                    filter += "dataelementid=" + id + "  ";
+                    filter += ") " + operator + " " + value + " ";
+                }
+            }
+        }
+
+        return filter;
+    }
+
+    private String getFilterOrgunitDescription( Collection<Integer> orgunitIds )
+    {
+        String description = "";
+        for ( Integer orgunit : orgunitIds )
+        {
+            description += organisationUnitService.getOrganisationUnit( orgunit ).getDisplayName() + " AND ";
+        }
+
+        return description.substring( 0, description.length() - 5 );
+    }
+
+    private String getFilterPeriodDescription( Collection<Period> periods, I18nFormat format )
+    {
+        String description = "";
+        for ( Period period : periods )
+        {
+            String startDate = format.formatDate( period.getStartDate() );
+            String endDate = format.formatDate( period.getEndDate() );
+            if ( period.getPeriodType() != null )
+            {
+                description += format.formatPeriod( period );
+            }
+            else
+            {
+                description += startDate + " -> " + endDate;
+            }
+            description += " AND ";
+        }
+
+        return description.substring( 0, description.length() - 5 );
+    }
+
+    private String getFilterDataDescription( Map<Integer, Collection<String>> deFilters )
+    {
+        String description = "";
+
+        if ( deFilters != null )
+        {
+            // Get filter criteria
+            Iterator<Integer> iterFilter = deFilters.keySet().iterator();
+            while ( iterFilter.hasNext() )
+            {
+                Integer id = iterFilter.next();
+                String deName = dataElementService.getDataElement( id ).getDisplayName();
+                for ( String filterValue : deFilters.get( id ) )
+                {
+                    int index = filterValue.indexOf( PatientAggregateReport.SEPARATE_FILTER );
+                    String operator = (filterValue.substring( 0, index ));
+                    String value = filterValue.substring( index + 1, filterValue.length() );
+
+                    description += deName + " " + operator + " " + value + " AND ";
+                }
+            }
+            description = description.substring( 0, description.length() - 5 );
+        }
+
+        return description;
+    }
+
+    public int averageNumberCompleted( Program program, Collection<Integer> orgunitIds, Date startDate, Date endDate,
+        Integer status )
+    {
+        Collection<ProgramInstance> programInstances = programInstanceService.getProgramInstancesByStatus(
+            ProgramInstance.STATUS_COMPLETED, program, orgunitIds, startDate, endDate );
+        Criteria criteria = getCriteria();
+        criteria.createAlias( "programInstance", "programInstance" );
+        criteria.createAlias( "programStage", "programStage" );
+        criteria.createAlias( "programInstance.patient", "patient" );
+        criteria.add( Restrictions.eq( "programInstance.program", program ) );
+        criteria.add( Restrictions.eq( "programInstance.status", status ) );
+        criteria.add( Restrictions.in( "organisationUnit.id", orgunitIds ) );
+        criteria.add( Restrictions.between( "programInstance.endDate", startDate, endDate ) );
+        criteria.add( Restrictions.eq( "completed", true ) );
+        if ( programInstances != null && programInstances.size() > 0 )
+        {
+            criteria.add( Restrictions.not( Restrictions.in( "programInstance", programInstances ) ) );
+        }
+
+        Number rs = (Number) criteria.setProjection( Projections.rowCount() ).uniqueResult();
+        return rs != null ? rs.intValue() : 0;
+    }
+
+    @SuppressWarnings( "unchecked" )
+    public Collection<Integer> getOrgunitIds( Date startDate, Date endDate )
+    {
+        Criteria criteria = getCriteria();
+        criteria.add( Restrictions.between( "executionDate", startDate, endDate ) );
+        criteria.createAlias( "organisationUnit", "orgunit" );
+        criteria.setProjection( Projections.distinct( Projections.projectionList().add(
+            Projections.property( "orgunit.id" ), "orgunitid" ) ) );
+        return criteria.list();
+    }
+
+    // ---------------------------------------------------------------------
+    // Get orgunitIds
+    // ---------------------------------------------------------------------
+
+    private Collection<Integer> getOrganisationUnits( Integer root, String facilityLB )
+    {
+        Set<Integer> orgunitIds = new HashSet<Integer>();
+
+        if ( facilityLB.equals( "selected" ) )
+        {
+            orgunitIds.add( root );
+        }
+        else if ( facilityLB.equals( "childrenOnly" ) )
+        {
+            orgunitIds.addAll( organisationUnitService.getOrganisationUnitHierarchy().getChildren( root ) );
+            orgunitIds.remove( root );
+        }
+        else
+        {
+            orgunitIds.addAll( organisationUnitService.getOrganisationUnitHierarchy().getChildren( root ) );
+        }
+
+        return orgunitIds;
+    }
+
+    /**
+     * Return the Ids of organisation units which events happened.
+     * 
+     */
+    private Collection<Integer> getServiceOrgunit( Collection<Integer> orgunitIds, Period period )
+    {
+        String sql = "select distinct organisationunitid from programstageinstance where executiondate>= '"
+            + DateUtils.getMediumDateString( period.getStartDate() ) + "' and executiondate<='"
+            + DateUtils.getMediumDateString( period.getEndDate() ) + "' and organisationunitid in ( "
+            + TextUtils.getCommaDelimitedString( orgunitIds ) + " )";
+
+        Collection<Integer> result = new HashSet<Integer>();
+        result = jdbcTemplate.query( sql, new RowMapper<Integer>()
+        {
+            public Integer mapRow( ResultSet rs, int rowNum )
+                throws SQLException
+            {
+                return rs.getInt( 1 );
+            }
+        } );
+
+        return result;
+    }
+
+    private void fillDataInGrid( Grid grid, SqlRowSet rs, Boolean displayTotals, I18n i18n, I18nFormat format )
+    {
+        int cols = rs.getMetaData().getColumnCount();
+        int dataCols = 0;
+
+        // Create column with Total column
+        for ( int i = 1; i <= cols; i++ )
+        {
+            grid.addHeader( new GridHeader( i18n.getString( rs.getMetaData().getColumnLabel( i ) ), false, false ) );
+            if ( rs.getMetaData().getColumnType( i ) != Types.VARCHAR )
+            {
+                dataCols++;
+            }
+        }
+
+        // Add total column if the number of columns is greater then 1
+        if ( displayTotals && dataCols > 1 )
+        {
+            grid.addHeader( new GridHeader( i18n.getString( "total" ), false, false ) );
+        }
+
+        double[] sumRow = new double[rs.getMetaData().getColumnCount() + 1];
+        while ( rs.next() )
+        {
+            grid.addRow();
+
+            double total = 0;
+            for ( int i = 1; i <= cols; i++ )
+            {
+                // meta column
+                if ( rs.getMetaData().getColumnType( i ) == Types.VARCHAR 
+                    || rs.getMetaData().getColumnType( i ) == Types.OTHER )
+                {
+                    grid.addValue( rs.getObject( i ) );
+                }
+                // values
+                else
+                {
+                    double value = rs.getDouble( i );
+                    sumRow[i] += value;
+                    total += value;
+                    grid.addValue( format.formatValue( value ) );
+                }
+            }
+
+            // total
+            if ( displayTotals && dataCols > 1 )
+            {
+                grid.addValue( format.formatValue( total ) );
+            }
+        }
+
+        // Add total row if the number of rows is greater then 1
+        if ( displayTotals && grid.getRows().size() > 1 )
+        {
+            grid.addRow();
+            grid.addValue( i18n.getString( "total" ) );
+            int total = 0;
+            for ( int i = cols - dataCols + 1; i <= cols; i++ )
+            {
+                grid.addValue( format.formatValue( sumRow[i] ) );
+
+                total += sumRow[i];
+            }
+            if ( cols > cols - dataCols + 1 )
+            {
+                grid.addValue( format.formatValue( total ) );
+            }
+        }
+    }
+
+    private void pivotTable( Grid grid, SqlRowSet rowSet, Boolean displayTotals, I18n i18n, I18nFormat format )
+    {
+        try
+        {
+            int cols = rowSet.getMetaData().getColumnCount();
+            int rows = 0;
+            double total = 0;
+            Map<Integer, List<Object>> columnValues = new HashMap<Integer, List<Object>>();
+            int index = 2;
+
+            grid.addHeader( new GridHeader( "", false, true ) );
+            while ( rowSet.next() )
+            {
+                rows++;
+
+                // Header grid
+                grid.addHeader( new GridHeader( rowSet.getString( 1 ), false, false ) );
+
+                // Column values
+                List<Object> column = new ArrayList<Object>();
+                total = 0;
+                for ( int i = 2; i <= cols; i++ )
+                {
+                    column.add( rowSet.getObject( i ) );
+
+                    // Total value of the column
+                    if ( rowSet.getMetaData().getColumnType( i ) != Types.VARCHAR )
+                    {
+                        total += rowSet.getDouble( i );
+                    }
+                }
+
+                // Add total value of the column
+                if ( displayTotals && cols > 2 )
+                {
+                    // grid.addValue( format.formatValue( total ) );
+                    column.add( format.formatValue( total ) );
+                }
+
+                columnValues.put( index, column );
+                index++;
+            }
+
+            // Add total header
+            if ( displayTotals && rows > 1 )
+            {
+                grid.addHeader( new GridHeader( i18n.getString( "total" ), false, false ) );
+            }
+
+            // First column
+            List<Object> column = new ArrayList<Object>();
+            for ( int i = 2; i <= cols; i++ )
+            {
+                grid.addRow();
+                column.add( i18n.getString( rowSet.getMetaData().getColumnLabel( i ) ) );
+            }
+
+            if ( displayTotals && cols > 2 )
+            {
+                grid.addRow();
+                column.add( i18n.getString( "total" ) );
+            }
+            grid.addColumn( column );
+
+            // Other columns
+            for ( int i = 2; i < index; i++ )
+            {
+                grid.addColumn( columnValues.get( i ) );
+            }
+
+            if ( displayTotals && rows > 1 )
+            {
+                // Total column
+                int allTotal = 0;
+                column = new ArrayList<Object>();
+                for ( int j = 0; j < cols - 1; j++ )
+                {
+                    total = 0;
+                    for ( int i = 2; i < index; i++ )
+                    {
+                        if ( rowSet.getMetaData().getColumnType( j + 2 ) != Types.VARCHAR )
+                        {
+                            total += (Long) columnValues.get( i ).get( j );
+                        }
+                    }
+                    column.add( format.formatValue( total ) );
+
+                    allTotal += total;
+                }
+                if ( cols > 2 )
+                {
+                    column.add( format.formatValue( allTotal ) );
+                }
+                grid.addColumn( column );
+            }
+        }
+        catch ( Exception ex )
+        {
+            ex.printStackTrace();
+        }
+    }
+
+}

=== modified file 'dhis-2/dhis-services/dhis-service-patient/src/main/resources/META-INF/dhis/beans.xml'
--- dhis-2/dhis-services/dhis-service-patient/src/main/resources/META-INF/dhis/beans.xml	2013-09-18 06:54:48 +0000
+++ dhis-2/dhis-services/dhis-service-patient/src/main/resources/META-INF/dhis/beans.xml	2013-09-18 14:05:25 +0000
@@ -8,7 +8,24 @@
 
 	<bean id="org.hisp.dhis.program.ProgramIndicatorStore"
 		class="org.hisp.dhis.program.hibernate.HibernateProgramIndicatorStore">
+<<<<<<< TREE
 		<property name="clazz" value="org.hisp.dhis.program.ProgramIndicator" />
+=======
+	<property name="clazz" value="org.hisp.dhis.program.ProgramIndicator" />
+		<property name="sessionFactory" ref="sessionFactory" />
+	</bean>
+	
+	<bean id="org.hisp.dhis.caseaggregation.CaseAggregationConditionManager"
+		class="org.hisp.dhis.caseaggregation.jdbc.JdbcCaseAggregationConditionManager">
+		<property name="jdbcTemplate" ref="jdbcTemplate" />
+		<property name="statementBuilder" ref="statementBuilder" />
+		<property name="dataElementService" ref="org.hisp.dhis.dataelement.DataElementService" />
+	</bean>
+	
+	<bean id="org.hisp.dhis.caseaggregation.CaseAggregationConditionStore"
+		class="org.hisp.dhis.caseaggregation.hibernate.HibernateCaseAggregationConditionStore">
+		<property name="clazz" value="org.hisp.dhis.caseaggregation.CaseAggregationCondition" />
+>>>>>>> MERGE-SOURCE
 		<property name="sessionFactory" ref="sessionFactory" />
 	</bean>
 

=== modified file 'dhis-2/dhis-services/dhis-service-reporting/src/main/java/org/hisp/dhis/chart/impl/DefaultChartService.java'
=== modified file 'dhis-2/dhis-services/dhis-service-reporting/src/main/java/org/hisp/dhis/datasetreport/jdbc/AnalyticsDataSetReportStore.java'
=== modified file 'dhis-2/dhis-services/dhis-service-reporting/src/main/java/org/hisp/dhis/report/impl/DefaultReportService.java'
--- dhis-2/dhis-services/dhis-service-reporting/src/main/java/org/hisp/dhis/report/impl/DefaultReportService.java	2013-09-03 18:28:10 +0000
+++ dhis-2/dhis-services/dhis-service-reporting/src/main/java/org/hisp/dhis/report/impl/DefaultReportService.java	2013-09-18 14:05:25 +0000
@@ -80,10 +80,15 @@
 public class DefaultReportService
     implements ReportService
 {
+<<<<<<< TREE
     public static final String ORGUNIT_LEVEL_COLUMN_PREFIX = "idlevel";
     public static final String ORGUNIT_UID_LEVEL_COLUMN_PREFIX = "uidlevel";
 
     private static final Encoder ENCODER = new Encoder();
+=======
+    public static final String ORGUNIT_LEVEL_COLUMN_PREFIX = "idlevel";
+    public static final String ORGUNIT_UID_LEVEL_COLUMN_PREFIX = "uidlevel";
+>>>>>>> MERGE-SOURCE
     
     // -------------------------------------------------------------------------
     // Dependencies

=== added directory 'dhis-2/dhis-services/dhis-service-sms'
=== added directory 'dhis-2/dhis-services/dhis-service-sms/src'
=== added directory 'dhis-2/dhis-services/dhis-service-sms/src/main'
=== added directory 'dhis-2/dhis-services/dhis-service-sms/src/main/java'
=== added directory 'dhis-2/dhis-services/dhis-service-sms/src/main/java/org'
=== added directory 'dhis-2/dhis-services/dhis-service-sms/src/main/java/org/hisp'
=== added directory 'dhis-2/dhis-services/dhis-service-sms/src/main/java/org/hisp/dhis'
=== added directory 'dhis-2/dhis-services/dhis-service-sms/src/main/java/org/hisp/dhis/sms'
=== added directory 'dhis-2/dhis-services/dhis-service-sms/src/main/java/org/hisp/dhis/sms/outbound'
=== added file 'dhis-2/dhis-services/dhis-service-sms/src/main/java/org/hisp/dhis/sms/outbound/SmsSender.java.OTHER'
--- dhis-2/dhis-services/dhis-service-sms/src/main/java/org/hisp/dhis/sms/outbound/SmsSender.java.OTHER	1970-01-01 00:00:00 +0000
+++ dhis-2/dhis-services/dhis-service-sms/src/main/java/org/hisp/dhis/sms/outbound/SmsSender.java.OTHER	2013-09-18 14:05:25 +0000
@@ -0,0 +1,295 @@
+/*
+ * Copyright (c) 2004-2012, University of Oslo
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ * * Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright notice,
+ *   this list of conditions and the following disclaimer in the documentation
+ *   and/or other materials provided with the distribution.
+ * * Neither the name of the HISP project nor the names of its contributors may
+ *   be used to endorse or promote products derived from this software without
+ *   specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+package org.hisp.dhis.sms.outbound;
+
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.hisp.dhis.message.MessageSender;
+import org.hisp.dhis.sms.SmsServiceException;
+import org.hisp.dhis.sms.smslib.SmsLibService;
+import org.hisp.dhis.user.CurrentUserService;
+import org.hisp.dhis.user.User;
+import org.hisp.dhis.user.UserService;
+import org.hisp.dhis.user.UserSetting;
+import org.hisp.dhis.user.UserSettingService;
+import org.springframework.beans.factory.annotation.Autowired;
+
+/**
+ * @author Nguyen Kim Lai
+ * 
+ * @version SmsSender.java 10:29:11 AM Apr 16, 2013 $
+ */
+public class SmsSender
+    implements MessageSender
+{
+    private static final Log log = LogFactory.getLog( SmsSender.class );
+
+    private static final char[] HEX_CHARS = "0123456789abcdef".toCharArray();
+
+    private static final int MAX_HEX_CHAR = 280;
+
+    // -------------------------------------------------------------------------
+    // Dependencies
+    // -------------------------------------------------------------------------
+
+    private CurrentUserService currentUserService;
+
+    public void setCurrentUserService( CurrentUserService currentUserService )
+    {
+        this.currentUserService = currentUserService;
+    }
+
+    private UserService userService;
+
+    public void setUserService( UserService userService )
+    {
+        this.userService = userService;
+    }
+
+    private OutboundSmsService outboundSmsService;
+
+    public void setOutboundSmsService( OutboundSmsService outboundSmsService )
+    {
+        this.outboundSmsService = outboundSmsService;
+    }
+
+    @Autowired
+    private OutboundSmsTransportService transportService;
+
+    /**
+     * Note this methods is invoked asynchronously.
+     */
+    // @Async
+    @Override
+    public String sendMessage( String subject, String text, User sender, Set<User> users, boolean forceSend )
+    {
+        if ( transportService == null || SmsLibService.gatewayMap == null || SmsLibService.gatewayMap.get( "bulk_gw" ) == null )
+        {
+            return null;
+        }
+        
+        String message = null;
+
+        Set<User> toSendList = new HashSet<User>();
+
+        String gatewayId = transportService.getDefaultGateway();
+        
+        if ( SmsLibService.gatewayMap.get( "bulk_gw" ).equals( gatewayId ) )
+        {
+            //bulk is limited in sending long SMS. to be continue....
+        }
+
+        if ( gatewayId != null && !gatewayId.trim().isEmpty() )
+        {
+            for ( User user : users )
+            {
+                if ( currentUserService.getCurrentUser() != null )
+                {
+                    if ( !currentUserService.getCurrentUser().equals( user ) )
+                    {
+                        if ( isQualifiedReceiver( user ) )
+                        {
+                            toSendList.add( user );
+                        }
+                    }
+                }
+                else if ( currentUserService.getCurrentUser() == null )
+                {
+                    if ( isQualifiedReceiver( user ) )
+                    {
+                        toSendList.add( user );
+                    }
+                }
+            }
+
+            Set<String> phoneNumbers = null;
+
+            if ( outboundSmsService != null || outboundSmsService.isEnabled() )
+            {
+                text = createMessage( subject, text, sender );
+
+                phoneNumbers = getRecipientsPhoneNumber( toSendList );
+
+                if ( !phoneNumbers.isEmpty() && phoneNumbers.size() > 0 )
+                {
+                    message = sendMessage( text, phoneNumbers, gatewayId );
+                }
+
+            }
+        }
+        
+        return message;
+    }
+
+    // -------------------------------------------------------------------------
+    // Supportive methods
+    // -------------------------------------------------------------------------
+
+    private boolean isQualifiedReceiver( User user )
+    {
+        // if receiver is raw number
+        if ( user.getFirstName() == null )
+        {
+            return true;
+        }
+        // if receiver is user
+        else
+        {
+            UserSetting userSetting = userService
+                .getUserSetting( user, UserSettingService.KEY_MESSAGE_SMS_NOTIFICATION );
+            if ( userSetting != null )
+            {
+                boolean sendSMSNotification = (Boolean) userSetting.getValue();
+                if ( sendSMSNotification == true )
+                {
+                    return true;
+                }
+                else
+                {
+                    return false;
+                }
+            }
+            else
+            {
+                return false;
+            }
+        }
+    }
+
+    private String createMessage( String subject, String text, User sender )
+    {
+        String name = "DHIS";
+
+        if ( sender != null )
+        {
+            name = sender.getUsername();
+        }
+
+        if ( subject == null || subject.isEmpty() )
+        {
+            subject = "";
+        }
+        else
+        {
+            subject = " - " + subject;
+        }
+
+        text = name + subject + ": " + text;
+
+        // Simplistic cut off 160 characters
+        int length = text.length();
+
+        return (length > 160) ? text.substring( 0, 157 ) + "..." : text;
+    }
+
+    private Set<String> getRecipientsPhoneNumber( Set<User> users )
+    {
+        Set<String> recipients = new HashSet<String>();
+
+        for ( User user : users )
+        {
+            String phoneNumber = user.getPhoneNumber();
+
+            if ( phoneNumber != null && !phoneNumber.trim().isEmpty() )
+            {
+                recipients.add( phoneNumber );
+            }
+        }
+
+        return recipients;
+    }
+
+    private String sendMessage( String text, Set<String> recipients, String gateWayId )
+    // private String sendMessage( String text, Set<String> recipients, String
+    // gateWayId, boolean isUnicode )
+    {
+        String message = null;
+        OutboundSms sms = new OutboundSms();
+        sms.setMessage( text );
+        sms.setRecipients( recipients );
+
+        try
+        {
+            message = outboundSmsService.sendMessage( sms, gateWayId );
+        }
+        catch ( SmsServiceException e )
+        {
+            message = "Unable to send message through sms: " + sms + e.getCause().getMessage();
+
+            log.warn( "Unable to send message through sms: " + sms, e );
+        }
+
+        return message;
+    }
+
+    public static String toHex( byte[] buf )
+    {
+        char[] chars = new char[2 * buf.length];
+        for ( int i = 0; i < buf.length; ++i )
+        {
+            chars[2 * i] = HEX_CHARS[(buf[i] & 0xF0) >>> 4];
+            chars[2 * i + 1] = HEX_CHARS[buf[i] & 0x0F];
+        }
+        return new String( chars );
+    }
+
+    public static List<String> spitLongHexString( String hexString, String message, List<String> result )
+    {
+
+        String firstTempHex = null;
+        String secondTempHex = null;
+        String firstTempString = null;
+        String secondTempString = null;
+        int indexToCut;
+
+        firstTempHex = hexString.substring( 0, MAX_HEX_CHAR );
+
+        int lastSpaceIndex = firstTempHex.lastIndexOf( "0020" );
+
+        firstTempHex = firstTempHex.substring( 0, lastSpaceIndex );
+        indexToCut = (firstTempHex.length() - 4) / 4;
+        firstTempString = message.substring( 0, indexToCut );
+        result.add( firstTempString );
+
+        secondTempHex = "feff" + hexString.substring( firstTempHex.length() + 4, hexString.length() );
+        secondTempString = message.substring( indexToCut + 1, message.length() );
+        if ( secondTempHex.length() <= MAX_HEX_CHAR )
+        {
+            result.add( secondTempString );
+            return result;
+        }
+        else
+        {
+            return spitLongHexString( secondTempHex, secondTempString, result );
+        }
+    }
+}

=== modified file 'dhis-2/dhis-support/dhis-support-jdbc/src/main/java/org/hisp/dhis/jdbc/statementbuilder/MySQLStatementBuilder.java'
--- dhis-2/dhis-support/dhis-support-jdbc/src/main/java/org/hisp/dhis/jdbc/statementbuilder/MySQLStatementBuilder.java	2013-09-12 07:29:29 +0000
+++ dhis-2/dhis-support/dhis-support-jdbc/src/main/java/org/hisp/dhis/jdbc/statementbuilder/MySQLStatementBuilder.java	2013-09-18 14:05:25 +0000
@@ -39,6 +39,7 @@
     @Override
     public String getDoubleColumnType()
     {
+<<<<<<< TREE
         return "decimal(26,1)";
     }
 
@@ -46,6 +47,9 @@
     public String getColumnQuote()
     {
         return "`";
+=======
+        return "decimal(26,1)";
+>>>>>>> MERGE-SOURCE
     }
 
     @Override

=== modified file 'dhis-2/dhis-support/dhis-support-system/src/main/java/org/hisp/dhis/system/util/MathUtils.java'
=== modified file 'dhis-2/dhis-support/dhis-support-system/src/main/java/org/hisp/dhis/system/util/StreamUtils.java'
=== modified file 'dhis-2/dhis-support/dhis-support-system/src/main/java/org/hisp/dhis/system/util/UniqueArrayList.java'
--- dhis-2/dhis-support/dhis-support-system/src/main/java/org/hisp/dhis/system/util/UniqueArrayList.java	2013-08-23 16:05:01 +0000
+++ dhis-2/dhis-support/dhis-support-system/src/main/java/org/hisp/dhis/system/util/UniqueArrayList.java	2013-09-18 14:05:25 +0000
@@ -1,3 +1,4 @@
+<<<<<<< TREE
 package org.hisp.dhis.system.util;
 
 /*
@@ -92,3 +93,98 @@
         return modified;
     }
 }
+=======
+package org.hisp.dhis.system.util;
+
+/*
+ * Copyright (c) 2004-2005, University of Oslo
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ * * Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright notice,
+ *   this list of conditions and the following disclaimer in the documentation
+ *   and/or other materials provided with the distribution.
+ * * Neither the name of the <ORGANIZATION> nor the names of its contributors may
+ *   be used to endorse or promote products derived from this software without
+ *   specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+import java.util.ArrayList;
+import java.util.Collection;
+
+/**
+ * @author Lars Helge Overland
+ */
+public class UniqueArrayList<E>
+    extends ArrayList<E>
+{    
+    @Override
+    public boolean add( E e )
+    {
+        return super.contains( e ) ? false : super.add( e );
+    }
+    
+    @Override
+    public void add( int index, E e )
+    {
+        if ( !super.contains( e ) )
+        {
+            super.add( index, e );
+        }
+    }
+    
+    @Override
+    public boolean addAll( Collection<? extends E> c )
+    {
+        boolean modified = false;
+        
+        if ( c != null )
+        {        
+            for ( E e : c )
+            {
+                if ( !super.contains( e ) )
+                {
+                    super.add( e );
+                    modified = true;
+                }
+            }
+        }
+        
+        return modified;
+    }
+    
+    @Override
+    public boolean addAll( int index, Collection<? extends E> c )
+    {
+        boolean modified = false;
+        
+        if ( c != null )
+        {        
+            for ( E e : c )
+            {
+                if ( !super.contains( e ) )
+                {
+                    super.add( index++, e );
+                    modified = true;
+                }
+            }
+        }
+        
+        return modified;
+    }
+}
+>>>>>>> MERGE-SOURCE

=== modified file 'dhis-2/dhis-support/dhis-support-system/src/main/java/org/hisp/dhis/system/util/ValidationUtils.java'
=== modified file 'dhis-2/dhis-support/dhis-support-system/src/test/java/org/hisp/dhis/system/util/MathUtilsTest.java'
--- dhis-2/dhis-support/dhis-support-system/src/test/java/org/hisp/dhis/system/util/MathUtilsTest.java	2013-08-23 16:05:01 +0000
+++ dhis-2/dhis-support/dhis-support-system/src/test/java/org/hisp/dhis/system/util/MathUtilsTest.java	2013-09-18 14:05:25 +0000
@@ -242,6 +242,7 @@
     {
         assertEquals( 7.5, MathUtils.getAverage( Arrays.asList( 5.0, 5.0, 10.0, 10.0 ) ), 0.01 );
     }
+<<<<<<< TREE
     
     @Test
     public void testGetRounded()
@@ -265,4 +266,18 @@
         assertEquals( 5d, MathUtils.calculateExpression( "sqrt(25)" ), 0.01 );
         assertEquals( 1d, MathUtils.calculateExpression( "mod(7,2)" ), 0.01 );
     }
+=======
+    
+    @Test
+    public void testGetRounded()
+    {
+        assertEquals( 10, MathUtils.getRounded( 10.00 ), 0.01 );
+        assertEquals( 10, MathUtils.getRounded( 10 ), 0.01 );
+        assertEquals( 0.53, MathUtils.getRounded( 0.5281 ), 0.01 );
+        assertEquals( 0.5, MathUtils.getRounded( 0.5 ), 0.01 );
+        assertEquals( 0, MathUtils.getRounded( 0 ), 0.01 );
+        assertEquals( -0.43, MathUtils.getRounded( -0.43123 ), 0.01 );
+        assertEquals( -10, MathUtils.getRounded( -10.00 ), 0.01 );        
+    }
+>>>>>>> MERGE-SOURCE
 }

=== modified file 'dhis-2/dhis-web/dhis-web-api/src/main/java/org/hisp/dhis/api/controller/ChartController.java'
=== modified file 'dhis-2/dhis-web/dhis-web-api/src/main/java/org/hisp/dhis/api/controller/MetaDataController.java'
=== modified file 'dhis-2/dhis-web/dhis-web-api/src/main/java/org/hisp/dhis/api/controller/PDFFormController.java'
--- dhis-2/dhis-web/dhis-web-api/src/main/java/org/hisp/dhis/api/controller/PDFFormController.java	2013-08-23 16:00:30 +0000
+++ dhis-2/dhis-web/dhis-web-api/src/main/java/org/hisp/dhis/api/controller/PDFFormController.java	2013-09-18 14:05:25 +0000
@@ -44,7 +44,12 @@
 import org.hisp.dhis.api.utils.ContextUtils.CacheStrategy;
 import org.hisp.dhis.api.utils.PdfDataEntryFormImportUtil;
 import org.hisp.dhis.common.IdentifiableObject.IdentifiableProperty;
-import org.hisp.dhis.dataset.DataSetService;
+<<<<<<< TREE
+import org.hisp.dhis.dataset.DataSetService;
+=======
+import org.hisp.dhis.dataset.DataSet;
+import org.hisp.dhis.dataset.DataSetService;
+>>>>>>> MERGE-SOURCE
 import org.hisp.dhis.dxf2.datavalueset.DataValueSetService;
 import org.hisp.dhis.dxf2.metadata.ImportOptions;
 import org.hisp.dhis.dxf2.pdfform.PdfDataEntryFormService;
@@ -53,8 +58,14 @@
 import org.hisp.dhis.i18n.I18nManager;
 import org.hisp.dhis.i18n.I18nManagerException;
 import org.hisp.dhis.importexport.ImportStrategy;
-import org.hisp.dhis.period.Period;
-import org.hisp.dhis.program.ProgramStageService;
+<<<<<<< TREE
+import org.hisp.dhis.period.Period;
+import org.hisp.dhis.program.ProgramStageService;
+=======
+import org.hisp.dhis.period.Period;
+import org.hisp.dhis.program.ProgramStage;
+import org.hisp.dhis.program.ProgramStageService;
+>>>>>>> MERGE-SOURCE
 import org.hisp.dhis.scheduling.TaskCategory;
 import org.hisp.dhis.scheduling.TaskId;
 import org.hisp.dhis.system.notification.Notifier;

=== modified file 'dhis-2/dhis-web/dhis-web-api/src/main/java/org/hisp/dhis/api/controller/ReportController.java'
--- dhis-2/dhis-web/dhis-web-api/src/main/java/org/hisp/dhis/api/controller/ReportController.java	2013-08-23 16:00:30 +0000
+++ dhis-2/dhis-web/dhis-web-api/src/main/java/org/hisp/dhis/api/controller/ReportController.java	2013-09-18 14:05:25 +0000
@@ -177,12 +177,21 @@
         
         I18nFormat format = i18nManager.getI18nFormat();
 
+<<<<<<< TREE
         if ( report == null )
         {
             ContextUtils.notFoundResponse( response, "Report does not exist: " + uid );
             return;
         }
         
+=======
+        if ( report == null )
+        {
+            ContextUtils.notFoundResponse( response, "Report does not exist: " + uid );
+            return null;
+        }
+        
+>>>>>>> MERGE-SOURCE
         if ( organisationUnitUid == null && report.hasReportTable() && report.getReportTable().hasReportParams()
             && report.getReportTable().getReportParams().isOrganisationUnitSet() )
         {

=== modified file 'dhis-2/dhis-web/dhis-web-api/src/main/java/org/hisp/dhis/api/controller/ReportTableController.java'
--- dhis-2/dhis-web/dhis-web-api/src/main/java/org/hisp/dhis/api/controller/ReportTableController.java	2013-08-23 16:00:30 +0000
+++ dhis-2/dhis-web/dhis-web-api/src/main/java/org/hisp/dhis/api/controller/ReportTableController.java	2013-09-18 14:05:25 +0000
@@ -306,6 +306,7 @@
         reportTable.getRowDimensions().clear();
         reportTable.getFilterDimensions().clear();
         
+<<<<<<< TREE
         reportTable.getColumnDimensions().addAll( getUniqueDimensions( reportTable.getColumns() ) );
         reportTable.getRowDimensions().addAll( getUniqueDimensions( reportTable.getRows() ) );
         reportTable.getFilterDimensions().addAll( getUniqueDimensions( reportTable.getFilters() ) );
@@ -314,5 +315,10 @@
         {
             reportTable.setLegendSet( mappingService.getMapLegendSet( reportTable.getLegendSet().getUid() ) );
         }
+=======
+        reportTable.getColumnDimensions().addAll( getUniqueDimensions( reportTable.getColumns() ) );
+        reportTable.getRowDimensions().addAll( getUniqueDimensions( reportTable.getRows() ) );
+        reportTable.getFilterDimensions().addAll( getUniqueDimensions( reportTable.getFilters() ) );        
+>>>>>>> MERGE-SOURCE
     }
 }

=== modified file 'dhis-2/dhis-web/dhis-web-api/src/main/java/org/hisp/dhis/api/utils/FormUtils.java'
=== modified file 'dhis-2/dhis-web/dhis-web-api/src/main/java/org/hisp/dhis/api/webdomain/form/InputType.java'
=== modified file 'dhis-2/dhis-web/dhis-web-api/src/main/resources/META-INF/dhis/servlet.xml'
=== modified file 'dhis-2/dhis-web/dhis-web-appmanager/src/main/java/org/hisp/dhis/appmanager/action/AddAppAction.java'
--- dhis-2/dhis-web/dhis-web-appmanager/src/main/java/org/hisp/dhis/appmanager/action/AddAppAction.java	2013-09-03 15:24:51 +0000
+++ dhis-2/dhis-web/dhis-web-appmanager/src/main/java/org/hisp/dhis/appmanager/action/AddAppAction.java	2013-09-18 14:05:25 +0000
@@ -28,6 +28,13 @@
  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
+<<<<<<< TREE
+=======
+import com.fasterxml.jackson.core.JsonParseException;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.opensymphony.xwork2.Action;
+>>>>>>> MERGE-SOURCE
 import java.io.BufferedInputStream;
 import java.io.File;
 import java.io.FileInputStream;

=== modified file 'dhis-2/dhis-web/dhis-web-appmanager/src/main/webapp/dhis-web-appmanager/getApps.vm'
--- dhis-2/dhis-web/dhis-web-appmanager/src/main/webapp/dhis-web-appmanager/getApps.vm	2013-08-16 12:29:21 +0000
+++ dhis-2/dhis-web/dhis-web-appmanager/src/main/webapp/dhis-web-appmanager/getApps.vm	2013-09-18 14:05:25 +0000
@@ -1,18 +1,43 @@
-<style type="text/css">
-#uploadArea {
-    border: 1px solid #ccc; 
-    border-radius: 3px; 
-    padding: 10px; 
-    width: 440px; 
-    margin-bottom: 30px;
-}
-
-#progressbar {
-    width: 460px;
-    margin-bottom: 30px;
-}
-</style>
-
+<<<<<<< TREE
+<style type="text/css">
+#uploadArea {
+    border: 1px solid #ccc; 
+    border-radius: 3px; 
+    padding: 10px; 
+    width: 440px; 
+    margin-bottom: 30px;
+}
+
+#progressbar {
+    width: 460px;
+    margin-bottom: 30px;
+}
+</style>
+
+=======
+<script type="text/javascript">
+jQuery(function() {
+	/* make sure that the leftBar is always visible when entering page. */
+	leftBar.showAnimated();
+        autoUpload();
+});
+</script>
+<style type="text/css">
+#uploadArea {
+    border: 1px solid #ccc; 
+    border-radius: 3px; 
+    padding: 10px; 
+    width: 440px; 
+    margin-bottom: 30px;
+}
+
+#progressbar {
+    width: 460px;
+    margin-bottom: 30px;
+}
+</style>
+
+>>>>>>> MERGE-SOURCE
 <div>
     <h3>$i18n.getString( "appmanager_app_store" ) #*openHelp( "appManager" )*#</h3>
     <div id="uploadArea">

=== modified file 'dhis-2/dhis-web/dhis-web-appmanager/src/main/webapp/dhis-web-appmanager/index.vm'
=== modified file 'dhis-2/dhis-web/dhis-web-appmanager/src/main/webapp/dhis-web-appmanager/javascript/uploadApp.js'
=== modified file 'dhis-2/dhis-web/dhis-web-caseentry/src/main/java/org/hisp/dhis/caseentry/action/caseaggregation/CaseAggregationFormAction.java'
=== modified file 'dhis-2/dhis-web/dhis-web-caseentry/src/main/java/org/hisp/dhis/caseentry/action/caseaggregation/CaseAggregationResultAction.java'
--- dhis-2/dhis-web/dhis-web-caseentry/src/main/java/org/hisp/dhis/caseentry/action/caseaggregation/CaseAggregationResultAction.java	2013-08-23 16:05:01 +0000
+++ dhis-2/dhis-web/dhis-web-caseentry/src/main/java/org/hisp/dhis/caseentry/action/caseaggregation/CaseAggregationResultAction.java	2013-09-18 14:05:25 +0000
@@ -40,6 +40,10 @@
 import org.hisp.dhis.common.Grid;
 import org.hisp.dhis.dataset.DataSet;
 import org.hisp.dhis.dataset.DataSetService;
+<<<<<<< TREE
+=======
+import org.hisp.dhis.datavalue.DataValueService;
+>>>>>>> MERGE-SOURCE
 import org.hisp.dhis.i18n.I18n;
 import org.hisp.dhis.i18n.I18nFormat;
 import org.hisp.dhis.organisationunit.OrganisationUnit;
@@ -54,7 +58,11 @@
 public class CaseAggregationResultAction
     implements Action
 {
+<<<<<<< TREE
     // -------------------------------------------------------------------------
+=======
+   // -------------------------------------------------------------------------
+>>>>>>> MERGE-SOURCE
     // Dependencies
     // -------------------------------------------------------------------------
 

=== modified file 'dhis-2/dhis-web/dhis-web-caseentry/src/main/java/org/hisp/dhis/caseentry/action/caseentry/LoadDataEntryAction.java'
=== modified file 'dhis-2/dhis-web/dhis-web-caseentry/src/main/java/org/hisp/dhis/caseentry/action/caseentry/UploadAnonymousEventAction.java'
=== modified file 'dhis-2/dhis-web/dhis-web-caseentry/src/main/java/org/hisp/dhis/caseentry/action/patient/PatientDashboardAction.java'
--- dhis-2/dhis-web/dhis-web-caseentry/src/main/java/org/hisp/dhis/caseentry/action/patient/PatientDashboardAction.java	2013-09-17 09:47:21 +0000
+++ dhis-2/dhis-web/dhis-web-caseentry/src/main/java/org/hisp/dhis/caseentry/action/patient/PatientDashboardAction.java	2013-09-18 14:05:25 +0000
@@ -229,10 +229,16 @@
         // Get patient-attribute-values
         // ---------------------------------------------------------------------
 
+<<<<<<< TREE
         Collection<PatientAttributeValue> _attributeValues = patientAttributeValueService
             .getPatientAttributeValues( patient );
         attributeValues = new HashSet<PatientAttributeValue>();
 
+=======
+       Collection<PatientAttributeValue> _attributeValues = patientAttributeValueService.getPatientAttributeValues( patient );
+        attributeValues = new HashSet<PatientAttributeValue>();
+        
+>>>>>>> MERGE-SOURCE
         for ( Program program : programs )
         {
             Collection<PatientAttribute> atttributes = program.getPatientAttributes();
@@ -249,9 +255,15 @@
         // Get patient-identifiers
         // ---------------------------------------------------------------------
 
+<<<<<<< TREE
         Collection<PatientIdentifier> _identifiers = patient.getIdentifiers();
         identifiers = new HashSet<PatientIdentifier>();
 
+=======
+        Collection<PatientIdentifier> _identifiers = patient.getIdentifiers();
+        identifiers = new HashSet<PatientIdentifier>();
+        
+>>>>>>> MERGE-SOURCE
         for ( Program program : programs )
         {
             Collection<PatientIdentifierType> identifierTypes = program.getPatientIdentifierTypes();
@@ -259,7 +271,11 @@
             {
                 if ( !identifierTypes.contains( identifier.getIdentifierType() ) )
                 {
+<<<<<<< TREE
                     identifiers.add( identifier );
+=======
+                    identifiers.add(identifier);
+>>>>>>> MERGE-SOURCE
                 }
             }
         }

=== modified file 'dhis-2/dhis-web/dhis-web-caseentry/src/main/resources/org/hisp/dhis/caseentry/i18n_module.properties'
--- dhis-2/dhis-web/dhis-web-caseentry/src/main/resources/org/hisp/dhis/caseentry/i18n_module.properties	2013-09-17 09:47:21 +0000
+++ dhis-2/dhis-web/dhis-web-caseentry/src/main/resources/org/hisp/dhis/caseentry/i18n_module.properties	2013-09-18 14:05:25 +0000
@@ -654,6 +654,7 @@
 toggle_risk_status = Toggle risk status
 with = with
 status_events = events
+<<<<<<< TREE
 use_data_element_form_names = Use data element form names
 section = Section
 orgunit_registered = Organisation registered
@@ -686,4 +687,8 @@
 enrollment_date = Enrollment date
 add_relative = Add relative
 who_is_the_new_relative_to_the_existing_person = Who is the new relative to the existing person?
-program_for_new_relative_to_be_enrolled_in = Program for new relative to be enrolled in
\ No newline at end of file
+program_for_new_relative_to_be_enrolled_in = Program for new relative to be enrolled in=======
+use_data_element_form_names = Use data element form names
+section = Section
+orgunit_registered = Organisation registered
+users_in_orgunit_registered = Users in organisation registered>>>>>>> MERGE-SOURCE

=== modified file 'dhis-2/dhis-web/dhis-web-caseentry/src/main/webapp/dhis-web-caseentry/activityPlanSelect.vm'
=== modified file 'dhis-2/dhis-web/dhis-web-caseentry/src/main/webapp/dhis-web-caseentry/app/app.js'
--- dhis-2/dhis-web/dhis-web-caseentry/src/main/webapp/dhis-web-caseentry/app/app.js	2013-09-10 15:46:44 +0000
+++ dhis-2/dhis-web/dhis-web-caseentry/src/main/webapp/dhis-web-caseentry/app/app.js	2013-09-18 14:05:25 +0000
@@ -2622,9 +2622,15 @@
 							{
 								filterValue = Ext.getCmp('filter_' + id).getValue();
 							}
+<<<<<<< TREE
 							if( filterValue == null 
 								|| filterValue == ''
 								|| filterValue==TR.i18n.please_select ){
+=======
+							if( filterValue == null 
+								|| filterValue == '' || filterValue != 0
+								|| filterValue==TR.i18n.please_select ){
+>>>>>>> MERGE-SOURCE
 								isValid = false;
 							}
 						}

=== modified file 'dhis-2/dhis-web/dhis-web-caseentry/src/main/webapp/dhis-web-caseentry/cacheManifest.vm'
--- dhis-2/dhis-web/dhis-web-caseentry/src/main/webapp/dhis-web-caseentry/cacheManifest.vm	2013-08-23 16:12:16 +0000
+++ dhis-2/dhis-web/dhis-web-caseentry/src/main/webapp/dhis-web-caseentry/cacheManifest.vm	2013-09-18 14:05:25 +0000
@@ -1,5 +1,9 @@
 CACHE MANIFEST
+<<<<<<< TREE
 # 2.13-SNAPSHOT V10
+=======
+# 2.12 V10
+>>>>>>> MERGE-SOURCE
 NETWORK:
 *
 CACHE:

=== modified file 'dhis-2/dhis-web/dhis-web-caseentry/src/main/webapp/dhis-web-caseentry/dataEntryForm.vm'
--- dhis-2/dhis-web/dhis-web-caseentry/src/main/webapp/dhis-web-caseentry/dataEntryForm.vm	2013-09-12 05:49:31 +0000
+++ dhis-2/dhis-web/dhis-web-caseentry/src/main/webapp/dhis-web-caseentry/dataEntryForm.vm	2013-09-18 14:05:25 +0000
@@ -35,7 +35,21 @@
 			</th>
 		</tr>
 		#end
+<<<<<<< TREE
 		
+=======
+
+		<tr id='entryPostComment'>
+			<th class='coordinates1'><label for="postComment">$i18n.getString('post_comment'):</label></th>
+			<th colspan='3'>
+				<input type="text" class="{validate:{maxlength:160}} criteria" id="commentInput"
+                        style="width:380px;#if($programStage.captureCoordinates=='false') margin-left:11px; padding-left: 2px;  #end "
+                       onkeypress="keypressOnComment( event, this );">
+				<input id="commentButton" type="button" style='width:40px' value="$i18n.getString('add')" onclick='addComment( byId("commentInput"), $programStageInstance.id )'>
+			</th>
+		</tr>
+
+>>>>>>> MERGE-SOURCE
 		#if( $programStage.getDataEntryType()=='section' )
 		<tr id="filterDataSetSectionTr" class='coordinates1'>
 			<th class='coordinates1'><label for="filterDataSetSection">$i18n.getString( "filter_on_section" )</label></th>

=== modified file 'dhis-2/dhis-web/dhis-web-caseentry/src/main/webapp/dhis-web-caseentry/javascript/anonymousRegistration.js'
=== modified file 'dhis-2/dhis-web/dhis-web-caseentry/src/main/webapp/dhis-web-caseentry/javascript/commons.js'
=== modified file 'dhis-2/dhis-web/dhis-web-caseentry/src/main/webapp/dhis-web-caseentry/javascript/entry.js'
--- dhis-2/dhis-web/dhis-web-caseentry/src/main/webapp/dhis-web-caseentry/javascript/entry.js	2013-09-12 05:49:31 +0000
+++ dhis-2/dhis-web/dhis-web-caseentry/src/main/webapp/dhis-web-caseentry/javascript/entry.js	2013-09-18 14:05:25 +0000
@@ -608,8 +608,13 @@
 
                 hideLoader();
 
+<<<<<<< TREE
                 if ( isCreateEvent) {
                     showAddEventForm(isCreateEvent);
+=======
+                if ( isCreateEvent ) {
+                    showAddEventForm(isCreateEvent);
+>>>>>>> MERGE-SOURCE
                 }
             } ).fail(function() {
                 if ( getProgramType() == 3 ) {

=== modified file 'dhis-2/dhis-web/dhis-web-caseentry/src/main/webapp/dhis-web-caseentry/jsonProgramMetaData.vm'
--- dhis-2/dhis-web/dhis-web-caseentry/src/main/webapp/dhis-web-caseentry/jsonProgramMetaData.vm	2013-09-12 05:49:31 +0000
+++ dhis-2/dhis-web/dhis-web-caseentry/src/main/webapp/dhis-web-caseentry/jsonProgramMetaData.vm	2013-09-18 14:05:25 +0000
@@ -12,6 +12,11 @@
     "enrollmentDescription":"$encoder.jsonEncode( ${program.dateOfEnrollmentDescription} )",
     "incidentDescription":"$encoder.jsonEncode( ${program.dateOfIncidentDescription} )",
     "type": "$!program.type",
+<<<<<<< TREE
+=======
+    "blockEntryForm": $!{program.blockEntryForm},
+    "remindCompleted": $!{program.remindCompleted},
+>>>>>>> MERGE-SOURCE
     "programStages":[#set( $pssize = $program.programStages.size() )
     #foreach( $ps in $program.programStages )
     {
@@ -19,6 +24,7 @@
         "uid": "$encoder.jsonEncode( ${ps.uid} )",
         "name": "$encoder.jsonEncode( ${ps.displayName} )",
         "reportDateDescription": "$encoder.jsonEncode( ${ps.reportDateDescription} )",
+<<<<<<< TREE
         "irregular": "$!{ps.irregular}",
         "displayGenerateEventBox": "$!{ps.displayGenerateEventBox}",
         "validCompleteOnly": "$!{ps.validCompleteOnly}",
@@ -26,6 +32,12 @@
         "blockEntryForm": "$!ps.blockEntryForm",
         "remindCompleted": "$!ps.remindCompleted",
 		"allowGenerateNextVisit": "$!ps.allowGenerateNextVisit"
+=======
+        "irregular": "$!{ps.irregular}",
+        "displayGenerateEventBox": "$!{ps.displayGenerateEventBox}",
+        "validCompleteOnly": "$!{ps.validCompleteOnly}",
+        "captureCoordinates": "$!{ps.captureCoordinates}"
+>>>>>>> MERGE-SOURCE
     }#if( $velocityCount < $pssize ),#end
     #end],
     "programAssociations": $programAssociations.get( ${program.id} )

=== modified file 'dhis-2/dhis-web/dhis-web-caseentry/src/main/webapp/dhis-web-caseentry/patientRegistrationList.vm'
--- dhis-2/dhis-web/dhis-web-caseentry/src/main/webapp/dhis-web-caseentry/patientRegistrationList.vm	2013-09-16 09:47:59 +0000
+++ dhis-2/dhis-web/dhis-web-caseentry/src/main/webapp/dhis-web-caseentry/patientRegistrationList.vm	2013-09-18 14:05:25 +0000
@@ -110,6 +110,7 @@
 					#end
 						
 					#set($value="")
+<<<<<<< TREE
 					#foreach( $identifierType in $identifierTypes)
 						#set($value="")
 						#if($identifierType.personDisplayName=='true')
@@ -123,6 +124,13 @@
 							#end
 							<a>$encoder.htmlEncode($value)</a>
 						</td>
+=======
+					#foreach( $identifier in $patient.identifiers)
+						#if($!identifier.identifierType)
+							#set($value=$identifier.identifier)
+						#else
+							#set($systemId=$identifier.identifier)
+>>>>>>> MERGE-SOURCE
 						#end
 					#end
 					
@@ -130,6 +138,7 @@
 						#set($value=$!patient.getFullName())
 					#end
 					#if($value=="")
+<<<<<<< TREE
 						#set($value=$systemId)
 					#end
 					#if($personDisplayName=='false')
@@ -137,6 +146,13 @@
 							<a>$encoder.htmlEncode($value)</a>
 						</td>
 					#end
+=======
+						#set($value=$systemId)
+					#end
+					<td style="cursor:pointer;" onclick="javascript:isDashboard=true;showPatientDashboardForm( '$patient.id' )">
+						<a>$encoder.htmlEncode($value)</a>
+					</td>
+>>>>>>> MERGE-SOURCE
 					
 					<td>#if($!patient.gender) $i18n.getString($!patient.gender) #end</td>
 					

=== modified file 'dhis-2/dhis-web/dhis-web-caseentry/src/main/webapp/dhis-web-caseentry/programStageCompletenessSelect.vm'
=== modified file 'dhis-2/dhis-web/dhis-web-caseentry/src/main/webapp/dhis-web-caseentry/programStageInstanceFlow.vm'
=== modified file 'dhis-2/dhis-web/dhis-web-caseentry/src/main/webapp/dhis-web-caseentry/programTrackingList.vm'
=== modified file 'dhis-2/dhis-web/dhis-web-caseentry/src/main/webapp/dhis-web-caseentry/programTrackingRecords.vm'
=== modified file 'dhis-2/dhis-web/dhis-web-caseentry/src/main/webapp/dhis-web-caseentry/programTrackingSelect.vm'
=== modified file 'dhis-2/dhis-web/dhis-web-caseentry/src/main/webapp/dhis-web-caseentry/updatePatientForm.vm'
=== modified file 'dhis-2/dhis-web/dhis-web-caseentry/src/main/webapp/dhis-web-caseentry/visitSchedule.vm'
=== modified file 'dhis-2/dhis-web/dhis-web-commons-resources/src/main/webapp/WEB-INF/classes/log4j.properties'
--- dhis-2/dhis-web/dhis-web-commons-resources/src/main/webapp/WEB-INF/classes/log4j.properties	2013-08-29 18:14:51 +0000
+++ dhis-2/dhis-web/dhis-web-commons-resources/src/main/webapp/WEB-INF/classes/log4j.properties	2013-09-18 14:05:25 +0000
@@ -31,5 +31,10 @@
 # Spring framework logging level
 log4j.logger.org.springframework = WARN
 log4j.logger.org.springframework.web = WARN
+<<<<<<< TREE
 
 # log4j.logger.org.hisp.dhis.system.util.Timer = ERROR
+=======
+
+# Quick logging level
+# log4j.logger.org.amplecode.quick = DEBUG>>>>>>> MERGE-SOURCE

=== modified file 'dhis-2/dhis-web/dhis-web-commons-resources/src/main/webapp/cacheManifest.vm'
--- dhis-2/dhis-web/dhis-web-commons-resources/src/main/webapp/cacheManifest.vm	2013-08-25 20:46:47 +0000
+++ dhis-2/dhis-web/dhis-web-commons-resources/src/main/webapp/cacheManifest.vm	2013-09-18 14:05:25 +0000
@@ -1,5 +1,9 @@
 CACHE MANIFEST
+<<<<<<< TREE
 # 2.13-SNAPSHOT V11
+=======
+# 2.12 V1
+>>>>>>> MERGE-SOURCE
 NETWORK:
 *
 CACHE:
@@ -55,3 +59,7 @@
 ../images/ajax-loader-bar.gif
 ../dhis-web-dataentry/javascript/form.js
 ../dhis-web-dataentry/javascript/entry.js
+../images/warning_small.png
+../images/success_small.png
+javascripts/jQuery/ui/css/redmond/images/ui-icons_469bdd_256x240.png
+javascripts/jQuery/ui/css/redmond/images/ui-icons_d8e7f3_256x240.png
\ No newline at end of file

=== modified file 'dhis-2/dhis-web/dhis-web-commons-resources/src/main/webapp/dhis-web-commons/about/about.vm'
--- dhis-2/dhis-web/dhis-web-commons-resources/src/main/webapp/dhis-web-commons/about/about.vm	2013-09-01 21:38:52 +0000
+++ dhis-2/dhis-web/dhis-web-commons-resources/src/main/webapp/dhis-web-commons/about/about.vm	2013-09-18 14:05:25 +0000
@@ -9,6 +9,7 @@
   <dt>$i18n.getString( "server_date" ):</dt><dd>$format.formatDateTime( $!info.serverDate )</dd>
   <dt>$i18n.getString( "environment_variable" ):</dt><dd>$!info.environmentVariable</dd>
   #if ( $currentUserIsSuper )
+<<<<<<< TREE
   <dt>$i18n.getString( "external_configuration_directory" ):</dt><dd>$!info.externalDirectory</dd>
   <dt>$i18n.getString( "database_type" ):</dt><dd>$!info.databaseInfo.type</dd>
   <dt>$i18n.getString( "database_name" ):</dt><dd>$!info.databaseInfo.name</dd>
@@ -22,5 +23,17 @@
   <dt>$i18n.getString( "os_version" ):</dt><dd>$!info.osVersion</dd>
   <dt>$i18n.getString( "server_memory" ):</dt><dd>$!info.memoryInfo</dd>
   <dt>$i18n.getString( "cpu_cores" ):</dt><dd>$!info.cpuCores</dd>
+=======
+  <dt>$i18n.getString( "java_opts" ):</dt><dd>$!javaOpts</dd>
+  <dt>$i18n.getString( "java_tmp_dir" ):</dt><dd>$!javaIoTmpDir</dd>
+  <dt>$i18n.getString( "java_version" ):</dt><dd>$systemProperties.get( "java.version" )</dd>
+  <dt>$i18n.getString( "java_vendor" ):</dt><dd>$systemProperties.get( "java.vendor" )</dd>
+  <dt>$i18n.getString( "os_name" ):</dt><dd>$systemProperties.get( "os.name" )</dd>
+  <dt>$i18n.getString( "os_architecture" ):</dt><dd>$systemProperties.get( "os.arch" )</dd>
+  <dt>$i18n.getString( "os_version" ):</dt><dd>$systemProperties.get( "os.version" )</dd>
+  <dt>$i18n.getString( "server_date" ):</dt><dd>$format.formatDateTime( $serverDate )</dd>
+  <dt>$i18n.getString( "server_memory" ):</dt><dd>$memoryInfo</dd>
+  <dt>$i18n.getString( "cpu_cores" ):</dt><dd>$cpuCores</dd>
+>>>>>>> MERGE-SOURCE
   #end
 </dl>
\ No newline at end of file

=== modified file 'dhis-2/dhis-web/dhis-web-commons-resources/src/main/webapp/dhis-web-commons/ouwt/ouwt.js'
--- dhis-2/dhis-web/dhis-web-commons-resources/src/main/webapp/dhis-web-commons/ouwt/ouwt.js	2013-09-09 11:23:06 +0000
+++ dhis-2/dhis-web/dhis-web-commons-resources/src/main/webapp/dhis-web-commons/ouwt/ouwt.js	2013-09-18 14:05:25 +0000
@@ -498,6 +498,7 @@
             subtree.reloadTree();
             selection.sync( false, selection.responseReceived );
         }
+<<<<<<< TREE
         else {
             $.ajax( {
                 url: '../dhis-web-commons-ajax-json/getOrganisationUnitTree.action',
@@ -517,6 +518,34 @@
             } ).fail( function() {
                 $( '#searchField' ).css( 'background-color', '#ffc5c5' );
             } );
+=======
+        else
+        {
+            $.ajax( {
+                url: '../dhis-web-commons-ajax-json/getOrganisationUnitTree.action',
+                data: { byName: name }
+            } ).done(function(data) {
+                if ( data.realRoot === undefined ) {
+                    if ( sessionStorage["organisationUnits"] === undefined )
+                    {
+                        sessionStorage["organisationUnits"] = JSON.stringify( data.organisationUnits );
+                    }
+                    else
+                    {
+                        var units = JSON.parse( sessionStorage["organisationUnits"] );
+                        $.extend(units, data.organisationUnits);
+                        sessionStorage["organisationUnits"] = JSON.stringify( units );
+                    }
+
+                    $.extend(organisationUnits, data.organisationUnits);
+                    selection.findByName();
+                }
+
+                $( '#searchField' ).css( 'background-color', '#ffc5c5' );
+            } ).fail(function() {
+                $( '#searchField' ).css( 'background-color', '#ffc5c5' );
+            });
+>>>>>>> MERGE-SOURCE
         }
     };
 
@@ -665,6 +694,7 @@
         }
     }
 
+<<<<<<< TREE
     this.ajaxGetChildren = function( parentId ) {
         return $.post( '../dhis-web-commons-ajax-json/getOrganisationUnitTree.action?parentId=' + parentId );
     };
@@ -725,6 +755,34 @@
                     def.resolve();
                 } else {
                     subtree.getChildren( parent.id ).done( function() {
+=======
+    function getAndCreateChildren(parentTag, parent)
+    {
+        if ( parent.c !== undefined )
+        {
+            if ( organisationUnits[parent.c[0]] !== undefined )
+            {
+                createChildren( parentTag, parent );
+            }
+            else
+            {
+                $.post( '../dhis-web-commons-ajax-json/getOrganisationUnitTree.action?parentId=' + parent.id,
+                function ( data, textStatus, jqXHR )
+                    {
+                        // load additional organisationUnits into sessionStorage
+                        if ( sessionStorage["organisationUnits"] === undefined )
+                        {
+                            sessionStorage["organisationUnits"] = JSON.stringify( data.organisationUnits );
+                        } 
+                        else 
+                        {
+                            var units = JSON.parse( sessionStorage["organisationUnits"] );
+                            $.extend(units, data.organisationUnits);
+                            sessionStorage["organisationUnits"] = JSON.stringify( units );
+                        }
+
+                        $.extend(organisationUnits, data.organisationUnits);
+>>>>>>> MERGE-SOURCE
                         createChildren( parentTag, parent );
                         def.resolve();
                     } );

=== modified file 'dhis-2/dhis-web/dhis-web-commons-resources/src/main/webapp/dhis-web-commons/security/login.vm'
--- dhis-2/dhis-web/dhis-web-commons-resources/src/main/webapp/dhis-web-commons/security/login.vm	2013-07-18 09:25:33 +0000
+++ dhis-2/dhis-web/dhis-web-commons-resources/src/main/webapp/dhis-web-commons/security/login.vm	2013-09-18 14:05:25 +0000
@@ -44,12 +44,22 @@
             <form id="loginForm" action="../../dhis-web-commons-security/login.action" method="post">
                 <table>
                     <tr>
+<<<<<<< TREE
                         <td><label for="j_username">$i18n.getString( "login_username" )</label></td>
                         <td><input type="text" id="j_username" name="j_username"></td>
+=======
+                        <td><label for="j_username">Username</label></td>
+                        <td><input type="text" id="j_username" name="j_username"></td>
+>>>>>>> MERGE-SOURCE
                     </tr>
                     <tr>
+<<<<<<< TREE
                         <td><label for="j_password">$i18n.getString( "login_password" )</label></td>
                         <td><input type="password" id="j_password" name="j_password" autocomplete="off"></td>
+=======
+                        <td><label for="j_password">Password</label></td>
+                        <td><input type="password" id="j_password" name="j_password" autocomplete="off"></td>
+>>>>>>> MERGE-SOURCE
                     </tr>
                     <tr>
                         <td></td>
@@ -80,6 +90,10 @@
             <div id="notificationArea">$!{keyApplicationNotification}</div>
             #end
         </div>
+<<<<<<< TREE
         <div id="footerArea"><span>$i18n.getString( "powered_by" ) <a href="http://www.dhis2.org";>DHIS 2</a>&nbsp;&nbsp;$!{keyApplicationFooter}</div>
+=======
+        <div id="footerArea"><span>Powered by <a href="http://www.dhis2.org";>DHIS 2</a>&nbsp;&nbsp;$!{keyApplicationFooter}</div>
+>>>>>>> MERGE-SOURCE
     </body>
 </html>

=== modified file 'dhis-2/dhis-web/dhis-web-commons/src/main/java/org/hisp/dhis/about/action/AboutAction.java'
--- dhis-2/dhis-web/dhis-web-commons/src/main/java/org/hisp/dhis/about/action/AboutAction.java	2013-09-01 21:38:52 +0000
+++ dhis-2/dhis-web/dhis-web-commons/src/main/java/org/hisp/dhis/about/action/AboutAction.java	2013-09-18 14:05:25 +0000
@@ -72,7 +72,53 @@
     {
         return userAgent;
     }
-    
+<<<<<<< TREE
+    
+=======
+
+    private String environmentVariable;
+
+    public String getEnvironmentVariable()
+    {
+        return environmentVariable;
+    }
+    
+    private String javaIoTmpDir;
+
+    public String getJavaIoTmpDir()
+    {
+        return javaIoTmpDir;
+    }
+
+    private String externalDirectory;
+
+    public String getExternalDirectory()
+    {
+        return externalDirectory;
+    }
+
+    private DatabaseInfo info;
+    
+    public DatabaseInfo getInfo()
+    {
+        return info;
+    }
+    
+    private String javaOpts;
+
+    public String getJavaOpts()
+    {
+        return javaOpts;
+    }
+        
+    private Properties systemProperties;
+    
+    public Properties getSystemProperties()
+    {
+        return systemProperties;
+    }
+
+>>>>>>> MERGE-SOURCE
     private boolean currentUserIsSuper;
 
     public boolean getCurrentUserIsSuper()
@@ -92,6 +138,52 @@
         HttpServletRequest request = ServletActionContext.getRequest();
 
         userAgent = request.getHeader( ContextUtils.HEADER_USER_AGENT );
+<<<<<<< TREE
+=======
+
+        // ---------------------------------------------------------------------
+        // External directory
+        // ---------------------------------------------------------------------
+
+        environmentVariable = locationManager.getEnvironmentVariable();
+        
+        try
+        {
+            File directory = locationManager.getExternalDirectory();
+        
+            externalDirectory = directory.getAbsolutePath();
+        }
+        catch ( LocationManagerException ex )
+        {
+            externalDirectory = i18n.getString( "not_set" );
+        }
+        
+        // ---------------------------------------------------------------------
+        // Database
+        // ---------------------------------------------------------------------
+
+        info = databaseInfoProvider.getDatabaseInfo();
+        
+        try
+        {
+            javaOpts = System.getenv( "JAVA_OPTS" );
+        }
+        catch ( SecurityException ex )
+        {
+            javaOpts = i18n.getString( "unknown" );
+        }
+        
+        try
+        {
+            javaIoTmpDir = System.getProperty( "java.io.tmpdir" );
+        }
+        catch ( SecurityException ex )
+        {
+            javaOpts = i18n.getString( "unknown" );
+        }
+        
+        systemProperties = System.getProperties();
+>>>>>>> MERGE-SOURCE
         
         currentUserIsSuper = currentUserService.currentUserIsSuper();
         

=== modified file 'dhis-2/dhis-web/dhis-web-commons/src/main/java/org/hisp/dhis/commons/action/GetOrganisationUnitTreeAction.java'
--- dhis-2/dhis-web/dhis-web-commons/src/main/java/org/hisp/dhis/commons/action/GetOrganisationUnitTreeAction.java	2013-08-23 16:05:01 +0000
+++ dhis-2/dhis-web/dhis-web-commons/src/main/java/org/hisp/dhis/commons/action/GetOrganisationUnitTreeAction.java	2013-09-18 14:05:25 +0000
@@ -177,7 +177,12 @@
 
             if ( parent != null )
             {
-                organisationUnits.addAll( parent.getChildren() );
+<<<<<<< TREE
+                organisationUnits.addAll( parent.getChildren() );
+=======
+                // organisationUnits.addAll( organisationUnitService.getOrganisationUnitWithChildren( parent.getId() ) );
+                organisationUnits.addAll( parent.getChildren() );
+>>>>>>> MERGE-SOURCE
             }
 
             return "partial";

=== modified file 'dhis-2/dhis-web/dhis-web-commons/src/main/java/org/hisp/dhis/interceptor/SystemSettingInterceptor.java'
--- dhis-2/dhis-web/dhis-web-commons/src/main/java/org/hisp/dhis/interceptor/SystemSettingInterceptor.java	2013-09-18 12:45:52 +0000
+++ dhis-2/dhis-web/dhis-web-commons/src/main/java/org/hisp/dhis/interceptor/SystemSettingInterceptor.java	2013-09-18 14:05:25 +0000
@@ -86,8 +86,13 @@
         map.put( KEY_APPLICATION_TITLE, systemSettingManager.getSystemSetting( KEY_APPLICATION_TITLE, DEFAULT_APPLICATION_TITLE ) );
         map.put( KEY_APPLICATION_INTRO, systemSettingManager.getSystemSetting( KEY_APPLICATION_INTRO ) );
         map.put( KEY_APPLICATION_NOTIFICATION, systemSettingManager.getSystemSetting( KEY_APPLICATION_NOTIFICATION ) );
+<<<<<<< TREE
         map.put( KEY_APPLICATION_FOOTER, systemSettingManager.getSystemSetting( KEY_APPLICATION_FOOTER ) );
         map.put( KEY_FLAG, systemSettingManager.getSystemSetting( KEY_FLAG, DEFAULT_FLAG ) );
+=======
+        map.put( KEY_APPLICATION_FOOTER, systemSettingManager.getSystemSetting( KEY_APPLICATION_FOOTER ) );
+        map.put( KEY_FLAG, systemSettingManager.getSystemSetting( KEY_FLAG ) );
+>>>>>>> MERGE-SOURCE
         map.put( KEY_FLAG_IMAGE, systemSettingManager.getFlagImage() );
         map.put( KEY_START_MODULE, systemSettingManager.getSystemSetting( KEY_START_MODULE, DEFAULT_START_MODULE ) );
         map.put( KEY_OMIT_INDICATORS_ZERO_NUMERATOR_DATAMART, systemSettingManager.getSystemSetting( KEY_OMIT_INDICATORS_ZERO_NUMERATOR_DATAMART, false ) );

=== modified file 'dhis-2/dhis-web/dhis-web-commons/src/main/java/org/hisp/dhis/ouwt/action/GetOrganisationUnitsByNameAction.java'
=== modified file 'dhis-2/dhis-web/dhis-web-commons/src/main/resources/META-INF/dhis/beans.xml'
=== modified file 'dhis-2/dhis-web/dhis-web-commons/src/main/resources/i18n_global.properties'
--- dhis-2/dhis-web/dhis-web-commons/src/main/resources/i18n_global.properties	2013-09-18 02:45:29 +0000
+++ dhis-2/dhis-web/dhis-web-commons/src/main/resources/i18n_global.properties	2013-09-18 14:05:25 +0000
@@ -87,8 +87,13 @@
 intro_dhis-web-light=Access a mobile device optimized version of data entry, messages and analysis.
 intro_dhis-web-mobile=Access a smartphone optimized version of data entry, settings, messages.
 intro_dhis-web-dashboard-integration=Get an overview of favorite charts, reports and maps and view or write messages.
+<<<<<<< TREE
 intro_dhis-web-visualizer=Create dynamic data visualizations for data elements and indicators.
 intro_dhis-web-pivot=Generate flexible pivot tables with data aggregated in all dimensions. 
+=======
+intro_dhis-web-visualizer=Create dynamic data visualizations for data elements and indicators.
+intro_dhis-web-pivot=Generate flexible pivot tables with data arranged and aggregated in all dimensions. 
+>>>>>>> MERGE-SOURCE
 intro_dhis-web-sms=Send reminders and notifications as SMS to phones, manually or as scheduled tasks.
 intro_dhis-web-spreadsheet-reporting=Generate and import data from reports based on predefined Excel templates.
 intro_dhis-web-appmanager=Access and upload apps, which are extensions to the standard user interface.

=== added file 'dhis-2/dhis-web/dhis-web-commons/src/main/resources/i18n_global_en_GB.properties.OTHER'
=== modified file 'dhis-2/dhis-web/dhis-web-dashboard-integration/src/main/webapp/dhis-web-dashboard-integration/dashboard.vm'
--- dhis-2/dhis-web/dhis-web-dashboard-integration/src/main/webapp/dhis-web-dashboard-integration/dashboard.vm	2013-09-10 07:40:25 +0000
+++ dhis-2/dhis-web/dhis-web-dashboard-integration/src/main/webapp/dhis-web-dashboard-integration/dashboard.vm	2013-09-18 14:05:25 +0000
@@ -20,8 +20,13 @@
 var i18n_add = '$encoder.jsEscape( $i18n.getString( "add" ), "'")';
 </script>
 
+<<<<<<< TREE
 <div id="dashboardHeader"><h3>
 <a href="profile.action?id=${currentUser.uid}"><img src="../images/user_small.png"></a> &nbsp;<a href="profile.action?id=${currentUser.uid}">$encoder.htmlEncode( $currentUser.name )</a>
+=======
+<h3>
+<a href="profile.action?id=${currentUser.uid}"><img src="../images/user_small.png"></a> &nbsp;<a href="profile.action?id=${currentUser.uid}">$encoder.htmlEncode( $currentUser.name )</a>
+>>>>>>> MERGE-SOURCE
 #if( !$currentUser.profileFilled )<span class="alert">(</span><a class="alert" href="../dhis-web-commons-about/showUpdateUserProfileForm.action">$i18n.getString( "update_profile" )</a><span class="alert">)</span> #end
 &nbsp;&#8226;&nbsp; <a href="showSendFeedback.action">$i18n.getString( "write_feedback" )</a>
 #if( $messageCount > 0 )&nbsp;&#8226;&nbsp; <a class="alert" href="message.action">$messageCount #if( $messageCount > 1 )$i18n.getString( "unread_messages" )#else$i18n.getString( "unread_message" )#end</a> #end

=== added file 'dhis-2/dhis-web/dhis-web-dataentry/src/main/java/org/hisp/dhis/de/action/CheckValidationRulesAction.java'
--- dhis-2/dhis-web/dhis-web-dataentry/src/main/java/org/hisp/dhis/de/action/CheckValidationRulesAction.java	1970-01-01 00:00:00 +0000
+++ dhis-2/dhis-web/dhis-web-dataentry/src/main/java/org/hisp/dhis/de/action/CheckValidationRulesAction.java	2013-09-18 14:05:25 +0000
@@ -0,0 +1,124 @@
+package org.hisp.dhis.de.action;
+
+import com.opensymphony.xwork2.Action;
+
+import org.hisp.dhis.constant.Constant;
+import org.hisp.dhis.constant.ConstantService;
+import org.hisp.dhis.validation.ValidationRule;
+import org.hisp.dhis.validation.ValidationRuleService;
+
+import java.util.Collection;
+import java.util.Date;
+
+/**
+ * @author Stefan Börjesson
+ */
+
+public class CheckValidationRulesAction implements Action {
+
+	// -------------------------------------------------------------------------
+	// Dependencies
+	// -------------------------------------------------------------------------
+
+	private ValidationRuleService validationRuleService;
+
+	public void setValidationRuleService(
+			ValidationRuleService validationRuleService) {
+		this.validationRuleService = validationRuleService;
+	}
+
+	private ConstantService constantService;
+
+	public void setConstantService(ConstantService constantService) {
+		this.constantService = constantService;
+	}
+
+	// -------------------------------------------------------------------------
+	// Output
+	// -------------------------------------------------------------------------
+
+	private long validationRulesTs;
+
+	public long getValidationRulesTs() {
+		return this.validationRulesTs;
+	}
+
+	private int numberOfValidationRules;
+
+	public int getNumberOfValidationRules() {
+		return this.numberOfValidationRules;
+	}
+
+	private long constantsTs;
+
+	public long getConstantsTs() {
+		return constantsTs;
+	}
+
+	private int numberOfConstants;
+
+	public int getNumberOfConstants() {
+		return this.numberOfConstants;
+	}
+
+	// -------------------------------------------------------------------------
+	// Action implementation
+	// -------------------------------------------------------------------------
+
+	public String execute() {
+		this.validationRulesTs = 0;
+		this.constantsTs = 0;
+		Date lastUpdatedDate = null;
+
+		// Validation Rules
+		Collection<ValidationRule> rules = this.validationRuleService
+				.getAllValidationRules();
+
+		// Loop to get the largest timestamp from the existing validation rules
+		for (ValidationRule rule : rules) {
+			if (lastUpdatedDate != null) {
+				if (rule.getLastUpdated() != null) {
+					if (rule.getLastUpdated().after(lastUpdatedDate)) {
+						lastUpdatedDate = rule.getLastUpdated();
+					}
+				}
+			} else {
+				lastUpdatedDate = rule.getLastUpdated();
+			}
+
+		}
+		// If date is null set TS to Long.MAX_VALUE to force update as rules
+		// might have been deleted.
+		this.validationRulesTs = lastUpdatedDate == null ? Long.MAX_VALUE
+				: lastUpdatedDate.getTime();
+
+		// Setting the number of validation rules to the size of the collection
+		// returned.
+		this.numberOfValidationRules = rules.size();
+
+		// Constants
+		lastUpdatedDate = null;
+		Collection<Constant> constants = constantService.getAllConstants();
+		for (Constant constant : constants) {
+			if (lastUpdatedDate != null) {
+				if (constant.getLastUpdated() != null) {
+					if (constant.getLastUpdated().after(lastUpdatedDate)) {
+						lastUpdatedDate = constant.getLastUpdated();
+					}
+				}
+			} else {
+				lastUpdatedDate = constant.getLastUpdated();
+			}
+
+		}
+
+		this.constantsTs = lastUpdatedDate == null ? Long.MAX_VALUE
+				: lastUpdatedDate.getTime();
+
+		// Setting the number of constants to the size of the collection
+		// returned.
+		this.numberOfConstants = constants.size();
+
+		return SUCCESS;
+	}
+}

=== added file 'dhis-2/dhis-web/dhis-web-dataentry/src/main/java/org/hisp/dhis/de/action/GetValidationRulesAction.java'
--- dhis-2/dhis-web/dhis-web-dataentry/src/main/java/org/hisp/dhis/de/action/GetValidationRulesAction.java	1970-01-01 00:00:00 +0000
+++ dhis-2/dhis-web/dhis-web-dataentry/src/main/java/org/hisp/dhis/de/action/GetValidationRulesAction.java	2013-09-18 14:05:25 +0000
@@ -0,0 +1,98 @@
+package org.hisp.dhis.de.action;
+
+import java.text.DecimalFormat;
+import java.util.Collection;
+
+import org.hisp.dhis.constant.Constant;
+import org.hisp.dhis.constant.ConstantService;
+import org.hisp.dhis.expression.ExpressionService;
+import org.hisp.dhis.validation.ValidationRule;
+import org.hisp.dhis.validation.ValidationRuleService;
+
+import com.opensymphony.xwork2.Action;
+
+/**
+ * @author Stefan Börjesson
+ */
+public class GetValidationRulesAction implements Action {
+
+	private ValidationRuleService validationRuleService;
+
+	public void setValidationRuleService(
+			ValidationRuleService validationRuleService) {
+		this.validationRuleService = validationRuleService;
+	}
+	
+	
+	
+	private ConstantService constantService;
+
+    public void setConstantService( ConstantService constantService )
+    {
+        this.constantService = constantService;
+    }
+    
+    private ExpressionService expressionService;
+
+    public void setExpressionService( ExpressionService expressionService)
+    {
+        this.expressionService = expressionService;
+    }
+
+    public ExpressionService getExpressionService()
+    {
+        return this.expressionService;
+    }
+    
+	private Collection<ValidationRule> validationRules;
+
+	public void setValidationRules(Collection<ValidationRule> validationRules) {
+		this.validationRules = validationRules;
+	}
+
+	public Collection<ValidationRule> getValidationRules() {
+		return this.validationRules;
+	}
+	
+	private Collection<Constant> constants;
+	
+	public Collection<Constant> getConstants() {
+		return constants;
+	}
+
+	public void setConstants(Collection<Constant> constants) {
+		this.constants = constants;
+	}
+	
+	private DecimalFormat df;
+	
+	public DecimalFormat getDf(){
+		return this.df;
+	}
+
+	@Override
+	public String execute() throws Exception {
+		df = new DecimalFormat();
+		df.setMaximumFractionDigits(12);
+		df.setMinimumFractionDigits(0);
+		df.setMaximumFractionDigits(1);
+		df.setGroupingUsed(false);
+		
+		this.validationRules = this.validationRuleService
+				.getAllValidationRules();
+		/*for(ValidationRule rule: this.validationRules){
+			System.out.println("rule.getPeriodType().getName() = " + rule.getPeriodType().getName());
+			System.out.println("rule.getType() = " + rule.getType());
+			System.out.println("rule.getOperator().getMathematicalOperator() = " + rule.getOperator().getMathematicalOperator());
+			System.out.println("rule.getLeftSide().getDescription() = " + rule.getLeftSide().getDescription());
+		    System.out.println("rule.getLeftSide().getExpression() = " + rule.getLeftSide().getExpression());
+		    System.out.println("rule.getRightSide().getDescription() = " + rule.getRightSide().getDescription());
+		    System.out.println("rule.getRightSide().getExpression() = " + rule.getRightSide().getExpression());
+		    System.out.println("rule.getRightSide().isNullIfBlank() = " + rule.getRightSide().isNullIfBlank());
+		}*/
+		
+		this.constants = constantService.getAllConstants();
+		
+		return SUCCESS;
+	}
+}

=== modified file 'dhis-2/dhis-web/dhis-web-dataentry/src/main/java/org/hisp/dhis/de/action/LoadFormAction.java'
=== modified file 'dhis-2/dhis-web/dhis-web-dataentry/src/main/resources/META-INF/dhis/beans.xml'
--- dhis-2/dhis-web/dhis-web-dataentry/src/main/resources/META-INF/dhis/beans.xml	2012-12-14 13:46:47 +0000
+++ dhis-2/dhis-web/dhis-web-dataentry/src/main/resources/META-INF/dhis/beans.xml	2013-09-18 14:05:25 +0000
@@ -129,4 +129,17 @@
     <property name="organisationUnitService" ref="org.hisp.dhis.organisationunit.OrganisationUnitService" />
   </bean>
 
+    <bean id="org.hisp.dhis.de.action.CheckValidationRulesAction" class="org.hisp.dhis.de.action.CheckValidationRulesAction"
+          scope="prototype">
+        <property name="validationRuleService" ref="org.hisp.dhis.validation.ValidationRuleService" />
+        <property name="constantService" ref="org.hisp.dhis.constant.ConstantService" />
+    </bean>
+
+    <bean id="org.hisp.dhis.de.action.GetValidationRulesAction" class="org.hisp.dhis.de.action.GetValidationRulesAction"
+          scope="prototype">
+        <property name="validationRuleService" ref="org.hisp.dhis.validation.ValidationRuleService" />
+        <property name="constantService" ref="org.hisp.dhis.constant.ConstantService" />
+        <property name="expressionService" ref="org.hisp.dhis.expression.ExpressionService" />
+    </bean>
+
 </beans>

=== modified file 'dhis-2/dhis-web/dhis-web-dataentry/src/main/resources/struts.xml'
--- dhis-2/dhis-web/dhis-web-dataentry/src/main/resources/struts.xml	2013-07-25 09:37:43 +0000
+++ dhis-2/dhis-web/dhis-web-dataentry/src/main/resources/struts.xml	2013-09-18 14:05:25 +0000
@@ -13,7 +13,7 @@
       <result name="success" type="velocity">/main.vm</result>
       <param name="page">/dhis-web-dataentry/select.vm</param>
       <param name="menu">/dhis-web-dataentry/menu.vm</param>
-      <param name="javascripts">../dhis-web-commons/ouwt/ouwt.js,javascript/form.js,javascript/entry.js,javascript/history.js</param>
+      <param name="javascripts">../dhis-web-commons/ouwt/ouwt.js,javascript/form.js,javascript/entry.js,javascript/history.js,javascript/ruleValidation.js</param>
       <param name="stylesheets">style/dhis-web-dataentry.css</param>
       <param name="manifest">../dhis-web-commons/cacheManifest.action</param>
     </action>
@@ -97,5 +97,13 @@
       <result name="success" type="chart"></result>
     </action>
 
+      <action name="checkValidationRules" class="org.hisp.dhis.de.action.CheckValidationRulesAction">
+          <result name="success" type="velocity-json">/dhis-web-dataentry/checkValidationRules.vm</result>
+      </action>
+
+      <action name="getValidationRules" class="org.hisp.dhis.de.action.GetValidationRulesAction">
+          <result name="success" type="velocity-json">/dhis-web-dataentry/getValidationRules.vm</result>
+      </action>
+
   </package>
 </struts>

=== added file 'dhis-2/dhis-web/dhis-web-dataentry/src/main/webapp/dhis-web-dataentry/checkValidationRules.vm'
--- dhis-2/dhis-web/dhis-web-dataentry/src/main/webapp/dhis-web-dataentry/checkValidationRules.vm	1970-01-01 00:00:00 +0000
+++ dhis-2/dhis-web/dhis-web-dataentry/src/main/webapp/dhis-web-dataentry/checkValidationRules.vm	2013-09-18 14:05:25 +0000
@@ -0,0 +1,6 @@
+{
+	"validationRulesTs":"${validationRulesTs}",
+	"numberOfValidationRules":"${numberOfValidationRules}",
+	"constantsTs":"${constantsTs}",
+	"numberOfConstants":"${numberOfConstants}"
+}
\ No newline at end of file

=== added file 'dhis-2/dhis-web/dhis-web-dataentry/src/main/webapp/dhis-web-dataentry/getValidationRules.vm'
--- dhis-2/dhis-web/dhis-web-dataentry/src/main/webapp/dhis-web-dataentry/getValidationRules.vm	1970-01-01 00:00:00 +0000
+++ dhis-2/dhis-web/dhis-web-dataentry/src/main/webapp/dhis-web-dataentry/getValidationRules.vm	2013-09-18 14:05:25 +0000
@@ -0,0 +1,31 @@
+#set( $size = $validationRules.size() )
+#set( $size2 = $constants.size() )
+{ "validationRules": [
+#foreach( $value in $validationRules )
+{
+    "id":"${value.id}",
+    "description":"${value.description}",
+    "leftSide":{
+    	"expression":"${value.leftSide.expression}",
+    	"isNullIfBlank":${value.leftSide.nullIfBlank},
+    	"description":"${expressionService.getExpressionDescription($value.leftSide.expression)}"
+    },
+    "rightSide":{
+    	"expression":"${value.rightSide.expression}",
+    	"isNullIfBlank":${value.rightSide.nullIfBlank},
+    	"description":"${expressionService.getExpressionDescription($value.rightSide.expression)}"
+    },
+    "operator":"${value.operator.mathematicalOperator}",
+    "validationResult": null
+}#if( $velocityCount < $size ),#end
+#end ],
+"constants": [
+#foreach( $constant in $constants)
+{
+    "id":"${constant.id}",
+    "description":"${constant.displayName}",
+    "value":"$df.format($constant.value)",
+    "uid":"${constant.uid}"
+}#if( $velocityCount < $size2 ),#end
+#end ]
+}

=== modified file 'dhis-2/dhis-web/dhis-web-dataentry/src/main/webapp/dhis-web-dataentry/javascript/entry.js'
=== modified file 'dhis-2/dhis-web/dhis-web-dataentry/src/main/webapp/dhis-web-dataentry/javascript/form.js'
--- dhis-2/dhis-web/dhis-web-dataentry/src/main/webapp/dhis-web-dataentry/javascript/form.js	2013-09-18 09:45:24 +0000
+++ dhis-2/dhis-web/dhis-web-dataentry/src/main/webapp/dhis-web-dataentry/javascript/form.js	2013-09-18 14:05:25 +0000
@@ -222,6 +222,7 @@
 	        log( 'Meta-data loaded' );
 
 	        updateForms();
+	        updateValidationRules();
 	    }
 	} );
 }
@@ -1037,6 +1038,79 @@
     displayEntryFormCompleted();
 }
 
+function insertOfflineDataValues(dataSetId, periodId, dataValueMap){
+    var formType = dataSets[dataSetId].type;
+
+    $( '[name="entryfield"]' ).each( function( i )
+        {
+            var id = $( this ).attr( 'id' );
+
+            var split = splitFieldId( id );
+            var dataElementId = split.dataElementId;
+            var optionComboId = split.optionComboId;
+            currentOrganisationUnitId = split.organisationUnitId;
+
+            var elem = storageManager.getDataValue( dataElementId, optionComboId, periodId, currentOrganisationUnitId );
+            if (elem != null)
+            {
+                var fieldId = '#' + elem.dataElementId + '-' + elem.optionComboId + '-val';
+
+                if ( $( fieldId ).length > 0 ) // Insert for fixed input fields
+                {
+                    if ( $( fieldId ).attr( 'name' ) == 'entrytrueonly' ) {
+                        $( fieldId ).attr('checked', true);
+                    } else {
+                        $( fieldId ).val( elem.value );
+                    }
+                }
+                else // Insert for potential dynamic input fields
+                {
+                    var dataElementId = elem.dataElementId;
+                    var optionComboId = elem.optionComboId;
+
+                    var selectElementId = '#' + getDynamicSelectElementId( dataElementId );
+
+                    if ( $( selectElementId ).length == 0 )
+                    {
+                        log( 'Could not find dynamic select element for data element: ' + dataElementId );
+                        return true;
+                    }
+
+                    var code = $( selectElementId ).attr( 'id' ).split( '-' )[0];
+
+                    if ( !isDefined( code ) )
+                    {
+                        log( 'Could not find code on select element: ' + selectElementId );
+                        return true;
+                    }
+
+                    var dynamicInputId = '#' + code + '-' + optionComboId + '-dyninput';
+
+                    if ( $( dynamicInputId ).length == 0 )
+                    {
+                        log( 'Could not find find dynamic input element for option combo: ' + optionComboId );
+                        return true;
+                    }
+
+                    // Set data element in select list
+
+                    $( selectElementId ).val( dataElementId );
+
+                    // Enable input fields and set value
+
+                    $( 'input[code="' + code + '"]' ).prop( 'disabled', false );
+                    $( 'input[code="' + code + '"]' ).css( 'background-color', COLOR_WHITE );
+
+                    $( dynamicInputId ).val( elem.val );
+                }
+
+                dataValueMap[elem.dataElementId+'-'+elem.optionComboId] = elem.val
+            }
+        }
+    );
+}
+
+
 function insertDataValues()
 {
     var dataValueMap = [];
@@ -1060,6 +1134,7 @@
     $( '[name="min"]' ).html( '' );
     $( '[name="max"]' ).html( '' );
 
+<<<<<<< TREE
     $( '.entryfield' ).filter( ':disabled' ).css( 'background-color', COLOR_GREY );
     
     $.ajax( {
@@ -1119,7 +1194,68 @@
 	                if ( $( commentId ).length > 0 )
 	                {
 	                    $( commentId ).attr( 'src', '../images/comment_active.png' );
+=======
+    $( '[name="entryfield"]' ).filter( ':disabled' ).css( 'background-color', COLOR_GREY );
+    
+    // Disable and grey dynamic fields to start with and enable later
+
+    $( '[name="dyninput"]' ).prop( 'disabled', true );    
+    $( '[name="dyninput"]' ).css( 'background-color', COLOR_GREY );
+
+    //Validation if user is Online or Offline
+    if(!dhis2.availability._isAvailable){
+        insertOfflineDataValues(dataSetId, periodId, dataValueMap);
+    } else{
+        
+	    $.ajax( {
+	    	url: 'getDataValues.action',
+	    	data:
+		    {
+		        periodId : periodId,
+		        dataSetId : dataSetId,
+		        organisationUnitId : currentOrganisationUnitId,
+	            multiOrganisationUnit: multiOrganisationUnit
+		    },
+		    dataType: 'json',
+		    error: function() // offline
+		    {
+		    	insertOfflineDataValues(dataSetId, periodId, dataValueMap);
+		    	$( '#contentDiv' ).show();
+		    	$( '#completenessDiv' ).show();
+		    	$( '#infoDiv' ).hide();
+		    	
+		    },
+		    success: function( json ) // online
+		    {
+		    	if ( json.locked )
+		    	{
+		    		$( '#contentDiv' ).hide();
+		    		$( '#completenessDiv' ).hide();
+		    		setHeaderDelayMessage( i18n_dataset_is_locked );
+		    		return;
+		    	}
+		    	else
+		    	{	    		
+		    		$( '#contentDiv' ).show();
+		    		$( '#completenessDiv' ).show();
+		    	}
+		    	
+		        // Set data values, works for selects too as data value=select value
+	
+		        $.safeEach( json.dataValues, function( i, value )
+		        {
+		            var fieldId = '#' + value.id + '-val';
+	
+		            if ( $( fieldId ).length > 0 ) // Insert for fixed input fields
+		            {
+	                    if ( $( fieldId ).attr( 'name' ) == 'entrytrueonly' ) {
+	                        $( fieldId ).attr('checked', true);
+	                    } else {
+	                        $( fieldId ).val( value.val );
+	                    }
+>>>>>>> MERGE-SOURCE
 	                }
+<<<<<<< TREE
 	                else if ( $( fieldId ).length > 0 )
 	                {
 	                    $( fieldId ).css( 'border-color', COLOR_BORDER_ACTIVE )
@@ -1188,6 +1324,104 @@
             }
         }
 	} );
+=======
+		            else // Insert for potential dynamic input fields
+		            {
+	                    var split = splitFieldId( value.id );
+		                var dataElementId = split.dataElementId;
+		                var optionComboId = split.optionComboId;
+		                
+		                var selectElementId = '#' + getDynamicSelectElementId( dataElementId );
+		                
+		                if ( $( selectElementId ).length == 0 )
+		                {
+		                	log( 'Could not find dynamic select element for data element: ' + dataElementId );
+		                	return true;
+		                }
+	
+	                	var code = $( selectElementId ).attr( 'id' ).split( '-' )[0];
+	        			
+	        			if ( !isDefined( code ) )
+	        			{
+	        				log( 'Could not find code on select element: ' + selectElementId );
+	        				return true;
+	        			}
+	
+	    				var dynamicInputId = '#' + code + '-' + optionComboId + '-dyninput';
+	
+	        			if ( $( dynamicInputId ).length == 0 )
+	    				{
+	        				log( 'Could not find find dynamic input element for option combo: ' + optionComboId );
+	        				return true;
+	    				}
+	
+	        			// Set data element in select list
+	        			    		    
+	        			$( selectElementId ).val( dataElementId );
+	
+	        			// Enable input fields and set value
+	        			
+	        		    $( 'input[code="' + code + '"]' ).prop( 'disabled', false );    
+	        		    $( 'input[code="' + code + '"]' ).css( 'background-color', COLOR_WHITE );
+	        		    
+	    				$( dynamicInputId ).val( value.val );
+		            }
+	
+		            dataValueMap[value.id] = value.val;
+		        } );
+	
+		        // Set min-max values and colorize violation fields
+	
+		        $.safeEach( json.minMaxDataElements, function( i, value )
+		        {
+		            var minId = value.id + '-min';
+		            var maxId = value.id + '-max';
+	
+		            var valFieldId = '#' + value.id + '-val';
+	
+		            var dataValue = dataValueMap[value.id];
+	
+		            if ( dataValue && ( ( value.min && new Number( dataValue ) < new Number(
+		            	value.min ) ) || ( value.max && new Number( dataValue ) > new Number( value.max ) ) ) )
+		            {
+		                $( valFieldId ).css( 'background-color', COLOR_ORANGE );
+		            }
+	
+		            currentMinMaxValueMap[minId] = value.min;
+		            currentMinMaxValueMap[maxId] = value.max;
+		        } );
+	
+		        // Update indicator values in form
+	
+		        updateIndicators();
+		        updateDataElementTotals();
+	
+		        // Set completeness button
+	
+		        if ( json.complete )
+		        {
+		            $( '#completeButton' ).attr( 'disabled', 'disabled' );
+		            $( '#undoButton' ).removeAttr( 'disabled' );
+	
+		            if ( json.storedBy )
+		            {
+		                $( '#infoDiv' ).show();
+		                $( '#completedBy' ).html( json.storedBy );
+		                $( '#completedDate' ).html( json.date );
+	
+		                currentCompletedByUser = json.storedBy;
+		            }
+		        }
+		        else
+		        {
+		            $( '#completeButton' ).removeAttr( 'disabled' );
+		            $( '#undoButton' ).attr( 'disabled', 'disabled' );
+		            $( '#infoDiv' ).hide();
+		        }
+		    }
+		} );
+    }
+>>>>>>> MERGE-SOURCE
 }
 
 function displayEntryFormCompleted()
@@ -1427,6 +1661,30 @@
     } );
 }
 
+
+function validate_offline( ignoreSuccessfulValidation, successCallback)
+{
+	var success = true;
+	var response = runOfflineValidations(ignoreSuccessfulValidation);
+	
+	if(response == ''){
+		var successHtml = '<h3>' + i18n_validation_result + ' &nbsp;<img src="../images/success_small.png"></h3>' +
+		'<p class="bold">' + i18n_successful_validation + '</p>';
+		if(!ignoreSuccessfulValidation){
+			displayValidationDialog( successHtml, 200 );
+		}
+	} else{
+		success = false;
+		displayValidationDialog( response, 500 );
+	}
+	
+	
+	if ( success && $.isFunction( successCallback ) )
+    {
+    	successCallback.call();
+    }
+}
+
 function validate( ignoreSuccessfulValidation, successCallback )
 {
 	var compulsoryCombinationsValid = validateCompulsoryCombinations();
@@ -1454,13 +1712,24 @@
 	    params['organisationUnitId'] = getCurrentOrganisationUnit();
         params['multiOrganisationUnit'] = multiOrganisationUnit;
 
+    if(!dhis2.availability._isAvailable)
+    {
+    	success = validate_offline( ignoreSuccessfulValidation, successCallback);
+    }
+    else
+    {
     $( '#validationDiv' ).load( 'validate.action', params, function( response, status, xhr ) {
     	var success = null;
     	
         if ( status == 'error' && !ignoreSuccessfulValidation )
         {
-            window.alert( i18n_operation_not_available_offline );
-            success = true;  // Accept if offline
+            //window.alert( i18n_operation_not_available_offline );
+            //success = true;  // Accept if offline
+        	success = validate_offline( ignoreSuccessfulValidation, successCallback);
+        	if ( success && $.isFunction( successCallback ) )
+            {
+            	successCallback.call();
+            }
         }
         else
         {
@@ -1482,6 +1751,7 @@
         	successCallback.call();
         }
     } );
+    }
 }
 
 function validateCompulsoryCombinations()
@@ -1637,6 +1907,49 @@
     } );
 }
 
+//-----------------------------------------------------------------------------
+//Local storage of Validation Rules
+//-----------------------------------------------------------------------------
+
+function updateValidationRules()
+{
+	log("Before checkValidationRules.action");
+	$.ajax( {
+        url: 'checkValidationRules.action',
+        dataType: 'json',
+        success: function( data, textStatus, jqXHR )
+        {
+        	var validationRulesControl = data; 
+        	var localValidationRulesControl = storageManager.getValidationRulesControl();
+
+        	if(localValidationRulesControl.validationRulesTs != validationRulesControl.validationRulesTs || 
+            		localValidationRulesControl.numberOfValidationRules != validationRulesControl.numberOfValidationRules ||
+            		localValidationRulesControl.constantsTs != validationRulesControl.constantsTs ||
+            		localValidationRulesControl.numberOfConstants != validationRulesControl.numberOfConstants){
+            	
+            	storageManager.purgeValidationRules();
+            	storageManager.purgeConstants();
+
+            	$.ajax( {
+                    url: 'getValidationRules.action',
+                    dataType: 'json',
+                    success: function( data, textStatus, jqXHR )
+                    {
+                    	storageManager.saveValidationRules(data);
+                    	storageManager.saveConstants(data);
+                    	storageManager.saveValidationRulesControl(validationRulesControl);
+                    }
+                } );
+            } 
+            else
+            {
+            	log("Validation rules in localstorage are up to date.");
+            }
+        }
+    } );
+}
+
+
 // TODO break if local storage is full
 
 // -----------------------------------------------------------------------------
@@ -1656,6 +1969,9 @@
     var KEY_FORM_VERSIONS = 'formversions';
     var KEY_DATAVALUES = 'datavalues';
     var KEY_COMPLETEDATASETS = 'completedatasets';
+    var KEY_VALIDATIONRULESCONTROL = 'validationrulescontrol';
+    var KEY_VALIDATIONRULE = 'validationrule-';
+    var KEY_CONSTANT = 'validationrulesconstants';
 
     /**
      * Returns the total number of characters currently in the local storage.
@@ -2145,6 +2461,179 @@
 
         return true;
     };
+    
+    
+    /**
+     * Method to retrive the timestamp of the validation rules in localstorage.
+     *
+     * @return The timestamp of the validation rules in localstorage.
+     */
+    
+    
+    this.getValidationRulesControl = function()
+    {
+    	var validationRuleControl = localStorage[KEY_VALIDATIONRULESCONTROL];
+    	if(validationRuleControl == null)
+    	{
+    		validationRuleControl = new Object();
+    		validationRuleControl.validationRulesTs = 0;
+    		validationRuleControl.numberOfValidationRules = 0;
+    		validationRuleControl.constantsTs = 0;
+    		validationRuleControl.numberOfValidationConstants = 0;
+    		return 0;
+    	} 
+    	else
+    	{
+    		return JSON.parse(validationRuleControl);
+    	}
+    	
+    };
+
+    /**
+     * Method to save a new timestamp of the validation rules in localstorage.
+     *
+     * @param The timestamp to be saved.
+     */
+    
+    this.saveValidationRulesControl = function(newValidationRulesControl)
+    {
+    	try
+    	{
+    		localStorage[KEY_VALIDATIONRULESCONTROL] = JSON.stringify(newValidationRulesControl);
+    	} 
+    	catch ( e )
+    	{
+    		log( 'Max local storage quota reached, validation rule timestamp not saved locally.');
+    		return false;
+    	}
+    	return true;
+    };
+    
+   
+    /**
+     * Method that purges the validation rules stored in localstorage.
+     *
+     */
+    
+    this.purgeValidationRules = function()
+    {
+    	for ( var i = 0; i < localStorage.length; i++ )
+        {
+            var key = localStorage.key( i );
+
+            if ( key.substring( 0, KEY_VALIDATIONRULE.length) == KEY_VALIDATIONRULE)
+            {
+            	localStorage.removeItem(key);
+            }
+        }
+    };
+    
+    
+    /**
+     * Method that purges the validation rules stored in localstorage.
+     * @param json The json object containing the new validation rules
+     */
+    
+    this.saveValidationRules = function(json)
+    {
+    	validationRules = json.validationRules;
+    	for(var i = 0; i < validationRules.length; i++)
+    	{
+    		try
+    		{
+    			localStorage[KEY_VALIDATIONRULE + validationRules[i].id] = JSON.stringify(validationRules[i]);
+        	} 
+        	catch ( e )
+        	{
+        		log( 'Max local storage quota reached, ignored validation rule: ' + validationRules[i].id );
+        		return false;
+        	}
+    	}
+    	return true;
+    };
+    
+    /**
+     * Method that returns all validation rules from localstorage.
+     * @return An object contining all validation rules.
+     */
+    
+    this.getValidationRules = function()
+    {
+    	var validationRules = [];
+
+        var validationRuleIndex = 0;
+
+    	for ( var i = 0; i < localStorage.length; i++ )
+        {
+            var key = localStorage.key( i );
+
+            if ( key.substring( 0, KEY_VALIDATIONRULE.length) == KEY_VALIDATIONRULE)
+            {
+            	validationRules[validationRuleIndex++] = JSON.parse(localStorage[key]);
+            }
+        }
+        return validationRules;
+    };
+    
+    
+    
+    /**
+     * Method that purges the constants stored in localstorage.
+     *
+     */
+    
+    this.purgeConstants = function()
+    {
+    	for ( var i = 0; i < localStorage.length; i++ )
+        {
+            var key = localStorage.key( i );
+
+            if ( key.substring( 0, KEY_CONSTANT.length) == KEY_CONSTANT)
+            {
+            	localStorage.removeItem(key);
+            }
+        }
+    };
+    
+    
+    /**
+     * Method that saves constants in localstorage.
+     * @param json The json object containing the new constnats
+     */
+    
+    this.saveConstants = function(json)
+    {
+    	constants = json.constants;
+    	if(constants != null){
+    		try
+    		{
+    			localStorage[KEY_CONSTANT] = JSON.stringify(constants);
+        	} 
+        	catch ( e )
+        	{
+        		log( 'Max local storage quota reached, ignored constants: ' + constants);
+        		return false;
+        	}
+    	}
+    	return true;
+    };
+    
+    /**
+     * Method that returns all constants localstorage.
+     * @return An object contining all constants.
+     */
+    
+    this.getConstants = function()
+    {
+    	var constants = [];
+    	if (localStorage[KEY_CONSTANT] != null){
+    		constants = JSON.parse(localStorage[KEY_CONSTANT]);
+    	}
+    	
+        return constants;
+    };
+    
+    
 }
 
 // -----------------------------------------------------------------------------

=== added file 'dhis-2/dhis-web/dhis-web-dataentry/src/main/webapp/dhis-web-dataentry/javascript/ruleValidation.js'
--- dhis-2/dhis-web/dhis-web-dataentry/src/main/webapp/dhis-web-dataentry/javascript/ruleValidation.js	1970-01-01 00:00:00 +0000
+++ dhis-2/dhis-web/dhis-web-dataentry/src/main/webapp/dhis-web-dataentry/javascript/ruleValidation.js	2013-09-18 14:05:25 +0000
@@ -0,0 +1,1468 @@
+
+/*
+ Based on ndef.parser, by Raphael Graf(r@xxxxxxxxxxxx)
+ http://www.undefined.ch/mparser/index.html
+
+ Ported to JavaScript and modified by Matthew Crumley (email@xxxxxxxxxxxxxxxxxx, http://silentmatt.com/)
+
+ Modified by Stefan Börjesson to correspond to the functionality in the JAVA JEP library's standard function set.
+ 
+*/
+
+//  Added by stlsmiths 6/13/2011
+//  re-define Array.indexOf, because IE doesn't know it ...
+//
+//  from http://stellapower.net/content/javascript-support-and-arrayindexof-ie
+
+
+/*if (!Array.indexOf) {
+	Array.prototype.indexOf = function (obj, start) {
+		for (var i = (start || 0); i < this.length; i++) {
+			if (this[i] === obj) {
+				return i;
+			}
+		}
+		return -1;
+	}
+}*/
+
+	
+var Parser = (function (scope)
+{
+	function object(o)
+	{
+		function F() {}
+		F.prototype = o;
+		return new F();
+	}
+
+	var TNUMBER = 0;
+	var TOP1 = 1;
+	var TOP2 = 2;
+	var TVAR = 3;
+	var TFUNCALL = 4;
+
+	function Token(type_, index_, prio_, number_)
+	{
+		this.type_ = type_;
+		this.index_ = index_ || 0;
+		this.prio_ = prio_ || 0;
+		this.number_ = (number_ !== undefined && number_ !== null) ? number_ : 0;
+		this.toString = function ()
+		{
+			switch (this.type_)
+			{
+				case TNUMBER:
+					return this.number_;
+				case TOP1:
+				case TOP2:
+				case TVAR:
+					return this.index_;
+				case TFUNCALL:
+					return "CALL";
+				default:
+					return "Invalid Token";
+			}
+		};
+	}
+
+	function Expression(tokens, ops1, ops2, functions) {
+		this.tokens = tokens;
+		this.ops1 = ops1;
+		this.ops2 = ops2;
+		this.functions = functions;
+	}
+
+	// Based on http://www.json.org/json2.js
+    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
+        escapable = /[\\\'\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
+        meta = {    // table of character substitutions
+            '\b': '\\b',
+            '\t': '\\t',
+            '\n': '\\n',
+            '\f': '\\f',
+            '\r': '\\r',
+            "'" : "\\'",
+            '\\': '\\\\'
+        };
+
+	function escapeValue(v) 
+	{
+		if (typeof v === "string") 
+		{
+			escapable.lastIndex = 0;
+	        return escapable.test(v) ?
+	            "'" + v.replace(escapable, function (a) {
+	                var c = meta[a];
+	                return typeof c === 'string' ? c :
+	                    '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
+	            }) + "'" :
+	            "'" + v + "'";
+		}
+		return v;
+	}
+
+	Expression.prototype = {
+		simplify: function (values) {
+			values = values || {};
+			var nstack = [];
+			var newexpression = [];
+			var n1;
+			var n2;
+			var f;
+			var L = this.tokens.length;
+			var item;
+			var i = 0;
+			for (i = 0; i < L; i++) 
+			{
+				item = this.tokens[i];
+				var type_ = item.type_;
+				if (type_ === TNUMBER) 
+				{
+					nstack.push(item);
+				}
+				else if (type_ === TVAR && (item.index_ in values)) 
+				{
+					item = new Token(TNUMBER, 0, 0, values[item.index_]);
+					nstack.push(item);
+				}
+				else if (type_ === TOP2 && nstack.length > 1) 
+				{
+					n2 = nstack.pop();
+					n1 = nstack.pop();
+					f = this.ops2[item.index_];
+					item = new Token(TNUMBER, 0, 0, f(n1.number_, n2.number_));
+					nstack.push(item);
+				}
+				else if (type_ === TOP1 && nstack.length > 0) 
+				{
+					n1 = nstack.pop();
+					f = this.ops1[item.index_];
+					item = new Token(TNUMBER, 0, 0, f(n1.number_));
+					nstack.push(item);
+				}
+				else 
+				{
+					while (nstack.length > 0) 
+					{
+						newexpression.push(nstack.shift());
+					}
+					newexpression.push(item);
+				}
+			}
+			while (nstack.length > 0) 
+			{
+				newexpression.push(nstack.shift());
+			}
+
+			return new Expression(newexpression, object(this.ops1), object(this.ops2), object(this.functions));
+		},
+
+		substitute: function (variable, expr) {
+			if (!(expr instanceof Expression)) 
+			{
+				expr = new Parser().parse(String(expr));
+			}
+			var newexpression = [];
+			var L = this.tokens.length;
+			var item;
+			var i = 0;
+			for (i = 0; i < L; i++) 
+			{
+				item = this.tokens[i];
+				var type_ = item.type_;
+				if (type_ === TVAR && item.index_ === variable) 
+				{
+					for (var j = 0; j < expr.tokens.length; j++) 
+					{
+						var expritem = expr.tokens[j];
+						var replitem = new Token(expritem.type_, expritem.index_, expritem.prio_, expritem.number_);
+						newexpression.push(replitem);
+					}
+				}
+				else 
+				{
+					newexpression.push(item);
+				}
+			}
+
+			var ret = new Expression(newexpression, object(this.ops1), object(this.ops2), object(this.functions));
+			return ret;
+		},
+
+		evaluate: function (values) {
+			values = values || {};
+			var nstack = [];
+			var n1;
+			var n2;
+			var f;
+			var L = this.tokens.length;
+			var item;
+			var i = 0;
+			for (i = 0; i < L; i++) 
+			{
+				item = this.tokens[i];
+				var type_ = item.type_;
+				if (type_ === TNUMBER) 
+				{
+					nstack.push(item.number_);
+				}
+				else if (type_ === TOP2) 
+				{
+					n2 = nstack.pop();
+					n1 = nstack.pop();
+					f = this.ops2[item.index_];
+					nstack.push(f(n1, n2));
+				}
+				else if (type_ === TVAR) 
+				{
+					if (item.index_ in values) 
+					{
+						nstack.push(values[item.index_]);
+					}
+					else if (item.index_ in this.functions) 
+					{
+						nstack.push(this.functions[item.index_]);
+					}
+					else 
+					{
+						throw new Error("undefined variable: " + item.index_);
+					}
+				}
+				else if (type_ === TOP1) 
+				{
+					n1 = nstack.pop();
+					f = this.ops1[item.index_];
+					nstack.push(f(n1));
+				}
+				else if (type_ === TFUNCALL) 
+				{
+					n1 = nstack.pop();
+					f = nstack.pop();
+					if (f.apply && f.call) 
+					{
+						if (Object.prototype.toString.call(n1) == "[object Array]") 
+						{
+							nstack.push(f.apply(undefined, n1));
+						}
+						else 
+						{
+							nstack.push(f.call(undefined, n1));
+						}
+					}
+					else 
+					{
+						throw new Error(f + " is not a function");
+					}
+				}
+				else 
+				{
+					throw new Error("invalid Expression");
+				}
+			}
+			if (nstack.length > 1) 
+			{
+				throw new Error("invalid Expression (parity)");
+			}
+			return nstack[0];
+		},
+
+		toString: function (toJS) {
+			var nstack = [];
+			var n1;
+			var n2;
+			var f;
+			var L = this.tokens.length;
+			var item;
+			var i = 0;
+			for (i = 0; i < L; i++) 
+			{
+				item = this.tokens[i];
+				var type_ = item.type_;
+				if (type_ === TNUMBER) 
+				{
+					nstack.push(escapeValue(item.number_));
+				}
+				else if (type_ === TOP2) 
+				{
+					n2 = nstack.pop();
+					n1 = nstack.pop();
+					f = item.index_;
+					if (toJS && f == "^") 
+					{
+						nstack.push("Math.pow(" + n1 + "," + n2 + ")");
+					}
+					else {
+						nstack.push("(" + n1 + f + n2 + ")");
+					}
+				}
+				else if (type_ === TVAR) 
+				{
+					nstack.push(item.index_);
+				}
+				else if (type_ === TOP1) 
+				{
+					n1 = nstack.pop();
+					f = item.index_;
+					if (f === "-") 
+					{
+						nstack.push("(" + f + n1 + ")");
+					}
+					else 
+					{
+						nstack.push(f + "(" + n1 + ")");
+					}
+				}
+				else if (type_ === TFUNCALL) 
+				{
+					n1 = nstack.pop();
+					f = nstack.pop();
+					nstack.push(f + "(" + n1 + ")");
+				}
+				else 
+				{
+					throw new Error("invalid Expression");
+				}
+			}
+			if (nstack.length > 1) 
+			{
+				throw new Error("invalid Expression (parity)");
+			}
+			return nstack[0];
+		},
+
+		variables: function () {
+			var L = this.tokens.length;
+			var vars = [];
+			for (var i = 0; i < L; i++) 
+			{
+				var item = this.tokens[i];
+				if (item.type_ === TVAR && (vars.indexOf(item.index_) == -1)) {
+					vars.push(item.index_);
+				}
+			}
+
+			return vars;
+		},
+
+		toJSFunction: function (param, variables) {
+			var f = new Function(param, "with(Parser.values) { return " + this.simplify(variables).toString(true) + "; }");
+			return f;
+		}
+	};
+
+	function add(a, b) 
+	{
+		return Number(a) + Number(b);
+	}
+	
+	function sub(a, b) 
+	{
+		return a - b; 
+	}
+	
+	function mul(a, b) 
+	{
+		return a * b;
+	}
+	
+	function div(a, b) 
+	{
+		return a / b;
+	}
+	
+	function mod(a, b) 
+	{
+		return a % b;
+	}
+	
+	function sum(a, b, c) 
+	{
+		return a+b+c;
+	}
+	
+	function concat(a, b) 
+	{
+		return "" + a + b;
+	}
+
+	function neg(a) 
+	{
+		return -a;
+	}
+
+	function random() 
+	{
+		return Math.random();
+	}
+
+	function fac(a) //a!
+	{ 
+		a = Math.floor(a);
+		var b = a;
+		while (a > 1) 
+		{
+			b = b * (--a);
+		}
+		return b;
+	}
+
+	function pyt(a, b) 
+	{
+		return Math.sqrt(a * a + b * b);
+	}
+	
+	function log10(a) 
+	{
+		return Math.log(a) / Math.LN10;
+	}
+	
+	function sinh(a)
+	{
+		var myTerm1 = Math.pow(Math.E, a);
+		var myTerm2 = Math.pow(Math.E, -a);
+
+		return (myTerm1-myTerm2)/2;
+	}
+	
+	function cosh(a)
+	{
+		var myTerm1 = Math.pow(Math.E, a);
+		var myTerm2 = Math.pow(Math.E, -a);
+
+		return (myTerm1+myTerm2)/2;
+	}
+	
+	function tanh (a) 
+	{
+		return (Math.exp(a)-Math.exp(-a))/(Math.exp(a)+Math.exp(-a));
+	}
+	
+	function asinh(a) 
+	{
+		return Math.log(a + Math.sqrt(a*a + 1));
+	}
+	
+	function acosh (a) 
+	{
+		return Math.log(a+Math.sqrt(a*a-1));
+	}
+	
+	function atanh (a) 
+	{
+		return 0.5*Math.log((1+a)/(1-a));
+	}
+	
+	function binom(n, k) 
+	{
+		var coeff = 1;
+		for (var i = n-k+1; i <= n; i++) coeff *= i;
+		for (var i = 1;     i <= k; i++) coeff /= i;
+		return coeff;
+	}
+
+	function append(a, b) 
+	{
+		if (Object.prototype.toString.call(a) != "[object Array]") 
+		{
+			return [a, b];
+		}
+		a = a.slice();
+		a.push(b);
+		return a;
+	}
+
+	function Parser()
+	{
+		this.success = false;
+		this.errormsg = "";
+		this.expression = "";
+
+		this.pos = 0;
+
+		this.tokennumber = 0;
+		this.tokenprio = 0;
+		this.tokenindex = 0;
+		this.tmpprio = 0;
+
+		this.ops1 = {
+			"sin": Math.sin, //In JEP
+			"cos": Math.cos, //In JEP
+			"tan": Math.tan, //In JEP
+			"asin": Math.asin, //In JEP
+			"acos": Math.acos, //In JEP
+			"atan": Math.atan, //In JEP
+			"sinh": sinh, //In JEP
+			"cosh": cosh, //In JEP
+			"tanh": tanh, //In JEP
+			"asinh": asinh, //In JEP
+			"acosh": acosh, //In JEP
+			"exp": Math.exp, //In JEP
+			"sqrt": Math.sqrt, //In JEP
+			"ln": Math.log, //In JEP
+			"log": log10, //In JEP
+			"abs": Math.abs, //In JEP
+			"ceil": Math.ceil,
+			"floor": Math.floor,
+			"round": Math.round,
+			"-": neg
+			
+		};
+
+		this.ops2 = {
+			"+": add,
+			"-": sub,
+			"*": mul,
+			"/": div,
+			"%": mod,
+			"^": Math.pow,
+			",": append,
+			"||": concat
+		};
+
+		this.functions = 
+		{
+			"rand": random, //In JEP
+			"fac": fac,
+			"min": Math.min,
+			"max": Math.max,
+			"pyt": pyt,
+			"pow": Math.pow,
+			"mod": mod, //In JEP
+			"sum": sum, //In JEP
+			"binom" : binom, //In JEP
+			"atan2": Math.atan2
+		};
+
+		this.consts = 
+		{
+			"E": Math.E,
+			"PI": Math.PI
+		};
+	}
+
+	Parser.parse = function (expr) 
+	{
+		return new Parser().parse(expr);
+	};
+
+	Parser.evaluate = function (expr, variables) 
+	{
+		return Parser.parse(expr).evaluate(variables);
+	};
+
+	Parser.Expression = Expression;
+
+	Parser.values = {
+		sin: Math.sin,
+		cos: Math.cos,
+		tan: Math.tan,
+		asin: Math.asin,
+		acos: Math.acos,
+		atan: Math.atan,
+		sqrt: Math.sqrt,
+		log: Math.log,
+		abs: Math.abs,
+		ceil: Math.ceil,
+		floor: Math.floor,
+		round: Math.round,
+		random: random,
+		fac: fac,
+		exp: Math.exp,
+		min: Math.min,
+		max: Math.max,
+		pyt: pyt,
+		pow: Math.pow,
+		atan2: Math.atan2,
+		E: Math.E,
+		PI: Math.PI
+	};
+
+	var PRIMARY      = 1 << 0;
+	var OPERATOR     = 1 << 1;
+	var FUNCTION     = 1 << 2;
+	var LPAREN       = 1 << 3;
+	var RPAREN       = 1 << 4;
+	var COMMA        = 1 << 5;
+	var SIGN         = 1 << 6;
+	var CALL         = 1 << 7;
+	var NULLARY_CALL = 1 << 8;
+
+	Parser.prototype = {
+		parse: function (expr) {
+			this.errormsg = "";
+			this.success = true;
+			var operstack = [];
+			var tokenstack = [];
+			this.tmpprio = 0;
+			var expected = (PRIMARY | LPAREN | FUNCTION | SIGN);
+			var noperators = 0;
+			this.expression = expr;
+			this.pos = 0;
+
+			while (this.pos < this.expression.length) 
+			{
+				if (this.isOperator()) 
+				{
+					if (this.isSign() && (expected & SIGN)) 
+					{
+						if (this.isNegativeSign()) 
+						{
+							this.tokenprio = 2;
+							this.tokenindex = "-";
+							noperators++;
+							this.addfunc(tokenstack, operstack, TOP1);
+						}
+						expected = (PRIMARY | LPAREN | FUNCTION | SIGN);
+					}
+					else if (this.isComment()) 
+					{
+
+					}
+					else 
+					{
+						if ((expected & OPERATOR) === 0) 
+						{
+							this.error_parsing(this.pos, "unexpected operator");
+						}
+						noperators += 2;
+						this.addfunc(tokenstack, operstack, TOP2);
+						expected = (PRIMARY | LPAREN | FUNCTION | SIGN);
+					}
+				}
+				else if (this.isNumber()) 
+				{
+					if ((expected & PRIMARY) === 0) 
+					{
+						this.error_parsing(this.pos, "unexpected number");
+					}
+					var token = new Token(TNUMBER, 0, 0, this.tokennumber);
+					tokenstack.push(token);
+
+					expected = (OPERATOR | RPAREN | COMMA);
+				}
+				else if (this.isString()) 
+				{
+					if ((expected & PRIMARY) === 0) 
+					{
+						this.error_parsing(this.pos, "unexpected string");
+					}
+					var token = new Token(TNUMBER, 0, 0, this.tokennumber);
+					tokenstack.push(token);
+
+					expected = (OPERATOR | RPAREN | COMMA);
+				}
+				else if (this.isLeftParenth()) 
+				{
+					if ((expected & LPAREN) === 0) 
+					{
+						this.error_parsing(this.pos, "unexpected \"(\"");
+					}
+
+					if (expected & CALL) 
+					{
+						noperators += 2;
+						this.tokenprio = -2;
+						this.tokenindex = -1;
+						this.addfunc(tokenstack, operstack, TFUNCALL);
+					}
+
+					expected = (PRIMARY | LPAREN | FUNCTION | SIGN | NULLARY_CALL);
+				}
+				else if (this.isRightParenth()) 
+				{
+				    if (expected & NULLARY_CALL) 
+					{
+						var token = new Token(TNUMBER, 0, 0, []);
+						tokenstack.push(token);
+					}
+					else if ((expected & RPAREN) === 0) 
+					{
+						this.error_parsing(this.pos, "unexpected \")\"");
+					}
+
+					expected = (OPERATOR | RPAREN | COMMA | LPAREN | CALL);
+				}
+				else if (this.isComma()) 
+				{
+					if ((expected & COMMA) === 0) 
+					{
+						this.error_parsing(this.pos, "unexpected \",\"");
+					}
+					this.addfunc(tokenstack, operstack, TOP2);
+					noperators += 2;
+					expected = (PRIMARY | LPAREN | FUNCTION | SIGN);
+				}
+				else if (this.isConst()) 
+				{
+					if ((expected & PRIMARY) === 0) 
+					{
+						this.error_parsing(this.pos, "unexpected constant");
+					}
+					var consttoken = new Token(TNUMBER, 0, 0, this.tokennumber);
+					tokenstack.push(consttoken);
+					expected = (OPERATOR | RPAREN | COMMA);
+				}
+				else if (this.isOp2()) 
+				{
+					if ((expected & FUNCTION) === 0) 
+					{
+						this.error_parsing(this.pos, "unexpected function");
+					}
+					this.addfunc(tokenstack, operstack, TOP2);
+					noperators += 2;
+					expected = (LPAREN);
+				}
+				else if (this.isOp1()) 
+				{
+					if ((expected & FUNCTION) === 0) 
+					{
+						this.error_parsing(this.pos, "unexpected function");
+					}
+					this.addfunc(tokenstack, operstack, TOP1);
+					noperators++;
+					expected = (LPAREN);
+				}
+				else if (this.isVar()) 
+				{
+					if ((expected & PRIMARY) === 0) 
+					{
+						this.error_parsing(this.pos, "unexpected variable");
+					}
+					var vartoken = new Token(TVAR, this.tokenindex, 0, 0);
+					tokenstack.push(vartoken);
+
+					expected = (OPERATOR | RPAREN | COMMA | LPAREN | CALL);
+				}
+				else if (this.isWhite()) 
+				{
+				}
+				else 
+				{
+					if (this.errormsg === "") 
+					{
+						this.error_parsing(this.pos, "unknown character");
+					}
+					else 
+					{
+						this.error_parsing(this.pos, this.errormsg);
+					}
+				}
+			}
+			if (this.tmpprio < 0 || this.tmpprio >= 10) 
+			{
+				this.error_parsing(this.pos, "unmatched \"()\"");
+			}
+			while (operstack.length > 0) 
+			{
+				var tmp = operstack.pop();
+				tokenstack.push(tmp);
+			}
+			if (noperators + 1 !== tokenstack.length) 
+			{
+				this.error_parsing(this.pos, "parity");
+			}
+
+			return new Expression(tokenstack, object(this.ops1), object(this.ops2), object(this.functions));
+		},
+
+		evaluate: function (expr, variables) 
+		{
+			return this.parse(expr).evaluate(variables);
+		},
+
+		error_parsing: function (column, msg) 
+		{
+			this.success = false;
+			this.errormsg = "parse error [column " + (column) + "]: " + msg;
+			throw new Error(this.errormsg);
+		},
+
+		addfunc: function (tokenstack, operstack, type_) {
+			var operator = new Token(type_, this.tokenindex, this.tokenprio + this.tmpprio, 0);
+			while (operstack.length > 0) 
+			{
+				if (operator.prio_ <= operstack[operstack.length - 1].prio_) 
+				{
+					tokenstack.push(operstack.pop());
+				}
+				else 
+				{
+					break;
+				}
+			}
+			operstack.push(operator);
+		},
+
+		isNumber: function () {
+			var r = false;
+			var str = "";
+			while (this.pos < this.expression.length) 
+			{
+				var code = this.expression.charCodeAt(this.pos);
+				if ((code >= 48 && code <= 57) || code === 46) 
+				{
+					str += this.expression.charAt(this.pos);
+					this.pos++;
+					this.tokennumber = parseFloat(str);
+					r = true;
+				}
+				else 
+				{
+					break;
+				}
+			}
+			return r;
+		},
+
+		unescape: function(v, pos) {
+			var buffer = [];
+			var escaping = false;
+
+			for (var i = 0; i < v.length; i++) 
+			{
+				var c = v.charAt(i);
+
+				if (escaping) 
+				{
+					switch (c) 
+					{
+					case "'":
+						buffer.push("'");
+						break;
+					case '\\':
+						buffer.push('\\');
+						break;
+					case '/':
+						buffer.push('/');
+						break;
+					case 'b':
+						buffer.push('\b');
+						break;
+					case 'f':
+						buffer.push('\f');
+						break;
+					case 'n':
+						buffer.push('\n');
+						break;
+					case 'r':
+						buffer.push('\r');
+						break;
+					case 't':
+						buffer.push('\t');
+						break;
+					case 'u':
+						// interpret the following 4 characters as the hex of the unicode code point
+						var codePoint = parseInt(v.substring(i + 1, i + 5), 16);
+						buffer.push(String.fromCharCode(codePoint));
+						i += 4;
+						break;
+					default:
+						throw this.error_parsing(pos + i, "Illegal escape sequence: '\\" + c + "'");
+					}
+					escaping = false;
+				} 
+				else 
+				{
+					if (c == '\\') 
+					{
+						escaping = true;
+					} 
+					else 
+					{
+						buffer.push(c);
+					}
+				}
+			}
+
+			return buffer.join('');
+		},
+
+		isString: function () 
+		{
+			var r = false;
+			var str = "";
+			var startpos = this.pos;
+			if (this.pos < this.expression.length && this.expression.charAt(this.pos) == "'") 
+			{
+				this.pos++;
+				while (this.pos < this.expression.length) 
+				{
+					var code = this.expression.charAt(this.pos);
+					if (code != "'" || str.slice(-1) == "\\") 
+					{
+						str += this.expression.charAt(this.pos);
+						this.pos++;
+					}
+					else 
+					{
+						this.pos++;
+						this.tokennumber = this.unescape(str, startpos);
+						r = true;
+						break;
+					}
+				}
+			}
+			return r;
+		},
+
+		isConst: function () {
+			var str;
+			for (var i in this.consts) 
+			{
+				if (true) 
+				{
+					var L = i.length;
+					str = this.expression.substr(this.pos, L);
+					if (i === str) 
+					{
+						this.tokennumber = this.consts[i];
+						this.pos += L;
+						return true;
+					}
+				}
+			}
+			return false;
+		},
+
+		isOperator: function () {
+			var code = this.expression.charCodeAt(this.pos);
+			if (code === 43) // +
+			{ 
+				this.tokenprio = 0;
+				this.tokenindex = "+";
+			}
+			else if (code === 45)  // -
+			{
+				this.tokenprio = 0;
+				this.tokenindex = "-";
+			}
+			else if (code === 124) // |
+			{ 
+				if (this.expression.charCodeAt(this.pos + 1) === 124) 
+				{
+					this.pos++;
+					this.tokenprio = 0;
+					this.tokenindex = "||";
+				}
+				else 
+				{
+					return false;
+				}
+			}
+			else if (code === 42) // *
+			{ 
+				this.tokenprio = 1;
+				this.tokenindex = "*";
+			}
+			else if (code === 47)  // /
+			{
+				this.tokenprio = 2;
+				this.tokenindex = "/";
+			}
+			else if (code === 37) // %
+			{ 
+				this.tokenprio = 2;
+				this.tokenindex = "%";
+			}
+			else if (code === 94) // ^
+			{ 
+				this.tokenprio = 3;
+				this.tokenindex = "^";
+			}
+			else 
+			{
+				return false;
+			}
+			this.pos++;
+			return true;
+		},
+
+		isSign: function () {
+			var code = this.expression.charCodeAt(this.pos - 1);
+			if (code === 45 || code === 43) // -
+			{ 
+				return true;
+			}
+			return false;
+		},
+
+		isPositiveSign: function () {
+			var code = this.expression.charCodeAt(this.pos - 1);
+			if (code === 43) // -
+			{ 
+				return true;
+			}
+			return false;
+		},
+
+		isNegativeSign: function () {
+			var code = this.expression.charCodeAt(this.pos - 1);
+			if (code === 45) // -
+			{ 
+				return true;
+			}
+			return false;
+		},
+
+		isLeftParenth: function () {
+			var code = this.expression.charCodeAt(this.pos);
+			if (code === 40) // (
+			{ 
+				this.pos++;
+				this.tmpprio += 10;
+				return true;
+			}
+			return false;
+		},
+
+		isRightParenth: function () {
+			var code = this.expression.charCodeAt(this.pos);
+			if (code === 41) // )
+			{ 
+				this.pos++;
+				this.tmpprio -= 10;
+				return true;
+			}
+			return false;
+		},
+
+		isComma: function () {
+			var code = this.expression.charCodeAt(this.pos);
+			if (code === 44) // ,
+			{ 
+				this.pos++;
+				this.tokenprio = -1;
+				this.tokenindex = ",";
+				return true;
+			}
+			return false;
+		},
+
+		isWhite: function () {
+			var code = this.expression.charCodeAt(this.pos);
+			if (code === 32 || code === 9 || code === 10 || code === 13) 
+			{
+				this.pos++;
+				return true;
+			}
+			return false;
+		},
+
+		isOp1: function () {
+			var str = "";
+			for (var i = this.pos; i < this.expression.length; i++) 
+			{
+				var c = this.expression.charAt(i);
+				if (c.toUpperCase() === c.toLowerCase()) 
+				{
+					if (i === this.pos || (c != '_' && (c < '0' || c > '9'))) {
+						break;
+					}
+				}
+				str += c;
+			}
+			if (str.length > 0 && (str in this.ops1)) 
+			{
+				this.tokenindex = str;
+				this.tokenprio = 5;
+				this.pos += str.length;
+				return true;
+			}
+			return false;
+		},
+
+		isOp2: function () {
+			var str = "";
+			for (var i = this.pos; i < this.expression.length; i++) 
+			{
+				var c = this.expression.charAt(i);
+				if (c.toUpperCase() === c.toLowerCase()) 
+				{
+					if (i === this.pos || (c != '_' && (c < '0' || c > '9'))) 
+					{
+						break;
+					}
+				}
+				str += c;
+			}
+			if (str.length > 0 && (str in this.ops2)) 
+			{
+				this.tokenindex = str;
+				this.tokenprio = 5;
+				this.pos += str.length;
+				return true;
+			}
+			return false;
+		},
+
+		isVar: function () {
+			var str = "";
+			for (var i = this.pos; i < this.expression.length; i++) 
+			{
+				var c = this.expression.charAt(i);
+				if (c.toUpperCase() === c.toLowerCase()) 
+				{
+					if (i === this.pos || (c != '_' && (c < '0' || c > '9'))) 
+					{
+						break;
+					}
+				}
+				str += c;
+			}
+			if (str.length > 0) 
+			{
+				this.tokenindex = str;
+				this.tokenprio = 4;
+				this.pos += str.length;
+				return true;
+			}
+			return false;
+		},
+
+		isComment: function () {
+			var code = this.expression.charCodeAt(this.pos - 1);
+			if (code === 47 && this.expression.charCodeAt(this.pos) === 42) 
+			{
+				this.pos = this.expression.indexOf("*/", this.pos) + 2;
+				if (this.pos === 1) 
+				{
+					this.pos = this.expression.length;
+				}
+				return true;
+			}
+			return false;
+		}
+	};
+
+	scope.Parser = Parser;
+	return Parser;
+})(typeof exports === 'undefined' ? {} : exports);
+
+
+/*
+ * Object for storing the result of the expression evaluation.
+ */
+
+function ValidationResult()
+{
+	this.rightSide;
+	this.leftSide;
+	this.result;
+}
+
+//
+// Method to calculate the value of an expression
+//
+
+function calculateExpression(exprIn)
+{
+	if(exprIn == null){
+		return null;
+	}
+	var expr = Parser.parse(exprIn);
+
+	var result = expr.evaluate();
+	
+	return result;
+}
+
+//
+// Method to retrieve an array of the applicable validation rules.
+//
+
+function getApplicableRules()
+{
+	var applicableRules = new Array();
+	var allValidationRules = storageManager.getValidationRules();
+	for(var i = 0; i < allValidationRules.length; i++)
+	{
+		if(isDataFieldsInCurrentForm(allValidationRules[i].leftSide.expression) && isDataFieldsInCurrentForm(allValidationRules[i].rightSide.expression))
+		{
+			applicableRules.push(allValidationRules[i]);
+		}
+	}
+	
+	return applicableRules;
+}
+
+//
+// Method to retrieve the data fields in an Expression
+//
+
+function isDataFieldsInCurrentForm(expr)
+{
+	var regex1 = /#{\w+\.\w+}/g;
+	var match1 = expr.match(regex1);
+	if(match1 != null)
+	{
+		for (var i = 0; i<match1.length; i++)
+		{
+			var dataField = match1[i].substring(2, match1[i].length -1);
+			var ids = dataField.split('.');
+			var fieldId = '#' + ids[0] + '-' + ids[1] + '-val';
+
+			if(!($(fieldId).length > 0))
+			{
+				return false;
+			}
+		}
+	}
+	return true;
+}
+
+//
+// Method to substitute the days value in an expression
+//
+
+
+function substituteDaysValues(expr, days)
+{
+	var regex1 = /\[days\]/g;
+	var outExpr  = expr;
+	if(days != null)
+	{
+		outExpr = outExpr.replace(regex1, days);
+	}
+	else
+	{
+		outExpr = outExpr.replace(regex1, "0");
+	}
+	return outExpr;
+}
+
+//
+// Method to substitute the data value token for its value.
+//
+
+function substituteDataValues(expr, nullIfBlank)
+{
+	var regex1 = /#{\w+\.\w+}/g;
+	
+	var outExpr  = expr;
+	
+	var match1 = expr.match(regex1);
+	if(match1 != null)
+	{
+		for (var i = 0; i<match1.length; i++)
+		{
+			var dataField = match1[i].substring(2, match1[i].length -1);
+			var ids = dataField.split('.');
+			var fieldId = '#' + ids[0] + '-' + ids[1] + '-val';
+			if($( fieldId ).val() != null && $( fieldId ).val() != '')
+			{
+				var value  = $( fieldId ).val();
+				outExpr = outExpr.replace(match1[i], value);
+			}
+			else
+			{
+				if(nullIfBlank)
+				{
+					return null;
+				}
+				else
+				{
+					outExpr = outExpr.replace(match1[i], "0");
+				}
+				
+			}
+		}
+	}
+	
+	return outExpr;
+}
+
+//
+// Method to substitute a constant for its value.
+//
+
+
+function substituteConstantValues(expr)
+{
+	var regex = /C{\w+\}/g;
+	var outExpr  = expr;
+	var match1 = expr.match(regex);
+	if(match1 != null)
+	{
+		for (var i = 0; i<match1.length; i++)
+		{
+			var constantFieldId = match1[i].substring(2, match1[i].length -1);
+			var constants = storageManager.getConstants();
+			
+			for(var j = 0; j < constants.length; j++)
+			{
+				if(constants[j].uid == constantFieldId)
+				{
+					value = constants[j].value;
+					outExpr = outExpr.replace(match1[i], value);
+				}
+			}
+		}
+	}
+	
+	return outExpr;
+}
+
+//
+// Method that substitutes all elements for their respective values.
+//
+
+function substituteValues(expr, nullIfBlank)
+{
+	var outExpression = expr;
+	outExpression = substituteDataValues(outExpression, nullIfBlank);
+	if(outExpression != null)
+	{
+		outExpression = substituteConstantValues(outExpression);
+		if(outExpression != null)
+		{
+			return substituteDaysValues(outExpression,null);
+		}
+	}
+	return null;
+}
+
+
+//
+// Method that validates an expression as true or false.
+//
+
+function validateExpression(leftSide, operator, rightSide)
+{
+	var result = new ValidationResult();
+	var leftSideValue = calculateExpression(leftSide);
+	var rightSideValue = calculateExpression(rightSide);
+	
+	result.leftSide = leftSideValue;
+	result.rightSide = rightSideValue;
+	
+	if(leftSideValue != null || operator == '[Compulsory pair]')
+	{
+		
+		if(rightSideValue != null || operator == '[Compulsory pair]')
+		{
+			switch(operator)
+			{
+				case '==':
+					result.result = (leftSideValue == rightSideValue);
+					return result; 
+				case '!=':
+					result.result = (leftSideValue != rightSideValue); 
+					return result;
+				case '>':
+					result.result = (leftSideValue > rightSideValue); 
+					return result;
+				case '>=':
+					result.result = (leftSideValue >= rightSideValue);
+					return result;
+				case '<':
+					result.result = (leftSideValue < rightSideValue); 
+					return result;
+				case '<=':
+					result.result = (leftSideValue <= rightSideValue); 
+					return result;
+				case '[Compulsory pair]':
+					result.result = (leftSide == null && rightSide == null) || (leftSide != null && rightSide != null); 
+					return result;
+				default:
+					log("Validation rule has an invalid operator: " + operator);
+					throw "Invalid operator in expression";
+			}
+		}
+		else
+		{
+			result.result = true;
+			return result;
+		}
+	}
+	else
+	{
+		result.result = true;
+		return result;
+	}
+}
+
+//
+// Method to run the validation rules offline from localstorage, based on the filled in information. 
+//
+
+function runOfflineValidations()
+{
+	var violations = new Array();
+	var validationRules = getApplicableRules();
+	for(var i = 0; i < validationRules.length; i++)
+	{
+		var leftSide = validationRules[i].leftSide.expression;
+		var rightSide = validationRules[i].rightSide.expression;
+		
+		leftSide = substituteValues(leftSide, validationRules[i].leftSide.isNullIfBlank);
+		rightSide = substituteValues(rightSide, validationRules[i].rightSide.isNullIfBlank);
+		
+		var result = validateExpression(leftSide, validationRules[i].operator, rightSide);
+
+		if(!result.result)
+		{
+			validationRules[i].validationResult = result;
+			violations.push(validationRules[i]);
+		}
+	}
+	
+	var response = '';
+	
+	if(violations.length == 0)
+	{
+		response = '';
+		
+	}
+	else
+	{
+		
+		var orgUnit = $('#selectedOrganisationUnit').val();
+		//Building error response
+		response += '<h3>' + i18n_validation_result + '&nbsp;<img src="../images/warning_small.png"></h3>';
+		response += '<p class="bold">' + i18n_data_entry_screen_has_following_errors + '</p>';
+		if(violations.length > 0)
+		{
+			//Table header
+			response += '<h3>' + orgUnit + '</h3>';
+			response += '<table class="listTable" width="100%">';
+			response += '<tr>';
+			response += '<th>' + i18n_validation_rule + '</th>';                
+			response += '<th>' + i18n_expression + '</th>';
+			response += '<th style="width:65px">' + i18n_left_side + '</th>';
+			response += '<th style="width:65px">' + i18n_operator + '</th>';
+			response += '<th style="width:65px">' + i18n_right_side + '</th>';
+			response += '</tr>';
+			
+			var listRow = 'class="listRow"';
+			var listAltRow = 'class="listAlternateRow"';
+			var rowClass = listRow;
+			
+			for(var i = 0; i < violations.length; i++)
+			{
+				response += '<tr>';
+				response += '<td style="height:32px" ' + rowClass + '>' + $('<div/>').text(violations[i].description).html() + '</td>';
+				response += '<td ' + rowClass + '>' + $('<div/>').text(violations[i].rightSide.description).html() + ' ' + $('<div/>').text(violations[i].operator).html() + ' ' + $('<div/>').text(violations[i].leftSide.description).html() + '</td>';
+				response += '<td ' + rowClass + '>' + (violations[i].validationResult.leftSide == null? '0':violations[i].validationResult.leftSide)+ '</td>';
+				response += '<td ' + rowClass + '>' + $('<div/>').text(violations[i].operator).html()  + '</td>';
+				response += '<td ' + rowClass + '>' + (violations[i].validationResult.rightSide == null? '0':violations[i].validationResult.rightSide ) + '</td>';
+				response += '</tr>';
+				
+				if(rowClass == listRow)
+				{
+					rowClass = listAltRow;
+				}
+				else
+				{
+					rowClass = listRow;
+				}
+			}
+			
+			response += '</table><br>';
+		}
+	}
+	
+	return response;
+	
+}
+

=== modified file 'dhis-2/dhis-web/dhis-web-dataentry/src/main/webapp/dhis-web-dataentry/select.vm'
--- dhis-2/dhis-web/dhis-web-dataentry/src/main/webapp/dhis-web-dataentry/select.vm	2013-07-18 10:10:22 +0000
+++ dhis-2/dhis-web/dhis-web-dataentry/src/main/webapp/dhis-web-dataentry/select.vm	2013-09-18 14:05:25 +0000
@@ -45,6 +45,12 @@
 var i18n_childrens_forms = '$encoder.jsEscape( $i18n.getString( "childrens_forms" ) , "'")';
 var i18n_no_periods_click_prev_year_button = '$encoder.jsEscape( $i18n.getString( "no_periods_click_prev_year_button" ) , "'")';
 var i18n_view_comment = '$encoder.jsEscape( $i18n.getString( "view_comment" ) , "'")';
+var i18n_data_entry_screen_has_following_errors = '$encoder.jsEscape( $i18n.getString( "data_entry_screen_has_following_errors" ) , "'")';
+var i18n_validation_rule = '$encoder.jsEscape( $i18n.getString( "validation_rule" ) , "'")';
+var i18n_expression = '$encoder.jsEscape( $i18n.getString( "expression" ) , "'")';
+var i18n_left_side = '$encoder.jsEscape( $i18n.getString( "left_side" ) , "'")';
+var i18n_operator = '$encoder.jsEscape( $i18n.getString( "operator" ) , "'")';
+var i18n_right_side = '$encoder.jsEscape( $i18n.getString( "right_side" ) , "'")';
 </script>
 
 <style type="text/css" media="print">

=== modified file 'dhis-2/dhis-web/dhis-web-importexport/src/main/java/org/hisp/dhis/importexport/action/datavalue/ImportDataValueAction.java'
--- dhis-2/dhis-web/dhis-web-importexport/src/main/java/org/hisp/dhis/importexport/action/datavalue/ImportDataValueAction.java	2013-08-28 07:27:01 +0000
+++ dhis-2/dhis-web/dhis-web-importexport/src/main/java/org/hisp/dhis/importexport/action/datavalue/ImportDataValueAction.java	2013-09-18 14:05:25 +0000
@@ -28,7 +28,14 @@
  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
+<<<<<<< TREE
 import com.opensymphony.xwork2.Action;
+=======
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.InputStream;
+
+>>>>>>> MERGE-SOURCE
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 import org.hisp.dhis.common.IdentifiableObject.IdentifiableProperty;
@@ -144,13 +151,23 @@
         InputStream in = new FileInputStream( upload );
 
         in = StreamUtils.wrapAndCheckCompressionFormat( in );
+<<<<<<< TREE
 
+=======
+        
+>>>>>>> MERGE-SOURCE
         ImportOptions options = new ImportOptions( dataElementIdScheme, orgUnitIdScheme, dryRun, strategy, skipExistingCheck );
 
         log.info( options );
-
-        scheduler.executeTask( new ImportDataValueTask( dataValueSetService, in, options, taskId, importFormat ) );
-
+<<<<<<< TREE
+
+        scheduler.executeTask( new ImportDataValueTask( dataValueSetService, in, options, taskId, importFormat ) );
+
+=======
+        
+        scheduler.executeTask( new ImportDataValueTask( dataValueSetService, in, options, taskId, importFormat ) );
+        
+>>>>>>> MERGE-SOURCE
         return SUCCESS;
     }
 }

=== modified file 'dhis-2/dhis-web/dhis-web-importexport/src/main/java/org/hisp/dhis/importexport/action/util/ImportDataValueTask.java'
--- dhis-2/dhis-web/dhis-web-importexport/src/main/java/org/hisp/dhis/importexport/action/util/ImportDataValueTask.java	2013-09-04 12:31:29 +0000
+++ dhis-2/dhis-web/dhis-web-importexport/src/main/java/org/hisp/dhis/importexport/action/util/ImportDataValueTask.java	2013-09-18 14:05:25 +0000
@@ -28,14 +28,19 @@
  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
+import java.io.InputStream;
+
 import org.hisp.dhis.dxf2.datavalueset.DataValueSetService;
 import org.hisp.dhis.dxf2.metadata.ImportOptions;
 import org.hisp.dhis.scheduling.TaskId;
 import org.springframework.security.core.Authentication;
 import org.springframework.security.core.context.SecurityContextHolder;
 
+<<<<<<< TREE
 import java.io.InputStream;
 
+=======
+>>>>>>> MERGE-SOURCE
 /**
  * @author Lars Helge Overland
  */
@@ -47,6 +52,7 @@
     public static final String FORMAT_PDF = "pdf";
 
     private DataValueSetService dataValueSetService;
+<<<<<<< TREE
 
     private InputStream inputStream;
 
@@ -59,9 +65,21 @@
     private final Authentication authentication;
 
     public ImportDataValueTask( DataValueSetService dataValueSetService, InputStream inputStream, ImportOptions options, TaskId taskId, String format )
+=======
+    private InputStream in;
+    private ImportOptions options;
+    private TaskId taskId;
+    private String format;
+
+    public ImportDataValueTask( DataValueSetService dataValueSetService, InputStream in, ImportOptions options, TaskId taskId, String format )
+>>>>>>> MERGE-SOURCE
     {
         this.dataValueSetService = dataValueSetService;
+<<<<<<< TREE
         this.inputStream = inputStream;
+=======
+        this.in = in;
+>>>>>>> MERGE-SOURCE
         this.options = options;
         this.taskId = taskId;
         this.format = format;
@@ -75,7 +93,11 @@
 
         if ( FORMAT_CSV.equals( format ) )
         {
+<<<<<<< TREE
             dataValueSetService.saveDataValueSetCsv( inputStream, options, taskId );
+=======
+            dataValueSetService.saveDataValueSetCsv( in, options, taskId );
+>>>>>>> MERGE-SOURCE
         }
         else if ( FORMAT_PDF.equals( format ) )
         {

=== modified file 'dhis-2/dhis-web/dhis-web-importexport/src/main/java/org/hisp/dhis/importexport/action/util/ImportMetaDataTask.java'
=== modified file 'dhis-2/dhis-web/dhis-web-importexport/src/main/resources/org/hisp/dhis/importexport/i18n_module.properties'
=== modified file 'dhis-2/dhis-web/dhis-web-light/src/main/java/org/hisp/dhis/light/dataentry/action/GetDataSetsAction.java'
=== modified file 'dhis-2/dhis-web/dhis-web-light/src/main/webapp/dhis-web-light/dataEntrySection.vm'
--- dhis-2/dhis-web/dhis-web-light/src/main/webapp/dhis-web-light/dataEntrySection.vm	2013-08-08 12:00:17 +0000
+++ dhis-2/dhis-web/dhis-web-light/src/main/webapp/dhis-web-light/dataEntrySection.vm	2013-09-18 14:05:25 +0000
@@ -84,8 +84,16 @@
 					<input type="text" maxlength="255" size="24" name="$key" value="$!dataValues.get($key)" />
 				#elseif( $dataElement.type == "int" && $dataElement.numberType == "negativeNumber" )
 					<input type="text" maxlength="255" size="24" name="$key" value="$!dataValues.get($key)" />
+<<<<<<< TREE
 				#elseif($dataElement.type=="trueOnly")
 					<input name="$key" type="checkbox" #if($!dataValues.get($key) == "on" ) checked #end/>
+=======
+				#elseif($dataElement.type=="trueOnly")
+					<select name="$key">
+						<option value="">$i18n.getString("please_select")</option>
+						<option #if( $prevDataValues.get( $key ) == "true" ) selected="selected" #end value="true">$i18n.getString("yes")</option>
+					</select>	
+>>>>>>> MERGE-SOURCE
 				#end
 				#end
 			#end

=== modified file 'dhis-2/dhis-web/dhis-web-maintenance/dhis-web-maintenance-dataadmin/src/main/java/org/hisp/dhis/dataadmin/action/lockexception/GetPeriodsAction.java'
=== modified file 'dhis-2/dhis-web/dhis-web-maintenance/dhis-web-maintenance-dataadmin/src/main/java/org/hisp/dhis/dataadmin/action/maintenance/PerformMaintenanceAction.java'
--- dhis-2/dhis-web/dhis-web-maintenance/dhis-web-maintenance-dataadmin/src/main/java/org/hisp/dhis/dataadmin/action/maintenance/PerformMaintenanceAction.java	2013-08-23 16:05:01 +0000
+++ dhis-2/dhis-web/dhis-web-maintenance/dhis-web-maintenance-dataadmin/src/main/java/org/hisp/dhis/dataadmin/action/maintenance/PerformMaintenanceAction.java	2013-09-18 14:05:25 +0000
@@ -187,10 +187,20 @@
         
         if ( clearDataMart )
         {
+<<<<<<< TREE
             aggregatedDataValueService.dropDataMart();
             aggregatedDataValueService.createDataMart();
             
             log.info( "'" + username + "': Cleared data mart" );
+=======
+            aggregatedDataValueService.deleteAggregatedDataValues();
+            aggregatedDataValueService.deleteAggregatedIndicatorValues();
+            
+            aggregatedOrgUnitDataValueService.deleteAggregatedDataValues();
+            aggregatedOrgUnitDataValueService.deleteAggregatedIndicatorValues();
+            
+            log.info( "'" + username + "': Cleared data mart" );
+>>>>>>> MERGE-SOURCE
         }
         
         if ( dataMartIndex )

=== modified file 'dhis-2/dhis-web/dhis-web-maintenance/dhis-web-maintenance-dataadmin/src/main/java/org/hisp/dhis/dataadmin/action/sqlview/ExportSqlViewResultAction.java'
=== modified file 'dhis-2/dhis-web/dhis-web-maintenance/dhis-web-maintenance-dataadmin/src/main/resources/META-INF/dhis/beans.xml'
--- dhis-2/dhis-web/dhis-web-maintenance/dhis-web-maintenance-dataadmin/src/main/resources/META-INF/dhis/beans.xml	2013-09-03 19:11:14 +0000
+++ dhis-2/dhis-web/dhis-web-maintenance/dhis-web-maintenance-dataadmin/src/main/resources/META-INF/dhis/beans.xml	2013-09-18 14:05:25 +0000
@@ -14,7 +14,21 @@
 	<property name="dataMartManager" ref="org.hisp.dhis.datamart.DataMartManager" />
     <property name="periodService" ref="org.hisp.dhis.period.PeriodService" />
     <property name="currentUserService" ref="org.hisp.dhis.user.CurrentUserService" />
-    <property name="categoryService" ref="org.hisp.dhis.dataelement.DataElementCategoryService" />
+<<<<<<< TREE
+    <property name="categoryService" ref="org.hisp.dhis.dataelement.DataElementCategoryService" />
+=======
+    <property name="categoryService" ref="org.hisp.dhis.dataelement.DataElementCategoryService" />
+  </bean>
+
+  <!-- Resource table -->
+
+  <bean id="org.hisp.dhis.dataadmin.action.resourcetable.GenerateResourceTableAction"
+      class="org.hisp.dhis.dataadmin.action.resourcetable.GenerateResourceTableAction"
+      scope="prototype">
+    <property name="resourceTableService" ref="org.hisp.dhis.resourcetable.ResourceTableService" />
+    <property name="sqlViewService" ref="org.hisp.dhis.sqlview.SqlViewService" />    
+    <property name="currentUserService" ref="org.hisp.dhis.user.CurrentUserService" />
+>>>>>>> MERGE-SOURCE
   </bean>
 
   <!-- Cache -->

=== modified file 'dhis-2/dhis-web/dhis-web-maintenance/dhis-web-maintenance-dataset/src/main/java/org/hisp/dhis/dataset/action/section/GreySectionAction.java'
=== modified file 'dhis-2/dhis-web/dhis-web-maintenance/dhis-web-maintenance-dataset/src/main/resources/org/hisp/dhis/dataset/i18n_module.properties'
--- dhis-2/dhis-web/dhis-web-maintenance/dhis-web-maintenance-dataset/src/main/resources/org/hisp/dhis/dataset/i18n_module.properties	2013-08-14 11:04:31 +0000
+++ dhis-2/dhis-web/dhis-web-maintenance/dhis-web-maintenance-dataset/src/main/resources/org/hisp/dhis/dataset/i18n_module.properties	2013-09-18 14:05:25 +0000
@@ -100,9 +100,13 @@
 form_details=Form details
 complete_allowed_only_if_validation_passes=Complete allowed only if validation passes
 notification_recipients=Complete notification recipients
+<<<<<<< TREE
 skip_offline=Skip offline
 render_as_tabs=Render sections as tabs
 render_horizontally=Render Vertically
+=======
+skip_offline=Skip offline
+>>>>>>> MERGE-SOURCE
 object_not_deleted_associated_by_objects=Object not deleted because it is associated by objects of type
 auto_save_data_entry_forms=Auto-save data entry forms
 notify_completing_user=Send notification to completing user

=== modified file 'dhis-2/dhis-web/dhis-web-maintenance/dhis-web-maintenance-patient/src/main/resources/org/hisp/dhis/patient/i18n_module.properties'
--- dhis-2/dhis-web/dhis-web-maintenance/dhis-web-maintenance-patient/src/main/resources/org/hisp/dhis/patient/i18n_module.properties	2013-09-17 06:08:16 +0000
+++ dhis-2/dhis-web/dhis-web-maintenance/dhis-web-maintenance-patient/src/main/resources/org/hisp/dhis/patient/i18n_module.properties	2013-09-18 14:05:25 +0000
@@ -409,6 +409,7 @@
 view_all = View all
 patient_attribute_visit_schedule = Patient Attribute Visit Schedule
 patient_attribute_visit_schedule_form = Patient attribute visit schedule
+<<<<<<< TREE
 intro_patient_attribute_visit_schedule = Configure which person attributes are added to the visit schedule. Gives better overview when used for tracking.
 selected_program_stages = Selected program stages
 patient = Person
@@ -474,4 +475,7 @@
 remind_creating_next_event_on_this_event_completed = Remind creating next event on this event completed
 data_entry_method = Data entry method
 local_identifier = Local Identifier
-scope = Scope
\ No newline at end of file
+scope = Scope=======
+intro_patient_attribute_visit_schedule = Configure which person attributes are added to the visit schedule. Gives better overview when used for tracking.
+selected_program_stages = Selected program stages
+>>>>>>> MERGE-SOURCE

=== modified file 'dhis-2/dhis-web/dhis-web-maintenance/dhis-web-maintenance-patient/src/main/webapp/dhis-web-maintenance-patient/caseAggregationForm.vm'
=== modified file 'dhis-2/dhis-web/dhis-web-maintenance/dhis-web-maintenance-patient/src/main/webapp/dhis-web-maintenance-patient/patientAttributeVisitSchedule.vm'
=== modified file 'dhis-2/dhis-web/dhis-web-maintenance/dhis-web-maintenance-patient/src/main/webapp/dhis-web-maintenance-patient/viewPatientRegistationForm.vm'
=== modified file 'dhis-2/dhis-web/dhis-web-maintenance/dhis-web-maintenance-settings/src/main/java/org/hisp/dhis/settings/action/system/SetAppearanceSettingsAction.java'
=== modified file 'dhis-2/dhis-web/dhis-web-maintenance/dhis-web-maintenance-user/src/main/java/org/hisp/dhis/user/action/ValidateRoleAction.java'
=== modified file 'dhis-2/dhis-web/dhis-web-maintenance/dhis-web-maintenance-user/src/main/webapp/dhis-web-maintenance-user/addRoleForm.vm'
=== modified file 'dhis-2/dhis-web/dhis-web-maintenance/dhis-web-maintenance-user/src/main/webapp/dhis-web-maintenance-user/updateRoleForm.vm'
=== modified file 'dhis-2/dhis-web/dhis-web-mapping/pom.xml'
=== added file 'dhis-2/dhis-web/dhis-web-mapping/src/main/java/org/hisp/dhis/mapping/action/AddMapViewToDashboardAction.java.OTHER'
--- dhis-2/dhis-web/dhis-web-mapping/src/main/java/org/hisp/dhis/mapping/action/AddMapViewToDashboardAction.java.OTHER	1970-01-01 00:00:00 +0000
+++ dhis-2/dhis-web/dhis-web-mapping/src/main/java/org/hisp/dhis/mapping/action/AddMapViewToDashboardAction.java.OTHER	2013-09-18 14:05:25 +0000
@@ -0,0 +1,101 @@
+package org.hisp.dhis.mapping.action;
+
+/*
+ * Copyright (c) 2004-2012, University of Oslo
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ * * Redistributions of source code must retain the above copyright notice, this
+ *   list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright notice,
+ *   this list of conditions and the following disclaimer in the documentation
+ *   and/or other materials provided with the distribution.
+ * * Neither the name of the HISP project nor the names of its contributors may
+ *   be used to endorse or promote products derived from this software without
+ *   specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+ * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.hisp.dhis.dashboard.DashboardContent;
+import org.hisp.dhis.dashboard.DashboardService;
+import org.hisp.dhis.mapping.Map;
+import org.hisp.dhis.mapping.MappingService;
+import org.hisp.dhis.user.CurrentUserService;
+import org.hisp.dhis.user.User;
+import org.springframework.beans.factory.annotation.Autowired;
+
+import com.opensymphony.xwork2.Action;
+
+/**
+ * @author Lars Helge Overland
+ */
+public class AddMapViewToDashboardAction
+    implements Action
+{
+    private static final Log log = LogFactory.getLog( AddMapViewToDashboardAction.class );
+    
+    // -------------------------------------------------------------------------
+    // Dependencies
+    // -------------------------------------------------------------------------
+
+    @Autowired
+    private CurrentUserService currentUserService;
+
+    @Autowired
+    private DashboardService dashboardService;
+
+    @Autowired
+    private MappingService mappingService;
+
+    // -------------------------------------------------------------------------
+    // Input
+    // -------------------------------------------------------------------------
+
+    private String id;
+
+    public void setId( String id )
+    {
+        this.id = id;
+    }
+
+    // -------------------------------------------------------------------------
+    // Action implementation
+    // -------------------------------------------------------------------------
+
+    public String execute()
+    {
+        User user = currentUserService.getCurrentUser();
+        
+        if ( user != null )
+        {        
+            DashboardContent content = dashboardService.getDashboardContent( user );
+            
+            Map map = mappingService.getMap( id );
+            
+            content.addMap( map );
+            
+            dashboardService.saveDashboardContent( content );
+            
+            log.info( "Added mapview '" + map.getName() + "' to dashboard for user '" + user.getName() + "'" );
+        }
+        else
+        {
+            log.warn( "Could not add mapview to dashboard, no current user" );
+        }
+        
+        return SUCCESS;
+    }
+}

=== modified file 'dhis-2/dhis-web/dhis-web-mapping/src/main/java/org/hisp/dhis/mapping/action/GetInfrastructuralDataElementMapValuesAction.java'
=== modified file 'dhis-2/dhis-web/dhis-web-mapping/src/main/resources/META-INF/dhis/beans.xml'
--- dhis-2/dhis-web/dhis-web-mapping/src/main/resources/META-INF/dhis/beans.xml	2013-07-24 17:28:39 +0000
+++ dhis-2/dhis-web/dhis-web-mapping/src/main/resources/META-INF/dhis/beans.xml	2013-09-18 14:05:25 +0000
@@ -18,6 +18,12 @@
         <property name="organisationUnitService" ref="org.hisp.dhis.organisationunit.OrganisationUnitService" />
     </bean>
 
+    <!-- Dashboard -->
+    
+    <bean id="org.hisp.dhis.mapping.action.AddMapViewToDashboardAction"
+        class="org.hisp.dhis.mapping.action.AddMapViewToDashboardAction"
+        scope="prototype"/>
+
 	<!-- OrganisationUnit -->
 
 	<bean id="org.hisp.dhis.mapping.action.GetOrganisationUnitChildrenAction"

=== modified file 'dhis-2/dhis-web/dhis-web-mapping/src/main/resources/struts.xml'
--- dhis-2/dhis-web/dhis-web-mapping/src/main/resources/struts.xml	2013-07-24 17:28:39 +0000
+++ dhis-2/dhis-web/dhis-web-mapping/src/main/resources/struts.xml	2013-09-18 14:05:25 +0000
@@ -14,7 +14,17 @@
     <action name="index" class="org.hisp.dhis.mapping.action.NoAction">
       <result name="success" type="redirect">app/index.html</result>
     </action>
+<<<<<<< TREE
 		
+=======
+	
+	<!-- Dashboard -->
+	
+	<action name="addMapViewToDashboard" class="org.hisp.dhis.mapping.action.AddMapViewToDashboardAction">
+	  <result name="success" type="velocity-json">/dhis-web-mapping/void.vm</result>
+	</action>
+	
+>>>>>>> MERGE-SOURCE
     <!-- Security -->
 	  
     <action name="deleteMapLegendSet" class="org.hisp.dhis.mapping.action.NoAction">

=== modified file 'dhis-2/dhis-web/dhis-web-mapping/src/main/webapp/dhis-web-mapping/app/scripts/app.js'
--- dhis-2/dhis-web/dhis-web-mapping/src/main/webapp/dhis-web-mapping/app/scripts/app.js	2013-09-09 15:57:35 +0000
+++ dhis-2/dhis-web/dhis-web-mapping/src/main/webapp/dhis-web-mapping/app/scripts/app.js	2013-09-18 14:05:25 +0000
@@ -55,8 +55,44 @@
 						}
 					}
 				}
-
+<<<<<<< TREE
+
+=======
+			}
+			return unescape(output);
+		};
+
+		util.svg = {};
+
+		util.svg.merge = function(str, strArray) {
+			if (strArray.length) {
+				str = str || '<svg></svg>';
+				for (var i = 0; i < strArray.length; i++) {
+					str = str.replace('</svg>', '');
+					strArray[i] = strArray[i].substring(strArray[i].indexOf('>') + 1);
+					str += strArray[i];
+				}
+			}
+			return str;
+		};
+
+		util.svg.getString = function(title, layers) {
+			var svgArray = [],
+				svg = '',
+				namespace,
+                title = Ext.htmlEncode(title),
+				titleSVG,
+				legendSVG = '',
+				scalelineSVG,
+				x = 20,
+				y = 35,
+				center = gis.viewport.centerRegion,
+				scalelineEl = Ext.get(Ext.query('.olControlScaleLineTop')[0]);
+
+			if (!layers.length) {
+>>>>>>> MERGE-SOURCE
 				return false;
+<<<<<<< TREE
 			};
 
 			util.map.getLayersByType = function(layerType) {
@@ -565,6 +601,393 @@
 			layer.window = GIS.app.WidgetWindow(layer);
 			GIS.core.createSelectHandlers(gis, layer);
 		}());
+=======
+			}
+
+			layers = layers.reverse();
+
+			namespace = 'xmlns="http://www.w3.org/2000/svg";';
+
+			svg = '<svg ' + namespace + ' width="' + center.getWidth() + '" height="' + center.getHeight() + '"></svg>';
+
+			titleSVG = '<g id="title" style="display: block; visibility: visible;">' +
+					   '<text id="title" x="' + x + '" y="' + y + '" font-size="18" font-weight="bold">' +
+					   '<tspan>' + title + '</tspan></text></g>';
+
+			y += 35;
+
+			for (var i = layers.length - 1; i > 0; i--) {
+				if (layers[i].id === gis.layer.facility.id) {
+					layers.splice(i, 1);
+					console.log(GIS.i18n.facility_layer_export_currently_not_supported);
+				}
+			}
+
+			for (var i = 0; i < layers.length; i++) {
+				var layer = layers[i],
+					id = layer.id,
+					legendConfig = layer.core.getLegendConfig(),
+					imageLegendConfig = layer.core.getImageLegendConfig(),
+					what,
+					when,
+					where,
+					legend;
+
+                // Html encode
+                for (var key in legendConfig) {
+                    if (legendConfig.hasOwnProperty(key)) {
+                        legendConfig[key] = Ext.htmlEncode(legendConfig[key]);
+                    }
+                }
+
+				// SVG
+				svgArray.push(layer.div.innerHTML);
+
+				// Legend
+				if (id !== gis.layer.boundary.id && id !== gis.layer.facility.id) {
+					what = '<g id="indicator" style="display: block; visibility: visible;">' +
+						   '<text id="indicator" x="' + x + '" y="' + y + '" font-size="12">' +
+						   '<tspan>' + legendConfig.what + '</tspan></text></g>';
+
+					y += 15;
+
+					when = '<g id="period" style="display: block; visibility: visible;">' +
+						   '<text id="period" x="' + x + '" y="' + y + '" font-size="12">' +
+						   '<tspan>' + legendConfig.when + '</tspan></text></g>';
+
+					y += 15;
+
+					where = '<g id="period" style="display: block; visibility: visible;">' +
+						   '<text id="period" x="' + x + '" y="' + y + '" font-size="12">' +
+						   '<tspan>' + legendConfig.where + '</tspan></text></g>';
+
+					y += 8;
+
+					legend = '<g>';
+
+					for (var j = 0; j < imageLegendConfig.length; j++) {
+						if (j !== 0) {
+							y += 15;
+						}
+
+						legend += '<rect x="' + x + '" y="' + y + '" height="15" width="30" ' +
+								  'fill="' + imageLegendConfig[j].color + '" stroke="#000000" stroke-width="1"/>';
+
+						legend += '<text id="label" x="' + (x + 40) + '" y="' + (y + 12) + '" font-size="12">' +
+								  '<tspan>' + imageLegendConfig[j].label + '</tspan></text>';
+					}
+
+					legend += '</g>';
+
+					legendSVG += (what + when + where + legend);
+
+					y += 50;
+				}
+			}
+
+			// Scale line
+			scalelineSVG = '<text x="' + (x + 3) + '" y="' + y + '" fill="#000">' + scalelineEl.dom.innerHTML + '</text>';
+
+			y += 3;
+			scalelineSVG += '<line x1="' + x + '" y1="' + y + '" x2="' + x + '" y2="' + (y + 3) + '" style="stroke:#000;stroke-width:1" />';
+			scalelineSVG += '<line x1="' + (x + scalelineEl.getWidth()) + '" y1="' + y + '" x2="' + (x + scalelineEl.getWidth()) + '" y2="' + (y + 3) + '" style="stroke:#000;stroke-width:1" />';
+
+			y += 3;
+			scalelineSVG += '<line x1="' + x + '" y1="' + y + '" x2="' + (x + scalelineEl.getWidth()) + '" y2="' + y + '" style="stroke:#000;stroke-width:1" />';
+
+			// Map
+			if (svgArray.length) {
+				svg = util.svg.merge(svg, svgArray);
+			}
+
+			svg = svg.replace('</svg>', (titleSVG + legendSVG + scalelineSVG) + '</svg>');
+
+			return svg;
+		};
+
+		util.json = {};
+
+		util.json.encodeString = function(str) {
+			return Ext.isString(str) ? str.replace(/[^a-zA-Z 0-9(){}<>_!+;:?*&%#-]+/g,'') : str;
+		};
+
+		util.json.decodeAggregatedValues = function(responseText) {
+			responseText = Ext.decode(responseText);
+			var values = [];
+
+			for (var i = 0; i < responseText.length; i++) {
+				values.push({
+					oi: responseText[i][0],
+					v: responseText[i][1]
+				});
+			}
+			return values;
+		};
+
+		util.gui.window = {};
+
+		util.gui.window.setPositionTopRight = function(window) {
+			var center = gis.viewport.centerRegion;
+			window.setPosition(gis.viewport.width - (window.width + 7), center.y + 8);
+		};
+
+		util.gui.window.setPositionTopLeft = function(window) {
+			window.setPosition(2,33);
+		};
+
+		util.gui.window.addHideOnBlurHandler = function(w) {
+			var el = Ext.get(Ext.query('.x-mask')[0]);
+
+			el.on('click', function() {
+				if (w.hideOnBlur) {
+					w.hide();
+				}
+			});
+
+			w.hasHideOnBlurHandler = true;
+		};
+
+		util.gui.window.addDestroyOnBlurHandler = function(w) {
+			var el = Ext.get(Ext.query('.x-mask')[0]);
+
+			el.on('click', function() {
+				if (w.destroyOnBlur) {
+					w.destroy();
+				}
+			});
+
+			w.hasDestroyOnBlurHandler = true;
+		};
+
+		return util;
+	};
+
+	GIS.app.getStores = function() {
+		var stores = gis.store;
+
+		stores.indicatorGroups = Ext.create('Ext.data.Store', {
+			fields: ['id', 'name'],
+			proxy: {
+				type: 'ajax',
+				url: gis.baseUrl + gis.conf.url.path_api + 'indicatorGroups.json?links=false&paging=false',
+				reader: {
+					type: 'json',
+					root: 'indicatorGroups'
+				}
+			},
+			cmp: [],
+			isLoaded: false,
+			loadFn: function(fn) {
+				if (this.isLoaded) {
+					fn.call();
+				}
+				else {
+					this.load(fn);
+				}
+			},
+			listeners: {
+				load: function() {
+					if (!this.isLoaded) {
+						this.isLoaded = true;
+						gis.util.gui.combo.setQueryMode(this.cmp, 'local');
+					}
+					this.sort('name', 'ASC');
+				}
+			}
+		});
+
+		stores.dataElementGroups = Ext.create('Ext.data.Store', {
+			fields: ['id', 'name'],
+			proxy: {
+				type: 'ajax',
+				url: gis.baseUrl + gis.conf.url.path_api + 'dataElementGroups.json?links=false&paging=false',
+				reader: {
+					type: 'json',
+					root: 'dataElementGroups'
+				}
+			},
+			cmp: [],
+			isLoaded: false,
+			loadFn: function(fn) {
+				if (this.isLoaded) {
+					fn.call();
+				}
+				else {
+					this.load(fn);
+				}
+			},
+			listeners: {
+				load: function() {
+					if (!this.isLoaded) {
+						this.isLoaded = true;
+						gis.util.gui.combo.setQueryMode(this.cmp, 'local');
+					}
+					this.sort('name', 'ASC');
+				}
+			}
+		});
+
+		stores.periodTypes = Ext.create('Ext.data.Store', {
+			fields: ['id', 'name'],
+			data: gis.conf.period.periodTypes
+		});
+
+		stores.infrastructuralPeriodsByType = Ext.create('Ext.data.Store', {
+			fields: ['id', 'name'],
+			proxy: {
+				type: 'ajax',
+				url: gis.baseUrl + gis.conf.url.path_gis + 'getPeriodsByPeriodType.action',
+				reader: {
+					type: 'json',
+					root: 'periods'
+				},
+				extraParams: {
+					name: gis.init.systemSettings.infrastructuralPeriodType
+				}
+			},
+			autoLoad: false,
+			isLoaded: false,
+			listeners: {
+				load: function() {
+					if (!this.isLoaded) {
+						this.isLoaded = true;
+					}
+				}
+			}
+		});
+
+		stores.groupSets = Ext.create('Ext.data.Store', {
+			fields: ['id', 'name'],
+			proxy: {
+				type: 'ajax',
+				url: gis.baseUrl + gis.conf.url.path_api + 'organisationUnitGroupSets.json?paging=false&links=false',
+				reader: {
+					type: 'json',
+					root: 'organisationUnitGroupSets'
+				}
+			},
+			isLoaded: false,
+			loadFn: function(fn) {
+				if (this.isLoaded) {
+					fn.call();
+				}
+				else {
+					this.load(fn);
+				}
+			},
+			listeners: {
+				load: function() {
+					if (!this.isLoaded) {
+						this.isLoaded = true;
+					}
+					this.sort('name', 'ASC');
+				}
+			}
+		});
+
+		stores.groupsByGroupSet = Ext.create('Ext.data.Store', {
+			fields: ['id', 'name', 'symbol'],
+			proxy: {
+				type: 'ajax',
+				url: '',
+				noCache: false,
+				reader: {
+					type: 'json',
+					root: 'organisationUnitGroups'
+				}
+			},
+			isLoaded: false,
+			loadFn: function(fn) {
+				if (this.isLoaded) {
+					fn.call();
+				}
+				else {
+					this.load(fn);
+				}
+			},
+			listeners: {
+				load: function() {
+					if (!this.isLoaded) {
+						this.isLoaded = true;
+					}
+					this.sort('name', 'ASC');
+				}
+			}
+		});
+
+		stores.legendSets = Ext.create('Ext.data.Store', {
+			fields: ['id', 'name'],
+			proxy: {
+				type: 'ajax',
+				url: gis.baseUrl + gis.conf.url.path_api + 'mapLegendSets.json?links=false&paging=false',
+				reader: {
+					type: 'json',
+					root: 'mapLegendSets'
+				}
+			},
+			isLoaded: false,
+			loadFn: function(fn) {
+				if (this.isLoaded) {
+					fn.call();
+				}
+				else {
+					this.load(fn);
+				}
+			},
+			listeners: {
+				load: function() {
+					if (!this.isLoaded) {
+						this.isLoaded = true;
+					}
+					this.sort('name', 'ASC');
+				}
+			}
+		});
+
+		stores.maps = Ext.create('Ext.data.Store', {
+			fields: ['id', 'name', 'lastUpdated', 'access'],
+			proxy: {
+				type: 'ajax',
+				reader: {
+					type: 'json',
+					root: 'maps'
+				}
+			},
+			isLoaded: false,
+			pageSize: 10,
+			page: 1,
+			defaultUrl: gis.baseUrl + gis.conf.url.path_api + 'maps.json?links=false',
+			loadStore: function(url) {
+				this.proxy.url = url || this.defaultUrl;
+
+				this.load({
+					params: {
+						pageSize: this.pageSize,
+						page: this.page
+					}
+				});
+			},
+			loadFn: function(fn) {
+				if (this.isLoaded) {
+					fn.call();
+				}
+				else {
+					this.load(fn);
+				}
+			},
+			listeners: {
+				load: function() {
+					if (!this.isLoaded) {
+						this.isLoaded = true;
+					}
+
+					this.sort('name', 'ASC');
+				}
+			}
+		});
+
+		return stores;
+>>>>>>> MERGE-SOURCE
 	};
 
 	GIS.app.createExtensions = function() {
@@ -4961,6 +5384,7 @@
 		return panel;
 	};
 
+<<<<<<< TREE
 	createViewport = function() {
 		var centerRegion,
 			eastRegion,
@@ -5354,6 +5778,398 @@
 		});
 
 		return viewport;
+=======
+	// GUI
+
+	GIS.app.init.onInitialize = function(r) {
+		var layer,
+			createViewport,
+			initialize;
+
+		createViewport = function() {
+			var centerRegion,
+				eastRegion,
+				downloadButton,
+				interpretationButton,
+				resizeButton,
+				viewport,
+				onRender,
+				afterRender;
+
+			resizeButton = Ext.create('Ext.button.Button', {
+				text: '>>>',
+				handler: function() {
+					eastRegion.toggleCollapse();
+				}
+			});
+
+			centerRegion = new GeoExt.panel.Map({
+				region: 'center',
+				map: gis.olmap,
+				cmp: {
+					tbar: {}
+				},
+				tbar: {
+					defaults: {
+						height: 26
+					},
+					items: function() {
+						var a = [];
+						a.push({
+							iconCls: 'gis-btn-icon-' + gis.layer.facility.id,
+							menu: gis.layer.facility.menu,
+							width: 26
+						});
+						a.push({
+							iconCls: 'gis-btn-icon-' + gis.layer.boundary.id,
+							menu: gis.layer.boundary.menu,
+							width: 26
+						});
+						a.push({
+							iconCls: 'gis-btn-icon-' + gis.layer.thematic1.id,
+							menu: gis.layer.thematic1.menu,
+							width: 26
+						});
+						a.push({
+							iconCls: 'gis-btn-icon-' + gis.layer.thematic2.id,
+							menu: gis.layer.thematic2.menu,
+							width: 26
+						});
+						a.push({
+							iconCls: 'gis-btn-icon-' + gis.layer.thematic3.id,
+							menu: gis.layer.thematic3.menu,
+							width: 26
+						});
+						a.push({
+							iconCls: 'gis-btn-icon-' + gis.layer.thematic4.id,
+							menu: gis.layer.thematic4.menu,
+							width: 26
+						});
+						a.push({
+							text: GIS.i18n.favorites,
+							menu: {},
+							handler: function() {
+								if (viewport.favoriteWindow && viewport.favoriteWindow.destroy) {
+									viewport.favoriteWindow.destroy();
+								}
+
+								viewport.favoriteWindow = GIS.app.FavoriteWindow();
+								viewport.favoriteWindow.show();
+							}
+						});
+						if (gis.init.user.isAdmin) {
+							a.push({
+								text: GIS.i18n.legend,
+								menu: {},
+								handler: function() {
+									if (viewport.legendSetWindow && viewport.legendSetWindow.destroy) {
+										viewport.legendSetWindow.destroy();
+									}
+
+									viewport.legendSetWindow = GIS.app.LegendSetWindow();
+									viewport.legendSetWindow.show();
+								}
+							});
+						}
+						a.push({
+							xtype: 'tbseparator',
+							height: 18,
+							style: 'border-color: transparent #d1d1d1 transparent transparent; margin-right: 4px',
+						});
+						a.push({
+							text: GIS.i18n.download,
+							menu: {},
+							disabled: true,
+							handler: function() {
+								if (viewport.downloadWindow && viewport.downloadWindow.destroy) {
+									viewport.downloadWindow.destroy();
+								}
+
+								viewport.downloadWindow = GIS.app.DownloadWindow();
+								viewport.downloadWindow.show();
+							},
+							xable: function() {
+								if (gis.util.map.hasVisibleFeatures()) {
+									this.enable();
+								}
+								else {
+									this.disable();
+								}
+							},
+							listeners: {
+								added: function() {
+									downloadButton = this;
+								}
+							}
+						});
+						a.push({
+							text: GIS.i18n.share,
+							menu: {},
+							disabled: true,
+							handler: function() {
+								if (viewport.interpretationWindow && viewport.interpretationWindow.destroy) {
+									viewport.interpretationWindow.destroy();
+								}
+
+								viewport.interpretationWindow = GIS.app.InterpretationWindow();
+								viewport.interpretationWindow.show();
+							},
+							listeners: {
+								added: function() {
+									interpretationButton = this;
+								}
+							}
+						});
+						a.push('->');
+
+						a.push({
+							text: GIS.i18n.table,
+                            toggleGroup: 'module',
+							handler: function(b) {
+                                window.location.href = '../../dhis-web-pivot/app/index.html';
+							}
+						});
+
+						a.push({
+							text: GIS.i18n.chart,
+                            toggleGroup: 'module',
+							handler: function(b) {
+                                window.location.href = '../../dhis-web-visualizer/app/index.html';
+							}
+						});
+
+						a.push({
+							text: GIS.i18n.map,
+                            toggleGroup: 'module',
+                            pressed: true
+						});
+
+						a.push({
+							xtype: 'tbseparator',
+							height: 18,
+							style: 'border-color: transparent #d1d1d1 transparent transparent; margin-right: 6px; margin-left: 3px',
+						});
+
+                        a.push({
+                            xtype: 'button',
+                            text: GIS.i18n.home,
+                            handler: function() {
+                                window.location.href = '../../dhis-web-commons-about/redirect.action';
+                            }
+						});
+
+						a.push(resizeButton);
+
+						return a;
+					}()
+				}
+			});
+
+			eastRegion = Ext.create('Ext.panel.Panel', {
+				region: 'east',
+				layout: 'anchor',
+				width: 200,
+				preventHeader: true,
+				collapsible: true,
+				collapseMode: 'mini',
+				items: [
+					{
+						title: GIS.i18n.layer_stack_transparency,
+						bodyStyle: 'padding: 4px 6px 3px',
+						items: GIS.app.LayersPanel(),
+						collapsible: true,
+						animCollapse: false
+					},
+					{
+						title: GIS.i18n.thematic_layer_1_legend,
+						bodyStyle: 'padding: 4px 6px 6px; border: 0 none',
+						collapsible: true,
+						collapsed: true,
+						animCollapse: false,
+						listeners: {
+							added: function() {
+								gis.layer.thematic1.legendPanel = this;
+							}
+						}
+					},
+					{
+						title: GIS.i18n.thematic_layer_2_legend,
+						bodyStyle: 'padding: 4px 6px 6px; border: 0 none',
+						collapsible: true,
+						collapsed: true,
+						animCollapse: false,
+						listeners: {
+							added: function() {
+								gis.layer.thematic2.legendPanel = this;
+							}
+						}
+					},
+					{
+						title: GIS.i18n.thematic_layer_3_legend,
+						bodyStyle: 'padding: 4px 6px 6px; border: 0 none',
+						collapsible: true,
+						collapsed: true,
+						animCollapse: false,
+						listeners: {
+							added: function() {
+								gis.layer.thematic3.legendPanel = this;
+							}
+						}
+					},
+					{
+						title: GIS.i18n.thematic_layer_4_legend,
+						bodyStyle: 'padding: 4px 6px 6px; border: 0 none',
+						collapsible: true,
+						collapsed: true,
+						animCollapse: false,
+						listeners: {
+							added: function() {
+								gis.layer.thematic4.legendPanel = this;
+							}
+						}
+					},
+					{
+						title: GIS.i18n.facility_layer_legend,
+						bodyStyle: 'padding: 4px 6px 6px; border: 0 none',
+						collapsible: true,
+						collapsed: true,
+						animCollapse: false,
+						listeners: {
+							added: function() {
+								gis.layer.facility.legendPanel = this;
+							}
+						}
+					}
+				],
+				listeners: {
+					collapse: function() {
+						resizeButton.setText('<<<');
+					},
+					expand: function() {
+						resizeButton.setText('>>>');
+					}
+				}
+			});
+
+			onRender = function(vp) {
+				gis.olmap.mask = Ext.create('Ext.LoadMask', vp.getEl(), {
+					msg: 'Loading'
+				});
+			};
+
+			afterRender = function() {
+
+				// Map tools
+				Ext.query('.zoomInButton')[0].innerHTML = '<img src="images/zoomin_24.png" />';
+				Ext.query('.zoomOutButton')[0].innerHTML = '<img src="images/zoomout_24.png" />';
+				Ext.query('.zoomVisibleButton')[0].innerHTML = '<img src="images/zoomvisible_24.png" />';
+				Ext.query('.measureButton')[0].innerHTML = '<img src="images/measure_24.png" />';
+
+				gis.olmap.events.register('click', null, function(e) {
+					if (gis.olmap.relocate.active) {
+						var el = Ext.query('#mouseposition')[0],
+							coordinates = '[' + el.childNodes[1].data + ',' + el.childNodes[3].data + ']',
+							center = gis.viewport.centerRegion;
+
+						Ext.Ajax.request({
+							url: gis.baseUrl + gis.conf.url.path_gis + 'updateOrganisationUnitCoordinates.action',
+							method: 'POST',
+							params: {id: gis.olmap.relocate.feature.attributes.id, coordinates: coordinates},
+							success: function(r) {
+								gis.olmap.relocate.active = false;
+								gis.olmap.relocate.window.destroy();
+
+								gis.olmap.relocate.feature.move({x: parseFloat(e.clientX - center.x), y: parseFloat(e.clientY - 28)});
+								gis.olmap.getViewport().style.cursor = 'auto';
+
+								console.log(gis.olmap.relocate.feature.attributes.name + ' relocated to ' + coordinates);
+							}
+						});
+					}
+				});
+
+				// Favorite
+				var id = gis.util.url.getUrlParam('id');
+
+				if (id) {
+					gis.map = {
+						id: id
+					};
+					GIS.core.MapLoader(gis).load();
+				}
+			};
+
+			viewport = Ext.create('Ext.container.Viewport', {
+				id: 'viewport',
+				layout: 'border',
+				eastRegion: eastRegion,
+				centerRegion: centerRegion,
+				downloadButton: downloadButton,
+				interpretationButton: interpretationButton,
+				items: [
+					centerRegion,
+					eastRegion
+				],
+				listeners: {
+					render: function() {
+						onRender(this);
+					},
+					afterrender: function() {
+						afterRender();
+					}
+				}
+			});
+
+			return viewport;
+		};
+
+		initialize = function() {
+			gis.init = GIS.app.getInits(r);
+			gis.baseUrl = gis.init.contextPath;
+
+			gis.util = GIS.app.getUtils();
+			gis.store = GIS.app.getStores();
+
+			layer = gis.layer.facility;
+			layer.menu = GIS.app.LayerMenu(layer, 'gis-toolbar-btn-menu-first');
+			layer.widget = GIS.app.LayerWidgetFacility(layer);
+			layer.window = GIS.app.WidgetWindow(layer);
+			GIS.core.createSelectHandlers(gis, layer);
+
+			layer = gis.layer.boundary;
+			layer.menu = GIS.app.LayerMenu(layer);
+			layer.widget = GIS.app.LayerWidgetBoundary(layer);
+			layer.window = GIS.app.WidgetWindow(layer);
+			GIS.core.createSelectHandlers(gis, layer);
+
+			layer = gis.layer.thematic1;
+			layer.menu = GIS.app.LayerMenu(layer);
+			layer.widget = GIS.app.LayerWidgetThematic(layer);
+			layer.window = GIS.app.WidgetWindow(layer);
+			GIS.core.createSelectHandlers(gis, layer);
+
+			layer = gis.layer.thematic2;
+			layer.menu = GIS.app.LayerMenu(layer);
+			layer.widget = GIS.app.LayerWidgetThematic(layer);
+			layer.window = GIS.app.WidgetWindow(layer);
+			GIS.core.createSelectHandlers(gis, layer);
+
+			layer = gis.layer.thematic3;
+			layer.menu = GIS.app.LayerMenu(layer);
+			layer.widget = GIS.app.LayerWidgetThematic(layer);
+			layer.window = GIS.app.WidgetWindow(layer);
+			GIS.core.createSelectHandlers(gis, layer);
+
+			layer = gis.layer.thematic4;
+			layer.menu = GIS.app.LayerMenu(layer);
+			layer.widget = GIS.app.LayerWidgetThematic(layer);
+			layer.window = GIS.app.WidgetWindow(layer);
+			GIS.core.createSelectHandlers(gis, layer);
+
+			gis.viewport = createViewport();
+			gis.viewport.gis = gis;
+		}();
+>>>>>>> MERGE-SOURCE
 	};
 	
 	initialize = function() {

=== modified file 'dhis-2/dhis-web/dhis-web-mapping/src/main/webapp/dhis-web-mapping/app/scripts/core.js'
--- dhis-2/dhis-web/dhis-web-mapping/src/main/webapp/dhis-web-mapping/app/scripts/core.js	2013-09-09 09:39:16 +0000
+++ dhis-2/dhis-web/dhis-web-mapping/src/main/webapp/dhis-web-mapping/app/scripts/core.js	2013-09-18 14:05:25 +0000
@@ -219,8 +219,232 @@
 
 			window.setPosition(centerRegionCenterX - (window.getWidth() / 2), centerRegionY);
 		};
+<<<<<<< TREE
 
 		onHoverUnselect = function fn(feature) {
+=======
+		geojson.features = [];
+
+		for (var i = 0; i < doc.geojson.length; i++) {
+			geojson.features.push({
+				geometry: {
+					type: parseInt(doc.geojson[i].ty) === 1 ? 'MultiPolygon' : 'Point',
+					coordinates: doc.geojson[i].co
+				},
+				properties: {
+					id: doc.geojson[i].uid,
+					internalId: doc.geojson[i].iid,
+					name: doc.geojson[i].na,
+					hcwc: doc.geojson[i].hc,
+					path: doc.geojson[i].path,
+					parentId: doc.geojson[i].pi,
+					parentName: doc.geojson[i].pn,
+					hasCoordinatesUp: doc.properties.hasCoordinatesUp
+				}
+			});
+		}
+
+		return geojson;
+	};
+
+	util.gui = {};
+	util.gui.combo = {};
+
+	util.gui.combo.setQueryMode = function(cmpArray, mode) {
+		for (var i = 0; i < cmpArray.length; i++) {
+			cmpArray[i].queryMode = mode;
+		}
+	};
+
+	return util;
+};
+
+GIS.core.getStores = function(gis) {
+	var stores = {};
+
+	stores.organisationUnitLevels = GIS.core.OrganisationUnitLevelStore(gis);
+
+	return stores;
+};
+
+GIS.core.getOLMap = function(gis) {
+	var olmap,
+		addControl;
+
+	addControl = function(name, fn) {
+		var button,
+			panel;
+
+		button = new OpenLayers.Control.Button({
+			displayClass: 'olControlButton',
+			trigger: function() {
+				fn.call(gis.olmap);
+			}
+		});
+
+		panel = new OpenLayers.Control.Panel({
+			defaultControl: button
+		});
+
+		panel.addControls([button]);
+
+		olmap.addControl(panel);
+
+		panel.div.className += ' ' + name;
+		panel.div.childNodes[0].className += ' ' + name + 'Button';
+	};
+
+	olmap = new OpenLayers.Map({
+		controls: [
+			new OpenLayers.Control.Navigation({
+				zoomWheelEnabled: true,
+				documentDrag: true
+			}),
+			new OpenLayers.Control.MousePosition({
+				prefix: '<span id="mouseposition" class="el-fontsize-10"><span class="text-mouseposition-lonlat">LON </span>',
+				separator: '<span class="text-mouseposition-lonlat">&nbsp;&nbsp;LAT </span>',
+				suffix: '<div id="google-logo" name="http://www.google.com/intl/en-US_US/help/terms_maps.html"; onclick="window.open(Ext.get(this).dom.attributes.name.nodeValue);"></div></span>'
+			}),
+			new OpenLayers.Control.Permalink(),
+			new OpenLayers.Control.ScaleLine({
+				geodesic: true,
+				maxWidth: 170,
+				minWidth: 100
+			})
+		],
+		displayProjection: new OpenLayers.Projection('EPSG:4326'),
+		maxExtent: new OpenLayers.Bounds(-20037508, -20037508, 20037508, 20037508),
+		mouseMove: {}, // Track all mouse moves
+		relocate: {} // Relocate organisation units
+	});
+
+	// Map events
+	olmap.events.register('mousemove', null, function(e) {
+		gis.olmap.mouseMove.x = e.clientX;
+		gis.olmap.mouseMove.y = e.clientY;
+	});
+
+	olmap.zoomToVisibleExtent = function() {
+		gis.util.map.zoomToVisibleExtent(this);
+	};
+
+	olmap.closeAllLayers = function() {
+		gis.layer.boundary.core.reset();
+		gis.layer.thematic1.core.reset();
+		gis.layer.thematic2.core.reset();
+		gis.layer.thematic3.core.reset();
+		gis.layer.thematic4.core.reset();
+		gis.layer.facility.core.reset();
+	};
+
+	addControl('zoomIn', olmap.zoomIn);
+	addControl('zoomOut', olmap.zoomOut);
+	addControl('zoomVisible', olmap.zoomToVisibleExtent);
+	addControl('measure', function() {
+		GIS.core.MeasureWindow(gis).show();
+	});
+
+	return olmap;
+};
+
+GIS.core.getLayers = function(gis) {
+	var layers = {},
+		createSelectionHandlers;
+
+	if (window.google) {
+		layers.googleStreets = new OpenLayers.Layer.Google('Google Streets', {
+			numZoomLevels: 20,
+			animationEnabled: true,
+			layerType: gis.conf.finals.layer.type_base,
+			layerOpacity: 1,
+			setLayerOpacity: function(number) {
+				if (number) {
+					this.layerOpacity = parseFloat(number);
+				}
+				this.setOpacity(this.layerOpacity);
+			}
+		});
+		layers.googleStreets.id = 'googleStreets';
+
+		layers.googleHybrid = new OpenLayers.Layer.Google('Google Hybrid', {
+			type: google.maps.MapTypeId.HYBRID,
+			numZoomLevels: 20,
+			animationEnabled: true,
+			layerType: gis.conf.finals.layer.type_base,
+			layerOpacity: 1,
+			setLayerOpacity: function(number) {
+				if (number) {
+					this.layerOpacity = parseFloat(number);
+				}
+				this.setOpacity(this.layerOpacity);
+			}
+		});
+		layers.googleHybrid.id = 'googleHybrid';
+	}
+
+    layers.openStreetMap = new OpenLayers.Layer.OSM.Mapnik('OpenStreetMap', {
+        layerType: gis.conf.finals.layer.type_base,
+        layerOpacity: 1,
+        setLayerOpacity: function(number) {
+            if (number) {
+                this.layerOpacity = parseFloat(number);
+            }
+            this.setOpacity(this.layerOpacity);
+        }
+    });
+    layers.openStreetMap.id = 'openStreetMap';
+
+	layers.facility = GIS.core.VectorLayer(gis, 'facility', GIS.i18n.facility_layer, {opacity: 0.8});
+	layers.facility.core = new mapfish.GeoStat.Facility(gis.olmap, {
+		layer: layers.facility,
+		gis: gis
+	});
+
+	layers.boundary = GIS.core.VectorLayer(gis, 'boundary', GIS.i18n.boundary_layer, {opacity: 0.8});
+	layers.boundary.core = new mapfish.GeoStat.Boundary(gis.olmap, {
+		layer: layers.boundary,
+		gis: gis
+	});
+
+	layers.thematic1 = GIS.core.VectorLayer(gis, 'thematic1', GIS.i18n.thematic_layer + ' 1', {opacity: 0.8});
+	layers.thematic1.core = new mapfish.GeoStat.Thematic1(gis.olmap, {
+		layer: layers.thematic1,
+		gis: gis
+	});
+
+	layers.thematic2 = GIS.core.VectorLayer(gis, 'thematic2', GIS.i18n.thematic_layer + ' 2', {opacity: 0.8});
+	layers.thematic2.core = new mapfish.GeoStat.Thematic2(gis.olmap, {
+		layer: layers.thematic2,
+		gis: gis
+	});
+
+	layers.thematic3 = GIS.core.VectorLayer(gis, 'thematic3', GIS.i18n.thematic_layer + ' 3', {opacity: 0.8});
+	layers.thematic3.core = new mapfish.GeoStat.Thematic3(gis.olmap, {
+		layer: layers.thematic3,
+		gis: gis
+	});
+
+	layers.thematic4 = GIS.core.VectorLayer(gis, 'thematic4', GIS.i18n.thematic_layer + ' 4', {opacity: 0.8});
+	layers.thematic4.core = new mapfish.GeoStat.Thematic4(gis.olmap, {
+		layer: layers.thematic4,
+		gis: gis
+	});
+
+	return layers;
+};
+
+GIS.core.createSelectHandlers = function(gis, layer) {
+	var isRelocate = !!GIS.app ? (gis.init.user.isAdmin ? true : false) : false,
+
+		window,
+		infrastructuralPeriod,
+		onHoverSelect,
+		onHoverUnselect,
+		onClickSelect;
+
+	onHoverSelect = function fn(feature) {
+		if (window) {
+>>>>>>> MERGE-SOURCE
 			window.destroy();
 		};
 
@@ -1314,6 +1538,7 @@
 
 			// Layer
 			layer.setLayerOpacity(view.opacity);
+<<<<<<< TREE
 
 			if (layer.item) {
 				layer.item.setValue(true);
@@ -1821,5 +2046,87 @@
 
 		return gis;
 	};
+=======
+		}
+
+		// Gui
+		if (loader.updateGui && Ext.isObject(layer.widget)) {
+			layer.widget.setGui(view);
+		}
+
+		// Zoom
+		if (loader.zoomToVisibleExtent) {
+			olmap.zoomToVisibleExtent();
+		}
+
+		// Mask
+		if (loader.hideMask) {
+			olmap.mask.hide();
+		}
+
+		// Map callback
+		if (loader.callBack) {
+			loader.callBack(layer);
+		}
+		else {
+			gis.map = null;
+			gis.viewport.interpretationButton.disable();
+		}
+	};
+
+	loader = {
+		compare: false,
+		updateGui: false,
+		zoomToVisibleExtent: false,
+		hideMask: false,
+		callBack: null,
+		load: function(view) {
+			gis.olmap.mask.show();
+
+			if (this.compare) {
+				compareView(view, true);
+			}
+			else {
+				loadOrganisationUnits(view);
+			}
+		},
+		loadData: loadData,
+		loadLegend: loadLegend
+	};
+
+	return loader;
+};
+
+GIS.core.getInstance = function(config) {
+	var gis = {},
+		layers = [];
+
+	gis.baseUrl = config && config.baseUrl ? config.baseUrl : '../..';
+	gis.el = config && config.el ? config.el : null;
+
+	gis.conf = GIS.core.getConfigs();
+	gis.util = GIS.core.getUtils(gis);
+	gis.store = GIS.core.getStores(gis);
+	gis.olmap = GIS.core.getOLMap(gis);
+	gis.layer = GIS.core.getLayers(gis);
+
+	if (window.google) {
+		layers.push(gis.layer.googleStreets, gis.layer.googleHybrid);
+	}
+
+	layers.push(gis.layer.openStreetMap,
+		gis.layer.thematic4,
+		gis.layer.thematic3,
+		gis.layer.thematic2,
+		gis.layer.thematic1,
+		gis.layer.boundary,
+		gis.layer.facility
+	);
+
+	gis.olmap.addLayers(layers);
+
+	return gis;
+};
+>>>>>>> MERGE-SOURCE
 
 });

=== modified file 'dhis-2/dhis-web/dhis-web-mapping/src/main/webapp/dhis-web-mapping/app/scripts/plugin.js'
=== modified file 'dhis-2/dhis-web/dhis-web-mobile/src/main/resources/dhis-mobile-manifest.appcache'
--- dhis-2/dhis-web/dhis-web-mobile/src/main/resources/dhis-mobile-manifest.appcache	2013-08-23 16:12:16 +0000
+++ dhis-2/dhis-web/dhis-web-mobile/src/main/resources/dhis-mobile-manifest.appcache	2013-09-18 14:05:25 +0000
@@ -1,5 +1,9 @@
 CACHE MANIFEST
+<<<<<<< TREE
 # 2.13-SNAPSHOT V10
+=======
+# 2.12 V10
+>>>>>>> MERGE-SOURCE
 
 CACHE:
 ../mobile/index

=== added file 'dhis-2/dhis-web/dhis-web-mobile/src/main/resources/org/hisp/dhis/web/mobile/i18n_module_fr.properties'
--- dhis-2/dhis-web/dhis-web-mobile/src/main/resources/org/hisp/dhis/web/mobile/i18n_module_fr.properties	1970-01-01 00:00:00 +0000
+++ dhis-2/dhis-web/dhis-web-mobile/src/main/resources/org/hisp/dhis/web/mobile/i18n_module_fr.properties	2013-09-18 14:05:25 +0000
@@ -0,0 +1,13 @@
+#Resource generated by I18n Resource Editor
+#Mon Apr 08 13:22:00 GMT 2013
+none_selected=Aucune selection
+change_to_invalid_page=A essay\u00E9 de passer \u00E0 une page non valide
+aggregate_reporting=Rapports agr\u00E9g\u00E9s
+no_messages=Aucun message
+no_organisation_units_for_data_entry=Aucune unit\u00E9 d'organisation disponible pour la saisie de donn\u00E9es
+unable_to_get_inbox=Impossible d'ouvir la boite de reception, veuillez r\u00E9essayer plus tard
+you_have=Vous avez
+form_stored=Formulaire stock\u00E9
+forms_stored=Formulaires stock\u00E9s
+unable_to_send_reply=Impossible d'envoyer la r\u00E9ponse, veuillez r\u00E9essayer plus tard
+no_data_is_stored=Aucune donn\u00E9e n'est enregistr\u00E9e

=== renamed file 'dhis-2/dhis-web/dhis-web-mobile/src/main/resources/org/hisp/dhis/web/mobile/i18n_module_fr.properties' => 'dhis-2/dhis-web/dhis-web-mobile/src/main/resources/org/hisp/dhis/web/mobile/i18n_module_fr.properties.moved'
=== modified file 'dhis-2/dhis-web/dhis-web-mobile/src/main/webapp/WEB-INF/dhis-web-mobile-velocity/data-entry.vm'
=== modified file 'dhis-2/dhis-web/dhis-web-pivot/src/main/webapp/dhis-web-pivot/app/scripts/app.js'
--- dhis-2/dhis-web/dhis-web-pivot/src/main/webapp/dhis-web-pivot/app/scripts/app.js	2013-09-10 11:22:22 +0000
+++ dhis-2/dhis-web/dhis-web-pivot/src/main/webapp/dhis-web-pivot/app/scripts/app.js	2013-09-18 14:05:25 +0000
@@ -3659,6 +3659,7 @@
 							config.items.push({id: r[i].data.id});
 						}
 					}
+<<<<<<< TREE
 				}
 				else if (toolMenu.menuValue === 'level') {
 					var levels = organisationUnitLevel.getValue();
@@ -3710,6 +3711,609 @@
                     style: 'padding-bottom:2px',
                     items: [
                         toolPanel,
+=======
+
+					return config.items.length ? config : null;
+				},
+				onExpand: function() {
+					var h = pt.viewport.westRegion.hasScrollbar ?
+						pt.conf.layout.west_scrollbarheight_accordion_organisationunit : pt.conf.layout.west_maxheight_accordion_organisationunit;
+					pt.util.dimension.panel.setHeight(h);
+					treePanel.setHeight(this.getHeight() - pt.conf.layout.west_fill_accordion_organisationunit);
+				},
+				items: [
+					{
+						layout: 'column',
+						bodyStyle: 'border:0 none; padding-bottom:3px; padding-left:7px',
+						items: [
+							userOrganisationUnit,
+							userOrganisationUnitChildren
+						]
+					},
+					treePanel
+				],
+				listeners: {
+					added: function() {
+						pt.cmp.dimension.panels.push(this);
+					},
+					expand: function(p) {
+						p.onExpand();
+					}
+				}
+			};
+
+			getDimensionPanels = function(dimensions, iconCls) {
+				var	getAvailableStore,
+					getSelectedStore,
+
+					createPanel,
+					getPanels;
+
+				getAvailableStore = function(dimension) {
+					return Ext.create('Ext.data.Store', {
+						fields: ['id', 'name'],
+						proxy: {
+							type: 'ajax',
+							url: pt.baseUrl + '/api/dimensions/' + dimension.id + '.json',
+							reader: {
+								type: 'json',
+								root: 'items'
+							}
+						},
+						isLoaded: false,
+						storage: {},
+						sortStore: function() {
+							this.sort('name', 'ASC');
+						},
+						reset: function() {
+							if (this.isLoaded) {
+								this.removeAll();
+								pt.util.store.loadFromStorage(this);
+								this.sortStore();
+							}
+						},
+						listeners: {
+							load: function(s) {
+								s.isLoaded = true;
+								pt.util.store.addToStorage(s);
+							}
+						}
+					});
+				};
+
+				getSelectedStore = function() {
+					return Ext.create('Ext.data.Store', {
+						fields: ['id', 'name'],
+						data: []
+					});
+				};
+
+				createPanel = function(dimension) {
+					var getAvailable,
+						getSelected,
+
+						availableStore,
+						selectedStore,
+						available,
+						selected,
+
+						panel;
+
+					getAvailable = function(availableStore) {
+						return Ext.create('Ext.ux.form.MultiSelect', {
+							cls: 'pt-toolbar-multiselect-left',
+							width: (pt.conf.layout.west_fieldset_width - pt.conf.layout.west_width_padding) / 2,
+							valueField: 'id',
+							displayField: 'name',
+							store: availableStore,
+							tbar: [
+								{
+									xtype: 'label',
+									text: PT.i18n.available,
+									cls: 'pt-toolbar-multiselect-left-label'
+								},
+								'->',
+								{
+									xtype: 'button',
+									icon: 'images/arrowright.png',
+									width: 22,
+									handler: function() {
+										pt.util.multiselect.select(available, selected);
+									}
+								},
+								{
+									xtype: 'button',
+									icon: 'images/arrowrightdouble.png',
+									width: 22,
+									handler: function() {
+										pt.util.multiselect.selectAll(available, selected);
+									}
+								}
+							],
+							listeners: {
+								afterrender: function() {
+									this.boundList.on('itemdblclick', function() {
+										pt.util.multiselect.select(available, selected);
+									}, this);
+								}
+							}
+						});
+					};
+
+					getSelected = function(selectedStore) {
+						return Ext.create('Ext.ux.form.MultiSelect', {
+							cls: 'pt-toolbar-multiselect-right',
+							width: (pt.conf.layout.west_fieldset_width - pt.conf.layout.west_width_padding) / 2,
+							valueField: 'id',
+							displayField: 'name',
+							ddReorder: true,
+							store: selectedStore,
+							tbar: [
+								{
+									xtype: 'button',
+									icon: 'images/arrowleftdouble.png',
+									width: 22,
+									handler: function() {
+										pt.util.multiselect.unselectAll(available, selected);
+									}
+								},
+								{
+									xtype: 'button',
+									icon: 'images/arrowleft.png',
+									width: 22,
+									handler: function() {
+										pt.util.multiselect.unselect(available, selected);
+									}
+								},
+								'->',
+								{
+									xtype: 'label',
+									text: PT.i18n.selected,
+									cls: 'pt-toolbar-multiselect-right-label'
+								}
+							],
+							listeners: {
+								afterrender: function() {
+									this.boundList.on('itemdblclick', function() {
+										pt.util.multiselect.unselect(available, selected);
+									}, this);
+								}
+							}
+						});
+					};
+
+					availableStore = getAvailableStore(dimension);
+					selectedStore = getSelectedStore();
+
+					dimensionIdAvailableStoreMap[dimension.id] = availableStore;
+					dimensionIdSelectedStoreMap[dimension.id] = selectedStore;
+
+					available = getAvailable(availableStore);
+					selected = getSelected(selectedStore);
+
+					availableStore.on('load', function() {
+						pt.util.multiselect.filterAvailable(available, selected);
+					});
+
+					panel = {
+						xtype: 'panel',
+						title: '<div class="' + iconCls + '">' + dimension.name + '</div>',
+						hideCollapseTool: true,
+						availableStore: availableStore,
+						selectedStore: selectedStore,
+						getDimension: function() {
+							var config = {
+								dimension: dimension.id,
+								items: []
+							};
+
+							selectedStore.each( function(r) {
+								config.items.push({id: r.data.id});
+							});
+
+							return config.items.length ? config : null;
+						},
+						onExpand: function() {
+							if (!availableStore.isLoaded) {
+								availableStore.load();
+							}
+
+							var h = pt.viewport.westRegion.hasScrollbar ?
+								pt.conf.layout.west_scrollbarheight_accordion_group : pt.conf.layout.west_maxheight_accordion_group;
+							pt.util.dimension.panel.setHeight(h);
+
+							pt.util.multiselect.setHeight(
+								[available, selected],
+								this,
+								pt.conf.layout.west_fill_accordion_dataset
+							);
+						},
+						items: [
+							{
+								xtype: 'panel',
+								layout: 'column',
+								bodyStyle: 'border-style:none',
+								items: [
+									available,
+									selected
+								]
+							}
+						],
+						listeners: {
+							added: function() {
+								pt.cmp.dimension.panels.push(this);
+							},
+							expand: function(p) {
+								p.onExpand();
+							}
+						}
+					};
+
+					return panel;
+				};
+
+				getPanels = function() {
+					var panels = [];
+
+					for (var i = 0, panel; i < dimensions.length; i++) {
+						panel = createPanel(dimensions[i]);
+
+						panels.push(panel);
+					}
+
+					return panels;
+				};
+
+				return getPanels();
+			};
+
+			validateSpecialCases = function(layout) {
+				var dimConf = pt.conf.finals.dimension;
+
+				if (!layout) {
+					return;
+				}
+
+				if (layout.filters && layout.filters.length) {
+					for (var i = 0; i < layout.filters.length; i++) {
+
+						// Indicators as filter
+						if (layout.filters[i].dimension === dimConf.indicator.objectName) {
+							alert(PT.i18n.indicators_cannot_be_specified_as_filter);
+							return;
+						}
+
+						// Categories as filter
+						if (layout.filters[i].dimension === dimConf.category.objectName) {
+							alert(PT.i18n.categories_cannot_be_specified_as_filter);
+							return;
+						}
+
+						// Data sets as filter
+						if (layout.filters[i].dimension === dimConf.category.objectName) {
+							alert(PT.i18n.data_sets_cannot_be_specified_as_filter);
+							return;
+						}
+					}
+				}
+
+				// Degs and datasets in the same query
+				//if (Ext.Array.contains(dimensionNames, dimConf.data.dimensionName) && pt.store.dataSetSelected.data.length) {
+					//for (var i = 0; i < pt.init.degs.length; i++) {
+						//if (Ext.Array.contains(dimensionNames, pt.init.degs[i].id)) {
+							//alert(PT.i18n.data_element_group_sets_cannot_be_specified_together_with_data_sets);
+							//return;
+						//}
+					//}
+				//}
+
+				return true;
+			};
+
+			update = function() {
+				var config = pt.util.pivot.getLayoutConfig(),
+				layout = pt.api.layout.Layout(config);
+
+				if (!validateSpecialCases(layout)) {
+					return;
+				}
+
+				pt.util.pivot.createTable(layout, pt);
+			};
+
+			accordionBody = Ext.create('Ext.panel.Panel', {
+				layout: 'accordion',
+				activeOnTop: true,
+				cls: 'pt-accordion',
+				bodyStyle: 'border:0 none; margin-bottom:2px',
+				height: 700,
+				items: function() {
+					var panels = [
+						indicator,
+						dataElement,
+						dataSet,
+						period,
+						organisationUnit
+					],
+					dims = Ext.clone(pt.init.dimensions);
+
+					pt.util.array.sortObjectsByString(dims);
+
+					panels = panels.concat(getDimensionPanels(dims, 'pt-panel-title-dimension'));
+
+					last = panels[panels.length - 1];
+					last.cls = 'pt-accordion-last';
+
+					return panels;
+				}()
+			});
+
+			accordion = Ext.create('Ext.panel.Panel', {
+				bodyStyle: 'border-style:none; padding:2px; padding-bottom:0; overflow-y:scroll;',
+				items: accordionBody,
+				listeners: {
+					added: function() {
+						pt.cmp.dimension.accordion = this;
+					}
+				}
+			});
+
+			westRegion = Ext.create('Ext.panel.Panel', {
+				region: 'west',
+				preventHeader: true,
+				collapsible: true,
+				collapseMode: 'mini',
+				width: function() {
+					if (Ext.isWebKit) {
+						return pt.conf.layout.west_width + 8;
+					}
+					else {
+						if (Ext.isLinux && Ext.isGecko) {
+							return pt.conf.layout.west_width + 13;
+						}
+						return pt.conf.layout.west_width + 17;
+					}
+				}(),
+				items: accordion
+			});
+
+			layoutButton = Ext.create('Ext.button.Button', {
+				text: 'Layout',
+				menu: {},
+				handler: function() {
+					if (!pt.viewport.layoutWindow) {
+						pt.viewport.layoutWindow = PT.app.LayoutWindow(pt);
+					}
+
+					pt.viewport.layoutWindow.show();
+				}
+			});
+
+			optionsButton = Ext.create('Ext.button.Button', {
+				text: 'Options',
+				menu: {},
+				handler: function() {
+					if (!pt.viewport.optionsWindow) {
+						pt.viewport.optionsWindow = PT.app.OptionsWindow();
+					}
+
+					pt.viewport.optionsWindow.show();
+				}
+			});
+
+			favoriteButton = Ext.create('Ext.button.Button', {
+				text: 'Favorites',
+				menu: {},
+				handler: function() {
+					if (pt.viewport.favoriteWindow) {
+						pt.viewport.favoriteWindow.destroy();
+					}
+
+					pt.viewport.favoriteWindow = PT.app.FavoriteWindow();
+					pt.viewport.favoriteWindow.show();
+				}
+			});
+
+			openTableLayoutTab = function(type, isNewTab) {
+				if (pt.baseUrl && pt.paramString) {
+					var url = pt.baseUrl + '/api/analytics.' + type + pt.util.pivot.getParamString(pt.xLayout);
+					url += '&tableLayout=true&columns=' + pt.xLayout.columnDimensionNames.join(';') + '&rows=' + pt.xLayout.rowDimensionNames.join(';');
+
+					window.open(url, isNewTab ? '_blank' : '_top');
+				}
+			};
+
+			downloadButton = Ext.create('Ext.button.Button', {
+				text: 'Download',
+				disabled: true,
+				menu: {
+					cls: 'pt-menu',
+					shadow: false,
+					showSeparator: false,
+					items: [
+						{
+							xtype: 'label',
+							text: PT.i18n.table_layout,
+							style: 'padding:7px 5px 5px 7px; font-weight:bold'
+						},
+						{
+							text: 'Microsoft Excel (.xls)',
+							iconCls: 'pt-menu-item-tablelayout',
+							handler: function() {
+								openTableLayoutTab('xls');
+							}
+						},
+						{
+							text: 'CSV (.csv)',
+							iconCls: 'pt-menu-item-tablelayout',
+							handler: function() {
+								openTableLayoutTab('csv');
+							}
+						},
+						{
+							text: 'HTML (.html)',
+							iconCls: 'pt-menu-item-tablelayout',
+							handler: function() {
+								openTableLayoutTab('html', true);
+							}
+						},
+						{
+							xtype: 'label',
+							text: PT.i18n.plain_data_sources,
+							style: 'padding:7px 5px 5px 7px; font-weight:bold'
+						},
+						{
+							text: 'JSON',
+							iconCls: 'pt-menu-item-datasource',
+							handler: function() {
+								if (pt.baseUrl && pt.paramString) {
+									window.open(pt.baseUrl + '/api/analytics.json' + pt.paramString, '_blank');
+								}
+							}
+						},
+						{
+							text: 'XML',
+							iconCls: 'pt-menu-item-datasource',
+							handler: function() {
+								if (pt.baseUrl && pt.paramString) {
+									window.open(pt.baseUrl + '/api/analytics.xml' + pt.paramString, '_blank');
+								}
+							}
+						},
+						{
+							text: 'Microsoft Excel',
+							iconCls: 'pt-menu-item-datasource',
+							handler: function() {
+								if (pt.baseUrl && pt.paramString) {
+									window.location.href = pt.baseUrl + '/api/analytics.xls' + pt.paramString;
+								}
+							}
+						},
+						{
+							text: 'CSV',
+							iconCls: 'pt-menu-item-datasource',
+							handler: function() {
+								if (pt.baseUrl && pt.paramString) {
+									window.location.href = pt.baseUrl + '/api/analytics.csv' + pt.paramString;
+								}
+							}
+						},
+						{
+							text: 'JRXML',
+							iconCls: 'pt-menu-item-datasource',
+							handler: function() {
+								if (pt.baseUrl && pt.paramString) {
+									window.open(pt.baseUrl + '/api/analytics.jrxml' + pt.paramString, '_blank');
+								}
+							}
+						}
+					],
+					listeners: {
+						afterrender: function() {
+							this.getEl().addCls('pt-toolbar-btn-menu');
+						}
+					}
+				}
+			});
+
+			interpretationButton = Ext.create('Ext.button.Button', {
+				text: PT.i18n.share,
+				menu: {},
+				disabled: true,
+				xable: function() {
+					if (pt.favorite) {
+						this.enable();
+						this.disabledTooltip.destroy();
+					}
+					else {
+						if (pt.xLayout) {
+							this.disable();
+							this.createTooltip();
+						}
+					}
+				},
+				disabledTooltip: null,
+				createTooltip: function() {
+					this.disabledTooltip = Ext.create('Ext.tip.ToolTip', {
+						target: this.getEl(),
+						html: PT.i18n.save_load_favorite_before_sharing,
+						'anchor': 'bottom'
+					});
+				},
+				handler: function() {
+					if (pt.viewport.interpretationWindow) {
+						pt.viewport.interpretationWindow.destroy();
+					}
+
+					pt.viewport.interpretationWindow = PT.app.InterpretationWindow();
+
+					if (pt.viewport.interpretationWindow) {
+						pt.viewport.interpretationWindow.show();
+					}
+				}
+			});
+
+			centerRegion = Ext.create('Ext.panel.Panel', {
+				region: 'center',
+				bodyStyle: 'padding:1px',
+				autoScroll: true,
+				tbar: {
+                    defaults: {
+                        height: 26
+                    },
+					items: [
+						{
+							text: '<<<',
+							handler: function(b) {
+								var text = b.getText();
+								text = text === '<<<' ? '>>>' : '<<<';
+								b.setText(text);
+
+								westRegion.toggleCollapse();
+							}
+						},
+						{
+							text: '<b>' + PT.i18n.update + '</b>',
+							handler: function() {
+								update();
+							}
+						},
+						layoutButton,
+						optionsButton,
+						{
+							xtype: 'tbseparator',
+							height: 18,
+							style: 'border-color:transparent; border-right-color:#d1d1d1; margin-right:4px',
+						},
+						favoriteButton,
+						downloadButton,
+						interpretationButton,
+                        '->',
+						{
+							text: PT.i18n.table,
+                            toggleGroup: 'module',
+							pressed: true
+						},
+						{
+							text: PT.i18n.chart,
+                            toggleGroup: 'module',
+							handler: function(b) {
+                                window.location.href = '../../dhis-web-visualizer/app/index.html';
+							}
+						},
+						{
+							text: PT.i18n.map,
+                            toggleGroup: 'module',
+							handler: function(b) {
+                                window.location.href = '../../dhis-web-mapping/app/index.html';
+							}
+						},
+						{
+							xtype: 'tbseparator',
+							height: 18,
+							style: 'border-color:transparent; border-right-color:#d1d1d1; margin-right:4px',
+						},
+>>>>>>> MERGE-SOURCE
                         {
                             width: pt.conf.layout.west_fieldset_width - pt.conf.layout.west_width_padding - 38,
                             layout: 'column',
@@ -4224,6 +4828,7 @@
 				defaults: {
 					height: 26
 				},
+<<<<<<< TREE
 				items: [
 					{
 						text: '<<<',
@@ -4466,12 +5071,141 @@
 							id: dim.dimensionName,
 							name: dimConf.objectNameMap[dim.dimensionName].name
 						});
+=======
+				listeners: {
+					afterrender: function(p) {
+						var liStyle = 'padding:3px 10px; color:#333',
+							html = '';
+
+						html += '<div style="padding:20px">';
+						html += '<div style="font-size:14px; padding-bottom:8px">' + PT.i18n.example1 + '</div>';
+						html += '<div style="' + liStyle + '">- ' + PT.i18n.example2 + '</div>';
+						html += '<div style="' + liStyle + '">- ' + PT.i18n.example3 + '</div>';
+						html += '<div style="' + liStyle + '">- ' + PT.i18n.example4 + '</div>';
+						html += '<div style="font-size:14px; padding-top:20px; padding-bottom:8px">' + PT.i18n.example5 + '</div>';
+						html += '<div style="' + liStyle + '">- ' + PT.i18n.example6 + '</div>';
+						html += '<div style="' + liStyle + '">- ' + PT.i18n.example7 + '</div>';
+						html += '<div style="' + liStyle + '">- ' + PT.i18n.example8 + '</div>';
+						html += '</div>';
+
+						p.update(html);
+					}
+				}
+			});
+
+			setFavorite = function(layout) {
+				var dimConf = pt.conf.finals.dimension,
+					xLayout,
+					dimMap,
+					recMap,
+					graphMap,
+					objectName,
+					periodRecords,
+					fixedPeriodRecords = [],
+                    dimNames = [],
+					isOu = false,
+					isOuc = false;
+
+				// State
+				pt.viewport.interpretationButton.enable();
+
+				// Create chart
+				pt.util.pivot.createTable(layout, pt);
+
+				// Set gui
+
+				xLayout = pt.util.pivot.getExtendedLayout(layout);
+				dimMap = xLayout.objectNameDimensionsMap;
+				recMap = xLayout.objectNameItemsMap;
+				graphMap = layout.parentGraphMap;
+
+				// Indicators
+				pt.store.indicatorSelected.removeAll();
+				objectName = dimConf.indicator.objectName;
+				if (dimMap[objectName]) {
+					pt.store.indicatorSelected.add(Ext.clone(recMap[objectName]));
+					pt.util.multiselect.filterAvailable({store: pt.store.indicatorAvailable}, {store: pt.store.indicatorSelected});
+				}
+
+				// Data elements
+				pt.store.dataElementSelected.removeAll();
+				objectName = dimConf.dataElement.objectName;
+				if (dimMap[objectName]) {
+					pt.store.dataElementSelected.add(Ext.clone(recMap[objectName]));
+					pt.util.multiselect.filterAvailable({store: pt.store.dataElementAvailable}, {store: pt.store.dataElementSelected});
+				}
+
+				// Data sets
+				pt.store.dataSetSelected.removeAll();
+				objectName = dimConf.dataSet.objectName;
+				if (dimMap[objectName]) {
+					pt.store.dataSetSelected.add(Ext.clone(recMap[objectName]));
+					pt.util.multiselect.filterAvailable({store: pt.store.dataSetAvailable}, {store: pt.store.dataSetSelected});
+				}
+
+				// Periods
+				pt.store.fixedPeriodSelected.removeAll();
+				pt.util.checkbox.setAllFalse();
+				periodRecords = recMap[dimConf.period.objectName] || [];
+				for (var i = 0, peroid, checkbox; i < periodRecords.length; i++) {
+					period = periodRecords[i];
+					checkbox = relativePeriod.valueComponentMap[period.id];
+					if (checkbox) {
+						checkbox.setValue(true);
+					}
+					else {
+						fixedPeriodRecords.push(period);
+					}
+				}
+				pt.store.fixedPeriodSelected.add(fixedPeriodRecords);
+				pt.util.multiselect.filterAvailable({store: pt.store.fixedPeriodAvailable}, {store: pt.store.fixedPeriodSelected});
+
+				// Group sets
+				for (var key in dimensionIdSelectedStoreMap) {
+					if (dimensionIdSelectedStoreMap.hasOwnProperty(key)) {
+						var a = dimensionIdAvailableStoreMap[key],
+							s = dimensionIdSelectedStoreMap[key];
+
+						if (s.getCount() > 0) {
+							a.reset();
+							s.removeAll();
+						}
+
+						if (recMap[key]) {
+							s.add(recMap[key]);
+							pt.util.multiselect.filterAvailable({store: a}, {store: s});
+						}
+					}
+				}
+
+				// Layout
+				pt.viewport.dimensionStore.reset(true);
+				pt.viewport.colStore.removeAll();
+				pt.viewport.rowStore.removeAll();
+				pt.viewport.filterStore.removeAll();
+
+				if (layout.columns) {
+                    dimNames = [];
+
+					for (var i = 0, dim; i < layout.columns.length; i++) {
+						dim = dimConf.objectNameMap[layout.columns[i].dimension];
+
+                        if (!Ext.Array.contains(dimNames, dim.dimensionName)) {
+                            pt.viewport.colStore.add({
+                                id: dim.dimensionName,
+                                name: dimConf.objectNameMap[dim.dimensionName].name
+                            });
+
+                            dimNames.push(dim.dimensionName);
+                        }
+>>>>>>> MERGE-SOURCE
 
 						dimNames.push(dim.dimensionName);
 					}
 
 					pt.viewport.dimensionStore.remove(pt.viewport.dimensionStore.getById(dim.dimensionName));
 				}
+<<<<<<< TREE
 			}
 
 			if (layout.rows) {
@@ -4485,12 +5219,30 @@
 							id: dim.dimensionName,
 							name: dimConf.objectNameMap[dim.dimensionName].name
 						});
+=======
+
+				if (layout.rows) {
+                    dimNames = [];
+
+					for (var i = 0, dim; i < layout.rows.length; i++) {
+						dim = dimConf.objectNameMap[layout.rows[i].dimension];
+
+                        if (!Ext.Array.contains(dimNames, dim.dimensionName)) {
+                            pt.viewport.rowStore.add({
+                                id: dim.dimensionName,
+                                name: dimConf.objectNameMap[dim.dimensionName].name
+                            });
+
+                            dimNames.push(dim.dimensionName);
+                        }
+>>>>>>> MERGE-SOURCE
 
 						dimNames.push(dim.dimensionName);
 					}
 
 					pt.viewport.dimensionStore.remove(pt.viewport.dimensionStore.getById(dim.dimensionName));
 				}
+<<<<<<< TREE
 			}
 
 			if (layout.filters) {
@@ -4504,6 +5256,23 @@
 							id: dim.dimensionName,
 							name: dimConf.objectNameMap[dim.dimensionName].name
 						});
+=======
+
+				if (layout.filters) {
+                    dimNames = [];
+
+					for (var i = 0, dim; i < layout.filters.length; i++) {
+						dim = dimConf.objectNameMap[layout.filters[i].dimension];
+
+                        if (!Ext.Array.contains(dimNames, dim.dimensionName)) {
+                            pt.viewport.filterStore.add({
+                                id: dim.dimensionName,
+                                name: dimConf.objectNameMap[dim.dimensionName].name
+                            });
+
+                            dimNames.push(dim.dimensionName);
+                        }
+>>>>>>> MERGE-SOURCE
 
 						dimNames.push(dim.dimensionName);
 					}
@@ -4550,6 +5319,7 @@
 				toolMenu.clickHandler('orgunit');
 				userOrganisationUnit.setValue(isOu);
 				userOrganisationUnitChildren.setValue(isOuc);
+<<<<<<< TREE
 				userOrganisationUnitGrandChildren.setValue(isOugc);
 			}
 
@@ -4566,6 +5336,69 @@
 			else {
 				treePanel.reset();
 			}
+=======
+
+				// If fav has organisation units, wait for tree callback before update
+				if (recMap[dimConf.organisationUnit.objectName] && Ext.isObject(graphMap)) {
+					treePanel.numberOfRecords = pt.util.object.getLength(graphMap);
+
+                    for (var i = 0, a = xLayout.objectNameItemsMap[dimConf.organisationUnit.objectName]; i < a.length; i++) {
+                        if (graphMap.hasOwnProperty(a[i].id)) {
+                            treePanel.multipleExpand(a[i].id, graphMap[a[i].id], false);
+                        }
+                    }
+				}
+				else {
+					treePanel.reset();
+				}
+			};
+
+			viewport = Ext.create('Ext.container.Viewport', {
+				layout: 'border',
+				accordion: accordion,
+				accordionBody: accordionBody,
+				westRegion: westRegion,
+				centerRegion: centerRegion,
+				updateViewport: update,
+				layoutButton: layoutButton,
+				optionsButton: optionsButton,
+				favoriteButton: favoriteButton,
+				downloadButton: downloadButton,
+				interpretationButton: interpretationButton,
+				userOrganisationUnit: userOrganisationUnit,
+				userOrganisationUnitChildren: userOrganisationUnitChildren,
+				setFavorite: setFavorite,
+				items: [
+					westRegion,
+					centerRegion
+				],
+				listeners: {
+					render: function(vp) {
+						pt.viewport = vp;
+					},
+					afterrender: function() {
+						pt.init.afterRender();
+					}
+				}
+			});
+
+			addListeners = function() {
+				pt.store.indicatorAvailable.on('load', function() {
+					pt.util.multiselect.filterAvailable(indicatorAvailable, indicatorSelected);
+				});
+
+				pt.store.dataElementAvailable.on('load', function() {
+					pt.util.multiselect.filterAvailable(dataElementAvailable, dataElementSelected);
+				});
+
+				pt.store.dataSetAvailable.on('load', function(s) {
+					pt.util.multiselect.filterAvailable(dataSetAvailable, dataSetSelected);
+					s.sort('name', 'ASC');
+				});
+			}();
+
+			return viewport;
+>>>>>>> MERGE-SOURCE
 		};
 
 		viewport = Ext.create('Ext.container.Viewport', {

=== modified file 'dhis-2/dhis-web/dhis-web-pivot/src/main/webapp/dhis-web-pivot/app/scripts/core.js'
--- dhis-2/dhis-web/dhis-web-pivot/src/main/webapp/dhis-web-pivot/app/scripts/core.js	2013-08-25 18:44:06 +0000
+++ dhis-2/dhis-web/dhis-web-pivot/src/main/webapp/dhis-web-pivot/app/scripts/core.js	2013-09-18 14:05:25 +0000
@@ -344,6 +344,7 @@
 					}
 					return false;
 				}
+<<<<<<< TREE
 			};
 
 			util.array = {
@@ -547,6 +548,365 @@
 
 							if (record) {
 								records.push(record);
+=======
+			}
+			return true;
+		}
+	};
+
+	util.array = {
+		sortDimensions: function(dimensions, key) {
+			key = key || 'dimensionName';
+
+			// Sort object order
+			Ext.Array.sort(dimensions, function(a,b) {
+				if (a[key] < b[key]) {
+					return -1;
+				}
+				if (a[key] > b[key]) {
+					return 1;
+				}
+				return 0;
+			});
+
+			// Sort object items, ids
+			for (var i = 0, dim; i < dimensions.length; i++) {
+				dim = dimensions[i];
+
+				if (dim.items) {
+					dimensions[i].items = util.array.sortDimensions(dim.items, 'id');
+				}
+
+				if (dim.ids) {
+					dimensions[i].ids = dim.ids.sort();
+				}
+			}
+
+			return dimensions;
+		},
+
+		sortObjectsByString: function(array, key) {
+			key = key || 'name';
+			array.sort( function(a, b) {
+				var nameA = a[key].toLowerCase(),
+					nameB = b[key].toLowerCase();
+
+				if (nameA < nameB) {
+					return -1;
+				}
+				if (nameA > nameB) {
+					return 1;
+				}
+				return 0;
+			});
+			return array;
+		}
+	};
+
+	util.number = {
+		getNumberOfDecimals: function(x) {
+			var tmp = new String(x);
+			return (tmp.indexOf('.') > -1) ? (tmp.length - tmp.indexOf('.') - 1) : 0;
+		},
+
+		roundIf: function(x, fix) {
+			if (Ext.isString(x)) {
+				x = parseFloat(x);
+			}
+
+			if (Ext.isNumber(x) && Ext.isNumber(fix)) {
+				var dec = pt.util.number.getNumberOfDecimals(x);
+				return dec > fix ? x.toFixed(fix) : x;
+			}
+			return x;
+		},
+
+		pp: function(x, nf) {
+			nf = nf || 'space';
+
+			if (nf === 'none') {
+				return x;
+			}
+
+			return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, pt.conf.pivot.digitGroupSeparator[nf]);
+		}
+	};
+
+	util.pivot = {
+		getExtendedLayout: function(layout) {
+			var dimConf = pt.conf.finals.dimension,
+				layout = Ext.clone(layout),
+				xLayout = {
+					columns: [],
+					rows: [],
+					filters: [],
+
+					columnObjectNames: [],
+					columnDimensionNames: [],
+					rowObjectNames: [],
+					rowDimensionNames: [],
+
+					// Axis
+					axisDimensions: [],
+					axisObjectNames: [],
+					axisDimensionNames: [],
+
+						// For param string
+					sortedAxisDimensionNames: [],
+
+					// Filter
+					filterDimensions: [],
+					filterObjectNames: [],
+					filterDimensionNames: [],
+
+						// For param string
+					sortedFilterDimensions: [],
+
+					// All
+					dimensions: [],
+					objectNames: [],
+					dimensionNames: [],
+
+					// Object name maps
+					objectNameDimensionsMap: {},
+					objectNameItemsMap: {},
+					objectNameIdsMap: {},
+
+					// Dimension name maps
+					dimensionNameDimensionsMap: {},
+					dimensionNameItemsMap: {},
+					dimensionNameIdsMap: {},
+
+						// For param string
+					dimensionNameSortedIdsMap: {}
+				};
+
+			Ext.applyIf(xLayout, layout);
+
+			// Columns, rows, filters
+			if (layout.columns) {
+				for (var i = 0, dim, items, xDim; i < layout.columns.length; i++) {
+					dim = layout.columns[i];
+					items = dim.items;
+					xDim = {};
+
+					xDim.dimension = dim.dimension;
+					xDim.objectName = dim.dimension;
+					xDim.dimensionName = dimConf.objectNameMap[dim.dimension].dimensionName;
+
+					if (items) {
+						xDim.items = items;
+						xDim.ids = [];
+
+						for (var j = 0; j < items.length; j++) {
+							xDim.ids.push(items[j].id);
+						}
+					}
+
+					xLayout.columns.push(xDim);
+
+					xLayout.columnObjectNames.push(xDim.objectName);
+					xLayout.columnDimensionNames.push(xDim.dimensionName);
+
+					xLayout.axisDimensions.push(xDim);
+					xLayout.axisObjectNames.push(xDim.objectName);
+					xLayout.axisDimensionNames.push(dimConf.objectNameMap[xDim.objectName].dimensionName);
+
+					xLayout.objectNameDimensionsMap[xDim.objectName] = xDim;
+					xLayout.objectNameItemsMap[xDim.objectName] = xDim.items;
+					xLayout.objectNameIdsMap[xDim.objectName] = xDim.ids;
+				}
+			}
+
+			if (layout.rows) {
+				for (var i = 0, dim, items, xDim; i < layout.rows.length; i++) {
+					dim = layout.rows[i];
+					items = dim.items;
+					xDim = {};
+
+					xDim.dimension = dim.dimension;
+					xDim.objectName = dim.dimension;
+					xDim.dimensionName = dimConf.objectNameMap[dim.dimension].dimensionName;
+
+					if (items) {
+						xDim.items = items;
+						xDim.ids = [];
+
+						for (var j = 0; j < items.length; j++) {
+							xDim.ids.push(items[j].id);
+						}
+					}
+
+					xLayout.rows.push(xDim);
+
+					xLayout.rowObjectNames.push(xDim.objectName);
+					xLayout.rowDimensionNames.push(xDim.dimensionName);
+
+					xLayout.axisDimensions.push(xDim);
+					xLayout.axisObjectNames.push(xDim.objectName);
+					xLayout.axisDimensionNames.push(dimConf.objectNameMap[xDim.objectName].dimensionName);
+
+					xLayout.objectNameDimensionsMap[xDim.objectName] = xDim;
+					xLayout.objectNameItemsMap[xDim.objectName] = xDim.items;
+					xLayout.objectNameIdsMap[xDim.objectName] = xDim.ids;
+				}
+			}
+
+			if (layout.filters) {
+				for (var i = 0, dim, items, xDim; i < layout.filters.length; i++) {
+					dim = layout.filters[i];
+					items = dim.items;
+					xDim = {};
+
+					xDim.dimension = dim.dimension;
+					xDim.objectName = dim.dimension;
+					xDim.dimensionName = dimConf.objectNameMap[dim.dimension].dimensionName;
+
+					if (items) {
+						xDim.items = items;
+						xDim.ids = [];
+
+						for (var j = 0; j < items.length; j++) {
+							xDim.ids.push(items[j].id);
+						}
+					}
+
+					xLayout.filters.push(xDim);
+
+					xLayout.filterDimensions.push(xDim);
+					xLayout.filterObjectNames.push(xDim.objectName);
+					xLayout.filterDimensionNames.push(dimConf.objectNameMap[xDim.objectName].dimensionName);
+
+					xLayout.objectNameDimensionsMap[xDim.objectName] = xDim;
+					xLayout.objectNameItemsMap[xDim.objectName] = xDim.items;
+					xLayout.objectNameIdsMap[xDim.objectName] = xDim.ids;
+				}
+			}
+
+			// Unique dimension names
+			xLayout.axisDimensionNames = Ext.Array.unique(xLayout.axisDimensionNames);
+			xLayout.filterDimensionNames = Ext.Array.unique(xLayout.filterDimensionNames);
+
+			xLayout.columnDimensionNames = Ext.Array.unique(xLayout.columnDimensionNames);
+			xLayout.rowDimensionNames = Ext.Array.unique(xLayout.rowDimensionNames);
+			xLayout.filterDimensionNames = Ext.Array.unique(xLayout.filterDimensionNames);
+
+				// For param string
+			xLayout.sortedAxisDimensionNames = Ext.clone(xLayout.axisDimensionNames).sort();
+			xLayout.sortedFilterDimensions = pt.util.array.sortDimensions(Ext.clone(xLayout.filterDimensions));
+
+			// All
+			xLayout.dimensions = [].concat(xLayout.axisDimensions, xLayout.filterDimensions);
+			xLayout.objectNames = [].concat(xLayout.axisObjectNames, xLayout.filterObjectNames);
+			xLayout.dimensionNames = [].concat(xLayout.axisDimensionNames, xLayout.filterDimensionNames);
+
+			// Dimension name maps
+			for (var i = 0, dimName; i < xLayout.dimensionNames.length; i++) {
+				dimName = xLayout.dimensionNames[i];
+
+				xLayout.dimensionNameDimensionsMap[dimName] = [];
+				xLayout.dimensionNameItemsMap[dimName] = [];
+				xLayout.dimensionNameIdsMap[dimName] = [];
+			}
+
+			for (var i = 0, xDim; i < xLayout.dimensions.length; i++) {
+				xDim = xLayout.dimensions[i];
+
+				xLayout.dimensionNameDimensionsMap[xDim.dimensionName].push(xDim);
+				xLayout.dimensionNameItemsMap[xDim.dimensionName] = xLayout.dimensionNameItemsMap[xDim.dimensionName].concat(xDim.items);
+				xLayout.dimensionNameIdsMap[xDim.dimensionName] = xLayout.dimensionNameIdsMap[xDim.dimensionName].concat(xDim.ids);
+			}
+
+				// For param string
+			for (var key in xLayout.dimensionNameIdsMap) {
+				if (xLayout.dimensionNameIdsMap.hasOwnProperty(key)) {
+					xLayout.dimensionNameSortedIdsMap[key] = Ext.clone(xLayout.dimensionNameIdsMap[key]).sort();
+				}
+			}
+
+			return xLayout;
+		},
+
+		getParamString: function(xLayout, isSorted) {
+			var axisDimensionNames = isSorted ? xLayout.sortedAxisDimensionNames : xLayout.axisDimensionNames,
+				filterDimensions = isSorted ? xLayout.sortedFilterDimensions : xLayout.filterDimensions,
+				dimensionNameIdsMap = isSorted ? xLayout.dimensionNameSortedIdsMap : xLayout.dimensionNameIdsMap,
+				paramString = '?',
+				dimConf = pt.conf.finals.dimension,
+				addCategoryDimension = false,
+				map = xLayout.dimensionNameItemsMap,
+				dx = dimConf.indicator.dimensionName;
+
+			for (var i = 0, dimName, items; i < axisDimensionNames.length; i++) {
+				dimName = axisDimensionNames[i];
+
+				paramString += 'dimension=' + dimName;
+
+				items = Ext.clone(dimensionNameIdsMap[dimName]);
+
+				if (dimName === dx) {
+					for (var j = 0, index; j < items.length; j++) {
+						index = items[j].indexOf('-');
+
+						if (index > 0) {
+							addCategoryDimension = true;
+							items[j] = items[j].substr(0, index);
+						}
+					}
+
+					items = Ext.Array.unique(items);
+				}
+
+				if (dimName !== dimConf.category.dimensionName) {
+					paramString += ':' + items.join(';');
+				}
+
+				if (i < (axisDimensionNames.length - 1)) {
+					paramString += '&';
+				}
+			}
+
+			if (addCategoryDimension) {
+				paramString += '&dimension=' + pt.conf.finals.dimension.category.dimensionName;
+			}
+
+			if (Ext.isArray(filterDimensions) && filterDimensions.length) {
+				for (var i = 0, dim; i < filterDimensions.length; i++) {
+					dim = filterDimensions[i];
+
+					paramString += '&filter=' + dim.dimensionName + ':' + dim.ids.join(';');
+				}
+			}
+
+			return paramString;
+		},
+
+		createTable: function(layout, pt) {
+			var dimConf = pt.conf.finals.dimension,
+				getSyncronizedXLayout,
+				//getParamString,
+				getExtendedResponse,
+				getExtendedAxis,
+				validateUrl,
+				getTableHtml,
+				initialize;
+
+			getSyncronizedXLayout = function(xLayout, response) {
+				var removeDimensionFromXLayout,
+					getHeaderNames,
+					dimensions = [].concat(xLayout.columns, xLayout.rows, xLayout.filters);
+
+				removeDimensionFromXLayout = function(objectName) {
+					var getUpdatedAxis;
+
+					getUpdatedAxis = function(axis) {
+						var dimension;
+						axis = Ext.clone(axis);
+
+						for (var i = 0; i < axis.length; i++) {
+							if (axis[i].dimension === objectName) {
+								dimension = axis[i];
+>>>>>>> MERGE-SOURCE
 							}
 						}
 
@@ -1923,6 +2283,7 @@
 							}
 
 							if (obj.parent) {
+<<<<<<< TREE
 								recursiveReduce(obj.parent);
 							}
 						};
@@ -2017,6 +2378,98 @@
 									empty: !Ext.Array.contains(empty, false)
 								});
 
+=======
+								obj.parent.children = obj.parent.children - 1;
+							}
+						}
+
+						if (obj.parent) {
+							recursiveReduce(obj.parent);
+						}
+					};
+
+					// Populate dim objects
+					if (xRowAxis) {
+						for (var i = 0, row; i < xRowAxis.objects.all[0].length; i++) {
+							row = [];
+
+							for (var j = 0, obj, newObj; j < xRowAxis.objects.all.length; j++) {
+								obj = xRowAxis.objects.all[j][i];
+								obj.type = 'dimension';
+								obj.cls = 'pivot-dim td-nobreak';
+								obj.noBreak = true;
+								obj.hidden = !(obj.rowSpan || obj.colSpan);
+								obj.htmlValue = xResponse.metaData.names[obj.id];
+
+								row.push(obj);
+							}
+
+							axisObjects.push(row);
+						}
+					}
+
+					// Value objects
+					for (var i = 0, valueItemsRow, valueObjectsRow, map = Ext.clone(xResponse.idValueMap); i < rowSize; i++) {
+						valueItemsRow = [];
+						valueObjectsRow = [];
+
+						for (var j = 0, id, value, htmlValue, empty; j < colSize; j++) {
+							id = (xColAxis ? xColAxis.ids[j] : '') + (xRowAxis ? xRowAxis.ids[i] : '');
+							empty = false;
+
+							if (map[id]) {
+								value = parseFloat(map[id]);
+								htmlValue = parseFloat(map[id]).toString();
+							}
+							else {
+								value = 0;
+								htmlValue = '&nbsp;';
+								empty = true;
+							}
+
+							valueItemsRow.push(value);
+							valueObjectsRow.push({
+								type: 'value',
+								cls: 'pivot-value',
+								value: value,
+								htmlValue: htmlValue,
+								empty: empty
+							});
+						}
+
+						valueItems.push(valueItemsRow);
+						valueObjects.push(valueObjectsRow);
+					}
+
+					// Value total objects
+					if (xColAxis && doTotals()) {
+						for (var i = 0, empty = [], total = 0; i < valueObjects.length; i++) {
+							for (j = 0, obj; j < valueObjects[i].length; j++) {
+								obj = valueObjects[i][j];
+
+								empty.push(obj.empty);
+								total += obj.value;
+							}
+
+							totalValueObjects.push({
+								type: 'valueTotal',
+								cls: 'pivot-value-total',
+								value: total,
+								htmlValue: Ext.Array.contains(empty, false) ? parseFloat(pt.util.number.roundIf(total, 2)).toString() : '&nbsp;',
+								empty: !Ext.Array.contains(empty, false)
+							});
+
+							empty = [];
+							total = 0;
+						}
+					}
+
+					// Hide empty rows (dims/values/totals)
+					if (xColAxis && xRowAxis) {
+						if (layout.hideEmptyRows) {
+							for (var i = 0, valueRow, empty, parent; i < valueObjects.length; i++) {
+								valueRow = valueObjects[i];
+>>>>>>> MERGE-SOURCE
 								empty = [];
 								total = 0;
 							}
@@ -2030,6 +2483,7 @@
 									empty = [];
 
 									for (var j = 0; j < valueRow.length; j++) {
+<<<<<<< TREE
 										empty.push(!!valueRow[j].empty);
 									}
 
@@ -2187,13 +2641,139 @@
 										cls: 'pivot-value-total-subgrandtotal',
 										value: subTotal,
 										htmlValue: Ext.Array.contains(empty, false) ? getRoundedHtmlValue(subTotal) : '',
+=======
+										valueRow[j].collapsed = true;
+									}
+
+									// Hide total
+									if (doTotals()) {
+										totalValueObjects[i].collapsed = true;
+									}
+
+									// Hide/reduce parent dim span
+									parent = axisObjects[i][xRowAxis.dims-1];
+									recursiveReduce(parent);
+								}
+							}
+						}
+					}
+
+					xValueObjects = Ext.clone(valueObjects);
+
+					// Col subtotals
+					if (doSubTotals(xColAxis)) {
+						var tmpValueObjects = [];
+
+						for (var i = 0, row, rowSubTotal, colCount; i < xValueObjects.length; i++) {
+							row = [];
+							rowSubTotal = 0;
+							colCount = 0;
+
+							for (var j = 0, item, collapsed = [], empty = []; j < xValueObjects[i].length; j++) {
+								item = xValueObjects[i][j];
+								rowSubTotal += item.value;
+								empty.push(!!item.empty);
+								collapsed.push(!!item.collapsed);
+								colCount++;
+
+								row.push(item);
+
+								if (colCount === colUniqueFactor) {
+									row.push({
+										type: 'valueSubtotal',
+										cls: 'pivot-value-subtotal',
+										value: rowSubTotal,
+										htmlValue: Ext.Array.contains(empty, false) ? parseFloat(pt.util.number.roundIf(rowSubTotal, 2)).toString() : '&nbsp',
+>>>>>>> MERGE-SOURCE
 										empty: !Ext.Array.contains(empty, false),
 										collapsed: !Ext.Array.contains(collapsed, false)
 									});
 
 									collapsed = [];
+<<<<<<< TREE
 									empty = [];
+=======
+								}
+							}
+
+							tmpValueObjects.push(row);
+						}
+
+						xValueObjects = tmpValueObjects;
+					}
+
+					// Row subtotals
+					if (doSubTotals(xRowAxis)) {
+						var tmpAxisObjects = [],
+							tmpValueObjects = [],
+							tmpTotalValueObjects = [],
+							getAxisSubTotalRow;
+
+						getAxisSubTotalRow = function(collapsed) {
+							var row = [];
+
+							for (var i = 0, obj; i < xRowAxis.dims; i++) {
+								obj = {};
+								obj.type = 'dimensionSubtotal';
+								obj.cls = 'pivot-dim-subtotal';
+								obj.collapsed = Ext.Array.contains(collapsed, true);
+
+								if (i === 0) {
+									obj.htmlValue = '&nbsp;';
+									obj.colSpan = xRowAxis.dims;
+								}
+								else {
+									obj.hidden = true;
+								}
+
+								row.push(obj);
+							}
+
+							return row;
+						};
+
+						// tmpAxisObjects
+						for (var i = 0, row, collapsed = []; i < axisObjects.length; i++) {
+							tmpAxisObjects.push(axisObjects[i]);
+							collapsed.push(!!axisObjects[i][0].collapsed);
+
+							// Insert subtotal after last objects
+							if (!Ext.isArray(axisObjects[i+1]) || !!axisObjects[i+1][0].root) {
+								tmpAxisObjects.push(getAxisSubTotalRow(collapsed));
+
+								collapsed = [];
+							}
+						}
+
+						// tmpValueObjects
+						for (var i = 0; i < tmpAxisObjects.length; i++) {
+							tmpValueObjects.push([]);
+						}
+
+						for (var i = 0; i < xValueObjects[0].length; i++) {
+							for (var j = 0, rowCount = 0, tmpCount = 0, subTotal = 0, empty = [], collapsed, item; j < xValueObjects.length; j++) {
+								item = xValueObjects[j][i];
+								tmpValueObjects[tmpCount++].push(item);
+								subTotal += item.value;
+								empty.push(!!item.empty);
+								rowCount++;
+
+								if (axisObjects[j][0].root) {
+									collapsed = !!axisObjects[j][0].collapsed;
+								}
+
+								if (!Ext.isArray(axisObjects[j+1]) || axisObjects[j+1][0].root) {
+									tmpValueObjects[tmpCount++].push({
+										type: item.type === 'value' ? 'valueSubtotal' : 'valueSubtotalTotal',
+										value: subTotal,
+										htmlValue: Ext.Array.contains(empty, false) ? parseFloat(pt.util.number.roundIf(subTotal, 2)).toString() : '&nbsp;',
+										collapsed: collapsed,
+										cls: item.type === 'value' ? 'pivot-value-subtotal' : 'pivot-value-subtotal-total'
+									});
+									rowCount = 0;
+>>>>>>> MERGE-SOURCE
 									subTotal = 0;
+<<<<<<< TREE
 									count = 0;
 								}
 							}
@@ -2253,6 +2833,29 @@
 									type: 'valueTotal',
 									value: total,
 									htmlValue: Ext.Array.contains(empty, false) ? getRoundedHtmlValue(total) : '',
+=======
+									empty = [];
+								}
+							}
+						}
+
+						// tmpTotalValueObjects
+						for (var i = 0, obj, collapsed = [], empty = [], subTotal = 0, count = 0; i < totalValueObjects.length; i++) {
+							obj = totalValueObjects[i];
+							tmpTotalValueObjects.push(obj);
+
+							collapsed.push(!!obj.collapsed);
+							empty.push(!!obj.empty);
+							subTotal += obj.value;
+							count++;
+
+							if (count === xRowAxis.span[0]) {
+								tmpTotalValueObjects.push({
+									type: 'valueTotalSubgrandtotal',
+									cls: 'pivot-value-total-subgrandtotal',
+									value: subTotal,
+									htmlValue: Ext.Array.contains(empty, false) ? parseFloat(pt.util.number.roundIf(subTotal, 2)).toString() : '&nbsp;',
+>>>>>>> MERGE-SOURCE
 									empty: !Ext.Array.contains(empty, false),
 									cls: 'pivot-value-total'
 								});
@@ -2309,6 +2912,7 @@
 								obj = totalColObjects[i];
 
 								total += obj.value;
+<<<<<<< TREE
 								empty.push(obj.empty);
 							}
 
@@ -2481,6 +3085,127 @@
 					});
 
 				}();
+=======
+								empty.push(!!obj.empty);
+							}
+
+							totalColObjects.push({
+								type: 'valueTotal',
+								value: total,
+								htmlValue: Ext.Array.contains(empty, false) ? parseFloat(pt.util.number.roundIf(total, 2)).toString() : '&nbsp;',
+								empty: !Ext.Array.contains(empty, false),
+								cls: 'pivot-value-total'
+							});
+
+							total = 0;
+							empty = [];
+						}
+
+						xTotalColObjects = Ext.clone(totalColObjects);
+
+						if (xColAxis && doSubTotals(xColAxis)) {
+							var tmp = [];
+
+							for (var i = 0, item, subTotal = 0, empty = [], colCount = 0; i < xTotalColObjects.length; i++) {
+								item = xTotalColObjects[i];
+								tmp.push(item);
+								subTotal += item.value;
+								empty.push(!!item.empty);
+								colCount++;
+
+								if (colCount === colUniqueFactor) {
+									tmp.push({
+										type: 'valueTotalSubgrandtotal',
+										value: subTotal,
+										htmlValue: Ext.Array.contains(empty, false) ? parseFloat(pt.util.number.roundIf(subTotal, 2)).toString() : '&nbsp;',
+										empty: !Ext.Array.contains(empty, false),
+										cls: 'pivot-value-total-subgrandtotal'
+									});
+
+									subTotal = 0;
+									colCount = 0;
+								}
+							}
+
+							xTotalColObjects = tmp;
+						}
+
+						// Total col html items
+						for (var i = 0; i < xTotalColObjects.length; i++) {
+							a.push(getTdHtml(xTotalColObjects[i]));
+						}
+					}
+
+					return a;
+				};
+
+				getGrandTotalHtmlArray = function() {
+					var total = 0,
+						empty = [],
+						a = [];
+
+					if (doTotals()) {
+						for (var i = 0, obj; i < totalColObjects.length; i++) {
+							obj = totalColObjects[i];
+
+							total += obj.value;
+							empty.push(obj.empty);
+							//values.push(totalColObjects[i].value);
+						}
+
+						if (xColAxis && xRowAxis) {
+							a.push(getTdHtml({
+								type: 'valueGrandTotal',
+								cls: 'pivot-value-grandtotal',
+								htmlValue: Ext.Array.contains(empty, false) ? parseFloat(pt.util.number.roundIf(total, 2)).toString() : '&nbsp;',
+								empty: !Ext.Array.contains(empty, false)
+							}));
+						}
+					}
+
+					return a;
+				};
+
+				getTotalHtmlArray = function() {
+					var dimTotalArray,
+						colTotal = getColTotalHtmlArray(),
+						grandTotal = getGrandTotalHtmlArray(),
+						row,
+						a = [];
+
+					if (doTotals()) {
+						if (xRowAxis) {
+							dimTotalArray = [getTdHtml({
+								type: 'dimensionSubtotal',
+								cls: 'pivot-dim-total',
+								colSpan: xRowAxis.dims,
+								htmlValue: 'Total'
+							})];
+						}
+
+						row = [].concat(dimTotalArray || [], Ext.clone(colTotal) || [], Ext.clone(grandTotal) || []);
+
+						a.push(row);
+					}
+
+					return a;
+				};
+
+				getHtml = function() {
+					var s = '<table id="' + pt.el + '" class="pivot">';
+
+					for (var i = 0; i < htmlArray.length; i++) {
+						s += '<tr>' + htmlArray[i].join('') + '</tr>';
+					}
+
+					return s += '</table>';
+				};
+
+				htmlArray = [].concat(getColAxisHtmlArray(), getRowHtmlArray(), getTotalHtmlArray());
+				htmlArray = Ext.Array.clean(htmlArray);
+
+				return getHtml(htmlArray);
+>>>>>>> MERGE-SOURCE
 			};
 
 			engine.loadTable = function(id, pt) {

=== modified file 'dhis-2/dhis-web/dhis-web-portal/india-pom.xml'
--- dhis-2/dhis-web/dhis-web-portal/india-pom.xml	2013-09-05 11:11:36 +0000
+++ dhis-2/dhis-web/dhis-web-portal/india-pom.xml	2013-09-18 14:05:25 +0000
@@ -2,21 +2,25 @@
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance";
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd";>
   <modelVersion>4.0.0</modelVersion>
-  
+
   <parent>
     <groupId>org.hisp.dhis</groupId>
     <artifactId>dhis-web</artifactId>
+<<<<<<< TREE
     <version>2.13-SNAPSHOT</version>
+=======
+    <version>2.12</version>
+>>>>>>> MERGE-SOURCE
   </parent>
-  
-  <artifactId>dhis-web-india-portal</artifactId>
+
+  <artifactId>dhis-web-portal</artifactId>
   <packaging>war</packaging>
   <name>DHIS Web Portal</name>
-  
+
   <build>
     <finalName>dhis</finalName>
   </build>
-  
+
   <dependencies>
 
     <dependency>
@@ -170,6 +174,7 @@
       <version>${project.version}</version>
       <type>war</type>
     </dependency>
+<<<<<<< TREE
     <dependency>
       <groupId>org.hisp.dhis</groupId>
       <artifactId>dhis-web-pivot</artifactId>
@@ -197,6 +202,81 @@
       <type>war</type>
     </dependency>
 	
+=======
+    <dependency>
+      <groupId>org.hisp.dhis</groupId>
+      <artifactId>dhis-web-pivot</artifactId>
+      <version>${project.version}</version>
+      <type>war</type>
+    </dependency>
+    <dependency>
+      <groupId>org.hisp.dhis</groupId>
+      <artifactId>dhis-web-appmanager</artifactId>
+      <version>${project.version}</version>
+      <type>war</type>
+    </dependency>
+	
+    <!-- India modules -->
+    	
+    <dependency>
+      <groupId>org.hisp.dhis</groupId>
+      <artifactId>dhis-web-alert</artifactId>
+      <version>${project.version}</version>
+      <type>war</type>
+    </dependency>
+	
+    <dependency>
+      <groupId>org.hisp.dhis</groupId>
+      <artifactId>dhis-web-dashboard</artifactId>
+      <version>${project.version}</version>
+      <type>war</type>
+    </dependency>
+	
+	<dependency>
+      <groupId>org.hisp.dhis</groupId>
+      <artifactId>dhis-web-dataentry-national</artifactId>
+      <version>${project.version}</version>
+      <type>war</type>
+    </dependency> 
+	
+    <dependency>
+      <groupId>org.hisp.dhis</groupId>
+      <artifactId>dhis-web-excelimport</artifactId>
+      <version>${project.version}</version>
+      <type>war</type>
+    </dependency>
+
+    <dependency>
+      <groupId>org.hisp.dhis</groupId>
+      <artifactId>dhis-web-maintenance-in</artifactId>
+      <version>${project.version}</version>
+      <type>war</type>
+    </dependency>
+
+    <dependency>
+      <groupId>org.hisp.dhis</groupId>
+      <artifactId>dhis-web-reports-national</artifactId>
+      <version>${project.version}</version>
+      <type>war</type>
+    </dependency>
+
+    <dependency>
+      <groupId>org.hisp.dhis</groupId>
+      <artifactId>dhis-web-survey</artifactId>
+      <version>${project.version}</version>
+      <type>war</type>
+    </dependency>
+	
+	<!-- SMS Mobile application -->
+	<!--
+    <dependency>
+      <groupId>org.hisp.dhis</groupId>
+      <artifactId>dhis-web-mobile</artifactId>
+      <version>${project.version}</version>
+      <type>war</type>
+    </dependency>
+	-->       
+>>>>>>> MERGE-SOURCE
   </dependencies>
   
   <properties>

=== modified file 'dhis-2/dhis-web/dhis-web-reporting/src/main/java/org/hisp/dhis/reporting/document/action/SaveDocumentAction.java'
=== modified file 'dhis-2/dhis-web/dhis-web-reporting/src/main/webapp/dhis-web-reporting/viewDataMartForm.vm'
=== modified file 'dhis-2/dhis-web/dhis-web-visualizer/src/main/webapp/dhis-web-visualizer/app/scripts/app.js'
--- dhis-2/dhis-web/dhis-web-visualizer/src/main/webapp/dhis-web-visualizer/app/scripts/app.js	2013-09-12 16:17:45 +0000
+++ dhis-2/dhis-web/dhis-web-visualizer/src/main/webapp/dhis-web-visualizer/app/scripts/app.js	2013-09-18 14:05:25 +0000
@@ -4654,6 +4654,7 @@
 				toolMenu.clickHandler('orgunit');
 				userOrganisationUnit.setValue(isOu);
 				userOrganisationUnitChildren.setValue(isOuc);
+<<<<<<< TREE
 				userOrganisationUnitGrandChildren.setValue(isOugc);
 			}
 
@@ -4740,6 +4741,73 @@
 		// right click handler
 		document.body.oncontextmenu = function() {
 			return false;
+=======
+
+				// If fav has organisation units, wait for tree callback before update
+				if (recMap[dimConf.organisationUnit.objectName] && Ext.isObject(graphMap)) {
+					treePanel.numberOfRecords = dv.util.object.getLength(graphMap);
+
+                    for (var i = 0, a = xLayout.objectNameItemsMap[dimConf.organisationUnit.objectName]; i < a.length; i++) {
+                        if (graphMap.hasOwnProperty(a[i].id)) {
+                            treePanel.multipleExpand(a[i].id, graphMap[a[i].id], false);
+                        }
+                    }
+				}
+				else {
+					treePanel.reset();
+				}
+			};
+
+			viewport = Ext.create('Ext.container.Viewport', {
+				layout: 'border',
+				chartType: chartType,
+				series: series,
+				category: category,
+				filter: filter,
+				accordion: accordion,
+				accordionBody: accordionBody,
+				westRegion: westRegion,
+				centerRegion: centerRegion,
+				updateViewport: update,
+				optionsButton: optionsButton,
+				favoriteButton: favoriteButton,
+				downloadButton: downloadButton,
+				interpretationButton: interpretationButton,
+				userOrganisationUnit: userOrganisationUnit,
+				userOrganisationUnitChildren: userOrganisationUnitChildren,
+				dataElementDetailLevel: dataElementDetailLevel,
+				setFavorite: setFavorite,
+				items: [
+					westRegion,
+					centerRegion
+				],
+				listeners: {
+					render: function(vp) {
+						dv.viewport = vp;
+					},
+					afterrender: function() {
+						dv.init.afterRender();
+					}
+				}
+			});
+
+			addListeners = function() {
+				dv.store.indicatorAvailable.on('load', function() {
+					dv.util.multiselect.filterAvailable(indicatorAvailable, indicatorSelected);
+				});
+
+				dv.store.dataElementAvailable.on('load', function() {
+					dv.util.multiselect.filterAvailable(dataElementAvailable, dataElementSelected);
+				});
+
+				dv.store.dataSetAvailable.on('load', function(s) {
+					dv.util.multiselect.filterAvailable(dataSetAvailable, dataSetSelected);
+					s.sort('name', 'ASC');
+				});
+			}();
+
+			return viewport;
+>>>>>>> MERGE-SOURCE
 		};
 
         Ext.Ajax.request({

=== modified file 'dhis-2/dhis-web/pom.xml'
--- dhis-2/dhis-web/pom.xml	2013-05-31 08:27:38 +0000
+++ dhis-2/dhis-web/pom.xml	2013-09-18 14:05:25 +0000
@@ -47,12 +47,19 @@
       <plugin>
         <groupId>org.mortbay.jetty</groupId>
         <artifactId>maven-jetty-plugin</artifactId>
-        <version>6.1.26</version>
+        <!-- <version>6.1.26</version> -->
         <configuration>
+          <scanIntervalSeconds>10</scanIntervalSeconds>
           <systemPropertyVariables>
             <org.mortbay.jetty.Request.maxFormContentSize>10000000</org.mortbay.jetty.Request.maxFormContentSize>
           </systemPropertyVariables>
           <contextPath>/</contextPath>
+           <connectors>
+            <!-- work around file locking on windows -->
+            <connector implementation="org.mortbay.jetty.bio.SocketConnector">
+                <port>8080</port><!-- this connector defaults to 1300 for some reason -->
+            </connector>
+        	</connectors>
         </configuration>
       </plugin>
     </plugins>

=== modified file 'dhis-2/pom.xml'
=== modified file 'local/in/dhis-in-api/pom.xml'
--- local/in/dhis-in-api/pom.xml	2013-08-13 12:39:25 +0000
+++ local/in/dhis-in-api/pom.xml	2013-09-18 14:05:25 +0000
@@ -1,3 +1,4 @@
+<<<<<<< TREE
 <project xmlns="http://maven.apache.org/POM/4.0.0"; xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance";
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd";>
   <modelVersion>4.0.0</modelVersion>
@@ -19,4 +20,30 @@
     </dependency>
   </dependencies>
 			
+=======
+<project xmlns="http://maven.apache.org/POM/4.0.0";
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance";
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd";>
+    <modelVersion>4.0.0</modelVersion>
+
+    <parent>
+        <groupId>org.hisp.dhis</groupId>
+        <artifactId>dhis</artifactId>
+        <version>2.12</version>
+    </parent>
+
+    <artifactId>dhis-in-api</artifactId>
+    <packaging>jar</packaging>
+    <name>DHIS India API</name>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.hisp.dhis</groupId>
+            <artifactId>dhis-api</artifactId>
+            <version>${project.version}</version>
+        </dependency>
+    </dependencies>
+
+
+>>>>>>> MERGE-SOURCE
 </project>

=== renamed file 'local/in/dhis-in-api/src/main/java/org/hisp/dhis/coldchain/reports/CCEMReport.java' => 'local/in/dhis-in-api/src/main/java/org/hisp/dhis/coldchain/reports/CCEMReport.java.THIS'
=== removed file 'local/in/dhis-in-api/src/main/java/org/hisp/dhis/coldchain/reports/CCEMReportDesign.java'
--- local/in/dhis-in-api/src/main/java/org/hisp/dhis/coldchain/reports/CCEMReportDesign.java	2012-06-13 06:35:38 +0000
+++ local/in/dhis-in-api/src/main/java/org/hisp/dhis/coldchain/reports/CCEMReportDesign.java	1970-01-01 00:00:00 +0000
@@ -1,43 +0,0 @@
-package org.hisp.dhis.coldchain.reports;
-
-public class CCEMReportDesign
-{
-
-    private int row;
-    
-    private String content;
-    
-    private String displayheading;
-    
-
-    public int getRow()
-    {
-        return row;
-    }
-
-    public void setRow( int row )
-    {
-        this.row = row;
-    }
-
-    public String getContent()
-    {
-        return content;
-    }
-
-    public void setContent( String content )
-    {
-        this.content = content;
-    }
-
-    public String getDisplayheading()
-    {
-        return displayheading;
-    }
-
-    public void setDisplayheading( String displayheading )
-    {
-        this.displayheading = displayheading;
-    }
-    
-}

=== renamed file 'local/in/dhis-in-api/src/main/java/org/hisp/dhis/coldchain/reports/CCEMReportManager.java' => 'local/in/dhis-in-api/src/main/java/org/hisp/dhis/coldchain/reports/CCEMReportManager.java.THIS'
=== removed file 'local/in/dhis-in-api/src/main/java/org/hisp/dhis/coldchain/reports/CCEMReportOutput.java'
--- local/in/dhis-in-api/src/main/java/org/hisp/dhis/coldchain/reports/CCEMReportOutput.java	2012-06-27 06:56:57 +0000
+++ local/in/dhis-in-api/src/main/java/org/hisp/dhis/coldchain/reports/CCEMReportOutput.java	1970-01-01 00:00:00 +0000
@@ -1,68 +0,0 @@
-package org.hisp.dhis.coldchain.reports;
-
-import java.util.List;
-
-public class CCEMReportOutput
-{
-
-    private String reportHeading;
-    
-    private String outputType;
-    
-    private List<String> tableHeadings;
-    
-    private List<List<String>> tableSubHeadings;
-    
-    private List<List<String>> tableData;
-
-    public List<String> getTableHeadings()
-    {
-        return tableHeadings;
-    }
-
-    public void setTableHeadings( List<String> tableHeadings )
-    {
-        this.tableHeadings = tableHeadings;
-    }
-
-    public List<List<String>> getTableData()
-    {
-        return tableData;
-    }
-
-    public void setTableData( List<List<String>> tableData )
-    {
-        this.tableData = tableData;
-    }
-
-    public List<List<String>> getTableSubHeadings()
-    {
-        return tableSubHeadings;
-    }
-
-    public void setTableSubHeadings( List<List<String>> tableSubHeadings )
-    {
-        this.tableSubHeadings = tableSubHeadings;
-    }
-
-    public String getReportHeading()
-    {
-        return reportHeading;
-    }
-
-    public void setReportHeading( String reportHeading )
-    {
-        this.reportHeading = reportHeading;
-    }
-
-    public String getOutputType()
-    {
-        return outputType;
-    }
-
-    public void setOutputType( String outputType )
-    {
-        this.outputType = outputType;
-    }
-    
-}

=== removed file 'local/in/dhis-in-api/src/main/java/org/hisp/dhis/coldchain/reports/CCEMSettings.java'
--- local/in/dhis-in-api/src/main/java/org/hisp/dhis/coldchain/reports/CCEMSettings.java	2012-06-13 06:35:38 +0000
+++ local/in/dhis-in-api/src/main/java/org/hisp/dhis/coldchain/reports/CCEMSettings.java	1970-01-01 00:00:00 +0000
@@ -1,30 +0,0 @@
-package org.hisp.dhis.coldchain.reports;
-
-public class CCEMSettings
-{
-
-    private String commonId;
-    
-    private String ccemId;
-
-    public String getCommonId()
-    {
-        return commonId;
-    }
-
-    public void setCommonId( String commonId )
-    {
-        this.commonId = commonId;
-    }
-
-    public String getCcemId()
-    {
-        return ccemId;
-    }
-
-    public void setCcemId( String ccemId )
-    {
-        this.ccemId = ccemId;
-    }
-    
-}

=== modified file 'local/in/dhis-in-api/src/main/java/org/hisp/dhis/config/Configuration_IN.java'
--- local/in/dhis-in-api/src/main/java/org/hisp/dhis/config/Configuration_IN.java	2012-05-30 10:46:26 +0000
+++ local/in/dhis-in-api/src/main/java/org/hisp/dhis/config/Configuration_IN.java	2013-09-18 14:05:25 +0000
@@ -39,7 +39,7 @@
     public static final String DEFAULT_REPORTFOLDER = "ra_national";
     
     public static final String DEFAULT_TEMPFOLDER = "temp";
-    
+
     private int id;
     
     private String key;

=== removed directory 'local/in/dhis-in-api/src/main/java/org/hisp/dhis/ihrissyncmanager'
=== removed file 'local/in/dhis-in-api/src/main/java/org/hisp/dhis/ihrissyncmanager/AggDataService.java'
--- local/in/dhis-in-api/src/main/java/org/hisp/dhis/ihrissyncmanager/AggDataService.java	2013-03-25 05:08:43 +0000
+++ local/in/dhis-in-api/src/main/java/org/hisp/dhis/ihrissyncmanager/AggDataService.java	1970-01-01 00:00:00 +0000
@@ -1,20 +0,0 @@
-package org.hisp.dhis.ihrissyncmanager;
-
-import org.hisp.dhis.dataelement.DataElement;
-import org.hisp.dhis.organisationunit.OrganisationUnit;
-import org.hisp.dhis.period.Period;
-
-/**
- * Gaurav<gaurav08021@xxxxxxxxx>, 8/27/12 [2:07 PM]
- */
-public interface AggDataService {
-
-    String ID = AggDataService.class.getName();
-
-    public DataElement createNewAggDataElement(String aggDataElementName);
-
-    public void addNewEntries(String aggDataElementName,OrganisationUnit orgUnit,Period period, Double aggValue);
-
-    public void deleteAggDataElement(String nameOfDataElement);
-
-}
\ No newline at end of file

=== removed file 'local/in/dhis-in-api/src/main/java/org/hisp/dhis/ihrissyncmanager/SyncIHRISOrgUnitService.java'
--- local/in/dhis-in-api/src/main/java/org/hisp/dhis/ihrissyncmanager/SyncIHRISOrgUnitService.java	2013-03-25 05:08:43 +0000
+++ local/in/dhis-in-api/src/main/java/org/hisp/dhis/ihrissyncmanager/SyncIHRISOrgUnitService.java	1970-01-01 00:00:00 +0000
@@ -1,13 +0,0 @@
-package org.hisp.dhis.ihrissyncmanager;
-
-import org.hisp.dhis.organisationunit.OrganisationUnit;
-
-/**
- * Gaurav<gaurav08021@xxxxxxxxx>, 8/29/12 [3:10 PM]
- */
-public interface SyncIHRISOrgUnitService {
-
-    String ID = SyncIHRISOrgUnitService.class.getName();
-
-    public OrganisationUnit createNewOrgUnit(String orgUnitName, String parentOrgUnitName);
-}

=== removed file 'local/in/dhis-in-api/src/main/java/org/hisp/dhis/ihrissyncmanager/SynciHRISUserService.java'
--- local/in/dhis-in-api/src/main/java/org/hisp/dhis/ihrissyncmanager/SynciHRISUserService.java	2013-03-25 05:08:43 +0000
+++ local/in/dhis-in-api/src/main/java/org/hisp/dhis/ihrissyncmanager/SynciHRISUserService.java	1970-01-01 00:00:00 +0000
@@ -1,19 +0,0 @@
-package org.hisp.dhis.ihrissyncmanager;
-
-import org.hisp.dhis.user.User;
-
-/**
- * Created with IntelliJ IDEA.
- * User: Mohit
- * Date: 29/8/12
- * Time: 1:44 PM
- * To change this template use File | Settings | File Templates.
- */
-public interface SynciHRISUserService
-{
-    String ID = SynciHRISUserService.class.getName();
-
-    public User createNewiHRISUser(String ihrisUsername, String firstName, String lastName, String email, String password);
-
-
-}

=== removed file 'local/in/dhis-in-api/src/main/java/org/hisp/dhis/reports/GlobalConfigService.java'
--- local/in/dhis-in-api/src/main/java/org/hisp/dhis/reports/GlobalConfigService.java	2012-06-30 10:19:34 +0000
+++ local/in/dhis-in-api/src/main/java/org/hisp/dhis/reports/GlobalConfigService.java	1970-01-01 00:00:00 +0000
@@ -1,19 +0,0 @@
-package org.hisp.dhis.reports;
-
-import java.io.File;
-import java.util.Map;
-
-/**
- * <gaurav>,Date: 6/26/12, Time: 2:25 PM
- */
-public interface GlobalConfigService {
-
-    String ID = GlobalConfigService.class.getName();
-
-    public File[] getFileNames();
-
-    public void updateDecodeFiles();
-
-    public void writeGlobalSettings(Map<String, String> globalValueMap);
-
-}

=== modified file 'local/in/dhis-in-api/src/main/java/org/hisp/dhis/reports/ReportModel.java'
--- local/in/dhis-in-api/src/main/java/org/hisp/dhis/reports/ReportModel.java	2010-12-29 07:57:25 +0000
+++ local/in/dhis-in-api/src/main/java/org/hisp/dhis/reports/ReportModel.java	2013-09-18 14:05:25 +0000
@@ -55,7 +55,8 @@
     
     public final static String RM_PROGRESSIVE_PERIOD = "PROGRESSIVE-PERIOD";
     
-        
+    public final static String RM_PROGRESSIVE_BATCH = "PROGRESSIVE-BATCH";
+    
     public static List<String> getReportModels()
     {
         List<String> reportModels = new ArrayList<String>();
@@ -81,6 +82,8 @@
         reportModels.add( RM_PROGRESSIVE_ORGUNIT );
         
         reportModels.add( RM_PROGRESSIVE_PERIOD );
+        
+        reportModels.add( RM_PROGRESSIVE_BATCH );
 
         return reportModels;            
     }

=== modified file 'local/in/dhis-in-api/src/main/java/org/hisp/dhis/reports/ReportService.java'
--- local/in/dhis-in-api/src/main/java/org/hisp/dhis/reports/ReportService.java	2012-07-26 09:20:56 +0000
+++ local/in/dhis-in-api/src/main/java/org/hisp/dhis/reports/ReportService.java	2013-09-18 14:05:25 +0000
@@ -36,8 +36,10 @@
 import org.hisp.dhis.dataelement.DataElement;
 import org.hisp.dhis.indicator.Indicator;
 import org.hisp.dhis.organisationunit.OrganisationUnit;
+import org.hisp.dhis.patient.Patient;
 import org.hisp.dhis.period.Period;
 import org.hisp.dhis.period.PeriodType;
+import org.hisp.dhis.program.Program;
 
 public interface ReportService
 {
@@ -68,7 +70,15 @@
     Collection<Report_in> getReportsByPeriodAndReportType( PeriodType periodType, String reportType );
 
     Collection<Report_in> getReportsByPeriodSourceAndReportType( PeriodType periodType, OrganisationUnit source, String reportType );
+	
+    // get Patients List ByOrgUnit
+    Collection<Patient> getPatientByOrgUnit( OrganisationUnit organisationUnit );
+    // get Programs List ByOrgUnit
+    Collection<Program> getProgramsByOrgUnit( OrganisationUnit organisationUnit );
 
+    // get Patients List By OrgUnit and Program
+    Collection<Patient> getPatientByOrgUnitAndProgram( OrganisationUnit organisationUnit, Program program );
+	
     // -------------------------------------------------------------------------
     // Report_in Design
     // -------------------------------------------------------------------------
@@ -105,6 +115,15 @@
     
     List<Report_inDesign> getReportDesign( String fileName );
     
+    
+    List<Report_inDesign> getReportDesignForGlobalSetting( String fileName );
+    
+    List<Report_inDesign> getReportDesignForTracker( String fileName );
+    
+    List<Report_inDesign> getReportDesignForHeader( String fileName );
+    
+    
+
     List<Report_inDesign> getDistrictFeedbackReportDesign( String fileName );
     
     String getResultDataValue( String formula, Date startDate, Date endDate, OrganisationUnit organisationUnit , String reportModelTB );
@@ -181,4 +200,18 @@
     String getDataelementIdsByStype( List<Report_inDesign> reportDesignList, String sType );
     
     Map<String, String> getAggNonNumberDataFromDataValueTable( String orgUnitIdsByComma, String dataElmentIdsByComma, String periodIdsByComma );
+    
+    
+    //
+    String getResultDataValueForOrgUnitGroupMember( String formula, String childOrgUnitsByComma ,Date startDate, Date endDate ,String reportModelTB );
+    
+    Integer getDataCountFromDataValueTable( String orgUnitIdsByComma, String dataElmentIdsByComma, String periodIdsByComma );
+    
+    
+    Map<String, String> getBatchDataFromDataValueTable( String orgUnitIdsByComma, String dataElmentIdsByComma, String periodIdsByComma );
+    
+    List<Report_inDesign> getHeaderInfo( String fileName );
+    
+    String getTextDataFromDataValueTable( String orgUnitIdsByComma, String dataElmentIdsByComma, String periodIdsByComma );
+    
 }

=== modified file 'local/in/dhis-in-api/src/main/java/org/hisp/dhis/reports/ReportStore.java'
--- local/in/dhis-in-api/src/main/java/org/hisp/dhis/reports/ReportStore.java	2012-04-16 11:29:53 +0000
+++ local/in/dhis-in-api/src/main/java/org/hisp/dhis/reports/ReportStore.java	2013-09-18 14:05:25 +0000
@@ -30,36 +30,44 @@
 import java.util.Collection;
 
 import org.hisp.dhis.organisationunit.OrganisationUnit;
+import org.hisp.dhis.patient.Patient;
 import org.hisp.dhis.period.PeriodType;
+import org.hisp.dhis.program.Program;
 
-public interface ReportStore
+public interface ReportStore 
 {
-    String ID = ReportStore.class.getName();
-
+        String ID = ReportStore.class.getName();
+        
     // -------------------------------------------------------------------------
     // Report_in
     // -------------------------------------------------------------------------
 
-    int addReport( Report_in report );
-
-    void updateReport( Report_in report );
-
-    void deleteReport( Report_in report );
-
-    Report_in getReport( int id );
-
-    Report_in getReportByName( String name );
-
-    Collection<Report_in> getReportBySource( OrganisationUnit source );
-
-    Collection<Report_in> getAllReports();
-
-    Collection<Report_in> getReportsByReportType( String reportType );
-
-    Collection<Report_in> getReportsByPeriodType( PeriodType periodType );
-
-    Collection<Report_in> getReportsByPeriodAndReportType( PeriodType periodType, String reportType );
-
-    Collection<Report_in> getReportsByPeriodSourceAndReportType( PeriodType periodType, OrganisationUnit source,
-        String reportType );
+        int addReport( Report_in report );
+        
+        void updateReport( Report_in report );
+        
+        void deleteReport( Report_in report );
+        
+        Report_in getReport( int id );
+        
+        Report_in getReportByName( String name );
+        
+        Collection<Report_in> getReportBySource( OrganisationUnit source );
+        
+        Collection<Report_in> getAllReports();
+        
+        Collection<Report_in> getReportsByReportType( String reportType );
+        
+        Collection<Report_in> getReportsByPeriodType( PeriodType periodType );
+        
+        Collection<Report_in> getReportsByPeriodAndReportType( PeriodType periodType, String reportType );
+
+        Collection<Report_in> getReportsByPeriodSourceAndReportType( PeriodType periodType, OrganisationUnit source, String reportType );
+		
+	// getPatientByOrgUnit
+	Collection<Patient> getPatientByOrgUnit( OrganisationUnit organisationUnit );
+    
+	// get Patients List By OrgUnit and Program
+	Collection<Patient> getPatientByOrgUnitAndProgram( OrganisationUnit organisationUnit, Program program );
+
 }

=== modified file 'local/in/dhis-in-api/src/main/java/org/hisp/dhis/reports/ReportType.java'
--- local/in/dhis-in-api/src/main/java/org/hisp/dhis/reports/ReportType.java	2012-07-24 12:38:31 +0000
+++ local/in/dhis-in-api/src/main/java/org/hisp/dhis/reports/ReportType.java	2013-09-18 14:05:25 +0000
@@ -67,6 +67,10 @@
     public final static String RT_RANKING_REPORT = "Ranking Reports";
 
     public final static String RT_FEEDBACK_TEMPLATE = "Feedback Template";
+    
+    public final static String RT_PROGRAMWISE_ORGUNITPROGRESS_REPORT = "Programwise OrgUnitProgress Reports";
+    
+    public final static String RT_PERIOD_ORGUNIT_SERVICE_PROGRESS_REPORT = "Period OrgUnit Progress Reports";
 
     public static List<String> getReportTypes()
     {
@@ -108,6 +112,10 @@
 
         reportTypes.add(RT_FEEDBACK_TEMPLATE);
         
+        reportTypes.add(RT_PROGRAMWISE_ORGUNITPROGRESS_REPORT);
+        
+        reportTypes.add(RT_PERIOD_ORGUNIT_SERVICE_PROGRESS_REPORT);
+        
         return reportTypes;
     }
 }

=== modified file 'local/in/dhis-in-api/src/main/java/org/hisp/dhis/reports/Report_inDesign.java'
--- local/in/dhis-in-api/src/main/java/org/hisp/dhis/reports/Report_inDesign.java	2012-07-24 12:38:31 +0000
+++ local/in/dhis-in-api/src/main/java/org/hisp/dhis/reports/Report_inDesign.java	2013-09-18 14:05:25 +0000
@@ -211,5 +211,4 @@
     public static final String E_PERIOD_MONTH = "PERIOD-MONTH";
     public static final String E_PERIOD_YEAR = "PERIOD-YEAR";
     
-    
 }
\ No newline at end of file

=== renamed file 'local/in/dhis-in-services/dhis-in-service-coldchain/pom.xml' => 'local/in/dhis-in-services/dhis-in-service-coldchain/pom.xml.THIS'
=== renamed file 'local/in/dhis-in-services/dhis-in-service-coldchain/src/main/java/org/hisp/dhis/coldchain/reports/DefaultCCEMReportManager.java' => 'local/in/dhis-in-services/dhis-in-service-coldchain/src/main/java/org/hisp/dhis/coldchain/reports/DefaultCCEMReportManager.java.THIS'
=== renamed file 'local/in/dhis-in-services/dhis-in-service-coldchain/src/main/resources/META-INF/dhis/beans.xml' => 'local/in/dhis-in-services/dhis-in-service-coldchain/src/main/resources/META-INF/dhis/beans.xml.THIS'
=== renamed file 'local/in/dhis-in-services/dhis-in-service-coldchain/src/main/resources/org/hisp/dhis/coldchain/hibernate/Equipment.hbm.xml' => 'local/in/dhis-in-services/dhis-in-service-coldchain/src/main/resources/org/hisp/dhis/coldchain/hibernate/Equipment.hbm.xml.THIS'
=== renamed file 'local/in/dhis-in-services/dhis-in-service-coldchain/src/main/resources/org/hisp/dhis/coldchain/hibernate/EquipmentDataValue.hbm.xml' => 'local/in/dhis-in-services/dhis-in-service-coldchain/src/main/resources/org/hisp/dhis/coldchain/hibernate/EquipmentDataValue.hbm.xml.THIS'
=== renamed file 'local/in/dhis-in-services/dhis-in-service-coldchain/src/main/resources/org/hisp/dhis/coldchain/hibernate/EquipmentStatus.hbm.xml' => 'local/in/dhis-in-services/dhis-in-service-coldchain/src/main/resources/org/hisp/dhis/coldchain/hibernate/EquipmentStatus.hbm.xml.THIS'
=== modified file 'local/in/dhis-in-services/dhis-in-service-configuration/pom.xml'
--- local/in/dhis-in-services/dhis-in-service-configuration/pom.xml	2013-08-13 12:39:25 +0000
+++ local/in/dhis-in-services/dhis-in-service-configuration/pom.xml	2013-09-18 14:05:25 +0000
@@ -1,11 +1,16 @@
-<project xmlns="http://maven.apache.org/POM/4.0.0"; xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance";
+<project xmlns="http://maven.apache.org/POM/4.0.0";
+  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance";
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd";>
   <modelVersion>4.0.0</modelVersion>
   
   <parent>
     <groupId>org.hisp.dhis</groupId>
     <artifactId>dhis-in-services</artifactId>
+<<<<<<< TREE
 	<version>2.13-SNAPSHOT</version>
+=======
+    <version>2.12</version>
+>>>>>>> MERGE-SOURCE
   </parent>
   
   <artifactId>dhis-in-service-configuration</artifactId>

=== modified file 'local/in/dhis-in-services/dhis-in-service-configuration/src/main/resources/org/hisp/dhis/config/hibernate/ConfigIn.hbm.xml'
--- local/in/dhis-in-services/dhis-in-service-configuration/src/main/resources/org/hisp/dhis/config/hibernate/ConfigIn.hbm.xml	2012-04-17 11:59:19 +0000
+++ local/in/dhis-in-services/dhis-in-service-configuration/src/main/resources/org/hisp/dhis/config/hibernate/ConfigIn.hbm.xml	2013-09-18 14:05:25 +0000
@@ -1,7 +1,7 @@
 <?xml version="1.0"?>
 <!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd";>
+  "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
+  "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd";>
 
 <hibernate-mapping>
   <class name="org.hisp.dhis.config.Configuration_IN" table="config_in">

=== modified file 'local/in/dhis-in-services/dhis-in-service-dataentrystatus/pom.xml'
--- local/in/dhis-in-services/dhis-in-service-dataentrystatus/pom.xml	2013-03-25 05:08:43 +0000
+++ local/in/dhis-in-services/dhis-in-service-dataentrystatus/pom.xml	2013-09-18 14:05:25 +0000
@@ -1,12 +1,13 @@
-<project xmlns="http://maven.apache.org/POM/4.0.0"; xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance";
+<project xmlns="http://maven.apache.org/POM/4.0.0";
+  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance";
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd";>
   <modelVersion>4.0.0</modelVersion>
   
-	<parent>
-		<groupId>org.hisp.dhis</groupId>
-		<artifactId>dhis-in-services</artifactId>
-		<version>2.12-SNAPSHOT</version>
-	</parent>
+  <parent>
+    <groupId>org.hisp.dhis</groupId>
+    <artifactId>dhis-in-services</artifactId>
+    <version>2.12</version>
+  </parent>
   
   <artifactId>dhis-in-service-dataentrystatus</artifactId>
   <packaging>jar</packaging>

=== modified file 'local/in/dhis-in-services/dhis-in-service-dataentrystatus/src/main/resources/org/hisp/dhis/dataentrystatus/hibernate/DataEntryStatus.hbm.xml'
--- local/in/dhis-in-services/dhis-in-service-dataentrystatus/src/main/resources/org/hisp/dhis/dataentrystatus/hibernate/DataEntryStatus.hbm.xml	2012-04-17 11:59:19 +0000
+++ local/in/dhis-in-services/dhis-in-service-dataentrystatus/src/main/resources/org/hisp/dhis/dataentrystatus/hibernate/DataEntryStatus.hbm.xml	2013-09-18 14:05:25 +0000
@@ -1,7 +1,7 @@
 <?xml version="1.0"?>
 <!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd";>
+  "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
+  "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd";>
 
 <hibernate-mapping>
   <class name="org.hisp.dhis.dataentrystatus.DataEntryStatus" table="dataentrystatus">

=== modified file 'local/in/dhis-in-services/dhis-in-service-dbmanager/pom.xml'
--- local/in/dhis-in-services/dhis-in-service-dbmanager/pom.xml	2013-03-25 05:08:43 +0000
+++ local/in/dhis-in-services/dhis-in-service-dbmanager/pom.xml	2013-09-18 14:05:25 +0000
@@ -1,69 +1,69 @@
 <project xmlns="http://maven.apache.org/POM/4.0.0";
-	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance";
-	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd";>
-	<modelVersion>4.0.0</modelVersion>
-	
-	<parent>
-		<groupId>org.hisp.dhis</groupId>
-		<artifactId>dhis-in-services</artifactId>
-		<version>2.12-SNAPSHOT</version>
-	</parent>
-	
-	<artifactId>dhis-in-service-dbmanager</artifactId>
-	<packaging>jar</packaging>
-	<name>DHIS India DBManager Service</name>
-	
-	<dependencies>
-		
-		<!-- DHIS -->
-		
-		<dependency>
-			<groupId>org.hisp.dhis</groupId>
-			<artifactId>dhis-api</artifactId>
-		</dependency>
-		<dependency>
-			<groupId>org.hisp.dhis</groupId>
-			<artifactId>dhis-in-api</artifactId>
-			<version>${project.version}</version>
-		</dependency>
-		<dependency>
-			<groupId>org.hisp.dhis</groupId>
-			<artifactId>dhis-service-core</artifactId>
-		</dependency>
-		<dependency>
-			<groupId>org.hisp.dhis</groupId>
-			<artifactId>dhis-support-hibernate</artifactId>
-		</dependency>
-		<dependency>
-			<groupId>org.hisp.dhis</groupId>
-			<artifactId>dhis-support-system</artifactId>
-		</dependency>
-		<!--
-		<dependency>
-		<groupId>org.hisp.dhis</groupId>
-		<artifactId>dhis-service-options</artifactId>
-		</dependency>  
-		-->
-		<dependency>
-			<groupId>net.sourceforge.jexcelapi</groupId>
-			<artifactId>jxl</artifactId>
-		</dependency>
-		
-		<!-- Other -->
-		<!--
-		<dependency>
-		<groupId>mysql</groupId>
-		<artifactId>mysql-connector-java</artifactId>
-		</dependency>
-		-->
-		<dependency>
-			<groupId>jep</groupId>
-			<artifactId>jep</artifactId>
-		</dependency>
-		<dependency>
-			<groupId>commons-collections</groupId>
-			<artifactId>commons-collections</artifactId>
-		</dependency>
-		
-	</dependencies>
+  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance";
+  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd";>
+  <modelVersion>4.0.0</modelVersion>
+  
+  <parent>
+    <groupId>org.hisp.dhis</groupId>
+    <artifactId>dhis-in-services</artifactId>
+    <version>2.12</version>
+  </parent>
+  
+  <artifactId>dhis-in-service-dbmanager</artifactId>
+  <packaging>jar</packaging>
+  <name>DHIS India DBManager Service</name>
+  
+  <dependencies>
+    
+    <!-- DHIS -->
+    
+     <dependency>
+      <groupId>org.hisp.dhis</groupId>
+      <artifactId>dhis-api</artifactId>
+    </dependency>
+     <dependency>
+      <groupId>org.hisp.dhis</groupId>
+      <artifactId>dhis-in-api</artifactId>
+      <version>${project.version}</version>
+    </dependency>
+    <dependency>
+      <groupId>org.hisp.dhis</groupId>
+      <artifactId>dhis-service-core</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>org.hisp.dhis</groupId>
+      <artifactId>dhis-support-hibernate</artifactId>
+    </dependency>    
+    <dependency>
+      <groupId>org.hisp.dhis</groupId>
+      <artifactId>dhis-support-system</artifactId>
+    </dependency>
+<!--
+    <dependency>
+      <groupId>org.hisp.dhis</groupId>
+      <artifactId>dhis-service-options</artifactId>
+    </dependency>  
+-->
+   <dependency>
+      <groupId>net.sourceforge.jexcelapi</groupId>
+      <artifactId>jxl</artifactId>
+    </dependency>
+        
+    <!-- Other -->
+    <!--
+    <dependency>
+      <groupId>mysql</groupId>
+      <artifactId>mysql-connector-java</artifactId>
+    </dependency>
+	  -->
+    <dependency>
+      <groupId>jep</groupId>
+      <artifactId>jep</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>commons-collections</groupId>
+      <artifactId>commons-collections</artifactId>
+    </dependency>
+	  
+  </dependencies>	  
 </project>

=== removed directory 'local/in/dhis-in-services/dhis-in-service-ihrissyncmanager'
=== removed file 'local/in/dhis-in-services/dhis-in-service-ihrissyncmanager/pom.xml'
--- local/in/dhis-in-services/dhis-in-service-ihrissyncmanager/pom.xml	2013-03-25 05:08:43 +0000
+++ local/in/dhis-in-services/dhis-in-service-ihrissyncmanager/pom.xml	1970-01-01 00:00:00 +0000
@@ -1,70 +0,0 @@
-<project xmlns="http://maven.apache.org/POM/4.0.0";
-	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance";
-	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd";>
-	<modelVersion>4.0.0</modelVersion>
-  
-	<parent>
-		<groupId>org.hisp.dhis</groupId>
-		<artifactId>dhis-in-services</artifactId>
-		<version>2.12-SNAPSHOT</version>
-	</parent>
-  
-  <artifactId>dhis-in-service-ihrissyncmanager</artifactId>
-  <packaging>jar</packaging>
-  <name>DHIS-IHRIS India Synchronisation Service</name>
-  
-  <dependencies>
-    
-    <!-- DHIS -->
-    
-    <dependency>
-      <groupId>org.hisp.dhis</groupId>
-      <artifactId>dhis-api</artifactId>
-    </dependency>
-    <dependency>
-      <groupId>org.hisp.dhis</groupId>
-      <artifactId>dhis-in-api</artifactId>
-	  <version>${project.version}</version>
-    </dependency>	
-    <dependency>
-      <groupId>org.hisp.dhis</groupId>
-      <artifactId>dhis-service-core</artifactId>
-    </dependency>
-    <dependency>
-      <groupId>org.hisp.dhis</groupId>
-      <artifactId>dhis-in-service-configuration</artifactId>
-      <version>${project.version}</version>
-    </dependency>   
-	<dependency>
-      <groupId>org.hisp.dhis</groupId>
-      <artifactId>dhis-service-aggregationengine-default</artifactId>
-      <version>${project.version}</version>   
-    </dependency>	  
-    <dependency>
-      <groupId>org.hisp.dhis</groupId>
-      <artifactId>dhis-support-system</artifactId>
-    </dependency>
-    <dependency>
-      <groupId>org.hisp.dhis</groupId>
-      <artifactId>dhis-service-reporting</artifactId>
-    </dependency>
-	
-    
-    <!-- Other -->
-    
-    <dependency>
-      <groupId>commons-logging</groupId>
-      <artifactId>commons-logging</artifactId>
-    </dependency>
-    <dependency>
-      <groupId>commons-math</groupId>
-      <artifactId>commons-math</artifactId>
-    </dependency>
-      <dependency>
-          <groupId>commons-dbcp</groupId>
-          <artifactId>commons-dbcp</artifactId>
-          <version>1.2.2</version>
-      </dependency>
-    
-  </dependencies>
-</project>

=== removed directory 'local/in/dhis-in-services/dhis-in-service-ihrissyncmanager/src'
=== removed directory 'local/in/dhis-in-services/dhis-in-service-ihrissyncmanager/src/main'
=== removed directory 'local/in/dhis-in-services/dhis-in-service-ihrissyncmanager/src/main/java'
=== removed directory 'local/in/dhis-in-services/dhis-in-service-ihrissyncmanager/src/main/java/org'
=== removed directory 'local/in/dhis-in-services/dhis-in-service-ihrissyncmanager/src/main/java/org/hisp'
=== removed directory 'local/in/dhis-in-services/dhis-in-service-ihrissyncmanager/src/main/java/org/hisp/dhis'
=== removed directory 'local/in/dhis-in-services/dhis-in-service-ihrissyncmanager/src/main/java/org/hisp/dhis/ihrissyncmanager'
=== removed file 'local/in/dhis-in-services/dhis-in-service-ihrissyncmanager/src/main/java/org/hisp/dhis/ihrissyncmanager/DefaultAggDataService.java'
--- local/in/dhis-in-services/dhis-in-service-ihrissyncmanager/src/main/java/org/hisp/dhis/ihrissyncmanager/DefaultAggDataService.java	2013-03-25 05:08:43 +0000
+++ local/in/dhis-in-services/dhis-in-service-ihrissyncmanager/src/main/java/org/hisp/dhis/ihrissyncmanager/DefaultAggDataService.java	1970-01-01 00:00:00 +0000
@@ -1,115 +0,0 @@
-package org.hisp.dhis.ihrissyncmanager;
-
-import org.hisp.dhis.dataelement.DataElement;
-import org.hisp.dhis.dataelement.DataElementCategoryOptionCombo;
-import org.hisp.dhis.dataelement.DataElementCategoryService;
-import org.hisp.dhis.dataelement.DataElementService;
-import org.hisp.dhis.datavalue.DataValue;
-import org.hisp.dhis.datavalue.DataValueService;
-import org.hisp.dhis.organisationunit.OrganisationUnit;
-import org.hisp.dhis.organisationunit.OrganisationUnitService;
-import org.hisp.dhis.period.Period;
-import org.hisp.dhis.period.PeriodService;
-
-/**
- * Gaurav<gaurav08021@xxxxxxxxx>, 8/27/12 [2:24 PM]
-**/
-
-public class DefaultAggDataService implements AggDataService {
-
-    DataElementService dataElementService;
-
-    public void setDataElementService(DataElementService dataElementService) {
-        this.dataElementService = dataElementService;
-    }
-
-    private DataElementCategoryService categoryService;
-
-    public void setCategoryService(DataElementCategoryService categoryService) {
-        this.categoryService = categoryService;
-    }
-
-    private DataValueService dataValueService;
-
-    public void setDataValueService(DataValueService dataValueService) {
-        this.dataValueService = dataValueService;
-    }
-
-    public OrganisationUnitService organisationUnitService;
-
-    public void setOrganisationUnitService(OrganisationUnitService organisationUnitService) {
-        this.organisationUnitService = organisationUnitService;
-    }
-
-    public PeriodService periodService;
-
-    public void setPeriodService(PeriodService periodService) {
-        this.periodService = periodService;
-    }
-
-
-    public DataElement createNewAggDataElement(String aggDataElementName)
-    {
-        DataElement checkIfDataElementExists = dataElementService.getDataElementByName(aggDataElementName);
-
-        if(checkIfDataElementExists == null)
-        {
-            DataElement newAggDataElement = new DataElement();
-
-            newAggDataElement.setName(aggDataElementName);
-
-            newAggDataElement.setShortName(aggDataElementName);
-
-            newAggDataElement.setActive(true);
-
-            newAggDataElement.setType("string");
-
-            newAggDataElement.setAggregationOperator("sum");
-
-            newAggDataElement.setZeroIsSignificant(false);
-
-            dataElementService.addDataElement(newAggDataElement);
-
-            return newAggDataElement;
-        }
-
-        return checkIfDataElementExists;
-    }
-
-    public void addNewEntries(String aggDataElementName,OrganisationUnit orgUnit,Period period, Double aggValue)
-    {
-        DataElement aggDataElement = createNewAggDataElement(aggDataElementName);
-
-        DataElementCategoryOptionCombo OptionCombo = categoryService.getDefaultDataElementCategoryOptionCombo();
-
-        DataValue dataValue = dataValueService.getDataValue(orgUnit,aggDataElement,period,OptionCombo);
-
-        if ((dataValue == null) && period != null )
-        {
-
-            DataValue newDataValue = new DataValue(aggDataElement,period,orgUnit,aggValue.toString(),OptionCombo);
-            dataValueService.addDataValue(newDataValue);
-
-        }
-        else if( dataValue.getPeriod().getStartDate().before(period.getStartDate()) && period != null)
-        {
-
-            dataValue.setValue(aggValue.toString());
-            dataValue.setPeriod(period);
-            dataValue.setSource(orgUnit);
-
-            dataValueService.updateDataValue(dataValue);
-        }
-    }
-
-    @Override
-    public void deleteAggDataElement(String nameOfDataElement) {
-
-
-        DataElement dataElementToDelete = dataElementService.getDataElementByName(nameOfDataElement);
-
-        dataValueService.deleteDataValuesByDataElement(dataElementToDelete);
-        dataElementService.deleteDataElement(dataElementToDelete);
-    }
-}
-

=== removed file 'local/in/dhis-in-services/dhis-in-service-ihrissyncmanager/src/main/java/org/hisp/dhis/ihrissyncmanager/DefaultSyncIHRISOrgUnitService.java'
--- local/in/dhis-in-services/dhis-in-service-ihrissyncmanager/src/main/java/org/hisp/dhis/ihrissyncmanager/DefaultSyncIHRISOrgUnitService.java	2013-03-25 05:08:43 +0000
+++ local/in/dhis-in-services/dhis-in-service-ihrissyncmanager/src/main/java/org/hisp/dhis/ihrissyncmanager/DefaultSyncIHRISOrgUnitService.java	1970-01-01 00:00:00 +0000
@@ -1,55 +0,0 @@
-package org.hisp.dhis.ihrissyncmanager;
-
-import org.hisp.dhis.dataelement.DataElementService;
-import org.hisp.dhis.organisationunit.OrganisationUnit;
-import org.hisp.dhis.organisationunit.OrganisationUnitService;
-
-/**
- * Gaurav<gaurav08021@xxxxxxxxx>, 8/29/12 [5:06 PM]
-**/
-
-public class DefaultSyncIHRISOrgUnitService implements SyncIHRISOrgUnitService {
-
-    DataElementService dataElementService;
-
-    public void setDataElementService(DataElementService dataElementService) {
-        this.dataElementService = dataElementService;
-    }
-
-    public OrganisationUnitService organisationUnitService;
-
-    public void setOrganisationUnitService(OrganisationUnitService organisationUnitService) {
-        this.organisationUnitService = organisationUnitService;
-    }
-
-    public OrganisationUnit createNewOrgUnit(String orgUnitName, String parentOrgUnitName)
-    {
-        OrganisationUnit checkIfOrgUnitExists = organisationUnitService.getOrganisationUnitByName(orgUnitName);
-
-        OrganisationUnit checkIfParentOrgUnitExists = organisationUnitService.getOrganisationUnitByName(parentOrgUnitName);
-
-        if(checkIfParentOrgUnitExists == null)
-        {
-            return null;
-        }
-        else if(checkIfOrgUnitExists == null && checkIfParentOrgUnitExists!= null)
-        {
-            OrganisationUnit newIHRISOrgUnit = new OrganisationUnit();
-
-            newIHRISOrgUnit.setName(orgUnitName);
-
-            newIHRISOrgUnit.setShortName(orgUnitName);
-
-            newIHRISOrgUnit.setActive(true);
-
-            newIHRISOrgUnit.setParent(checkIfParentOrgUnitExists);
-
-            organisationUnitService.addOrganisationUnit(newIHRISOrgUnit);
-
-            return newIHRISOrgUnit;
-        }
-
-        return checkIfOrgUnitExists;
-    }
-
-}

=== removed file 'local/in/dhis-in-services/dhis-in-service-ihrissyncmanager/src/main/java/org/hisp/dhis/ihrissyncmanager/DefaultSynciHRISUserService.java'
--- local/in/dhis-in-services/dhis-in-service-ihrissyncmanager/src/main/java/org/hisp/dhis/ihrissyncmanager/DefaultSynciHRISUserService.java	2013-03-25 05:08:43 +0000
+++ local/in/dhis-in-services/dhis-in-service-ihrissyncmanager/src/main/java/org/hisp/dhis/ihrissyncmanager/DefaultSynciHRISUserService.java	1970-01-01 00:00:00 +0000
@@ -1,111 +0,0 @@
-package org.hisp.dhis.ihrissyncmanager;
-
-import org.hisp.dhis.organisationunit.OrganisationUnit;
-import org.hisp.dhis.organisationunit.OrganisationUnitService;
-import org.hisp.dhis.security.PasswordManager;
-import org.hisp.dhis.user.CurrentUserService;
-import org.hisp.dhis.user.User;
-import org.hisp.dhis.user.UserCredentials;
-import org.hisp.dhis.user.UserService;
-
-import java.util.Collection;
-import java.util.HashSet;
-
-/**
- * Created with IntelliJ IDEA.
- * User: Mohit
- * Date: 29/8/12
- * Time: 2:00 PM
- * To change this template use File | Settings | File Templates.
- */
-public class DefaultSynciHRISUserService implements SynciHRISUserService {
-    UserService userService;
-
-    public void setUserService(UserService userService) {
-        this.userService = userService;
-    }
-
-    CurrentUserService currentUserService;
-
-    public void setCurrentUserService(CurrentUserService currentUserService) {
-        this.currentUserService = currentUserService;
-    }
-
-    PasswordManager passwordManager;
-
-    public void setPasswordManager(PasswordManager passwordManager) {
-        this.passwordManager = passwordManager;
-    }
-
-
-    OrganisationUnitService organisationUnitService;
-
-    public void setOrganisationUnitService(OrganisationUnitService organisationUnitService) {
-        this.organisationUnitService = organisationUnitService;
-    }
-
-    @Override
-    public User createNewiHRISUser(String ihrisUsername, String firstName, String lastName, String email, String password) {
-
-        UserCredentials currentUserCredentials = currentUserService.getCurrentUser() != null ? currentUserService
-                .getCurrentUser().getUserCredentials() : null;
-
-
-        // ---------------------------------------------------------------------
-        // Create userCredentials and user
-        // ---------------------------------------------------------------------
-
-        Collection<OrganisationUnit> orgUnits = organisationUnitService.getAllOrganisationUnits();
-
-        Collection<User> tempUserList = userService.getAllUsers();
-
-        boolean isUpdated = false;
-
-        User user = new User();
-        user.setSurname(lastName);
-        user.setFirstName(firstName);
-        user.setEmail(email);
-
-        user.updateOrganisationUnits(new HashSet<OrganisationUnit>(orgUnits));
-
-        UserCredentials userCredentials = new UserCredentials();
-        userCredentials.setUser(user);
-
-        userCredentials.setUsername(ihrisUsername);
-        userCredentials.setPassword(passwordManager.encodePassword(ihrisUsername, password));
-        user.setUserCredentials(userCredentials);
-
-        if (tempUserList != null) {
-            for (User existingUser : tempUserList) {
-
-                UserCredentials existingUserCredentials = userService.getUserCredentials(existingUser);
-
-                if (existingUserCredentials != null && existingUserCredentials.getUsername().equalsIgnoreCase(ihrisUsername)) {
-                    existingUser.setSurname(lastName);
-                    existingUser.setFirstName(firstName);
-                    existingUser.setEmail(email);
-
-                    existingUserCredentials.setUser(existingUser);
-
-                    existingUserCredentials.setUsername(ihrisUsername);
-                    existingUserCredentials.setPassword(passwordManager.encodePassword(ihrisUsername, password));
-                    existingUser.setUserCredentials(existingUserCredentials);
-
-                    userService.updateUser(existingUser);
-                    userService.updateUserCredentials(existingUserCredentials);
-                    isUpdated = true;
-                }
-
-
-            }
-        }
-
-        if (!isUpdated) {
-            userService.addUser(user);
-            userService.addUserCredentials(userCredentials);
-        }
-
-        return user;
-
-    }
-}

=== removed directory 'local/in/dhis-in-services/dhis-in-service-ihrissyncmanager/src/main/java/org/hisp/dhis/ihrissyncmanager/scheduledtasks'
=== removed file 'local/in/dhis-in-services/dhis-in-service-ihrissyncmanager/src/main/java/org/hisp/dhis/ihrissyncmanager/scheduledtasks/SyncIHRISOrgTreeService.java'
--- local/in/dhis-in-services/dhis-in-service-ihrissyncmanager/src/main/java/org/hisp/dhis/ihrissyncmanager/scheduledtasks/SyncIHRISOrgTreeService.java	2013-03-25 05:08:43 +0000
+++ local/in/dhis-in-services/dhis-in-service-ihrissyncmanager/src/main/java/org/hisp/dhis/ihrissyncmanager/scheduledtasks/SyncIHRISOrgTreeService.java	1970-01-01 00:00:00 +0000
@@ -1,582 +0,0 @@
-package org.hisp.dhis.ihrissyncmanager.scheduledtasks;
-
-import org.hisp.dhis.hierarchy.HierarchyViolationException;
-import org.hisp.dhis.organisationunit.OrganisationUnit;
-import org.hisp.dhis.organisationunit.OrganisationUnitService;
-import org.hisp.dhis.user.CurrentUserService;
-import org.springframework.jdbc.core.JdbcTemplate;
-import org.springframework.jdbc.support.rowset.SqlRowSet;
-import org.springframework.transaction.annotation.Transactional;
-
-import javax.sql.DataSource;
-import java.util.Date;
-
-/**
- * Gaurav<gaurav08021@xxxxxxxxx>, 9/13/12 [1:21 PM]
- */
-
-public class SyncIHRISOrgTreeService implements Runnable{
-
-
-    private JdbcTemplate jdbcTemplate;
-
-    public void setDataSource(DataSource dataSource) {
-        this.jdbcTemplate = new JdbcTemplate(dataSource);
-    }
-
-    private OrganisationUnitService organisationUnitService;
-
-    private CurrentUserService currentUserService;
-
-    public void setCurrentUserService(CurrentUserService currentUserService) {
-        this.currentUserService = currentUserService;
-    }
-
-    public void setOrganisationUnitService(OrganisationUnitService organisationUnitService) {
-        this.organisationUnitService = organisationUnitService;
-    }
-
-
-    public void createOrgUnitMaps() {
-
-
-        System.out.println("* INFO: CREATING MAPPING TABLES");
-
-        int countTables = 0;
-
-        if (jdbcTemplate.queryForList("SHOW tables LIKE \"country_mapping\"").size() == 0) {
-            jdbcTemplate.update("CREATE TABLE country_mapping (" +
-                    "id int AUTO_INCREMENT, " +
-                    "ihrisid varchar(20) NOT NULL, " +
-                    "dhisid int NOT NULL, " +
-                    "status char, " +
-                    "PRIMARY KEY (id)" +
-                    ")");
-        }
-
-        if (jdbcTemplate.queryForList("SHOW tables LIKE \"region_mapping\"").size() == 0) {
-            jdbcTemplate.update("CREATE TABLE region_mapping (" +
-                    "id int AUTO_INCREMENT, " +
-                    "ihrisid varchar(20) NOT NULL, " +
-                    "dhisid int NOT NULL, " +
-                    "status char, " +
-                    "PRIMARY KEY (id)" +
-                    ")");
-        }
-
-        if (jdbcTemplate.queryForList("SHOW tables LIKE \"district_mapping\"").size() == 0) {
-            jdbcTemplate.update("CREATE TABLE district_mapping (" +
-                    "id int AUTO_INCREMENT, " +
-                    "ihrisid varchar(20) NOT NULL, " +
-                    "dhisid int NOT NULL, " +
-                    "status char, " +
-                    "PRIMARY KEY (id)" +
-                    ")");
-        }
-
-
-        if (jdbcTemplate.queryForList("SHOW tables LIKE \"county_mapping\"").size() == 0) {
-            jdbcTemplate.update("CREATE TABLE county_mapping (" +
-                    "id int AUTO_INCREMENT, " +
-                    "ihrisid varchar(20) NOT NULL, " +
-                    "dhisid int NOT NULL, " +
-                    "status char, " +
-                    "PRIMARY KEY (id)" +
-                    ")");
-
-
-        }
-    }
-
-    public void replicateIhrisOrgTree() {
-
-        System.out.println("\n\n* INFO: Stating the iHRIS tree replication process.\n\n");
-
-        createOrgUnitMaps();
-
-        String countryQuery = "SELECT name,id FROM hippo_country";
-
-        SqlRowSet countryRowSet = jdbcTemplate.queryForRowSet(countryQuery);
-
-        while (countryRowSet.next()) {
-
-            String countryName = countryRowSet.getString(1);
-
-            OrganisationUnit country = organisationUnitService.getOrganisationUnitByName(countryName);
-
-            if (country == null) {
-                OrganisationUnit newIHRISOrgUnit = new OrganisationUnit();
-
-                newIHRISOrgUnit.setName(countryName);
-
-                newIHRISOrgUnit.setShortName(countryName);
-
-                newIHRISOrgUnit.setActive(true);
-
-                organisationUnitService.addOrganisationUnit(newIHRISOrgUnit);
-
-                int newIHRISOrgUnitId = newIHRISOrgUnit.getId();
-
-                jdbcTemplate.update("INSERT INTO country_mapping (ihrisid, dhisid, status) VALUES (" + "\"" + countryRowSet.getString(2) + "\", " + "\"" + newIHRISOrgUnitId + "\", " + " \'S\' )");
-            }
-
-            String regionQuery = "SELECT name,id FROM hippo_region where country=\"" + countryRowSet.getString(2) + "\"";
-
-            SqlRowSet regionRowSet = jdbcTemplate.queryForRowSet(regionQuery);
-
-            while (regionRowSet.next()) {
-
-                String regionName = regionRowSet.getString(1);
-
-                OrganisationUnit region = organisationUnitService.getOrganisationUnitByName(regionName);
-
-                OrganisationUnit regionParent = organisationUnitService.getOrganisationUnitByName(countryName);
-
-                if (region == null) {
-                    OrganisationUnit newIHRISOrgUnit = new OrganisationUnit();
-
-                    newIHRISOrgUnit.setName(regionName);
-
-                    newIHRISOrgUnit.setShortName(regionName);
-
-                    newIHRISOrgUnit.setParent(regionParent);
-
-                    newIHRISOrgUnit.setActive(true);
-
-                    organisationUnitService.addOrganisationUnit(newIHRISOrgUnit);
-
-                    int newIHRISOrgUnitId = newIHRISOrgUnit.getId();
-
-                    jdbcTemplate.update("INSERT INTO region_mapping (ihrisid, dhisid, status) VALUES (" + "\"" + regionRowSet.getString(2) + "\", " + "\"" + newIHRISOrgUnitId + "\", " + " \'S\' )");
-                }
-
-                String districtQuery = "SELECT name,id FROM hippo_district where region=\"" + regionRowSet.getString(2) + "\"";
-
-                SqlRowSet districtRowSet = jdbcTemplate.queryForRowSet(districtQuery);
-
-                while (districtRowSet.next()) {
-
-                    String districtName = districtRowSet.getString(1);
-
-                    OrganisationUnit district = organisationUnitService.getOrganisationUnitByName(districtName);
-
-                    OrganisationUnit districtParent = organisationUnitService.getOrganisationUnitByName(regionName);
-
-                    if (district == null) {
-                        OrganisationUnit newIHRISOrgUnit = new OrganisationUnit();
-
-                        newIHRISOrgUnit.setName(districtName);
-
-                        newIHRISOrgUnit.setShortName(districtName);
-
-                        newIHRISOrgUnit.setParent(districtParent);
-
-                        newIHRISOrgUnit.setActive(true);
-
-                        organisationUnitService.addOrganisationUnit(newIHRISOrgUnit);
-
-                        int newIHRISOrgUnitId = newIHRISOrgUnit.getId();
-
-                        jdbcTemplate.update("INSERT INTO district_mapping (ihrisid, dhisid, status) VALUES (" + "\"" + districtRowSet.getString(2) + "\", " + "\"" + newIHRISOrgUnitId + "\", " + " \'S\' )");
-                    }
-
-                    String countyQuery = "SELECT name,id FROM hippo_county where district=\"" + districtRowSet.getString(2) + "\"";
-
-                    SqlRowSet countyRowSet = jdbcTemplate.queryForRowSet(countyQuery);
-
-                    while (countyRowSet.next()) {
-
-                        String countyName = countyRowSet.getString(1);
-
-                        OrganisationUnit county = organisationUnitService.getOrganisationUnitByName(countyName);
-
-                        OrganisationUnit countyParent = organisationUnitService.getOrganisationUnitByName(districtName);
-
-                        if (county == null) {
-                            OrganisationUnit newIHRISOrgUnit = new OrganisationUnit();
-
-                            newIHRISOrgUnit.setName(countyName);
-
-                            newIHRISOrgUnit.setShortName(countyName);
-
-                            newIHRISOrgUnit.setParent(countyParent);
-
-                            newIHRISOrgUnit.setActive(true);
-
-                            organisationUnitService.addOrganisationUnit(newIHRISOrgUnit);
-
-                            int newIHRISOrgUnitId = newIHRISOrgUnit.getId();
-
-                            jdbcTemplate.update("INSERT INTO county_mapping (ihrisid, dhisid, status) VALUES (" + "\"" + countyRowSet.getString(2) + "\", " + "\"" + newIHRISOrgUnitId + "\", " + " \'S\' )");
-                        }
-                    }
-
-                }
-            }
-        }
-
-    }
-
-
-    public void deleteIhrisOrgTreeFromDhis() {
-
-        System.out.println("\n\n* INFO: Stating the iHRIS tree truncation process.\n\n");
-
-        String delCounties = "SELECT dhisid FROM county_mapping";
-
-        SqlRowSet delCountySet = jdbcTemplate.queryForRowSet(delCounties);
-
-        while (delCountySet.next())
-        {
-            int dhisID = delCountySet.getInt(1);
-
-            OrganisationUnit organisationUnitToDelete = organisationUnitService.getOrganisationUnit(dhisID);
-
-            if (organisationUnitToDelete != null) {
-                try {
-                    organisationUnitService.deleteOrganisationUnit(organisationUnitToDelete);
-                } catch (HierarchyViolationException e) {
-                    System.out.println("* ERROR :HierarchyViolationException while deleting [ " + organisationUnitToDelete.getName() + "]");
-                }
-            }
-        }
-
-        jdbcTemplate.update("DROP TABLE county_mapping");
-
-        String delDistricts = "SELECT dhisid FROM district_mapping";
-
-        SqlRowSet delDistrictSet = jdbcTemplate.queryForRowSet(delDistricts);
-
-        while (delDistrictSet.next()) {
-            int dhisID = delDistrictSet.getInt(1);
-
-            OrganisationUnit organisationUnitToDelete = organisationUnitService.getOrganisationUnit(dhisID);
-
-            if (organisationUnitToDelete != null) {
-                try {
-                    organisationUnitService.deleteOrganisationUnit(organisationUnitToDelete);
-                } catch (HierarchyViolationException e) {
-                    System.out.println("* ERROR :HierarchyViolationException while deleting [ " + organisationUnitToDelete.getName() + "]");
-                }
-            }
-        }
-
-        jdbcTemplate.update("DROP TABLE district_mapping");
-
-        String delRegion = "SELECT dhisid FROM region_mapping";
-
-        SqlRowSet delRegionSet = jdbcTemplate.queryForRowSet(delRegion);
-
-        while (delRegionSet.next()) {
-            int dhisID = delRegionSet.getInt(1);
-
-            OrganisationUnit organisationUnitToDelete = organisationUnitService.getOrganisationUnit(dhisID);
-
-            if (organisationUnitToDelete != null) {
-                try {
-                    organisationUnitService.deleteOrganisationUnit(organisationUnitToDelete);
-                } catch (HierarchyViolationException e) {
-                    System.out.println("* ERROR :HierarchyViolationException while deleting [ " + organisationUnitToDelete.getName() + "]");
-                }
-            }
-        }
-
-        jdbcTemplate.update("DROP TABLE region_mapping");
-
-        String delCountry = "SELECT dhisid FROM country_mapping";
-
-        SqlRowSet delCountrySet = jdbcTemplate.queryForRowSet(delCountry);
-
-        while (delCountrySet.next()) {
-            int dhisID = delCountrySet.getInt(1);
-
-            OrganisationUnit organisationUnitToDelete = organisationUnitService.getOrganisationUnit(dhisID);
-
-            if (organisationUnitToDelete != null) {
-                try {
-                    organisationUnitService.deleteOrganisationUnit(organisationUnitToDelete);
-                } catch (HierarchyViolationException e) {
-                    System.out.println("* ERROR :HierarchyViolationException while deleting [ " + organisationUnitToDelete.getName() + "]");
-                }
-            }
-        }
-
-        jdbcTemplate.update("DROP TABLE country_mapping");
-
-        replicateIhrisOrgTree();
-
-    }
-
-
-    public void checkForIhrisOrgTreeUpdate() {
-
-
-        System.out.println("\n* NOTICE: IHRIS ORGANISATION UNIT SYNC PROCESS STARTED @[" + new Date() + "]");
-
-
-        if(jdbcTemplate.queryForList("SHOW tables LIKE \"%_mapping\"").size() < 4)
-        {
-            System.out.println("* NOTE: Mapping tables FOUND.");
-            replicateIhrisOrgTree();
-        }
-
-        else
-        {
-
-            String checkCounty = "SELECT dhisid,ihrisid FROM county_mapping";
-
-            SqlRowSet checkCountySet = jdbcTemplate.queryForRowSet(checkCounty);
-
-            while (checkCountySet.next()) {
-
-                int dhisID = checkCountySet.getInt(1);
-
-                String ihrisID = checkCountySet.getString(2);
-
-                String getIhrisDetailsQuery = "SELECT name,district FROM hippo_county WHERE id=" + "\"" + ihrisID + "\"";
-
-                SqlRowSet ihrisDetailSet = jdbcTemplate.queryForRowSet(getIhrisDetailsQuery);
-
-                String ihrisOUName = null;
-
-                String ihrisParentName = null;
-
-                while (ihrisDetailSet.next()) {
-                    ihrisOUName = ihrisDetailSet.getString(1).trim();
-
-                    String ihrisOUParentQuery = "SELECT name FROM hippo_district WHERE id=" + "\"" + ihrisDetailSet.getString(2) + "\"";
-
-                    SqlRowSet ihrisParentDetailSet = jdbcTemplate.queryForRowSet(ihrisOUParentQuery);
-
-                    while (ihrisParentDetailSet.next())
-                    {
-                        ihrisParentName = ihrisParentDetailSet.getString(1);
-                    }
-                }
-
-                OrganisationUnit organisationUnit = organisationUnitService.getOrganisationUnit(dhisID);
-
-                if(organisationUnit==null || ihrisOUName==null || ihrisParentName ==null)
-                {
-                    System.out.println("* INFO: REFERENCED ORG. UNIT MISSING");
-                    deleteIhrisOrgTreeFromDhis();
-                    return;
-                }
-
-                String dhisOrgUnitName = organisationUnit.getName();
-
-                OrganisationUnit organisationUnitParent = organisationUnit.getParent();
-
-                String parentName;
-
-                if(organisationUnitParent!=null){
-
-                    parentName = organisationUnitParent.getName();
-
-                }
-                else{
-
-                    System.out.println("* INFO: REFERENCED ORG. UNIT PARENT MISSING");
-                    deleteIhrisOrgTreeFromDhis();
-                    return;
-
-                }
-
-                if (!((dhisOrgUnitName.trim()).equalsIgnoreCase(ihrisOUName.trim()) && (parentName.trim()).equalsIgnoreCase(ihrisParentName.trim()))) {
-
-                    System.out.println("* INFO: MIS-MATCH FOUND IN ["+dhisOrgUnitName+"("+ihrisOUName+")"+" ,"+parentName+"("+ihrisParentName+")"+"]");
-                    deleteIhrisOrgTreeFromDhis();
-                    return;
-                }
-
-
-            }
-
-
-            String checkDistrict = "SELECT dhisid,ihrisid FROM district_mapping";
-
-            SqlRowSet checkDistrictSet = jdbcTemplate.queryForRowSet(checkDistrict);
-
-            while (checkDistrictSet.next()) {
-
-                int dhisID = checkDistrictSet.getInt(1);
-
-                String ihrisID = checkDistrictSet.getString(2);
-
-                String getIhrisDetailsQuery = "SELECT name,region FROM hippo_district WHERE id=" + "\"" + ihrisID + "\"";
-
-                SqlRowSet ihrisDetailSet = jdbcTemplate.queryForRowSet(getIhrisDetailsQuery);
-
-                String ihrisOUName = null;
-
-                String ihrisParentName = null;
-
-                while (ihrisDetailSet.next()) {
-                    ihrisOUName = ihrisDetailSet.getString(1).trim();
-
-                    String ihrisOUParentQuery = "SELECT name FROM hippo_region WHERE id=" + "\"" + ihrisDetailSet.getString(2) + "\"";
-
-                    SqlRowSet ihrisParentDetailSet = jdbcTemplate.queryForRowSet(ihrisOUParentQuery);
-
-                    while (ihrisParentDetailSet.next()) {
-                        ihrisParentName = ihrisParentDetailSet.getString(1);
-                    }
-                }
-
-                OrganisationUnit organisationUnit = organisationUnitService.getOrganisationUnit(dhisID);
-
-                if(organisationUnit==null || ihrisOUName==null || ihrisParentName ==null)
-                {
-                    System.out.println("* INFO: REFERENCED ORG. UNIT MISSING");
-                    deleteIhrisOrgTreeFromDhis();
-                    return;
-                }
-
-                String dhisOrgUnitName = organisationUnit.getName();
-
-                OrganisationUnit organisationUnitParent = organisationUnit.getParent();
-
-                String parentName;
-
-                if(organisationUnitParent!=null){
-
-                    parentName = organisationUnitParent.getName();
-
-                }
-                else{
-
-                    System.out.println("* INFO: REFERENCED ORG. UNIT PARENT MISSING");
-                    deleteIhrisOrgTreeFromDhis();
-                    return;
-
-                }
-
-                if (!((dhisOrgUnitName.trim()).equalsIgnoreCase(ihrisOUName.trim()) && (parentName.trim()).equalsIgnoreCase(ihrisParentName.trim()))) {
-
-                    System.out.println("* INFO: MIS-MATCH FOUND IN ["+dhisOrgUnitName+"("+ihrisOUName+")"+" ,"+parentName+"("+ihrisParentName+")"+"]");
-                    deleteIhrisOrgTreeFromDhis();
-                    return;
-                }
-            }
-
-
-            String checkRegion = "SELECT dhisid,ihrisid FROM region_mapping";
-
-            SqlRowSet checkRegionSet = jdbcTemplate.queryForRowSet(checkRegion);
-
-            while (checkRegionSet.next()) {
-
-                int dhisID = checkRegionSet.getInt(1);
-
-                String ihrisID = checkRegionSet.getString(2);
-
-                String getIhrisDetailsQuery = "SELECT name,country FROM hippo_region WHERE id=" + "\"" + ihrisID + "\"";
-
-                SqlRowSet ihrisDetailSet = jdbcTemplate.queryForRowSet(getIhrisDetailsQuery);
-
-                String ihrisOUName = null;
-
-                String ihrisParentName = null;
-
-                while (ihrisDetailSet.next()) {
-                    ihrisOUName = ihrisDetailSet.getString(1).trim();
-
-                    String ihrisOUParentQuery = "SELECT name FROM hippo_country WHERE id=" + "\"" + ihrisDetailSet.getString(2) + "\"";
-
-                    SqlRowSet ihrisParentDetailSet = jdbcTemplate.queryForRowSet(ihrisOUParentQuery);
-
-                    while (ihrisParentDetailSet.next()) {
-                        ihrisParentName = ihrisParentDetailSet.getString(1);
-                    }
-                }
-
-                OrganisationUnit organisationUnit = organisationUnitService.getOrganisationUnit(dhisID);
-
-                if(organisationUnit==null || ihrisOUName==null || ihrisParentName ==null)
-                {
-                    System.out.println("* INFO: REFERENCED ORG. UNIT MISSING");
-                    deleteIhrisOrgTreeFromDhis();
-                    return;
-                }
-
-                String dhisOrgUnitName = organisationUnit.getName();
-
-                OrganisationUnit organisationUnitParent = organisationUnit.getParent();
-
-                String parentName;
-
-                if(organisationUnitParent!=null){
-
-                   parentName = organisationUnitParent.getName();
-
-                }
-                else{
-
-                    System.out.println("* INFO: REFERENCED ORG. UNIT PARENT MISSING");
-                    deleteIhrisOrgTreeFromDhis();
-                    return;
-
-                }
-
-                if (!((dhisOrgUnitName.trim()).equalsIgnoreCase(ihrisOUName.trim()) && (parentName.trim()).equalsIgnoreCase(ihrisParentName.trim()))) {
-
-                    System.out.println("* INFO: MIS-MATCH FOUND IN ["+dhisOrgUnitName+"("+ihrisOUName+")"+" ,"+parentName+"("+ihrisParentName+")"+"]");
-                    deleteIhrisOrgTreeFromDhis();
-                    return;
-                }
-            }
-
-
-            String checkCountry = "SELECT dhisid,ihrisid FROM country_mapping";
-
-            SqlRowSet checkCountrySet = jdbcTemplate.queryForRowSet(checkCountry);
-
-            while (checkCountrySet.next()) {
-
-                int dhisID = checkCountrySet.getInt(1);
-
-                String ihrisID = checkCountrySet.getString(2);
-
-                String getIhrisDetailsQuery = "SELECT name FROM hippo_country WHERE id=" + "\"" + ihrisID + "\"";
-
-                SqlRowSet ihrisDetailSet = jdbcTemplate.queryForRowSet(getIhrisDetailsQuery);
-
-                String ihrisOUName = null;
-
-                while (ihrisDetailSet.next()) {
-                    ihrisOUName = ihrisDetailSet.getString(1).trim();
-                }
-
-                OrganisationUnit organisationUnit = organisationUnitService.getOrganisationUnit(dhisID);
-
-                if(organisationUnit==null || ihrisOUName==null)
-                {
-                    System.out.println("* INFO: REFERENCED ORG. UNIT MISSING");
-                    deleteIhrisOrgTreeFromDhis();
-                    return;
-                }
-
-                String dhisOrgUnitName = organisationUnit.getName();
-
-                if (!((dhisOrgUnitName.trim()).equalsIgnoreCase(ihrisOUName.trim()))) {
-
-                    System.out.println("* INFO: MIS-MATCH FOUND IN ["+dhisOrgUnitName+"("+ihrisOUName+")"+"]");
-                    deleteIhrisOrgTreeFromDhis();
-                    return;
-                }
-            }
-
-
-        }
-
-        System.out.println("* NOTICE: IHRIS ORGANISATION UNIT SYNC PROCESS FINISHED @[" + new Date() + "]\n");
-    }
-
-
-    @Override
-    @Transactional
-    public void run()
-    {
-        checkForIhrisOrgTreeUpdate();
-    }
-}

=== removed directory 'local/in/dhis-in-services/dhis-in-service-ihrissyncmanager/src/main/resources'
=== removed directory 'local/in/dhis-in-services/dhis-in-service-ihrissyncmanager/src/main/resources/META-INF'
=== removed directory 'local/in/dhis-in-services/dhis-in-service-ihrissyncmanager/src/main/resources/META-INF/dhis'
=== removed file 'local/in/dhis-in-services/dhis-in-service-ihrissyncmanager/src/main/resources/META-INF/dhis/beans.xml'
--- local/in/dhis-in-services/dhis-in-service-ihrissyncmanager/src/main/resources/META-INF/dhis/beans.xml	2013-03-25 05:08:43 +0000
+++ local/in/dhis-in-services/dhis-in-service-ihrissyncmanager/src/main/resources/META-INF/dhis/beans.xml	1970-01-01 00:00:00 +0000
@@ -1,44 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<beans xmlns="http://www.springframework.org/schema/beans";
-       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance";
-       xsi:schemaLocation="
-http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd";>
-
-    <bean id="org.hisp.dhis.ihrissyncmanager.AggDataService" class="org.hisp.dhis.ihrissyncmanager.DefaultAggDataService">
-        <property name="organisationUnitService" ref="org.hisp.dhis.organisationunit.OrganisationUnitService"/>
-        <property name="periodService" ref="org.hisp.dhis.period.PeriodService"/>
-        <property name="dataElementService" ref="org.hisp.dhis.dataelement.DataElementService"/>
-        <property name="dataValueService" ref="org.hisp.dhis.datavalue.DataValueService"/>
-        <property name="categoryService"  ref="org.hisp.dhis.dataelement.DataElementCategoryService"/>
-    </bean>
-
-    <bean id="org.hisp.dhis.ihrissyncmanager.SyncIHRISOrgUnitService"
-          class="org.hisp.dhis.ihrissyncmanager.DefaultSyncIHRISOrgUnitService">
-        <property name="organisationUnitService" ref="org.hisp.dhis.organisationunit.OrganisationUnitService"/>
-        <property name="dataElementService" ref="org.hisp.dhis.dataelement.DataElementService"/>
-    </bean>
-
-    <bean id="org.hisp.dhis.ihrissyncmanager.SynciHRISUserService"
-          class="org.hisp.dhis.ihrissyncmanager.DefaultSynciHRISUserService">
-        <property name="organisationUnitService" ref="org.hisp.dhis.organisationunit.OrganisationUnitService"/>
-        <property name="userService" ref="org.hisp.dhis.user.UserService"/>
-        <property name="passwordManager" ref="org.hisp.dhis.security.PasswordManager"/>
-        <property name="currentUserService" ref="org.hisp.dhis.user.CurrentUserService"/>
-    </bean>
-
-
-    <bean id="ihrisDataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
-        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
-        <property name="url" value="jdbc:mysql://localhost:3306/ihris_manage"/>
-        <property name="username" value="root"/>
-        <property name="password" value="admin"/>
-    </bean>
-
-    <bean id="org.hisp.dhis.ihrissyncmanager.scheduledtasks.SyncIHRISOrgTree"
-          class="org.hisp.dhis.ihrissyncmanager.scheduledtasks.SyncIHRISOrgTreeService">
-        <property name="dataSource" ref="ihrisDataSource"/>
-        <property name="organisationUnitService" ref="org.hisp.dhis.organisationunit.OrganisationUnitService"/>
-        <property name="currentUserService" ref="org.hisp.dhis.user.CurrentUserService"/>
-    </bean>
-
-</beans>

=== modified file 'local/in/dhis-in-services/dhis-in-service-linelisting/pom.xml'
--- local/in/dhis-in-services/dhis-in-service-linelisting/pom.xml	2013-03-25 05:08:43 +0000
+++ local/in/dhis-in-services/dhis-in-service-linelisting/pom.xml	2013-09-18 14:05:25 +0000
@@ -1,69 +1,69 @@
 <project xmlns="http://maven.apache.org/POM/4.0.0";
-	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance";
-	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd";>
-	<modelVersion>4.0.0</modelVersion>
-	
-	<parent>
-		<groupId>org.hisp.dhis</groupId>
-		<artifactId>dhis-in-services</artifactId>
-		<version>2.12-SNAPSHOT</version>
-	</parent>
-	
-	<artifactId>dhis-in-service-linelisting</artifactId>
-	<packaging>jar</packaging>
-	<name>DHIS India Linelisting Service</name>
-	
-	<dependencies>
-		
-		<!-- DHIS -->
-		
-		<dependency>
-			<groupId>org.hisp.dhis</groupId>
-			<artifactId>dhis-api</artifactId>
-		</dependency>
-		<dependency>
-			<groupId>org.hisp.dhis</groupId>
-			<artifactId>dhis-in-api</artifactId>
-			<version>${project.version}</version>
-		</dependency>
-		<dependency>
-			<groupId>org.hisp.dhis</groupId>
-			<artifactId>dhis-service-core</artifactId>
-		</dependency>
-		<dependency>
-			<groupId>org.hisp.dhis</groupId>
-			<artifactId>dhis-support-hibernate</artifactId>
-		</dependency>
-		<dependency>
-			<groupId>org.hisp.dhis</groupId>
-			<artifactId>dhis-support-system</artifactId>
-		</dependency>
-		<!--	  
-		<dependency>
-		<groupId>org.hisp.dhis</groupId>
-		<artifactId>dhis-service-options</artifactId>
-		</dependency>
-		-->
-		<dependency>
-			<groupId>net.sourceforge.jexcelapi</groupId>
-			<artifactId>jxl</artifactId>
-		</dependency>
-		
-		<!-- Other -->
-		<!--
-		<dependency>
-		<groupId>mysql</groupId>
-		<artifactId>mysql-connector-java</artifactId>
-		</dependency>
-		-->
-		<dependency>
-			<groupId>jep</groupId>
-			<artifactId>jep</artifactId>
-		</dependency>
-		<dependency>
-			<groupId>commons-collections</groupId>
-			<artifactId>commons-collections</artifactId>
-		</dependency>
-		
-	</dependencies>
+  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance";
+  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd";>
+  <modelVersion>4.0.0</modelVersion>
+  
+  <parent>
+    <groupId>org.hisp.dhis</groupId>
+    <artifactId>dhis-in-services</artifactId>
+    <version>2.12</version>
+  </parent>
+  
+  <artifactId>dhis-in-service-linelisting</artifactId>
+  <packaging>jar</packaging>
+  <name>DHIS India Linelisting Service</name>
+    
+  <dependencies>
+    
+    <!-- DHIS -->
+    
+     <dependency>
+      <groupId>org.hisp.dhis</groupId>
+      <artifactId>dhis-api</artifactId>
+    </dependency>
+     <dependency>
+      <groupId>org.hisp.dhis</groupId>
+      <artifactId>dhis-in-api</artifactId>
+	  <version>${project.version}</version>
+    </dependency>
+    <dependency>
+      <groupId>org.hisp.dhis</groupId>
+      <artifactId>dhis-service-core</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>org.hisp.dhis</groupId>
+      <artifactId>dhis-support-hibernate</artifactId>
+    </dependency>      
+    <dependency>
+      <groupId>org.hisp.dhis</groupId>
+      <artifactId>dhis-support-system</artifactId>
+    </dependency>
+<!--	  
+    <dependency>
+      <groupId>org.hisp.dhis</groupId>
+      <artifactId>dhis-service-options</artifactId>
+    </dependency>
+-->	
+   <dependency>
+      <groupId>net.sourceforge.jexcelapi</groupId>
+      <artifactId>jxl</artifactId>
+    </dependency>
+    
+    <!-- Other -->
+    <!--
+    <dependency>
+      <groupId>mysql</groupId>
+      <artifactId>mysql-connector-java</artifactId>
+    </dependency>
+	  -->
+    <dependency>
+      <groupId>jep</groupId>
+      <artifactId>jep</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>commons-collections</groupId>
+      <artifactId>commons-collections</artifactId>
+    </dependency>
+	  
+  </dependencies>	  
 </project>

=== modified file 'local/in/dhis-in-services/dhis-in-service-linelisting/src/main/resources/org/hisp/dhis/linelisting/hibernate/Employee.hbm.xml'
--- local/in/dhis-in-services/dhis-in-service-linelisting/src/main/resources/org/hisp/dhis/linelisting/hibernate/Employee.hbm.xml	2012-04-17 11:59:19 +0000
+++ local/in/dhis-in-services/dhis-in-service-linelisting/src/main/resources/org/hisp/dhis/linelisting/hibernate/Employee.hbm.xml	2013-09-18 14:05:25 +0000
@@ -1,7 +1,7 @@
 <?xml version="1.0"?>
 <!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd";>
+  "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
+  "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd";>
 
 <hibernate-mapping>
   <class name="org.hisp.dhis.linelisting.Employee" table="employee">

=== modified file 'local/in/dhis-in-services/dhis-in-service-linelisting/src/main/resources/org/hisp/dhis/linelisting/hibernate/LineListDataElementMap.hbm.xml'
--- local/in/dhis-in-services/dhis-in-service-linelisting/src/main/resources/org/hisp/dhis/linelisting/hibernate/LineListDataElementMap.hbm.xml	2012-04-17 11:59:19 +0000
+++ local/in/dhis-in-services/dhis-in-service-linelisting/src/main/resources/org/hisp/dhis/linelisting/hibernate/LineListDataElementMap.hbm.xml	2013-09-18 14:05:25 +0000
@@ -1,7 +1,7 @@
 <?xml version="1.0"?>
 <!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd";>
+  "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
+  "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd";>
 
 <hibernate-mapping>
   

=== modified file 'local/in/dhis-in-services/dhis-in-service-linelisting/src/main/resources/org/hisp/dhis/linelisting/hibernate/LineListElement.hbm.xml'
--- local/in/dhis-in-services/dhis-in-service-linelisting/src/main/resources/org/hisp/dhis/linelisting/hibernate/LineListElement.hbm.xml	2012-04-17 11:59:19 +0000
+++ local/in/dhis-in-services/dhis-in-service-linelisting/src/main/resources/org/hisp/dhis/linelisting/hibernate/LineListElement.hbm.xml	2013-09-18 14:05:25 +0000
@@ -1,7 +1,7 @@
 <?xml version="1.0"?>
 <!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd";>
+  "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
+  "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd";>
 
 <hibernate-mapping>
   <class name="org.hisp.dhis.linelisting.LineListElement" table="linelistelement">

=== modified file 'local/in/dhis-in-services/dhis-in-service-linelisting/src/main/resources/org/hisp/dhis/linelisting/hibernate/LineListGroup.hbm.xml'
--- local/in/dhis-in-services/dhis-in-service-linelisting/src/main/resources/org/hisp/dhis/linelisting/hibernate/LineListGroup.hbm.xml	2012-04-17 11:59:19 +0000
+++ local/in/dhis-in-services/dhis-in-service-linelisting/src/main/resources/org/hisp/dhis/linelisting/hibernate/LineListGroup.hbm.xml	2013-09-18 14:05:25 +0000
@@ -1,7 +1,7 @@
 <?xml version="1.0"?>
 <!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd";>
+  "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
+  "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd";>
 
 <hibernate-mapping>
   <class name="org.hisp.dhis.linelisting.LineListGroup" table="linelistgroup">

=== modified file 'local/in/dhis-in-services/dhis-in-service-linelisting/src/main/resources/org/hisp/dhis/linelisting/hibernate/LineListOption.hbm.xml'
--- local/in/dhis-in-services/dhis-in-service-linelisting/src/main/resources/org/hisp/dhis/linelisting/hibernate/LineListOption.hbm.xml	2012-04-17 11:59:19 +0000
+++ local/in/dhis-in-services/dhis-in-service-linelisting/src/main/resources/org/hisp/dhis/linelisting/hibernate/LineListOption.hbm.xml	2013-09-18 14:05:25 +0000
@@ -1,7 +1,7 @@
 <?xml version="1.0"?>
 <!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- "http://www.hibernate.org/dtd/hibernate-mapping-