var dashBoard;
var plot1,plot2,plot3;


 
$( document ).ready(function() { 
 
	 if($("#expenseData").val() == ""){	
	 
		$("#div_participant").html("<br/><br/><br/><br/><br/><center><h3>"+lblExpenseNOTFOUND+"</h3></center>");
		 
		return;
	}
 
	
	 var loadTabs = new LoadTabs();
	   loadTabs.startLoading( $.parseJSON($("#expenseData").val()));
	  
});

 

function LoadTabs(){
	 
	this.startLoading =  function startLoading(data){
		 
		this.generateExpenseList(data);
	 }

	this.calculateBalance =  function calculateBalance(){
		
	}

	 

	this.loadSettings = function loadSettings(){
		
	}
	
	

	this.generateExpenseList = function generateExpenseList(expenseInfoObj){		
		 
		dashBoard = new DashBoard();
		 
		 $.each( expenseInfoObj, function( key, val ) {
			 
			 if(key == "Expense"){ 
 				 
				 var expenseObj = new Expense();				 
				 expenseObj.id = val.id;
				 expenseObj.unique_url = val.unique_url;
				 expenseObj.title = val.title; 
				 expenseObj.currency= val.currency;
				 expenseObj.description = val.description;
				 expenseObj.create_date = val.create_date;	
				 expenseObj.version = val.version;				 
				 
				 dashBoard.expense = expenseObj;				 
				 
				 $("#expenseTitleDiv").html(expenseObj.title);
				 $("#expenseDescDiv").html(expenseObj.description);
				 
				 
			 } else if(key === "FamilyExpense"){
				  $.each(val, function (i, object) {
				
					  var familyExpense = new FamilyExpense();
					 
					  familyExpense.id = object.id;			
					  familyExpense.expenseId = object.id;		
					  familyExpense.recordType = object.record_type;			
					  familyExpense.expenseName = object.what;
					  familyExpense.expenseCategory = object.category;
					  familyExpense.category = object.category;
					 
					  familyExpense.amount = object.amount; 
					  familyExpense.expenseDate = object.expense_date_new; 
					  familyExpense.create_date = object.create_date;					 
					  familyExpense.number_of_notes= object.number_of_notes;					  
					  familyExpense.type= object.type; 
					   
					 
					  
					  if(familyExpense.recordType == 1){
					    dashBoard.familyExpenses[familyExpense.id] = familyExpense;
					  	dashBoard.globalExpenseIndex++;
					  } else {
					    dashBoard.familyIncomes[familyExpense.id] = familyExpense;
					  	dashBoard.globalIncomeIndex++;
					  }
					  
				  }); 
			 }	 else if(key === "Category"){
				  $.each(val, function (i, object) {
				
					  var category = new Category();
					 
					  category.id = object.id;			
					  category.type = object.type;			
					  category.name = object.name;
					   
					  dashBoard.categories[category.id] = category; 
					  
				  }); 
			 }			 
			 
		 }); 
	
		 dashBoard.displayCovePage();
 
		dashBoard.setCurrentDate();
		 
	}
}
  

function DashBoard(){
	this.expense;	 
	this.familyExpenses = [];	
	this.filteredFamilyExpenses = [];
	this.familyIncomes = [];	
	this.filteredFamilyIncomes = [];
	this.categories = [];
	
	this.gridData = [];  
	this.gridIncomeData = [];  
	 
	this.currentEditFamilyExpense;
	this.categoryHtml = "";
	
	this.currentRecordType = 1;
	
	
	this.currentDate ;
	
	this.isAddMode = true;
	
	this.globalExpenseIndex = 0;
	this.globalIncomeIndex = 0;
	
	 
	
	 this.displayCovePage = function displayCovePage(){
		  var justCreated = $("#justCreated").val();
		  
		   $("#participantBox").hide();
		   $("#tabs").show();
		   $("#tabs" ).tabs( { active: 1 } );
		   
			$("#expenseCreatedByDiv").html(lblCreatedOna + dashBoard.getFormatedDbDate(dashBoard.expense.create_date));
	 		   
		  if(justCreated == "yes"){ 
		  	 
		  	 
		  	$("#tabs" ).tabs( { active: 1 } );
		 
		//	dashBoard.setParticipantGridExtension(); 
		  } else{
		  
			 //hide loading
			 $("#dvLoading").hide();			 
		 }
		 
		  dashBoard.showIncomeList();   	  
		  dashBoard.showExpenseList();	
		  //	 
		  dashBoard.setCategory(1,"");	
	 }
	 
   
	this.showExpenseList = function showExpenseList(){
 
		dashBoard.gridData = [];		
		 dashBoard.isAddMode = true;
		 
		 for (var index in dashBoard.familyExpenses) {
		 
			dashBoard.gridData.push(dashBoard.getDataByExpense(dashBoard.familyExpenses[index])); 
		 }
 
		dashBoard.reloadGrid();  
		 
 	}
 	
 	this.showIncomeList = function showIncomeList(){
 
		dashBoard.gridIncomeData = [];		
		dashBoard.isAddMode = true;
		 
		 for (var index in dashBoard.familyIncomes) {		 
			dashBoard.gridIncomeData.push(dashBoard.getDataByExpense(dashBoard.familyIncomes[index])); 
		 }
 
		dashBoard.loadIncomeGrid();  		 
 	}
	
	
	this.getDataByExpense = function getDataByExpense(familyExpenseObj){
		
		var key = familyExpenseObj.id;
		 dashBoard.filteredFamilyExpenses[key] = dashBoard.getFilteredExpenseObj(familyExpenseObj);
 		
		 return [dashBoard.filteredFamilyExpenses[key].id,dashBoard.filteredFamilyExpenses[key].expenseName,dashBoard.filteredFamilyExpenses[key].expenseCategory,dashBoard.filteredFamilyExpenses[key].expenseDate,dashBoard.filteredFamilyExpenses[key].expenseDay,dashBoard.showFormatedAmount(dashBoard.filteredFamilyExpenses[key].amount)]; 
	}
	
	this.getFilteredExpenseObj = function getFilteredExpenseObj(familyExpenseObj){
		
		var filteredFamilyExpenseObj = new FilteredFamilyExpense();
		
		filteredFamilyExpenseObj.id = familyExpenseObj.id; 		
		filteredFamilyExpenseObj.expenseName=familyExpenseObj.expenseName;
		filteredFamilyExpenseObj.expenseCategory=familyExpenseObj.expenseCategory;
		filteredFamilyExpenseObj.expenseDate = familyExpenseObj.expenseDate;//dashBoard.getFormatedDate(familyExpenseObj.expenseDate);	
		filteredFamilyExpenseObj.expenseDay = dashBoard.getDayByDate(familyExpenseObj.expenseDate);			 
		filteredFamilyExpenseObj.amount = dashBoard.getFormatedAmount(familyExpenseObj.amount);
 		filteredFamilyExpenseObj.noOfNotes=familyExpenseObj.noOfNotes;
 		
		return filteredFamilyExpenseObj;
	}
	
	this.getFilteredExpenseObjPrint = function getFilteredExpenseObjPrint(familyExpenseObj){
		
		var filteredFamilyExpenseObj = new FilteredFamilyExpense();
		
		filteredFamilyExpenseObj.id = familyExpenseObj.id;
 		filteredFamilyExpenseObj.amount = dashBoard.showFormatedAmount(familyExpenseObj.amount);
		filteredFamilyExpenseObj.expenseName=familyExpenseObj.expenseName;
		filteredFamilyExpenseObj.expenseCategory=familyExpenseObj.expenseCategory;
		filteredFamilyExpenseObj.expenseDate = familyExpenseObj.expenseDate;//dashBoard.getFormatedDate(familyExpenseObj.expenseDate);		 
		filteredFamilyExpenseObj.noOfNotes=familyExpenseObj.noOfNotes;
 		
		return filteredFamilyExpenseObj;
	}
	
	this.getDayByDate = function getDayByDate(dateUnix){
		var dateObj = new Date(dateUnix*1000);
		 
		var d = new Date();
		var weekday = new Array(7);
		weekday[0]=  "Sunday";
		weekday[1] = "Monday";
		weekday[2] = "Tuesday";
		weekday[3] = "Wednesday";
		weekday[4] = "Thursday";
		weekday[5] = "Friday";
		weekday[6] = "Saturday";

		return weekday[dateObj.getDay()]; 
		
	}
	
	this.reloadGrid = function reloadGrid(){
 
		var  initDateEdit = function(elem) {
            setTimeout(function() {
                $(elem).datepicker({
                    dateFormat: 'dd-M-yy',
                    autoSize: true,
                    showOn: 'button', // it dosn't work in searching dialog
                    changeYear: true,
                    changeMonth: true,
                    showButtonPanel: true,
                    showWeek: true
                });
                //$(elem).focus();
         },100);
        };
      
        var maxRowNum = dashBoard.globalExpenseIndex;
        
   
        if(maxRowNum<101){
        	maxRowNum = 100;
        }  
        
         
		$("#grid").jqGrid({ 
		    datatype: "local",
		    height: 232, 
		    title:false,
		    colNames: ['SI', lblForWhatReason, lblCategory, lblWhen, lblDay, lblAmount+'('+dashBoard.expense.currency+')?'],
		    colModel: [
		    {
		        name: 'SI',
		        index: 'SI',
		        width: 0,
		        sorttype: "int",
		        hidden:true,
		        key:true
		    },
		    {
		        name: 'Reason',
		        index: 'Reason',
		        align:'center',
		        width: 290,
		        formoptions:{rowpos:1},
		        editable: true,			         
		        editrules:{required:true},
		        editoptions:{maxlength:25},
		        sorttype: "float" 
		        
		    },
		    {
		        name: 'Category',
		        index: 'Category',
		        width: 180 ,
		        align:'center',
		        formoptions:{rowpos:2},
		        editable: true, 		        
                edittype:'select',
                editoptions:{value:'1:X',defaultValue:'X' }
		    },		    
		    {
		        name: 'Date',
		        index: 'Date',		       
		        width: 85,
		        align:'center', 
		        sorttype:'date',                               
                formoptions:{rowpos:3},
                editable:true,                    
                editrules:{required:true},
                editoptions: {dataInit:initDateEdit}
	         },
		    {
		        name: 'Day',
		        index: 'Day',
		        align:'center',
		        width: 75,
		        sorttype: "float",
		        cellattr: function (rowId, tv, rawObject, cm, rdata) { return 'style="white-space: normal !important;"' }
		    },
		    {
		        name: 'Amount',
		        index: 'Amount',
		        align:'center',
		        width: 120,
		        formoptions:{elmsuffix:'('+dashBoard.expense.currency+')', rowpos:4},
		        editable: true,			         
		        editrules:{required:true},
		        editoptions:{ maxlength:18,dataInit: function (el) {
	                $(el).keyup(function () {	                	
	                    
	                	el.value = el.value.replace(/[^0-9\.]/g,'');
	                	if(el.value.replace(/[^.]/g, "").length == 2){
	                		el.value = el.value.substring(0, el.value.length-1);
	                	}	                	
	                	dashBoard.changeExpenseAmount();
	                });
	              }
		        }
		    },
		    ],
		    rowNum      : maxRowNum,	         
            rowList:[10,20,50,maxRowNum],            
            pager: '#expense_pager',
            gridview:true,
            rownumbers:true,
            autoencode:true,
            ignoreCase:true,           
            viewrecords: true,
            sortorder: 'desc',
            caption:'Expense List' 
		}  
		);
 		 
		dashBoard.addRowsToGrid(dashBoard.gridData,'#grid');
	 
	 		$("#grid").jqGrid('setGridParam', {
			onSelectRow: function(rowid,iRow,iCol,e){
				
				if(!iCol){					 
					dashBoard.isAddMode = false;			
					dashBoard.loadForEdit();					 
				}
	    		 
				}
			}
		);
		
		$("#grid").jqGrid('setGridParam', {ondblClickRow: function(rowid,iRow,iCol,e){
			dashBoard.isAddMode = false; 
			jQuery(this).jqGrid('editGridRow', rowid);
			
		}});
		
	 
		
		$("#grid").jqGrid('navGrid','#expense_pager',{
			add:true,addtitle: lblAddExpense,
			edit:true,edittitle: lblModifyExpense,
			del:true,deltitle: lblDeleteExpense ,
			search:true,searchtitle: lblFindExpenses},
			{ 
			      recreateForm: true,
			      beforeInitData: function () {
			    	  
			    	  dashBoard.isAddMode = false;
			    	 
			      }
			  },
			  {  
			      recreateForm: true,
			      beforeInitData: function () {
			    	  dashBoard.isAddMode = true;
			         
			      }
			  }
		
		);
	  
		
      dashBoard.setExpenseGridExtension(); 
		
	 
		jQuery("#grid").setGridParam({rowNum:maxRowNum}).trigger("reloadGrid");
	  
		$('.ui-jqgrid-bdiv').scrollTop($('#grid')[0].scrollHeight);
		 
	}
	
	this.setExpenseGridExtension = function setExpenseGridExtension(){
		$.extend($.jgrid.edit, {
			addCaption: lblAddExpense,
			editCaption: lblModifyExpense,
		    bSubmit: lblSave,
		    bCancel: lblCancel,
		    
		    recreateForm: true,
		    beforeShowForm: function () { 
		    	 
		    	if(dashBoard.isAddMode == true){ 
		    		
		        	$('<a >Save & Continue<span class="ui-icon ui-icon-disk"></span></a>')
		            .click(function() {
		            	dashBoard.validateExpenseAddForm(0);
		               })
		            .addClass("fm-button ui-state-default ui-corner-all fm-button-icon-left")
		            .prependTo("#Act_Buttons>td.EditButton");
		        	
		    		$('#Category').find('option').remove().end().append(dashBoard.categoryHtml); 
		    	    
				      $("#Date").val(dashBoard.currentDate);
		    	} else { 
		    		dashBoard.loadForEdit();
		    	}		      
		    },
		    
		   beforeSubmit: function(response, postData) {             
			   dashBoard.validateExpenseAddForm(1);			   
            }
		
		});
		
		$.extend($.jgrid.del, {
			 
			caption: lblDeleteExpense,
            msg: lblWantDeleteExpense,
		   beforeSubmit: function(response, postData) {             
				dashBoard.deleteExpense();			   
            }		
		});				
	}
	 
	 
	 	
	this.loadIncomeGrid = function loadIncomeGrid(){
		
		var  initDateEdit = function(elem) {
            setTimeout(function() {
                $(elem).datepicker({
                    dateFormat: 'dd-M-yy',
                    autoSize: true,
                    showOn: 'button', // it dosn't work in searching dialog
                    changeYear: true,
                    changeMonth: true,
                    showButtonPanel: true,
                    showWeek: true
                });
               
         },100);
        };
      
        var maxRowNum = dashBoard.globalIncomeIndex; 
   
        if(maxRowNum<101){
        	maxRowNum = 100;
        }   
         
		$("#income_grid").jqGrid({ 
		    datatype: "local",
		    height: 232, 
		    title:false,
			colNames: ['SI', lblForWhatReason, lblCategory, lblWhen, lblDay, lblAmount + '('+dashBoard.expense.currency+')?'],
		    colModel: [
		    {
		        name: 'SI',
		        index: 'SI',
		        width: 0,
		        sorttype: "int",
		        hidden:true,
		        key:true
		    },
		    {
		        name: 'Reason',
		        index: 'Reason',
		        align:'center',
		        width: 290,
		        formoptions:{rowpos:1},
		        editable: true,			         
		        editrules:{required:true},
		        editoptions:{maxlength:25},
		        sorttype: "float" 
		        
		    },
		    {
		        name: 'Category',
		        index: 'Category',
		        width: 180 ,
		        align:'center',
		        formoptions:{rowpos:2},
		        editable: true, 		        
                edittype:'select',
                editoptions:{value:'1:X',defaultValue:'X' }
		    },		    
		    {
		        name: 'Date',
		        index: 'Date',		       
		        width: 85,
		        align:'center', 
		        sorttype:'date',                               
                formoptions:{rowpos:3},
                editable:true,                    
                editrules:{required:true},
                editoptions: {dataInit:initDateEdit}
	         },
		    {
		        name: 'Day',
		        index: 'Day',
		        align:'center',
		        width: 75,
		        sorttype: "float",
		        cellattr: function (rowId, tv, rawObject, cm, rdata) { return 'style="white-space: normal !important;"' }
		    },
		    {
		        name: 'Amount',
		        index: 'Amount',
		        align:'center',
		        width: 120,
		        formoptions:{elmsuffix:'('+dashBoard.expense.currency+')', rowpos:4},
		        editable: true,			         
		        editrules:{required:true},
		        editoptions:{ maxlength:18,dataInit: function (el) {
	                $(el).keyup(function () {
	                	
	                    //alert(el.value);
	                	el.value = el.value.replace(/[^0-9\.]/g,'');
	                	if(el.value.replace(/[^.]/g, "").length == 2){
	                		el.value = el.value.substring(0, el.value.length-1);
	                	}
	                	
	                	 
	                	dashBoard.changeExpenseAmount();
	                });
	              }
		        }
		    },
		    ],
		    rowNum      : maxRowNum,	         
            rowList:[10,20,50,maxRowNum],            
            pager: '#income_pager',
            gridview:true,
            rownumbers:true,
            autoencode:true,
            ignoreCase:true,           
            viewrecords: true,
            sortorder: 'desc',
            caption:lblIncomeList
		}  
		);
 		 
		dashBoard.addRowsToGrid(dashBoard.gridIncomeData,'#income_grid');
	 
	 		$("#income_grid").jqGrid('setGridParam', {
			onSelectRow: function(rowid,iRow,iCol,e){
				
				if(!iCol){					
					dashBoard.isAddMode = false;			
					dashBoard.loadForEdit();					
				}
	    		 
				}
			}
		);
		
		$("#income_grid").jqGrid('setGridParam', {ondblClickRow: function(rowid,iRow,iCol,e){
			dashBoard.isAddMode = false; 
			jQuery(this).jqGrid('editGridRow', rowid);
			
		}});
		
	 
		
		$("#income_grid").jqGrid('navGrid','#income_pager',{
			add:true,addtitle: lblAddIncome,
			edit:true,edittitle: lblModifyIncome,
			del:true,deltitle: lblDeleteIncome ,
			search:true,searchtitle: lblFindIncome},
			{ 
			      recreateForm: true,
			      beforeInitData: function () {
			    	  
			    	  dashBoard.isAddMode = false;
			    	 
			      }
			  },
			  {  
			      recreateForm: true,
			      beforeInitData: function () {
			    	  dashBoard.isAddMode = true;
			         
			      }
			  }
		
		);	  
	 
		jQuery("#income_grid").setGridParam({rowNum:maxRowNum}).trigger("reloadGrid");
	  
		$('.ui-jqgrid-bdiv').scrollTop($('#income_grid')[0].scrollHeight); 
	}
	 
	 this.setIncomeGridExtension = function setIncomeGridExtension(){
		$.extend($.jgrid.edit, {
			addCaption: lblAddIncome,
			editCaption: lblModifyIncome,
		    bSubmit: lblSave,
		    bCancel: lblCancel,
		   // width:300,
		    
		    recreateForm: true,
		    beforeShowForm: function () { 
		    	 
		    	if(dashBoard.isAddMode == true){ 
		    		
		        	$('<a >Save & Continue<span class="ui-icon ui-icon-disk"></span></a>')
		            .click(function() {
		            	dashBoard.validateExpenseAddForm(0);
		               })
		            .addClass("fm-button ui-state-default ui-corner-all fm-button-icon-left")
		            .prependTo("#Act_Buttons>td.EditButton");
		        	
		    		$('#Category').find('option').remove().end().append(dashBoard.categoryHtml); 
		    	    
				      $("#Date").val(dashBoard.currentDate);
		    	} else { 
		    		dashBoard.loadForEdit();
		    	}		      
		    },
		    
		   beforeSubmit: function(response, postData) {             
			   dashBoard.validateExpenseAddForm(1);
			   
            }
		
		});
		
		$.extend($.jgrid.del, {

            caption: lblDeleteIncome,
            msg: lblWantDeleteIncome,
		   beforeSubmit: function(response, postData) {             
				dashBoard.deleteIncome();			   
            }
		
		});
		
		
	}
	
	 
	
	this.loadForEdit = function loadForEdit(){
	   if(dashBoard.currentRecordType == "1"){
		var rowId =$("#grid").jqGrid('getGridParam','selrow');		 
		var rowData = jQuery("#grid").getRowData(rowId);	 
		dashBoard.showEditUI(dashBoard.familyExpenses[rowData['SI']]);
	  } else {
		var rowId =$("#income_grid").jqGrid('getGridParam','selrow');		 
		var rowData = jQuery("#income_grid").getRowData(rowId);	 
		dashBoard.showEditUI(dashBoard.familyIncomes[rowData['SI']]);
	 }
		$('#Category').find('option').remove().end().append(dashBoard.categoryHtml);
	}
	
 
	
	 
	this.updateBalance = function updateBalance(){
		//balance
	}
	 
	
	this.setCategory = function setCategory(type,defaultValue){
		
		dashBoard.categoryHtml = "";
		
		dashBoard.currentRecordType = type;
		
		for (var index in dashBoard.categories) {		 
			if(dashBoard.categories[index].type == "0" || dashBoard.categories[index].type ==  type ){
				if(defaultValue == dashBoard.categories[index].name){
					dashBoard.categoryHtml += '<option value="'+dashBoard.categories[index].name+'" selected role="option">'+dashBoard.categories[index].name+'</option>';		
				} else {
					dashBoard.categoryHtml += '<option value="'+dashBoard.categories[index].name+'" role="option">'+dashBoard.categories[index].name+'</option>';			 	 
 				}
 			}
 		
 		}
	}
	 
	this.showEditUI =function showEditUI(expenseObj){
		
		dashBoard.currentEditFamilyExpense = expenseObj;
		
		//set Category
		 dashBoard.setCategory(dashBoard.currentRecordType,expenseObj.expenseCategory);
		
		//assign parts and freeze amounts to all participants		 
	 
 
	}
	 
	// Utilities functions
	this.getCurrency = function getCurrency(){
		return dashBoard.expense.currency;
	}
	
	this.getFormatedAmount = function getFormatedAmount(amount){
		 return parseFloat(amount).toFixed(15);
	}
	
	this.getFormatedAmountDB = function getFormatedAmountDB(amount){
		 return parseFloat(amount).toFixed(4);
	}
	
	this.showFormatedAmount = function showFormatedAmount(amount){
		 return parseFloat(amount).toFixed(2);
	}
	
	this.getFormatedDate = function getFormatedDate(date){
		
		 var dateObj = new Date((new Date(date*1000)).toUTCString());
		 
		  var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
		  var year = dateObj.getFullYear();
		  var month = months[dateObj.getMonth()];
		  var date = String(dateObj.getDate());
		  var time ;
		 
		  if(date.length == 1){
			  
			  time = '0'+ date + '-' + month + '-' + year ;		  
			  
		  } else {
			  time = date + '-' + month + '-' + year ;
		  }
	 
		 
		  return time;
	}
	
	this.getFormatedDbDate = function getFormatedDbDate(date){
		 
		 var time ;
		 
		if(date != ""){ 
			var dateObj = date.split(" ");
			 var dateInfo = dateObj[0].split("-");
			 
			  var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
			  var year = dateInfo[0];
			  var month = months[parseInt(dateInfo[1])-1];
			  var date = String(dateInfo[2]);
			 
			 
			  if(date.length == 1){
				  
				  time = '0'+ date + '-' + month + '-' + year ;		  
				  
			  } else {
				  time = date + '-' + month + '-' + year ;
			  }
	 
		}
		
		return time;
	}
	
	this.setCurrentDate = function setCurrentDate(){
		
		  var dateObj = new Date();
	 
		  var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
		  var year = dateObj.getFullYear();
		  var month = months[dateObj.getMonth()];
		  var date = String(dateObj.getDate());
		  
		  if(date.length == 1){
			  date = "0"+date;
		  }
		  
		  dashBoard.currentDate = date + '-' + month + '-' + year ;
		  
	}
	
	
	
	 
	
	this.inArrayElement = function inArrayElement(array, value){
		 
		var result = false;
		    for(var i=0;i<array.length;i++) {
		        if(array[i] === value){
		        	result = true;
		        	break;
		        }
		    }
		    return result;
		 
	}
	
	 this.isCategoryExistInObj = function isCategoryExistInObj(catArray, categoryName){
		 
		var result = false;
		var category;
		    for(var id in catArray) {
		  
		    	category = catArray[id];		    	   
		        if(category.name === categoryName){
		        	result = true;
		        	break;
		        }
		    }
		    return result;
		 
	}
	
	 
	
	this.validateExpenseAddForm = function validateExpenseAddForm(source){
		
		var errorMessage = "";

        //validate expense name
        if (!$('#Reason').val().trim()) {
            errorMessage = lblEnterNameOfExpense
        } else if ($('#Reason').val().trim().length>25){
            errorMessage = lblExpenseNameLessThanChar
        }
		
		//validate amount field
        if(errorMessage == ""){
            if(!$('#Amount').val().trim()){
                errorMessage = lblValidAmount
            } else if (parseFloat($('#Amount').val()) <= parseFloat(0)) {
                errorMessage = lblValidAmount
            }
        }
		 
		
		//validate date	
		if(errorMessage == ""){
			
			if($('#Date').val().trim() != ""){
				var dateArray  = $('#Date').val().trim().split("-");
				if(dateArray.length != 3){
					errorMessage = lblDateNotValid;
				} else {
					errorMessage = isValidDate(dateArray);
				}
			}
		}
		 
		
		//set or clear error message
		if(errorMessage != ""){
			dashBoard.showErrorMessage(errorMessage);
		} else {
			
			dashBoard.clearErrorMessage();
			addExpense();
			if(source == 1){
				$(".ui-icon-closethick").trigger('click');
			} else {
				dashBoard.clearAddForm();
			}
		}
		 
	}
	
	this.showErrorMessage = function showErrorMessage(msg){
		$("#FormError").show();
		$(".ui-state-error").html(msg);
	}
	
	this.clearErrorMessage = function clearErrorMessage(){
		$("#FormError").hide();
		$(".ui-state-error").html("");
	}
	
	this.clearAddForm = function clearAddForm(){
		$('#Reason').val("");
		$('#Amount').val(""); 
        $('#Reason').focus();
	}
	
	this.addRowsToGrid = function addRowsToGrid(data,grid_id){
		var names = ['SI', 'Reason','Category', 'Date', 'Day', 'Amount'];
		var mydata = [];
		 

		for (var i = 0; i < data.length; i++) {
		    mydata[i] = {};
		    
		    for (var j = 0; j < data[i].length; j++) {
		    	 
		        mydata[i][names[j]] = data[i][j];
		    }
		}
		
		if(dashBoard.isAddMode == true){
			for (var i = 0; i < mydata.length; i++) {
				 
			    $(grid_id).jqGrid('addRowData',data[i][0], mydata[i]);
			}
 
		} else { 
				
			 $(grid_id).jqGrid('setRowData', data[0][0], mydata[0]);
			 dashBoard.isAddMode = true;
		}
		
	}
	
	this.getExpenseUniqueId = function getExpenseUniqueId(){
		
		var maxExpId = 0;
		var extractedIndex = 0;
		var expenseIdArray;
		if(dashBoard.currentRecordType == "1"){
			for (var id in dashBoard.familyExpenses) {		
				expenseIdArray = dashBoard.familyExpenses[id].id.split("-");			
				if(maxExpId < parseInt(expenseIdArray[1])){			
					maxExpId = parseInt(expenseIdArray[1]);
				}
			}
		} else {
		
			for (var id in dashBoard.familyIncomes) {		
				expenseIdArray = dashBoard.familyIncomes[id].id.split("-");			
				if(maxExpId < parseInt(expenseIdArray[1])){			
					maxExpId = parseInt(expenseIdArray[1]);
				}
			}
		}
		
		return  dashBoard.currentRecordType+"-"+String(pad(maxExpId+1, 5))+"-"+dashBoard.expense.id;
 	}
	
	this.isValueModified = function isValueModified(oldExpObj,newExpObj){
		
		var isChanged = false;
		 
		if(oldExpObj.expenseName != newExpObj.expenseName){			 
			isChanged = true;
		}  else if(oldExpObj.expenseCategory != newExpObj.expenseCategory){			 
			isChanged = true;
		} else if(oldExpObj.expenseDate != newExpObj.expenseDate){			 
			isChanged = true;
		} else if(parseFloat(oldExpObj.amount) != parseFloat(newExpObj.amount)){			
			isChanged = true;
		}  		
		
		return isChanged;
		
	}
	
	
	this.addExpenseToGrid = function addExpenseToGrid(){
		var familyExpenseObj ;
		
		//collect data from edit form 		
		if(dashBoard.isAddMode == true){			
			familyExpenseObj= new FamilyExpense();		 
			familyExpenseObj.id = dashBoard.getExpenseUniqueId();			
			familyExpenseObj.expenseId = dashBoard.expense.id;
			familyExpenseObj.isAdd = "8";
			familyExpenseObj = dashBoard.getInputFormData(familyExpenseObj);
			familyExpenseObj.type = 1;
			
			familyExpenseObj.recordType = dashBoard.currentRecordType;
			
			if(familyExpenseObj.recordType == "1"){
				dashBoard.globalExpenseIndex++;
			} else {
				dashBoard.globalIncomeIndex++;
			}
			 
			
		} else {
			 
			familyExpenseObj = new FamilyExpense();
			familyExpenseObj = dashBoard.getInputFormData(familyExpenseObj);
			//check whether data is modified or not. If not change then return
			if(!dashBoard.isValueModified(dashBoard.currentEditFamilyExpense,familyExpenseObj)){
				return;
			}  
			
			familyExpenseObj = dashBoard.currentEditFamilyExpense;			
			familyExpenseObj = dashBoard.getInputFormData(familyExpenseObj); 
			
			familyExpenseObj.expenseId = dashBoard.expense.id;
			familyExpenseObj.isAdd = "9";
			
			familyExpenseObj.id = dashBoard.currentEditFamilyExpense.id; 			 
		}		 
		
		familyExpenseObj.isreimburse = 0;	
		
		
		dashBoard.processExpenseData(familyExpenseObj);	 
	}
	
	this.processExpenseData = function processExpenseData(familyExpenseObj){
		 
		 if(familyExpenseObj.recordType == "1"){
		 	dashBoard.familyExpenses[familyExpenseObj.id] =  familyExpenseObj;		
		 	sendDataToServer(familyExpenseObj,"#expenseForm"); 
			var data = [];		 
			data.push(dashBoard.getDataByExpense(familyExpenseObj)); 		 
 			dashBoard.addRowsToGrid(data,'#grid');  		
 			//go to the last page after adding record
 			dashBoard.setPageAfterAdd('#grid'); 		
		 } else {
		 	dashBoard.familyIncomes[familyExpenseObj.id] =  familyExpenseObj;
		 	sendDataToServer(familyExpenseObj,"#expenseForm");
			var data = [];			 
			data.push(dashBoard.getDataByExpense(familyExpenseObj));
 			dashBoard.addRowsToGrid(data,'#income_grid');  		
 			//go to the last page after adding record
 			dashBoard.setPageAfterAdd('#income_grid'); 		
		 }		
	}
	
	this.setPageAfterAdd = function setPageAfterAdd(grid_id){
		if(dashBoard.isAddMode == true){ 
			var lastPage = $(grid_id).getGridParam('lastpage');
			var totalRecords = $(grid_id).getGridParam('records');		 
			var rowNum =  $(grid_id).getGridParam('rowNum');
			
			 if(totalRecords > (rowNum*lastPage)){
				 lastPage++;
			 }
			
	 		$(grid_id).setGridParam({page:lastPage});			 
			$(grid_id).trigger("reloadGrid");
 		}
	}
	
	this.setPageAfterDelete = function setPageAfterDelete(grid_id){
		  	
			var currentPage = $(grid_id).getGridParam('page');
			var rowCount = $(grid_id).getGridParam('reccount');
			var rowNum =  $(grid_id).getGridParam('rowNum');
		 
			if(rowCount==0 && currentPage>1){
				currentPage = currentPage-1;
				$(grid_id).setGridParam({page:currentPage});			 
				
			}  
			$(grid_id).trigger("reloadGrid");
 		 
	}	
	
	this.getInputFormData = function getInputFormData(familyExpenseObj){
 		
		var amountStr = "";
		var isDetails = false;
		 
		familyExpenseObj.expenseCategory = $('#Category').val();		 
		familyExpenseObj.expenseName = $('#Reason').val();
		familyExpenseObj.amount = $('#Amount').val();		
		familyExpenseObj.expenseDate = $('#Date').val();// getTimeStampByInputDate($('#Date').val());
				
		return familyExpenseObj;
	}
	
	this.deleteExpense = function deleteExpense(){
		
		var rowId =$("#grid").jqGrid('getGridParam','selrow'); 
		var i;
	 	 
		$('#grid').jqGrid('delRowData', rowId);	 
		var deletedExpObj = dashBoard.familyExpenses[rowId];
		 
		delete dashBoard.familyExpenses[rowId];
		 
		deletedExpObj.isAdd = "10"; 	 
	 
		deletedExpObj.expenseId = dashBoard.expense.id;
		dashBoard.setPageAfterDelete('#grid');
		sendDataToServer(deletedExpObj,"#expenseForm");
		$(".ui-icon-closethick").trigger('click');		
	}
	
	this.deleteIncome = function deleteIncome(){
		
		var rowId =$("#income_grid").jqGrid('getGridParam','selrow'); 
		var i;
	 	 
		$('#income_grid').jqGrid('delRowData', rowId);	 
		var deletedExpObj = dashBoard.familyIncomes[rowId];
		 
		delete dashBoard.familyIncomes[rowId];
		 
		deletedExpObj.isAdd = "10"; 	 
	 
		deletedExpObj.expenseId = dashBoard.expense.id;
		dashBoard.setPageAfterDelete('#income_grid');
		sendDataToServer(deletedExpObj,"#expenseForm");
		$(".ui-icon-closethick").trigger('click');		
	}
	
	
	this.createGraphImage = function createGraphImage(){
		$("#balance_chart_image").html("");
		var imgData = $('#balance_chart').jqplotToImageStr({});  
		var imgElem = $('<img\/>').attr('src',imgData).attr('id',"graph_image_id").attr('alt',"balance.png");  
	 
		 dashBoard.downloadImage("graph_image_id");
 	}
	
	
	this.downloadImage = function downloadImage(imageURL) {

	    try {
	    	var img = document.getElementById(imageURL);
	    	window.open(img.src.replace('image/png', 'image/png'), "_blank"); 
	    }
	    catch (err) {
	     
	        alert(lblCantDownload);
	    }

	    return true;
	}
	
	 
	
	this.drawGraph = function drawGraph(){
		
		if(plot1){
			
			  plot1.destroy(); 
		}
		 
		 
		if(plot2){
			
			  plot2.destroy(); 
		}
		 
		 
		if(plot3){
			
			  plot3.destroy(); 
		}
		 
	 
	     var data = [];	     
	     var barLabel = [];	 
	     var ticks = [];
	     
	     var data_income = [];	     
	     var barLabel_income = [];	 
	     var ticks_income = [];
	     var data_balance = [];	
	     
	    
	     
	     var totalExpense = 0;
	     var totalIncome = 0;
	     var balance = 0;
	     var balance_color_code = "#008000";
	     var actualBalance = 0;
	     
	     
	     var catObj;
	     
	     var expenseCategories = [];
	     var incomeCategories = [];
	    
	   
	     var noOfExpenseCategories = 0;
	     var noOfIncomeCategories = 0;
	     
	     
	  
	     for (var index in dashBoard.familyExpenses) { 
	      
	    	  totalExpense = parseFloat(totalExpense) + parseFloat(dashBoard.familyExpenses[index].amount);
		     if(dashBoard.isCategoryExistInObj(expenseCategories,dashBoard.familyExpenses[index].expenseCategory)){	       
		    	 //get the object
		      	catObj = expenseCategories[dashBoard.familyExpenses[index].expenseCategory];
		     	catObj.amount = parseFloat(catObj.amount) + parseFloat(dashBoard.familyExpenses[index].amount);
		        expenseCategories[dashBoard.familyExpenses[index].expenseCategory] = catObj;	     
		     } else {
		      	 noOfExpenseCategories++;
		     	 //insert new entry into expenseCategories
		     	 catObj = new Category();
		     	 catObj.name = dashBoard.familyExpenses[index].expenseCategory;
		     	 catObj.amount =  dashBoard.familyExpenses[index].amount;
		     	 expenseCategories[catObj.name] = catObj;
		     } 
	     } 
	    
	     
			var sortableExpenseCategories = [];
			for (var index in expenseCategories)
				sortableExpenseCategories.push([expenseCategories[index].name, expenseCategories[index].amount])
			 
			sortableExpenseCategories.sort(function(a, b) {return b[1] - a[1]})
			 
			for (var index in sortableExpenseCategories ) {
				data.push(parseFloat(dashBoard.showFormatedAmount(sortableExpenseCategories[index][1])));		
	    	 	barLabel.push(dashBoard.showFormatedAmount(parseFloat(sortableExpenseCategories[index][1])));	    	 
	    	 	ticks.push(sortableExpenseCategories[index][0] + "\n"+parseFloat(dashBoard.showFormatedAmount(sortableExpenseCategories[index][1]))+" "+dashBoard.expense.currency);	    	 
			}
	     
	  //   for (var index in expenseCategories) {  
	      //	 data.push(parseFloat(dashBoard.showFormatedAmount(expenseCategories[index].amount)));		
	    	// barLabel.push(dashBoard.showFormatedAmount(parseFloat(expenseCategories[index].amount)));	    	 
	    	// ticks.push(expenseCategories[index].name + "\n"+parseFloat(dashBoard.showFormatedAmount(expenseCategories[index].amount))+" "+dashBoard.expense.currency);	    	 
	     // } 
	    
		for (var index in dashBoard.familyIncomes) {  
	     	 totalIncome = parseFloat(totalIncome) + parseFloat(dashBoard.familyIncomes[index].amount);
		     if(dashBoard.isCategoryExistInObj(incomeCategories,dashBoard.familyIncomes[index].expenseCategory)){	       
		    	 //get the object
		     	catObj = incomeCategories[dashBoard.familyIncomes[index].expenseCategory];
		     	catObj.amount = parseFloat(catObj.amount) + parseFloat(dashBoard.familyIncomes[index].amount);
		     	incomeCategories[dashBoard.familyIncomes[index].expenseCategory] = catObj;	     
		     } else {
		      	  noOfIncomeCategories++;
		     	 //insert new entry into incomeCategories
		     	 catObj = new Category();
		     	 catObj.name = dashBoard.familyIncomes[index].expenseCategory;
		     	 catObj.amount =  dashBoard.familyIncomes[index].amount;
		     	 incomeCategories[catObj.name] = catObj;
		     } 
	     } 
	     
	     
	     //calculate balance
	     balance = parseFloat(totalIncome) - parseFloat(totalExpense);
	     actualBalance = balance;
	     
	     if(parseFloat(balance) < parseFloat(0)){
	   		balance_color_code = "#FF0000";
	     	balance = parseFloat(balance) * (-1);
	     }  
	     
		var sortableIncomeCategories = [];
		for (var index in incomeCategories)
			sortableIncomeCategories.push([incomeCategories[index].name, incomeCategories[index].amount])
		 
		sortableIncomeCategories.sort(function(a, b) {return b[1] - a[1]})
		 
		for (var index in sortableIncomeCategories ) {
			data_income.push(parseFloat(dashBoard.showFormatedAmount(sortableIncomeCategories[index][1])));		
    	 	barLabel_income.push(dashBoard.showFormatedAmount(parseFloat(sortableIncomeCategories[index][1])));	    	 
    	 	ticks_income.push(sortableIncomeCategories[index][0] + "\n"+parseFloat(dashBoard.showFormatedAmount(sortableIncomeCategories[index][1]))+" "+dashBoard.expense.currency);	    	 
		}
	     
	//	for (var index in incomeCategories) {  
	     // 	 data_income.push(parseFloat(dashBoard.showFormatedAmount(incomeCategories[index].amount)));		
	    //	 barLabel_income.push(dashBoard.showFormatedAmount(parseFloat(incomeCategories[index].amount)));
	    //	 ticks_income.push(incomeCategories[index].name+"\n"+parseFloat(dashBoard.showFormatedAmount(incomeCategories[index].amount))+" "+dashBoard.expense.currency);	    	 
	     // }
	      
	     if(noOfExpenseCategories < 3){
	       $("#expense_chart").css("width", "250px");
	     } else {
	       $("#expense_chart").css("width", (noOfExpenseCategories*100)+"px");
	     }
	     
	      if(noOfIncomeCategories < 3){
	       $("#income_chart").css("width", "250px");
	     } else {
	       $("#income_chart").css("width", (noOfIncomeCategories*100)+"px");
	     }
	     
	     
	     var options_income = {
		    
		        seriesDefaults:{
		            renderer:$.jqplot.BarRenderer,
		            rendererOptions: {fillToZero: true}
		        },
		        axesDefaults:{min:0},
		         
		        series:[
		            { 
		            	color: '#ADFF2F',
		            	showMarker: true,
		            	pointLabels:{
			                show: true,
			                labels:barLabel_income
			              }
		            } 
		        ],
		         
		        negativeSeriesColors: ["#FF0000"],
		        axes: {
		            
		            xaxis: {
		                renderer: $.jqplot.CategoryAxisRenderer,
		                ticks: ticks_income
		            },
		           
		            yaxis: {
		                pad: 0.18,
		                tickOptions: {formatString: '%d '+dashBoard.expense.currency}
		            }
		        },
		        title: { 
		        	text: 'Incomes of "'+dashBoard.expense.title+'"'
		            	
		        },
		         
		    };  
	    
	  
		var options_expense = {
		        
		        seriesDefaults:{
		            renderer:$.jqplot.BarRenderer,
		            rendererOptions: {fillToZero: true}
		        }, 
		         axesDefaults:{min:0},
		        series:[
		            {
		            	 
		            	color: '#A9A9A9', 
		            	showMarker: true,
		            	pointLabels:{
			                show: true,
			                labels:barLabel
			              }
		            } 
		        ],
		        
		        negativeSeriesColors: ["#FF0000"],
		        axes: {
		            
		            xaxis: {
		                renderer: $.jqplot.CategoryAxisRenderer,
		                ticks: ticks
		            },
		            
		            yaxis: {
		                pad: 0.18,
		                tickOptions: {formatString: '%d '+dashBoard.expense.currency}
		            }
		        },
		        title: { 
		        	text: 'Expenses of "'+dashBoard.expense.title+'"'
		            	
		        },
		        highlighter: {
        show:true,
        sizeAdjust: 10,
        tooltipLocation: 'n',
        tooltipAxes: 'yref',
        useAxesFormatters: false,
},
		         
		    };  
		    
		   /* var options_balance = {
		        
		       gridPadding: {top:0, bottom:38, left:0, right:0},
		        seriesDefaults:{
		            renderer:$.jqplot.PieRenderer, 
		            trendline:{ show:false }, 
		            rendererOptions: { padding: 8, showDataLabels: false }
		        },
		        seriesColors:  ["#068481","#B7C8B6", balance_color_code],
		        legend:{
		            show:true, 
		            placement: 'outside', 
		            rendererOptions: {
		                numberRows: 1
		            }, 
		            location:'s',
		            marginTop: '15px'
		        }       
		         
		    };  */

        var ticks = [lblIncome, lblExpens, lblBalance];
		 var data_balance = [['Income', totalIncome],['Expense',totalExpense],['Balance',balance]];
		
		 var options_balance = {			        
			        seriesDefaults:{
			        	 renderer:$.jqplot.BarRenderer,
			                rendererOptions: { 
			                	fillToZero: true,
			                	 varyBarColor: true
			                	},
			                    pointLabels: {show: true}
			        }, 
			        seriesColors:  ["#ADFF2F","#A9A9A9", balance_color_code],
			         axesDefaults:{min:0},
			        
			       
			        axes: {
			            
			            xaxis: {
			                renderer: $.jqplot.CategoryAxisRenderer,
			               
			                ticks: ticks
			              
			            },
			            
			            yaxis: {
			                pad: 0.18,
			                
			            }
			        } ,
			        highlighter: {
	        show:true,
	        sizeAdjust: 10,
	        tooltipLocation: 'n',
	        tooltipAxes: 'yref',
	        useAxesFormatters: false,
	},
			         
			    };  
 
		// var data_balance = [totalIncome,totalExpense,balance];
	     
	    
	        
		//  var data_balance = [['Income', totalIncome],['Expense', totalExpense], ['Balance', balance]];
		 
		 var data_balance = [totalIncome,totalExpense,balance];
			 
			 plot1 = $.jqplot('income_chart', [data_income],options_income);  
		     plot2 = $.jqplot('expense_chart', [data],options_expense);		    
		     plot3 = $.jqplot('balance_chart', [data_balance],options_balance);  
		     
		     
		     //set balance description
		     
		     var balancePaymentHtml = "";


        balancePaymentHtml = balancePaymentHtml + '<br/>'+lblTotalIncome+' :<span><b>'+dashBoard.showFormatedAmount(totalIncome)+'</b> '+dashBoard.expense.currency+'</span><br/>';
        balancePaymentHtml = balancePaymentHtml + lblTotalExpense+' :<span><b>'+dashBoard.showFormatedAmount(totalExpense)+'</b> '+dashBoard.expense.currency+'</span><br/>';
        balancePaymentHtml = balancePaymentHtml + '<p>-----------------------------</p>';
        balancePaymentHtml = balancePaymentHtml + '<p><b>' + lblBalance+' :</b><span>'+dashBoard.showFormatedAmount(actualBalance)+' '+dashBoard.expense.currency+'</span></p>';
 
	  
			$("#balance_description_div").html(balancePaymentHtml);
		   
		 
	} 
	
	 
	
	///////////////////////////////////////////////////////////////// Participant section ////////////////////////////////////////////
	
	 
	
	this.processAfterValidation = function processAfterValidation(errorMessage){
		if(errorMessage != ""){
			dashBoard.showErrorMessage(errorMessage);
		} else {			
			dashBoard.clearErrorMessage();
			dashBoard.addParticipant($('#Name').val().trim(),"2");
			$(".ui-icon-closethick").trigger('click');
		}
	}
	
	 
	this.printExpense = function printExpense(){
		var data_expense =[];
		var data_income =[];
		var totalExpense = 0;
	    var totalIncome = 0;
	    var balance = 0; 
		
		for (var id in dashBoard.familyExpenses) {	 
		 	totalExpense = parseFloat(totalExpense) + parseFloat(dashBoard.familyExpenses[id].amount);  
			data_expense.push(dashBoard.getFilteredExpenseObjPrint(dashBoard.familyExpenses[id]));
			 
		}
		
		for (var id in dashBoard.familyIncomes) {
			totalIncome = parseFloat(totalIncome) + parseFloat(dashBoard.familyIncomes[id].amount);	   
			data_income.push(dashBoard.getFilteredExpenseObjPrint(dashBoard.familyIncomes[id]));
			 
		}
 
  		//calculate balance
	     balance = parseFloat(totalIncome) - parseFloat(totalExpense);
		 
		$("#printExpense").val(JSON.stringify(dashBoard.expense));		
		$("#printExpenseList").val(JSON.stringify(data_expense));
		$("#printIncomeList").val(JSON.stringify(data_income));		 
		$("#printNames").val(JSON.stringify(dashBoard.getFormatedDbDate(dashBoard.expense.create_date)+","+dashBoard.showFormatedAmount(totalIncome)+","+dashBoard.showFormatedAmount(totalExpense)+","+dashBoard.showFormatedAmount(balance)));
				
	 
		$("#printForm").submit();
		 	 
	}
}


function isValidDate(dateArray){
	
	var errorMessage = "";
	var error = "Date is not valid";
	 
	var day = dateArray[0];
	var month = dateArray[1];
	var year = dateArray[2];
	
	month = getNoMonthFromStrMon(month);
	
	if(month == ""){
		errorMessage = error;
	}
    
    if(errorMessage == ""){
    	
    	 
    	if((parseInt(day) <= 31 && parseInt(day) >= 1)
    			&& (parseInt(month) <= 12 && parseInt(month) >= 1)
    			&&  (parseInt(year) <= 2999 && parseInt(year) >= 1900)){
    		 
    		if(parseInt(month)== 2 && parseInt(day) > 28){
    			if(!isLeapYear(year)){
    				 
    				errorMessage = error;
    			}  
    		}
    		
    	} else {
    		 
    		errorMessage = error;
    	}
    	 
    }
  
 
	 
	 return errorMessage;
	
}

function getNoMonthFromStrMon(month){
	
	 
	
var months = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec'];
	
	switch (month.toLowerCase()) {
    case months[0]:
    	month = "01";
        break;
    case months[1]:
    	month = "02";
        break;
    case months[2]:
    	month = "03";
        break;
    case months[3]:
    	month = "04";
        break;
    case months[4]:
    	month = "05";
        break;
    case months[5]:
    	month = "06";
        break;
    case months[6]:
    	month = "07";
        break;
    case months[7]:
    	month = "08";
        break;
    case months[8]:
    	month = "09";
        break;
    case months[9]:
    	month = "10";
        break;
    case months[10]:
    	month = "11";
        break;
    case months[11]:
    	month = "12";
        break;
    default:
    	month = "";
	}
	
	return month;
}

function getTimeStampByInputDate(dateStr){
	var dateArray  = dateStr.trim().split("-");
	if(dateArray[0].length == 1){		 
		dateArray[0] = "0"+dateArray[0];
	}
	return (new Date(dateArray[2]+"-"+getNoMonthFromStrMon(dateArray[1])+"-"+dateArray[0]).getTime())/1000;
}

function isLeapYear(year)
{
  return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}

function pad(n, width, z) {
	  z = z || '0';
	  n = n + '';
	  return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}


function addExpense(){
	
	if(dashBoard.isAddMode == true){
		dashBoard.addExpenseToGrid();
	
		
	} else {
		dashBoard.addExpenseToGrid();
		
		
	}
	
	
}

function sendDataToServer(formData,formName){	
	 
   
      
        
}

function loadData(formData,formName){	
	
    var formUrl = $(formName).attr('action');
	$.ajax({
       type: 'POST',
       url: formUrl,
       data: formData,
       success: function(data,textStatus,xhr){
    	 
    	   var loadTabs = new LoadTabs();
    	   loadTabs.startLoading( $.parseJSON(data));
               if(data.trim()  == "+000"){     
               	                  
               //	alert("Success")
               } else{
               
               }
       },
       error: function(xhr,textStatus,error){
       
       }
   });	
       
}



$('#sendEmailForm').submit(function(){
	
	$("#ExpenseEmailExpenseTitle").val(dashBoard.expense.title);
	$("#ExpenseEmailUniqueURL").val(dashBoard.expense.unique_url);
	
    //serialize form data
    var formData = $(this).serialize();
    //get form action
    var formUrl = $(this).attr('action');
    
 
    
        
    return false;
});


 


 

$('#updateGroupExpenseForm').submit(function(){
    //serialize form data
   
    //get form action
    var formUrl = $(this).attr('action');
    
	$('#updateGroupExpenseForm').find('span').text("");
	
	if(dashBoard.expense.title == $("#ExpenseTitle").val().trim()
	&& dashBoard.expense.currency == $("#ExpenseCurrency").val().trim()
	& dashBoard.expense.description == $("#ExpenseDescription").val().trim()
	){
		return false;
	}
	
	
		 
	dashBoard.expense.title =  $("#ExpenseTitle").val();
  	dashBoard.expense.currency = $("#ExpenseCurrency").val();
	dashBoard.expense.description = $("#ExpenseDescription").val(); 
	dashBoard.expense.version =  parseInt(dashBoard.expense.version) + 1;
	$("#ExpenseVersion").val(dashBoard.expense.version);
	
	//show updated value
	 $("#expenseTitleDiv").html(dashBoard.expense.title);
	 $("#expenseDescDiv").html(dashBoard.expense.description);
	
	 var formData = $(this).serialize();
	
	
	$('#grid').jqGrid('GridUnload'); 
	dashBoard.showExpenseList();
	$('#income_grid').jqGrid('GridUnload'); 
	dashBoard.showIncomeList();
    
     
    return false;
});
 
function showMessage(message){
	$("#error_dialog" ).html(message);
	$("#error_dialog" ).dialog();
}

function sendEmail(formData,formName){	
	
     //get form action
     var formUrl = $(formName).attr('action');
     
    
	 
}
  
function Expense(){
	this.id;
	this.unique_url;
	this.title;
	this.currency;
	this.description;
	this.create_date;	
	this.version
}

function FamilyExpense(){
	//this.index;
	this.id;
	this.expenseId;
	this.recordType;
	this.isAdd;	 
	this.expenseName;
	this.expenseCategory;
	this.amount;	 
	this.expenseDate; 
	this.expenseDay; 
	this.noOfNotes;
 	this.isreimburse;	 
	this.type;//1=normal expense,2=balance entry	 
}

function FilteredFamilyExpense(){
	this.id;	 
	this.amount;
	this.expenseName;
	this.expenseCategory;
	this.expenseDate;
	this.expenseDay;	 	
	this.noOfNotes;
 
}

function Category(){
	this.id;	 
	this.name;
	this.type; 
	this.amount; 
}

 
function Email(){
	this.email;
	this.uniqueURL;
	this.title;
}

 