var dashBoard;
var plot1;



$( document ).ready(function() {

    var dialog, form,
        name = $( "#name" ),

        allFields = $( [] ).add( name ),
        tips = $( ".validateTips" );



    function updateTips( t ) {
        tips.text( t ).addClass( "ui-state-highlight" );
    }

    function checkLength( o,  min, max ) {
        if ( o.val().length < min ) {
            o.focus();
            updateTips( lblEnterName );
            return false;
        } else if(o.val().length > max){
            o.focus();
            updateTips( lblNameMustHaveLessThan+max+lblCharacters );
            return false;
        }else {
            return true;
        }
    }

    function checkParticipantAvailability(o,value){var result = true;
        var participantName = value.trim();

        for (var index in dashBoard.participants) {

            if(dashBoard.participants[index].name.toLowerCase() == participantName.toLowerCase()){
                o.focus();
                updateTips( lblParticipantExist );
                result = false;
            }

        }

        if(participantName != "" && participantName.indexOf(',') === -1 && participantName.indexOf('|') === -1){


        } else {
            updateTips(lblParticipantShouldNotContain);
            result = false;
        }

        return result;

    }


    function addNewParticipant() {
        var valid = true;
        allFields.removeClass( "ui-state-error" );
        valid =  checkLength( name, 1, 12 );
        if(valid){
            valid = checkParticipantAvailability(name,name.val());
        }

        if ( valid ) {
            dashBoard.addParticipant(name.val(),"1");
            dialog.dialog( "close" );
        }
        return valid;
    }


    dialog = $( "#dialog-form" ).dialog({
        autoOpen: false,
        height: 170,
        width: 70,
        modal: true,
        buttons: {
            "Add": addNewParticipant,
            Cancel: function() {
                dialog.dialog( "close" );
            }
        },
        close: function() {
            form[ 0 ].reset();
            allFields.removeClass( "ui-state-error" );
        }
    });



    form = dialog.find( "form" ).on( "submit", function( event ) {
        event.preventDefault();
        addNewParticipant();
    });


    $( "#create-participant" ).click(function() {
        dialog.dialog( "open" );
    });

    if($("#expenseData").val() == ""){
        $("#expense_table_title_id").html("");
        $("#div_participant").html("<br/><br/><br/><br/><br/><center><h3>"+LBL_EXPENSE_NOT_FOUND+"</h3></center>");
        $("#create-participant").hide();
        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.loadParticipants = function loadParticipants(){

    }

    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.defaultMeal = val.default_meal;
                expenseObj.version = val.version;

                dashBoard.expense = expenseObj;


                $("#expenseTitleDiv").html(expenseObj.title);
                $("#expenseDescDiv").html(expenseObj.description);

            } else if(key === "Participant"){


                $.each(val, function (i, object) {
                    var participantObj = new Participant();
                    participantObj.id = object.participant_id;
                    participantObj.name = object.name;
                    participantObj.isCreator = object.is_creator;
                    participantObj.create_date = object.create_date;
                    participantObj.balance = 0;
                    participantObj.numberOfMeal = 0.0;

                    participantObj.mealCost = 0;
                    participantObj.totalPaid = 0;
                    participantObj.totalSpent = 0;

                    dashBoard.participants[participantObj.id] = participantObj;

                });



            } else if(key === "GroupExpense"){
                $.each(val, function (i, object) {

                    var groupExpense = new GroupExpense();

                    groupExpense.id = object.id;
                    groupExpense.expenseType = object.expense_type;
                    groupExpense.paidBy = object.paid_by_participant_id;
                    groupExpense.expenseName = object.what;
                    groupExpense.create_date = object.create_date;
                    groupExpense.amount = object.amount;
                    groupExpense.participantAmountStr = object.participant_amount;
                    groupExpense.expenseDate = object.expense_date_new;
                    groupExpense.number_of_notes= object.number_of_notes;
                    groupExpense.number_of_modificaiton= object.number_of_modificaiton;
                    groupExpense.isDetails= object.isDetails;
                    groupExpense.type= object.type;

                    dashBoard.groupExpenses[groupExpense.id] = groupExpense;
                    dashBoard.globalExpenseIndex++;

                });
            } else if(key === "Meal"){

                $.each(val, function (i, object) {

                    var meal = new Meal();
                    meal.id = object.id;
                    meal.expenseId = object.expense_id;
                    meal.date = object.date_new;
                    meal.participantMealStr = object.meal_amount;



                    dashBoard.meals[meal.id] = meal;
                    dashBoard.globalMealIndex++;

                });
            }


        });


        dashBoard.displayCovePage();

        dashBoard.setDefaultMeal();
        dashBoard.setCurrentDate();

    }
}





function DashBoard(){
    this.expense;
    this.participants = [];
    this.groupExpenses = [];
    this.filteredGroupExpenses = [];

    this.meals = [];
    this.filteredMeals = [];

    this.gridData = [];

    this.participantAmtHtmlFormat = "";
    this.mealAmtHtmlFormat = "";

    this.loginParticipantId = "";
    this.loginParticipantName = "";

    this.paidByHtml = "";

    this.currentInputAmount = "0";
    this.currentEditGroupExpense;
    this.currentEditMeal;

    this.currentDate ;

    this.isAddMode = true;

    this.globalExpenseIndex = 0;

    this.globalMealIndex = 0;

    this.defaultBreakfast = 0;
    this.defaultLunch = 0;
    this.defaultDinner = 0;

    this.maxMealDate = 0;

    this.isMealGridLoadedAlready = 0;

    this.totalMeal;
    this.yourMeal;
    this.totalCost;
    this.yourCost;


    this.setDefaultMeal = function setDefaultMeal(){

        var defaultMealStrArray = dashBoard.expense.defaultMeal.split("|");
        this.defaultBreakfast = dashBoard.showMealFormatedAmount(defaultMealStrArray[0]);
        this.defaultLunch = dashBoard.showMealFormatedAmount(defaultMealStrArray[1]);
        this.defaultDinner = dashBoard.showMealFormatedAmount(defaultMealStrArray[2]);
    }


    this.displayCovePage = function displayCovePage(){
        var justCreated = $("#justCreated").val();
        var createdBy = "";

        if(justCreated == "yes"){
            var createdById = "";
            for (var index in dashBoard.participants) {
                if(dashBoard.participants[index].isCreator == "1"){
                    createdBy = dashBoard.participants[index].name;
                    createdById = dashBoard.participants[index].id;
                    break;
                }
            }
            dashBoard.loginParticipant(createdById);
            $("#expenseCreatedByDiv").html("Created By "+createdBy+" on "+dashBoard.getFormatedDbDate(dashBoard.expense.create_date));
            $("#tabs" ).tabs( { active: 3 } );
            dashBoard.resetParticipantBalance();
            dashBoard.displayParticipantList();
            dashBoard.setParticipantGridExtension();
        } else{

            $("#dvLoading").hide();

            dashBoard.addParticipantToList();
        }
    }


    this.addParticipantToList = function addParticipantToList(){

        var participantListHtml = '<table class="gridTable">';
        var noOfParticipant = 0;

        for (var index in dashBoard.participants) {
            noOfParticipant++;
        }
        for (var index in dashBoard.participants) {

            if(dashBoard.participants[index].isCreator == "1"){
                createdBy = dashBoard.participants[index].name;
            }

            if(noOfParticipant < 6){
                participantListHtml = participantListHtml + '<tr ><td><a title="'+lblClickToLogin+'" style="cursor:pointer;" onClick=dashBoard.loginParticipant('+"'"+dashBoard.participants[index].id+"'"+')><img src="/cdn/images/participant_icon.png" title="Click to login as '+dashBoard.participants[index].name+'"/>&nbsp;'+dashBoard.participants[index].name+'</a></td><td></td></tr>';
            } else {
                participantListHtml = participantListHtml + '<tr ><td><a  title="'+lblClickToLogin+'" style="cursor:pointer;" onClick=dashBoard.loginParticipant('+"'"+dashBoard.participants[index].id+"'"+')>&nbsp;'+dashBoard.participants[index].name+'</a></td><td></td></tr>';
            }


        }

        participantListHtml = participantListHtml + "</table>" ;


        $("#expenseCreatedByDiv").html(lblCreatedBy+createdBy+lblOn+dashBoard.getFormatedDbDate(dashBoard.expense.create_date));
        $("#div_participant").html(participantListHtml);

    }

    this.loginParticipant = function loginParticipant(participantId){
        dashBoard.loginParticipantId = participantId;
        dashBoard.loginParticipantName = dashBoard.participants[participantId].name;

        $("#expenseLoginAsDiv").html("You are logged in as <b>"+dashBoard.loginParticipantName+"</b> <a  style= \"cursor:pointer;	color: #0757A4\" onClick=\"dashBoard.logout()\">[Quit]</a>");
        dashBoard.showExpenseList();

        $("#printOptionId").show();
        $("#mealsOptionId").show();

        $("#participantBox").hide();
        $("#tabs").show();


        dashBoard.setPaidBy(dashBoard.loginParticipantId);
    }

    this.logout = function logout(){
        $("#expenseLoginAsDiv").html("");
        $("#participantBox").show();
        $("#tabs").hide();
    }

    this.getNumberOfParticipants = function getNumberOfParticipants(){
        var totalParticipant = 0;
        for (var index in dashBoard.participants) {

            totalParticipant++;
        }
        return totalParticipant;
    }



    this.generateLogList = function generateLogList(logData,source){

        var logList = [];

        if(logData != "" ){
            logList = $.parseJSON(logData);
        }

        var data = [];

        $.each( logList, function( key, val ) {

            $.each(val, function (model, object) {
                if(model=="Log"){
                    data.push([object.id, object.create_date,object.previous_paid_by,object.previous_desc,object.new_desc]);
                }
            });

        });





        var maxRowNum = data.length;
        if(maxRowNum<101){
            maxRowNum = 100;
        }


        if(source == 2 && data.length == 0){

            data.push([lblRecordNotFound]);

            $("#log_grid").jqGrid({
                    datatype: "local",
                    height: 190,

                    colNames: [' '],
                    colModel: [
                        {
                            name: ' ',
                            index: ' ',
                            sortable: false,
                            width: 650,
                            align:'center',

                        }

                    ],



                    gridview:true,

                    viewrecords: true,

                    caption:lblExpenseLog
                }

            );



            var names = [' '];
            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];
                }
            }


            for (var i = 0; i < mydata.length; i++) {
                $("#log_grid").jqGrid('addRowData',data[i][0]+1, mydata[i]);
            }



        } else {

            $("#log_grid").jqGrid({
                    datatype: "local",
                    height: 190,

                    colNames: ['SI', lblChangedOn, lblPaidBy, lblPreviousDescription, lblNewDescription],
                    colModel: [
                        {
                            name: 'SI',
                            index: 'SI',
                            width: 0,
                            sorttype: "int",
                            hidden:true
                        },
                        {
                            name: 'Changed On',
                            index: 'Changed On',
                            width: 110 ,
                            align:'center',
                            editable: true

                        } ,
                        {
                            name: 'Paid By',
                            index: 'Paid By',
                            width: 80 ,
                            align:'center',
                            editable: true

                        } ,
                        {
                            name: 'Previous Description',
                            index: 'Previous Description',
                            width: 272 ,
                            align:'center',
                            cellattr: function (rowId, tv, rawObject, cm, rdata) { return 'style="white-space: normal !important;"' }


                        } ,
                        {
                            name: 'New Description',
                            index: 'New Description',
                            width: 272 ,
                            align:'center',
                            cellattr: function (rowId, tv, rawObject, cm, rdata) { return 'style="white-space: normal !important;"' }


                        }

                    ],

                    rowNum      : maxRowNum,
                    rowList:[10,20,50,maxRowNum],
                    pager: '#log_pager',
                    gridview:true,
                    rownumbers:true,
                    autoencode:true,
                    ignoreCase:true,

                    viewrecords: true,
                    sortorder: 'desc',
                    caption:lblExpenseLog
                }

            );

            $("#log_grid").jqGrid('navGrid','#log_pager',{
                add:false,
                edit:false ,
                del:false ,
                search:true,searchtitle: lblFindLog}

            );


            var names = ['SI', 'Changed On', 'Paid By','Previous Description','New Description'];
            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];
                }
            }


            for (var i = 0; i < mydata.length; i++) {

                $("#log_grid").jqGrid('addRowData',data[i][0]+1, mydata[i]);
            }

        }

    }


    this.showExpenseList = function showExpenseList(){



        dashBoard.gridData = [];
        dashBoard.isAddMode = true;

        for (var index in dashBoard.groupExpenses) {
            dashBoard.gridData.push(dashBoard.getDataByExpense(dashBoard.groupExpenses[index]));
        }

        dashBoard.setParticipantAmtHtmlFormat();

        dashBoard.reloadGrid();
    }


    this.setUIMealDate = function setUIMealDate(){
        var maxDate = 0;
        for (var index in dashBoard.meals) {
            if(maxDate < dashBoard.meals[index].date){
                maxDate = dashBoard.meals[index].date;
            }
        }

        if(maxDate == 0){
            dashBoard.maxMealDate = dashBoard.currentDate;
        } else{

            dashBoard.maxMealDate = this.getNextDayFormatedDate(maxDate);
        }

    }


    this.getDataByExpense = function getDataByExpense(groupExpenseObj){

        var key = groupExpenseObj.id;
        dashBoard.filteredGroupExpenses[key] = dashBoard.getFilteredExpenseObj(groupExpenseObj);

        return [dashBoard.filteredGroupExpenses[key].id,dashBoard.filteredGroupExpenses[key].expenseType,dashBoard.filteredGroupExpenses[key].paidBy, dashBoard.showFormatedAmount(dashBoard.filteredGroupExpenses[key].amount), dashBoard.filteredGroupExpenses[key].expenseName, dashBoard.filteredGroupExpenses[key].expenseDate,dashBoard.filteredGroupExpenses[key].involves,dashBoard.filteredGroupExpenses[key].forYou];
    }

    this.getDataByMeal = function getDataByMeal(mealObj){

        var key = mealObj.id;

        dashBoard.filteredMeals[key] = dashBoard.getFilteredMealObj(mealObj);
        return [dashBoard.filteredMeals[key].id,dashBoard.filteredMeals[key].date,dashBoard.filteredMeals[key].day,dashBoard.filteredMeals[key].breakfast,dashBoard.filteredMeals[key].lunch,dashBoard.filteredMeals[key].dinner,dashBoard.filteredMeals[key].involves];
    }

    this.getFilteredExpenseObj = function getFilteredExpenseObj(groupExpenseObj){

        var filteredGroupExpenseObj = new FilteredGroupExpense();

        filteredGroupExpenseObj.id = groupExpenseObj.id;
        filteredGroupExpenseObj.expenseType = groupExpenseObj.expenseType;
        filteredGroupExpenseObj.paidBy = dashBoard.participants[groupExpenseObj.paidBy].name;
        filteredGroupExpenseObj.amount = dashBoard.getFormatedAmount(groupExpenseObj.amount);
        filteredGroupExpenseObj.expenseName=groupExpenseObj.expenseName;
        filteredGroupExpenseObj.expenseDate = groupExpenseObj.expenseDate;//dashBoard.getFormatedDate(groupExpenseObj.expenseDate);
        if(filteredGroupExpenseObj.expenseType == "2"){

            filteredGroupExpenseObj.involves= "[Mess Members]";
            filteredGroupExpenseObj.forYou= "-";
        } else {
            filteredGroupExpenseObj.involves=dashBoard.getInvolveString(groupExpenseObj.participantAmountStr);
            filteredGroupExpenseObj.forYou = dashBoard.showFormatedAmount(dashBoard.getForYouString(groupExpenseObj.participantAmountStr));

        }


        filteredGroupExpenseObj.noOfNotes=groupExpenseObj.noOfNotes;
        filteredGroupExpenseObj.noOfModification=groupExpenseObj.noOfModification;

        return filteredGroupExpenseObj;
    }

    this.getFilteredExpenseObjPrint = function getFilteredExpenseObjPrint(groupExpenseObj){

        var filteredGroupExpenseObj = new FilteredGroupExpense();

        filteredGroupExpenseObj.id = groupExpenseObj.id;
        filteredGroupExpenseObj.expenseType = groupExpenseObj.expenseType;
        filteredGroupExpenseObj.paidBy = dashBoard.participants[groupExpenseObj.paidBy].name;
        filteredGroupExpenseObj.amount = dashBoard.showFormatedAmount(groupExpenseObj.amount);
        filteredGroupExpenseObj.expenseName=groupExpenseObj.expenseName;
        filteredGroupExpenseObj.expenseDate = groupExpenseObj.expenseDate;//dashBoard.getFormatedDate(groupExpenseObj.expenseDate);
        if(filteredGroupExpenseObj.expenseType == "2"){

            filteredGroupExpenseObj.involves= "[Mess Members]";
            filteredGroupExpenseObj.forYou= "-";
        } else {
            filteredGroupExpenseObj.involves=dashBoard.getInvolveString(groupExpenseObj.participantAmountStr);
            filteredGroupExpenseObj.forYou = dashBoard.showFormatedAmount(dashBoard.getForYouString(groupExpenseObj.participantAmountStr));

        }


        filteredGroupExpenseObj.noOfNotes=groupExpenseObj.noOfNotes;
        filteredGroupExpenseObj.noOfModification=groupExpenseObj.noOfModification;

        return filteredGroupExpenseObj;
    }

    this.getFilteredMealObj = function getFilteredMealObj(mealObj){

        var breakfast = parseFloat(0);
        var lunch = parseFloat(0);
        var dinner = parseFloat(0);

        var filteredMealObj = new FilteredMeal();

        filteredMealObj.id = mealObj.id;

        filteredMealObj.date = mealObj.date;//dashBoard.getFormatedDate(mealObj.date);
        filteredMealObj.day = dashBoard.getDayByDate(mealObj.date);

        if(mealObj.participantMealStr != ""){

            var participantStrArr = mealObj.participantMealStr.split(",");
            for(var i=0;i<participantStrArr.length;i++){
                var participantArr = participantStrArr[i].split("|");
                if(dashBoard.showFormatedAmount(parseFloat(participantArr[1])) != dashBoard.showFormatedAmount(0)){
                    breakfast = breakfast + parseFloat(participantArr[1]);
                }

                if(dashBoard.showFormatedAmount(parseFloat(participantArr[2])) != dashBoard.showFormatedAmount(0)){
                    lunch = lunch + parseFloat(participantArr[2]);
                }

                if(dashBoard.showFormatedAmount(parseFloat(participantArr[3])) != dashBoard.showFormatedAmount(0)){
                    dinner = dinner + parseFloat(participantArr[3]);
                }
            }

        }




        filteredMealObj.breakfast = dashBoard.showMealFormatedAmount(breakfast);
        filteredMealObj.lunch= dashBoard.showMealFormatedAmount(lunch);
        filteredMealObj.dinner = dashBoard.showMealFormatedAmount(dinner);
        filteredMealObj.involves = dashBoard.getInvolveString(mealObj.participantMealStr);

        return filteredMealObj;
    }


    this.getFilteredMyMealObj = function getFilteredMyMealObj(mealObj){

        var breakfast = parseFloat(0);
        var lunch = parseFloat(0);
        var dinner = parseFloat(0);

        var filteredMealObj = new FilteredMeal();

        filteredMealObj.id = mealObj.id;

        filteredMealObj.date = mealObj.date;//dashBoard.getFormatedDate(mealObj.date);
        filteredMealObj.day = dashBoard.getDayByDate(mealObj.date);

        if(mealObj.participantMealStr != ""){

            var participantStrArr = mealObj.participantMealStr.split(",");


            for(var i=0;i<participantStrArr.length;i++){


                var participantArr = participantStrArr[i].split("|");
                if(participantArr[0] == dashBoard.loginParticipantId){

                    if(dashBoard.showFormatedAmount(parseFloat(participantArr[1])) != dashBoard.showFormatedAmount(0)){
                        breakfast = breakfast + parseFloat(participantArr[1]);
                    }

                    if(dashBoard.showFormatedAmount(parseFloat(participantArr[2])) != dashBoard.showFormatedAmount(0)){
                        lunch = lunch + parseFloat(participantArr[2]);
                    }

                    if(dashBoard.showFormatedAmount(parseFloat(participantArr[3])) != dashBoard.showFormatedAmount(0)){
                        dinner = dinner + parseFloat(participantArr[3]);
                    }

                }

            }

        }




        filteredMealObj.breakfast = dashBoard.showMealFormatedAmount(breakfast);
        filteredMealObj.lunch= dashBoard.showMealFormatedAmount(lunch);
        filteredMealObj.dinner = dashBoard.showMealFormatedAmount(dinner);
        filteredMealObj.involves = dashBoard.getInvolveString(mealObj.participantMealStr);

        return filteredMealObj;
    }


    this.getDayByDate = function getDayByDate(dateUnix){

        var dateStrArray = dateUnix.split("-");


        // alert(dateStrArray[2]+"-"+getNoMonthFromStrMon(dateStrArray[1])+"-"+dateStrArray[0]);

        //alert(dateStrArray[0]);
        //alert(dateStrArray[2]+"-"+getNoMonthFromStrMon(dateStrArray[1]+"-"+dateStrArray[0]));
        var dateObj = new Date(dateStrArray[2]+"-"+getNoMonthFromStrMon(dateStrArray[1])+"-"+dateStrArray[0]);

        //	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', lblExpenseType, lblWhoPaid, lblHowMuch+'('+dashBoard.expense.currency+')?', lblWhatReason, lblWhen,lblInvoles,lblForYou+'('+dashBoard.expense.currency+')?'],
                colModel: [
                    {
                        name: 'SI',
                        index: 'SI',
                        width: 0,
                        sorttype: "int",
                        hidden:true,
                        key:true
                    },
                    {
                        name: 'ExpenseType',
                        index: 'ExpenseType',
                        width: 0,
                        sorttype: "int",
                        hidden:true
                    },
                    {
                        name: 'PaidBy',
                        index: 'PaidBy',
                        width: 90 ,
                        align:'center',
                        formoptions:{rowpos:2},
                        editable: true,
                        edittype:'select',
                        editoptions:{value:'1:X',defaultValue:'X' }
                    },
                    {
                        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);
                                }

                                if(el.value == ""){
                                    dashBoard.currentInputAmount = 0;
                                } else {
                                    dashBoard.currentInputAmount = el.value;
                                }

                                dashBoard.changeExpenseAmount();
                            });
                        }
                        }
                    },
                    {
                        name: 'Reason',
                        index: 'Reason',
                        align:'center',
                        width: 190,
                        formoptions:{rowpos:1},
                        editable: true,
                        editrules:{required:true},
                        editoptions:{maxlength:25},
                        sorttype: "float"

                    },
                    {
                        name: 'Date',
                        index: 'Date',
                        width: 80,
                        align:'center',
                        sorttype:'date',
                        formoptions:{rowpos:3},
                        editable:true,
                        editrules:{required:true},
                        editoptions: {dataInit:initDateEdit}
                    },
                    {
                        name: 'Involve',
                        index: 'Involve',
                        align:'center',
                        width: 150,
                        sorttype: "float"
                    },
                    {
                        name: 'For you?',
                        index: 'For you?',
                        align:'center',
                        width: 100,
                        sorttype: "float"
                    }
                ],
                rowNum      : maxRowNum,
                rowList:[10,20,50,maxRowNum],
                pager: '#expense_pager',
                gridview:true,
                rownumbers:true,
                autoencode:true,
                ignoreCase:true,

                viewrecords: true,
                sortorder: 'desc',
                caption:lblExpenseList

            }

        );


        dashBoard.addRowsToGrid(dashBoard.gridData);


        $("#grid").jqGrid('setGridParam', {
                onSelectRow: function(rowid,iRow,iCol,e){

                    if(!iCol){

                        dashBoard.removeParticipantAmtRows();
                        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: lblEditExpense,
                del:true,deltitle: lblDeleteExpense ,
                search:true,searchtitle: lblFindExpenses},
            { // Edit
                recreateForm: true,
                beforeInitData: function () {

                    dashBoard.isAddMode = false;

                }
            },
            { // Add
                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: lblEditExpense,
            bSubmit: lblSave,
            bCancel: lblCancel,
            width:300,

            recreateForm: true,
            beforeShowForm: function () {

                var dlgDiv = $("#editmodgrid");
                dlgDiv[0].style.top = "30px";

                if(dashBoard.isAddMode == true){

                    $('#tr_Amount>td.DataTD>input').insertAfter( '   ');

                    $(dashBoard.participantAmtHtmlFormat).insertAfter("#tr_Amount");

                    $('<a >'+lblSaveContinue+'<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");

                    $('#PaidBy').find('option').remove().end().append(dashBoard.paidByHtml);
                    dashBoard.refreshParticipantsExpenseProperties(1);
                    dashBoard.setAllCheckImpact();
                    dashBoard.hideShowParticipantDetails(false);
                    dashBoard.showMessHtml();
                    $("#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.removeParticipantAmtRows = function removeParticipantAmtRows(){
        $('#tr_IsMessExpense').remove();
        $('#tr_IsDetails').remove();
        $('#tr_selectAll').remove();
        for (var index in dashBoard.participants) {
            $('#tr_Participant'+dashBoard.participants[index].id).remove();
            $('#tr_ParticipantDetails'+dashBoard.participants[index].id).remove();
        }


    }

    this.loadForEdit = function loadForEdit(){


        $('#tr_Amount>td.DataTD>input').insertAfter( '   ');

        $(dashBoard.participantAmtHtmlFormat).insertAfter("#tr_Amount");


        var rowId =$("#grid").jqGrid('getGridParam','selrow');


        var rowData = jQuery("#grid").getRowData(rowId);

        dashBoard.showEditUI(dashBoard.groupExpenses[rowData['SI']]);
        $('#PaidBy').find('option').remove().end().append(dashBoard.paidByHtml);
    }

    this.loadForEditMeal = function loadForEditMeal(){

        $('#tr_Date>td.DataTD>input').insertAfter( '   ');

        $(dashBoard.mealAmtHtmlFormat).insertAfter("#tr_Date");

        var rowId =$("#meal_grid").jqGrid('getGridParam','selrow');


        var rowData = jQuery("#meal_grid").getRowData(rowId);

        dashBoard.showEditMealUI(dashBoard.meals[rowData['SI']]);

    }

    this.changeSingleInvolve = function changeSingleInvolve(participantId){

        if($("#chkParticipant"+participantId).is(':checked')){
            dashBoard.participants[participantId].currentInputExpensePart = 1;
        } else {
            $("#selectAll").prop('checked', false);
            dashBoard.participants[participantId].currentInputExpensePart = 0;
            dashBoard.participants[participantId].isFreeze = 0;
        }

        dashBoard.calculateFinalFreezeExpenseAmount();

        dashBoard.showFreezeAmount();
        dashBoard.setShadowOnPartTextBox();
        dashBoard.scanCheckAllCheckbox();
        dashBoard.scanParticipantCheckBoxs();
    }

    this.changeSingleInvolveMeal = function changeSingleInvolveMeal(participantId){

        var numberOfUnselect = 0;
        var numberOfSelect = 0;
        var total = 0;

        for (var index in dashBoard.participants) {
            total++;

            if($("#chkParticipantMeal"+dashBoard.participants[index].id).is(':checked')){

                numberOfSelect++;
            } else {
                numberOfUnselect++;
            }
        }


        if(numberOfSelect == total){
            $("#selectAllMeal").prop('checked', true);
        } else if(numberOfUnselect == total) {
            $("#selectAllMeal").prop('checked', false);
        }

        if($("#chkParticipantMeal"+dashBoard.participants[participantId].id).is(':checked')){
            dashBoard.participants[participantId].breakfast = dashBoard.defaultBreakfast;
            dashBoard.participants[participantId].lunch = dashBoard.defaultLunch;
            dashBoard.participants[participantId].dinner = dashBoard.defaultDinner;

        } else {

            dashBoard.participants[participantId].breakfast = 0;
            dashBoard.participants[participantId].lunch = 0;
            dashBoard.participants[participantId].dinner = 0;
        }

        $("#breakfast_"+dashBoard.participants[participantId].id).val(dashBoard.showMealFormatedAmount(dashBoard.participants[participantId].breakfast));
        $("#lunch_"+dashBoard.participants[participantId].id).val(dashBoard.showMealFormatedAmount(dashBoard.participants[participantId].lunch));
        $("#dinner_"+dashBoard.participants[participantId].id).val(dashBoard.showMealFormatedAmount(dashBoard.participants[participantId].dinner));

    }

    this.changeDetailsPart = function changeDetailsPart(participantId){

        var originalValue = $("#participantTextPart"+participantId).val();

        var filteredValue = $("#participantTextPart"+participantId).val().replace(/[^0-9]/g,'');


        if(filteredValue != "" && parseInt(filteredValue) != dashBoard.participants[participantId].currentInputExpensePart){

            dashBoard.participants[participantId].currentInputExpensePart = parseInt(filteredValue);
            dashBoard.participants[participantId].isFreeze = 0;


            dashBoard.calculateFinalFreezeExpenseAmount();
            dashBoard.showPartAndFreezeAmtInDetails();
            dashBoard.scanParticipantCheckBoxs();
            dashBoard.setShadowOnPartTextBox();

        } else if(originalValue != "") {

            if(filteredValue == "0"){
                dashBoard.participants[participantId].isFreeze = 0;
                dashBoard.participants[participantId].currentInputExpensePart = 0;
            }

            dashBoard.calculateFinalFreezeExpenseAmount();
            dashBoard.showPartAndFreezeAmtInDetails();
            dashBoard.scanParticipantCheckBoxs();
            dashBoard.setShadowOnPartTextBox();
        } else if(originalValue == "") {

            if(dashBoard.participants[participantId].isFreeze == 0){

                dashBoard.participants[participantId].currentInputExpensePart = 0;
            }

            dashBoard.calculateFinalFreezeExpenseAmount();
            dashBoard.showPartAndFreezeAmtInDetails();
            dashBoard.scanParticipantCheckBoxs();
            dashBoard.setShadowOnPartTextBox();

        }


    }

    this.changeDetailsFreeze = function changeDetailsFreeze(participantId){

        var originalValue = $("#participantTextFreeze"+participantId).val();

        var filteredValue = $("#participantTextFreeze"+participantId).val().replace(/[^0-9\.]/g,'');

        if(filteredValue.replace(/[^.]/g, "").length == 2){
            filteredValue = filteredValue.substring(0, filteredValue.length-1);
        }

        if(filteredValue != "" && dashBoard.showFormatedAmount(parseFloat(filteredValue)) != dashBoard.showFormatedAmount(parseFloat(dashBoard.participants[participantId].currentInputExpenseFreezeAmt))){

            dashBoard.participants[participantId].currentInputExpensePart = 0;
            dashBoard.participants[participantId].currentInputExpenseFreezeAmt = dashBoard.getFormatedAmount(parseFloat(filteredValue));


            if(parseFloat(filteredValue) == parseFloat(0)){
                dashBoard.participants[participantId].isFreeze = 0;
            } else {
                dashBoard.participants[participantId].isFreeze = 1;
            }

            dashBoard.calculateFinalFreezeExpenseAmount();
            dashBoard.showPartAndFreezeAmtInDetails();
            dashBoard.scanParticipantCheckBoxs();
            dashBoard.setShadowOnPartTextBox();
        }   else if(originalValue != "") {


            dashBoard.calculateFinalFreezeExpenseAmount();
            dashBoard.showPartAndFreezeAmtInDetails();
            dashBoard.scanParticipantCheckBoxs();
            dashBoard.setShadowOnPartTextBox();
        } else if(originalValue == "") {

            dashBoard.participants[participantId].currentInputExpensePart = 0;
            dashBoard.participants[participantId].currentInputExpenseFreezeAmt = dashBoard.getFormatedAmount(0);
            dashBoard.participants[participantId].isFreeze = 0;

            dashBoard.calculateFinalFreezeExpenseAmount();
            dashBoard.showPartAndFreezeAmtInDetails();
            dashBoard.scanParticipantCheckBoxs();
            dashBoard.setShadowOnPartTextBox();
        }


    }



    this.changeExpenseAmount = function changeExpenseAmount(){

        dashBoard.calculateFinalFreezeExpenseAmount();
        dashBoard.showFreezeAmount();
        dashBoard.showPartAndFreezeAmtInDetails();
        dashBoard.scanParticipantCheckBoxs();
        dashBoard.setShadowOnPartTextBox();

    }

    this.setShadowOnPartTextBox = function setShadowOnPartTextBox(){


        for (var index in dashBoard.participants) {
            if(dashBoard.participants[index].isFreeze == 1){
                $("#participantTextPart"+dashBoard.participants[index].id).prop("value", '');
                $("#participantTextPart"+dashBoard.participants[index].id).css('background-color' , '#DEDEDE');
            } else {

                $("#participantTextPart"+dashBoard.participants[index].id).css('background-color' , '#FFFFF');
            }

        }

    }



    this.scanParticipantCheckBoxs = function scanParticipantCheckBoxs(){

        var isAllCheck = true;
        var numberOfInvolves = 0;
        var noOfParticipant = 0;

        for (var index in dashBoard.participants) {

            noOfParticipant++;

            if(parseFloat(dashBoard.participants[index].currentInputExpenseFreezeAmt) > 0){
                numberOfInvolves++;
                $("#chkParticipant"+dashBoard.participants[index].id).prop('checked', true);
            } else {
                isAllCheck = false;
                $("#chkParticipant"+dashBoard.participants[index].id).prop('checked', false);
            }
        }



        if(numberOfInvolves == noOfParticipant){
            isAllCheck = true;
        }


        if(isAllCheck == false){
            $("#selectAll").prop('checked', false);
        } else {
            $("#selectAll").prop('checked', true);
        }


    }

    this.scanCheckAllCheckbox = function scanCheckAllCheckbox(){


        var numberOfInvolves = 0;
        var noOfParticipant = 0;

        for (var index in dashBoard.participants) {
            noOfParticipant++;
            if(parseFloat(dashBoard.participants[index].currentInputExpenseFreezeAmt) > 0){
                numberOfInvolves++;
            }



        }

        if(numberOfInvolves == noOfParticipant){
            $("#selectAll").prop('checked', true);
        } else {
            $("#selectAll").prop('checked', false);
        }

    }


    this.setAllCheckImpact = function setAllCheckImpact(){

        var commonValue = dashBoard.getFormatedAmount(0);
        var isCheckAll = false;

        if($("#selectAll").is(':checked')){
            isCheckAll = true;

        }

        for (var index in dashBoard.participants) {

            if(isCheckAll == true){
                $("#chkParticipant"+dashBoard.participants[index].id).prop('checked', true);

                if(dashBoard.participants[index].currentInputExpensePart >= 0){
                    dashBoard.participants[index].currentInputExpensePart = 1;
                }


            } else {
                $("#chkParticipant"+dashBoard.participants[index].id).prop('checked', false);

                dashBoard.participants[index].currentInputExpensePart=0;
                dashBoard.participants[index].currentInputExpenseFreezeAmt=dashBoard.getFormatedAmount(0);
            }



        }

        dashBoard.calculateFinalFreezeExpenseAmount();
        dashBoard.showFreezeAmount();
        dashBoard.setShadowOnPartTextBox();

    }


    this.setAllCheckImpactMeal = function setAllCheckImpactMeal(){

        var commonValue = dashBoard.getFormatedAmount(0);
        var isCheckAll = false;

        if($("#selectAllMeal").is(':checked')){
            isCheckAll = true;

        }

        for (var index in dashBoard.participants) {

            if(isCheckAll == true){
                $("#chkParticipantMeal"+dashBoard.participants[index].id).prop('checked', true);

                dashBoard.participants[index].breakfast = dashBoard.defaultBreakfast;
                dashBoard.participants[index].lunch = dashBoard.defaultLunch;
                dashBoard.participants[index].dinner = dashBoard.defaultDinner;
            } else {
                $("#chkParticipantMeal"+dashBoard.participants[index].id).prop('checked', false);
                dashBoard.participants[index].breakfast = 0;
                dashBoard.participants[index].lunch = 0;
                dashBoard.participants[index].dinner = 0;
            }



        }


        dashBoard.showMealAmount();

    }



    this.refreshParticipantsExpenseProperties = function refreshParticipantsExpenseProperties(defaultPart){
        dashBoard.currentInputAmount = 0;
        for (var index in dashBoard.participants) {
            dashBoard.participants[index].currentInputExpensePart = defaultPart;
            dashBoard.participants[index].isFreeze = 0;
            dashBoard.participants[index].currentInputExpenseFreezeAmt=dashBoard.getFormatedAmount(0);
        }

    }

    this.refreshParticipantsMealProperties = function refreshParticipantsMealProperties(){

        for (var index in dashBoard.participants) {
            dashBoard.participants[index].breakfast = dashBoard.defaultBreakfast;
            dashBoard.participants[index].lunch = dashBoard.defaultLunch;
            dashBoard.participants[index].dinner = dashBoard.defaultDinner;
        }

    }

    this.showFreezeAmount = function showFreezeAmount(){
        for (var index in dashBoard.participants) {
            $("#pamount_"+dashBoard.participants[index].id).html(dashBoard.showFormatedAmount(dashBoard.participants[index].currentInputExpenseFreezeAmt)+" "+dashBoard.expense.currency);

        }

    }

    this.showMealAmount = function showMealAmount(){
        for (var index in dashBoard.participants) {

            $("#breakfast_"+dashBoard.participants[index].id).val(dashBoard.showMealFormatedAmount(dashBoard.participants[index].breakfast));
            $("#lunch_"+dashBoard.participants[index].id).val(dashBoard.showMealFormatedAmount(dashBoard.participants[index].lunch));
            $("#dinner_"+dashBoard.participants[index].id).val(dashBoard.showMealFormatedAmount(dashBoard.participants[index].dinner));

        }
    }


    this.calculateFinalFreezeExpenseAmount = function calculateFinalFreezeExpenseAmount(){

        //get total parts of current participants
        var totalParts = 0;
        var totalFreezeAmt = dashBoard.getFormatedAmount(0);
        for (var index in dashBoard.participants) {


            if(parseFloat(dashBoard.participants[index].currentInputExpenseFreezeAmt) == parseFloat(0)){
                dashBoard.participants[index].isFreeze = 0;
            }

            if(dashBoard.participants[index].isFreeze == 0){
                totalParts += parseInt(dashBoard.participants[index].currentInputExpensePart);
            } else {
                totalFreezeAmt = dashBoard.getFormatedAmount(parseFloat(totalFreezeAmt)+ parseFloat(dashBoard.participants[index].currentInputExpenseFreezeAmt));
            }
        }


        if((dashBoard.getFormatedAmount(dashBoard.currentInputAmount) > dashBoard.getFormatedAmount(0))
            && (parseFloat(totalFreezeAmt) > parseFloat(dashBoard.currentInputAmount))){

        } else if(dashBoard.getFormatedAmount(dashBoard.currentInputAmount)>0 && parseFloat(totalFreezeAmt) == parseFloat(dashBoard.currentInputAmount)){

            dashBoard.resetUnfreezeAmt();
            totalParts = 0;
        }

        //set final freeze amount
        for (var index in dashBoard.participants) {

            if(dashBoard.participants[index].isFreeze == 0 && totalParts > 0){

                dashBoard.participants[index].currentInputExpenseFreezeAmt = dashBoard.getFormatedAmount(((parseFloat(dashBoard.currentInputAmount)-parseFloat(totalFreezeAmt))/totalParts)*dashBoard.participants[index].currentInputExpensePart);

                if(parseFloat(dashBoard.participants[index].currentInputExpenseFreezeAmt) < 0){
                    dashBoard.participants[index].currentInputExpenseFreezeAmt = dashBoard.getFormatedAmount(0);
                }
            } else if(dashBoard.participants[index].isFreeze == 0){
                dashBoard.participants[index].currentInputExpenseFreezeAmt = dashBoard.getFormatedAmount(0);
            }
        }

    }

    this.resetAllPartAndFreezeAmt = function resetAllPartAndFreezeAmt(){
        for (var index in dashBoard.participants) {
            if(dashBoard.participants[index].isFreeze == 0){
                dashBoard.participants[index].currentInputExpensePart = 1;
                dashBoard.participants[index].isFreeze = 0;
            }
        }
    }

    this.resetUnfreezeAmt = function resetUnfreezeAmt(){

    }

    this.updateBalance = function updateBalance(){

    }

    this.filterMealInput = function filterMealInput(objid){


        var value = $(objid).val();

        $(objid).val(value.replace(/[^0-9\.]/g,''));
        if(value.replace(/[^.]/g, "").length == 2){
            $(objid).val(value.substring(0,value.length-1));

        }

        if($(objid).val() == ""){
            $(objid).val(0);
        }

    }


    this.setParticipantAmtHtmlFormat = function setParticipantAmtHtmlFormat(){
        dashBoard.paidByHtml = "";
        var result = '<tr id="tr_IsMessExpense" class="FormData" rowpos="5"><td class="CaptionTD"></td><td class="DataTD">&nbsp;<input class="FormElement ui-widget-content ui-corner-all" role="checkbox" name="isMessExpense" id="isMessExpense" onClick="dashBoard.setIsMessCheckImpact()" type="checkbox" checked> Room Expense</td></tr>';


        result += '<tr id="tr_IsDetails" class="FormData" rowpos="5"><td class="CaptionTD"></td><td class="DataTD">&nbsp;<input class="FormElement ui-widget-content ui-corner-all" role="checkbox" name="Details" id="Details" onClick="dashBoard.setDetailsCheckImpact()" type="checkbox"> Split</td></tr>';
        result += '<tr class="FormData" ><td colspan="2"><table class="gridTablePopup gridTableCheckbox">';

        result += '<tr id="tr_selectAll"  rowpos="6"><th width="60">'+lblAll+' <input  role="checkbox" name="selectAll" id="selectAll" onClick="dashBoard.setAllCheckImpact()" checked type="checkbox"></th> <th colspan="2">&nbsp;</th> </tr>';

        for (var index in dashBoard.participants) {

            result += '<tr id="tr_Participant'+dashBoard.participants[index].id+'"   rowpos="7"><td><input onClick="dashBoard.changeSingleInvolve('+"'"+dashBoard.participants[index].id+"'"+')"  role="checkbox" name="Participant'+dashBoard.participants[index].id+'" id="chkParticipant'+dashBoard.participants[index].id+'" type="checkbox"></td><td>'+ dashBoard.participants[index].name+' </td><td><div id="pamount_'+dashBoard.participants[index].id+'"></div></td></tr>';
        }

        result = result + ' </table></td></tr>';
        dashBoard.setPaidBy(dashBoard.loginParticipantId);



        result += '<tr class="FormData" ><td colspan="2"><table class="gridTablePopup gridTableCheckbox">';
        for (var index in dashBoard.participants) {
            result += '<tr id="tr_ParticipantDetails'+dashBoard.participants[index].id+'"   rowpos="7"><td  >'+dashBoard.participants[index].name+' </td><td><input type=text   onblur="dashBoard.changeDetailsPart('+"'"+dashBoard.participants[index].id+"'"+')" id="participantTextPart'+dashBoard.participants[index].id +'" maxlength="5" style="width: 40px"> </td><td><input type=text  onblur="dashBoard.changeDetailsFreeze('+"'"+dashBoard.participants[index].id+"'"+')"  id="participantTextFreeze'+dashBoard.participants[index].id +'" style="width: 90px"> '+dashBoard.expense.currency+'</td></tr>';
        }
        result = result + ' </table></td></tr>';

        dashBoard.participantAmtHtmlFormat = result;
    }

    this.setMealAmtHtmlFormat = function setMealAmtHtmlFormat(){

        var result = '';




        result += '<tr class="FormData" ><td colspan="2"><table class="gridTablePopup gridTableCheckbox">';

        result += '<tr  id="tr_selectAllMeal" rowpos="6"><th width="60">'+lblAll+' <input class="FormElement ui-widget-content ui-corner-all" role="checkbox" name="selectAllMeal" id="selectAllMeal" onClick="dashBoard.setAllCheckImpactMeal()" checked type="checkbox"></th> <th></th><th>Breakfast</th><th>Lunch</th><th>Dinner</th></tr>';

        for (var index in dashBoard.participants) {

            result += '<tr id="tr_Participantmeal'+dashBoard.participants[index].id+'"   rowpos="7"><td ><input onClick="dashBoard.changeSingleInvolveMeal('+"'"+dashBoard.participants[index].id+"'"+')" role="checkbox" name="ParticipantMeal'+dashBoard.participants[index].id+'" id="chkParticipantMeal'+dashBoard.participants[index].id+'" type="checkbox"></td><td>'+ dashBoard.participants[index].name+' </td><td > <input type=text class="gridInput" size="5" onKeyUp="dashBoard.filterMealInput('+'breakfast_'+dashBoard.participants[index].id+')"  id="breakfast_'+dashBoard.participants[index].id+'" ></td><td><input type=text class="gridInput"  size="5"  onKeyUp="dashBoard.filterMealInput('+'lunch_'+dashBoard.participants[index].id+')"    id="lunch_'+dashBoard.participants[index].id+'" ></td><td><input class="gridInput" type=text  size="5"  onKeyUp="dashBoard.filterMealInput('+'dinner_'+dashBoard.participants[index].id+')"    id="dinner_'+dashBoard.participants[index].id+'" >   </td></tr>';
        }

        result = result + ' </table></td></tr>';

        dashBoard.mealAmtHtmlFormat = result;
    }

    this.setPaidBy = function setPaidBy(selectedParticipantId){

        dashBoard.paidByHtml = "";

        for (var index in dashBoard.participants) {

            if(dashBoard.participants[index].id == selectedParticipantId){

                dashBoard.paidByHtml += '<option value="'+dashBoard.participants[index].id+'" selected role="option">'+dashBoard.participants[index].name+'</option>';
            } else {
                dashBoard.paidByHtml += '<option value="'+dashBoard.participants[index].id+'" role="option">'+dashBoard.participants[index].name+'</option>';
            }
        }
    }

    this.setParticipantAmountInfoByAmtStr = function setParticipantAmountInfoByAmtStr(amtStr){

        var amtStrArray = amtStr.split(",");
        var totalInvolves = 0;
        var noOfParticipant = 0;

        for (var index in dashBoard.participants) {
            noOfParticipant++;
        }

        for(var i=0;i<amtStrArray.length;i++){
            var values = amtStrArray[i].split("|");

            if(values[1] == ""){

                dashBoard.participants[values[0]].isFreeze = 1;
                dashBoard.participants[values[0]].currentInputExpensePart = 0;
            } else {
                dashBoard.participants[values[0]].isFreeze = 0;
                dashBoard.participants[values[0]].currentInputExpensePart = values[1];
            }

            dashBoard.participants[values[0]].currentInputExpenseFreezeAmt = values[2];
            if(parseFloat(dashBoard.participants[values[0]].currentInputExpenseFreezeAmt) > parseFloat(0)){
                totalInvolves++;
                $("#chkParticipant"+values[0]).prop('checked', true);
            }
        }

        //check or uncheck checkBox
        if(totalInvolves != noOfParticipant ){
            $("#selectAll").prop('checked', false);
        }

    }

    this.setParticipantMealInfoByMealStr = function setParticipantMealInfoByMealStr(mealStr){

        var mealStrArray = mealStr.split(",");
        var totalInvolves = 0;
        var totalParNum = 0;

        for (var index in dashBoard.participants) {

            dashBoard.participants[index].breakfast = dashBoard.defaultBreakfast;
            dashBoard.participants[index].lunch = dashBoard.defaultLunch;
            dashBoard.participants[index].dinner = dashBoard.defaultDinner;
            totalParNum++;
        }

        for(var i=0;i<mealStrArray.length;i++){
            var values = mealStrArray[i].split("|");


            dashBoard.participants[values[0]].breakfast = values[1];
            dashBoard.participants[values[0]].lunch = values[2];
            dashBoard.participants[values[0]].dinner = values[3];

            if(parseFloat(values[1]) > parseFloat(0)
                || parseFloat(values[2]) > parseFloat(0)
                || parseFloat(values[3]) > parseFloat(0)){

                totalInvolves++;
                $("#chkParticipantMeal"+values[0]).prop('checked', true);
            }
        }

        if(totalInvolves != totalParNum ){
            $("#selectAllMeal").prop('checked', false);
        }

        dashBoard.showMealAmount();
    }

    this.showEditUI =function showEditUI(expenseObj){

        dashBoard.currentEditGroupExpense = expenseObj;

        //set paid by
        dashBoard.setPaidBy(expenseObj.paidBy);

        //assign parts and freeze amounts to all participants
        if(expenseObj.isDetails == 1){
            dashBoard.refreshParticipantsExpenseProperties(0);
        } else {
            dashBoard.refreshParticipantsExpenseProperties(0);
        }

        if(expenseObj.expenseType == "1"){
            dashBoard.setParticipantAmountInfoByAmtStr(expenseObj.participantAmountStr);
        }

        dashBoard.currentInputAmount = expenseObj.amount;



        if(expenseObj.isDetails == 1){
            dashBoard.hideShowParticipantDetails(true);
            $("#Details").prop('checked', true);

        } else {
            dashBoard.hideShowParticipantDetails(false)

        }

        if(expenseObj.expenseType == "2"){
            dashBoard.showMessHtml();
        } else {
            $("#isMessExpense").prop('checked', false);
            dashBoard.showGroupExpenseHtml();
            dashBoard.setDetailsCheckImpact();

        }



    }

    this.showEditMealUI =function showEditMealUI(mealObj){

        dashBoard.currentEditMeal = mealObj;

        dashBoard.setParticipantMealInfoByMealStr(mealObj.participantMealStr);

        var totalParNum = 0;
        var totalSelectedPart = 0;
        for (var index in dashBoard.participants) {
            totalParNum++;
        }
        var participantMealStrArr = mealObj.participantMealStr.split(",");
        for (var index in participantMealStrArr) {
            if(participantMealStrArr[index] != ""){
                totalSelectedPart++;
            }
        }

        if(totalSelectedPart == totalParNum){
            $("#selectAllMeal").prop('checked', true);
        }
    }

    this.setIsMessCheckImpact = function setIsMessCheckImpact(){

        if($("#isMessExpense").is(':checked')){
            dashBoard.showMessHtml();
        }  else {
            $("#Details").prop('checked', false);
            $("#selectAll").prop('checked', true);
            dashBoard.setAllCheckImpact();
            dashBoard.showGroupExpenseHtml();
        }
    }


    this.showMessHtml = function showMessHtml(){

        $("#tr_IsDetails").hide();
        $("#tr_selectAll").hide();
        for (var index in dashBoard.participants) {
            $("#tr_Participant"+dashBoard.participants[index].id).hide();
            $("#tr_ParticipantDetails"+dashBoard.participants[index].id).hide();
        }


    }

    this.showGroupExpenseHtml = function showGroupExpenseHtml(){

        $("#tr_IsDetails").show();
        $("#tr_selectAll").show();

        if($("#tr_IsDetails").is(':checked')){
            for (var index in dashBoard.participants) {
                $("#tr_Participant"+dashBoard.participants[index].id).hide();
                $("#tr_ParticipantDetails"+dashBoard.participants[index].id).show();
            }

        } else {
            for (var index in dashBoard.participants) {
                $("#tr_Participant"+dashBoard.participants[index].id).show();
                $("#tr_ParticipantDetails"+dashBoard.participants[index].id).hide();
            }
        }

    }

    this.setDetailsCheckImpact = function setDetailsCheckImpact(){

        if($("#Details").is(':checked')){
            dashBoard.hideShowParticipantDetails(true);
        }  else {
            dashBoard.hideShowParticipantDetails(false);
        }
        dashBoard.setShadowOnPartTextBox();
    }


    this.showPartAndFreezeAmtInDetails = function showPartAndFreezeAmtInDetails(){
        for (var index in dashBoard.participants) {
            //set part and freezeAmt from participants
            $("#participantTextPart"+dashBoard.participants[index].id).val(dashBoard.participants[index].currentInputExpensePart);
            $("#participantTextFreeze"+dashBoard.participants[index].id).val(dashBoard.showFormatedAmount(dashBoard.participants[index].currentInputExpenseFreezeAmt));
        }
    }

    this.hideShowParticipantDetails = function hideShowParticipantDetails(isDetails){
        if(isDetails == true){
            //hide simple
            $("#tr_selectAll").hide();
            for (var index in dashBoard.participants) {
                $("#tr_Participant"+dashBoard.participants[index].id).hide();
                $("#tr_ParticipantDetails"+dashBoard.participants[index].id).show();
            }

            dashBoard.showPartAndFreezeAmtInDetails();

        } else {
            $("#tr_selectAll").show();
            for (var index in dashBoard.participants) {
                $("#tr_Participant"+dashBoard.participants[index].id).show();
                $("#tr_ParticipantDetails"+dashBoard.participants[index].id).hide();
            }
            dashBoard.showFreezeAmount();


        }
    }

    // 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.showMealFormatedAmount = function showMealFormatedAmount(amount){
        return parseFloat(amount).toFixed(1);
    }

    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.getNextDayFormatedDate = function getNextDayFormatedDate(date){

        var dateObj = new Date((new Date(date*1000)).toUTCString());
        dateObj.setTime(dateObj.getTime() + 86400000);

        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 != ""  && date != null){
            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.getInvolveString = function getInvolveString(participantAmountStr){

        var involveStrAll = "";
        var involveStrExcept = "";
        var involveParticipantList = [];


        //calculate involveStr
        var participantInvolveList = participantAmountStr.split(",");
        for(var i=0;i<participantInvolveList.length;i++){

            var participantAndAmountArray = participantInvolveList[i].split("|");
            involveParticipantList[i] = participantAndAmountArray[0];
            if(i==0){
                involveStrAll = dashBoard.participants[participantAndAmountArray[0]].name;
            } else {
                involveStrAll += ","+dashBoard.participants[participantAndAmountArray[0]].name;
            }
        }



        //calculate involveStrExcept
        if( dashBoard.getNumberOfParticipants() == involveParticipantList.length){
            involveStrExcept = "all";
        } else{


            for (var index in dashBoard.participants) {

                if( dashBoard.inArrayElement(involveParticipantList,dashBoard.participants[index].id) == false){
                    if(involveStrExcept==""){
                        involveStrExcept += "all except "+dashBoard.participants[index].name;
                    } else {
                        involveStrExcept += ","+ dashBoard.participants[index].name;
                    }
                }
            }


        }




        if(involveStrAll.length>involveStrExcept.length){
            return involveStrExcept;
        } else{
            return involveStrAll;
        }


    }


    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.getForYouString = function getForYouString(participantAmountStr){

        var forYou = "";

        var participantInvolveList = participantAmountStr.split(",");
        for(var i=0;i<participantInvolveList.length;i++){

            var participantAndAmountArray = participantInvolveList[i].split("|");

            if(participantAndAmountArray[0]== dashBoard.loginParticipantId){

                forYou = dashBoard.getFormatedAmount(participantAndAmountArray[2]);
            }
        }

        if(forYou==""){
            forYou = dashBoard.getFormatedAmount(0);
        }

        return forYou;
    }


    this.validateExpenseAddForm = function validateExpenseAddForm(source){

        var errorMessage = "";

        //validate expense name
        if (!$('#Reason').val().trim()) {
            errorMessage = lblPleaseEnterNameOfExpense
        } 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 freeze amount
        if(errorMessage == ""){
            var totalFreezeAmt = dashBoard.getFormatedAmount(0);

            for (var index in dashBoard.participants) {

                totalFreezeAmt = parseFloat(totalFreezeAmt) + parseFloat(dashBoard.getFormatedAmount(dashBoard.participants[index].currentInputExpenseFreezeAmt));
            }

            if(!$("#isMessExpense").is(':checked')){

                if(dashBoard.showFormatedAmount(totalFreezeAmt) != dashBoard.showFormatedAmount($('#Amount').val().trim())){
                    errorMessage = lblDistributedAmountSame
                }
            }
        }



        //validate date
        if(errorMessage == ""){

            if($('#Date').val().trim() != ""){
                var dateArray  = $('#Date').val().trim().split("-");
                if(dateArray.length != 3){
                    errorMessage = LBL_DATE_NOT_VALID;
                } 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();
                dashBoard.setIsMessCheckImpact();
            }
        }

    }

    this.validateMealAddForm = function validateMealAddForm(source){

        var errorMessage = "";

        if(errorMessage == ""){

            if($('#Date').val().trim() != ""){
                var dateArray  = $('#Date').val().trim().split("-");
                if(dateArray.length != 3){
                    errorMessage = lblDateNotValid;
                } else {
                    errorMessage = isValidDate(dateArray);
                }
            }
        }

        //check the date already exist in grid or not
        if(errorMessage == ""){
            var checkDate = true;
            var dateVal  = $('#Date').val().trim();//getTimeStampByInputDate($('#Date').val().trim());

            if(dashBoard.isAddMode == false){
                var rowId =$("#meal_grid").jqGrid('getGridParam','selrow');
                var rowData = jQuery("#meal_grid").getRowData(rowId);

                if($('#Date').val().trim() == dashBoard.meals[rowData['SI']].date ){
                    checkDate = false;
                }
            }

            if(checkDate){
                for (var id in dashBoard.meals) {
                    if(dashBoard.meals[id].date == dateVal){
                        errorMessage = lblMealsAddedOnThisDate;
                        break;
                    }
                }
            }


        }


        //set or clear error message
        if(errorMessage != ""){
            dashBoard.showErrorMessage(errorMessage);
        } else {

            dashBoard.clearErrorMessage();

            addMeal();

            if(source == 1){
                $(".ui-icon-closethick").trigger('click');

            }  else {
                dashBoard.clearMealForm();
            }
        }

    }


    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("");
        $("#Details").prop('checked', false);
        $("#selectAll").prop('checked', true);
        dashBoard.refreshParticipantsExpenseProperties(1);
        dashBoard.setAllCheckImpact();
        dashBoard.hideShowParticipantDetails(false);
        $('#Reason').focus();
    }

    this.addRowsToGrid = function addRowsToGrid(data){
        var names = ['SI','ExpenseType', 'PaidBy', 'Amount', 'Reason', 'Date','Involve','For you?'];
        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").jqGrid('addRowData',data[i][0], mydata[i]);
            }


            //Set the page to the last page

        } else {
            $("#grid").jqGrid('setRowData', data[0][0], mydata[0]);
            dashBoard.isAddMode = true;
        }


    }

    this.addMealRowsToGrid = function addMealRowsToGrid(data){
        var names = ['SI', 'Date', 'Day', 'Breakfast', 'Lunch','Dinner','Involves'];
        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++) {



                $("#meal_grid").jqGrid('addRowData',data[i][0], mydata[i]);
            }


            //Set the page to the last page



        } else {


            $("#meal_grid").jqGrid('setRowData', data[0][0], mydata[0]);
            dashBoard.isAddMode = true;
        }


    }

    this.getExpenseUniqueId = function getExpenseUniqueId(){

        var maxExpId = 0;
        var extractedIndex = 0;
        var expenseIdArray;

        for (var id in dashBoard.groupExpenses) {

            expenseIdArray = dashBoard.groupExpenses[id].id.split("-");

            if(expenseIdArray[0]== dashBoard.loginParticipantId &&  maxExpId < parseInt(expenseIdArray[1])){

                maxExpId = parseInt(expenseIdArray[1]);
            }
        }

        return String(dashBoard.loginParticipantId) + "-"+ String(pad(maxExpId+1, 5))+"-"+dashBoard.expense.id;
    }

    this.getMealUniqueId = function getMealUniqueId(){

        var maxExpId = 0;
        var extractedIndex = 0;
        var mealIdArray;

        for (var id in dashBoard.meals) {

            mealIdArray = dashBoard.meals[id].id.split("-");

            if(mealIdArray[0]== dashBoard.loginParticipantId &&  maxExpId < parseInt(mealIdArray[1])){

                maxExpId = parseInt(mealIdArray[1]);
            }
        }

        return String(dashBoard.loginParticipantId) + "-"+ 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.paidBy != newExpObj.paidBy){

            isChanged = true;
        } else if(oldExpObj.expenseDate != newExpObj.expenseDate){

            isChanged = true;
        } else if(parseFloat(oldExpObj.amount) != parseFloat(newExpObj.amount)){
            isChanged = true;
        } else if(oldExpObj.participantAmountStr != newExpObj.participantAmountStr){
            isChanged = true;
        } else if(oldExpObj.expenseType != newExpObj.expenseType){
            isChanged = true;
        }

        return isChanged;

    }

    this.isMealValueModified = function isMealValueModified(oldMealObj,newMealObj){

        var isChanged = false;

        if(newMealObj.oldDate != newMealObj.date){
            isChanged = true;
        }  else if(oldMealObj.participantMealStr != newMealObj.participantMealStr){
            isChanged = true;
        }

        return isChanged;

    }


    this.addExpenseToGrid = function addExpenseToGrid(){
        var groupExpenseObj ;

        var previousDesc;
        var newDesc;
        var previousPaidBy;

        //collect data from edit form
        if(dashBoard.isAddMode == true){



            groupExpenseObj= new GroupExpense();
            groupExpenseObj.id = dashBoard.getExpenseUniqueId();
            groupExpenseObj.expenseId = dashBoard.expense.id;
            groupExpenseObj.isAdd = "1";
            groupExpenseObj = dashBoard.getInputFormData(groupExpenseObj);
            groupExpenseObj.type = 1;

            dashBoard.globalExpenseIndex++;

        } else {

            groupExpenseObj = new GroupExpense();
            groupExpenseObj = dashBoard.getInputFormData(groupExpenseObj);

            //check whether data is modified or not. If not change then return
            if(!dashBoard.isValueModified(dashBoard.currentEditGroupExpense,groupExpenseObj)){
                return;
            } else {

                previousPaidBy = dashBoard.participants[dashBoard.currentEditGroupExpense.paidBy].name;

                previousDesc = dashBoard.getGeneratedLog(dashBoard.currentEditGroupExpense);

                newDesc = dashBoard.getGeneratedLog(groupExpenseObj);
            }


            groupExpenseObj = dashBoard.currentEditGroupExpense;
            groupExpenseObj = dashBoard.getInputFormData(groupExpenseObj);

            groupExpenseObj.expenseId = dashBoard.expense.id;
            groupExpenseObj.isAdd = "2";

            groupExpenseObj.id = dashBoard.currentEditGroupExpense.id;

            groupExpenseObj.previousDesc  = previousDesc;
            groupExpenseObj.newDesc = newDesc;
            groupExpenseObj.previousPaidBy  = previousPaidBy;

        }


        if(groupExpenseObj.expenseType == "2"){

            groupExpenseObj.isDetails = 0;
        }



        groupExpenseObj.isreimburse = 0;


        dashBoard.processExpenseData(groupExpenseObj);


    }
    this.addMealToGrid = function addMealToGrid(){
        var mealObj ;


        //collect data from edit form
        if(dashBoard.isAddMode == true){

            mealObj= new Meal();

            mealObj.expenseId = dashBoard.expense.id;
            mealObj.isAdd = "5";
            mealObj.id = dashBoard.getMealUniqueId();

            mealObj = dashBoard.getMealInputFormData(mealObj);

            dashBoard.globalMealIndex++;

        } else {

            mealObj = new Meal();
            mealObj = dashBoard.getMealInputFormData(mealObj);
            //check whether data is modified or not. If not change then return

            var rowId =$("#meal_grid").jqGrid('getGridParam','selrow');
            var rowData = jQuery("#meal_grid").getRowData(rowId);

            mealObj.oldDate = dashBoard.meals[rowData['SI']].date;

            if(!dashBoard.isMealValueModified(dashBoard.meals[rowData['SI']],mealObj)){
                return;
            }


            mealObj.expenseId = dashBoard.expense.id;
            mealObj.isAdd = "6";

            mealObj.id = dashBoard.currentEditMeal.id;

        }


        dashBoard.processMealData(mealObj);

    }

    this.processExpenseData = function processExpenseData(groupExpenseObj){

        dashBoard.groupExpenses[groupExpenseObj.id] =  groupExpenseObj;

        sendDataToServer(groupExpenseObj,"#expenseForm");


        var data = [];


        data.push(dashBoard.getDataByExpense(groupExpenseObj));

        dashBoard.addRowsToGrid(data);

        //go to the last page after adding record
        dashBoard.setPageAfterAdd('#grid');


    }

    this.processMealData = function processMealDate(mealObj){

        dashBoard.meals[mealObj.id] =  mealObj;

        sendDataToServer(mealObj,"#expenseForm");


        var data = [];


        data.push(dashBoard.getDataByMeal(mealObj));

        dashBoard.addMealRowsToGrid(data);

        //go to the last page after adding record
        dashBoard.setPageAfterAdd('#meal_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.getGeneratedLog = function getGeneratedLog(expenseObj){

        var logStr = "";

        logStr += "[Expense:"+expenseObj.expenseName+"],";
        logStr += "[PaidBy:"+dashBoard.participants[expenseObj.paidBy].name+"],";
        logStr += "[Date:"+expenseObj.expenseDate+"],";
        logStr += "[Amount:"+dashBoard.showFormatedAmount(expenseObj.amount)+' '+dashBoard.expense.currency+"],";
        logStr += "[Involves:";


        if(expenseObj.expenseType == "2"){
            logStr += "Mess Members";
        } else {


            var participantAmtStrArray = expenseObj.participantAmountStr.split(",");
            for (var index in participantAmtStrArray) {
                var dataArray = participantAmtStrArray[index].split("|");
                if(index == 0){
                    logStr += dashBoard.participants[dataArray[0]].name+"="+dashBoard.showFormatedAmount(dataArray[2]);
                } else {
                    logStr += ","+dashBoard.participants[dataArray[0]].name+"="+dashBoard.showFormatedAmount(dataArray[2]);
                }
            }

        }
        logStr += "]";


        return logStr;
    }

    this.getInputFormData = function getInputFormData(groupExpenseObj){



        var amountStr = "";
        var isDetails = false;

        groupExpenseObj.paidBy = $('#PaidBy').val();
        groupExpenseObj.expenseName = $('#Reason').val();
        groupExpenseObj.amount = $('#Amount').val();
        groupExpenseObj.expenseDate =  $('#Date').val();//getTimeStampByInputDate($('#Date').val());

        //return groupExpenseObj;

        for (var index in dashBoard.participants) {
            if($("#chkParticipant"+dashBoard.participants[index].id).is(':checked')){

                if(amountStr == ""){
                    if(dashBoard.participants[index].isFreeze == 1){
                        dashBoard.participants[index].currentInputExpensePart = "";
                    }
                    amountStr += dashBoard.participants[index].id+"|"+dashBoard.participants[index].currentInputExpensePart+"|"+dashBoard.getFormatedAmountDB(dashBoard.participants[index].currentInputExpenseFreezeAmt);

                } else {
                    if(dashBoard.participants[index].isFreeze == 1){
                        dashBoard.participants[index].currentInputExpensePart = "";
                    }
                    amountStr += ","+ dashBoard.participants[index].id+"|"+dashBoard.participants[index].currentInputExpensePart+"|"+dashBoard.getFormatedAmountDB(dashBoard.participants[index].currentInputExpenseFreezeAmt);

                }
            }

            if((dashBoard.participants[index].isFreeze == 1) || dashBoard.participants[index].currentInputExpensePart > 1){
                isDetails = true;
            }
        }

        if(isDetails){
            groupExpenseObj.isDetails = 1;
        } else {
            groupExpenseObj.isDetails = 0;
        }


        groupExpenseObj.participantAmountStr = amountStr;

        //set expenseType
        if($("#isMessExpense").is(':checked')){
            groupExpenseObj.expenseType = "2";
        } else {
            groupExpenseObj.expenseType = "1";
        }

        return groupExpenseObj;
    }

    this.getMealInputFormData = function getMealInputFormData(mealObj){

        var mealStr = "";

        mealObj.date = $('#Date').val();//getTimeStampByInputDate($('#Date').val());

        for (var index in dashBoard.participants) {
            if($("#chkParticipantMeal"+dashBoard.participants[index].id).is(':checked')){

                if(mealStr == ""){
                    mealStr += dashBoard.participants[index].id+"|"+ dashBoard.showMealFormatedAmount(parseFloat($("#breakfast_"+dashBoard.participants[index].id).val()))+"|"+dashBoard.showMealFormatedAmount(parseFloat($("#lunch_"+dashBoard.participants[index].id).val()))+"|"+dashBoard.showMealFormatedAmount(parseFloat($("#dinner_"+dashBoard.participants[index].id).val()));

                } else {

                    mealStr += ","+ dashBoard.participants[index].id+"|"+ dashBoard.showMealFormatedAmount(parseFloat($("#breakfast_"+dashBoard.participants[index].id).val()))+"|"+dashBoard.showMealFormatedAmount(parseFloat($("#lunch_"+dashBoard.participants[index].id).val()))+"|"+dashBoard.showMealFormatedAmount(parseFloat($("#dinner_"+dashBoard.participants[index].id).val()));

                }
            }

        }

        mealObj.participantMealStr = mealStr;

        return mealObj;
    }

    this.deleteExpense = function deleteExpense(){

        var rowId =$("#grid").jqGrid('getGridParam','selrow');
        var i;

        $('#grid').jqGrid('delRowData', rowId);
        var deletedExpObj = dashBoard.groupExpenses[rowId];

        delete dashBoard.groupExpenses[rowId];

        deletedExpObj.isAdd = "3";

        //set log info
        deletedExpObj.previousDesc  = dashBoard.getGeneratedLog(deletedExpObj);
        deletedExpObj.newDesc = "Deleted";
        deletedExpObj.previousPaidBy  = dashBoard.participants[deletedExpObj.paidBy].name;


        //call ajax for DB update

        deletedExpObj.expenseId = dashBoard.expense.id;
        dashBoard.setPageAfterDelete('#grid');
        sendDataToServer(deletedExpObj,"#expenseForm");
        $(".ui-icon-closethick").trigger('click');


    }

    this.deleteMeal = function deleteMeal(){

        var rowId =$("#meal_grid").jqGrid('getGridParam','selrow');
        var i;

        $('#meal_grid').jqGrid('delRowData', rowId);
        var deletedMeal = dashBoard.meals[rowId];

        delete dashBoard.meals[rowId];

        deletedMeal.isAdd = "7";

        //set log info

        deletedMeal.expenseId = dashBoard.expense.id;


        dashBoard.setPageAfterDelete('#meal_grid');
        sendDataToServer(deletedMeal,"#expenseForm");
        $(".ui-icon-closethick").trigger('click');


    }


    this.resetParticipantBalance = function resetParticipantBalance(){

        var amtStr = "";
        var paidBy ;
        var amount;
        var totalMeal = 0;
        var totalCost = 0;
        var perMealCost = 0;
        var yourMeal = 0;
        var yourCost = 0;

        dashBoard.resetParticipantMeal();

        for (var index in dashBoard.participants) {
            dashBoard.participants[index].balance = dashBoard.getFormatedAmountDB(parseFloat(0));
            dashBoard.participants[index].totalPaid = dashBoard.getFormatedAmountDB(parseFloat(0));
            dashBoard.participants[index].totalSpent = dashBoard.getFormatedAmountDB(parseFloat(0));
            if(parseFloat(dashBoard.participants[index].numberOfMeal) > 0 ){
                dashBoard.participants[index].isDeletable = 0;
            } else {
                dashBoard.participants[index].isDeletable = 1;
            }
            if(dashBoard.participants[index].id == dashBoard.loginParticipantId){
                yourMeal = dashBoard.getFormatedAmountDB(parseFloat(yourMeal) + parseFloat(dashBoard.participants[index].numberOfMeal));
            }
            totalMeal = dashBoard.getFormatedAmountDB(parseFloat(totalMeal) + parseFloat(dashBoard.participants[index].numberOfMeal));
        }

        //for(var i=0;i<dashBoard.groupExpenses.length;i++){
        for (var id in dashBoard.groupExpenses) {

            paidBy =  dashBoard.groupExpenses[id].paidBy;
            amount =  dashBoard.groupExpenses[id].amount;

            if(dashBoard.groupExpenses[id].expenseType == "1"){


                amtStr =  dashBoard.groupExpenses[id].participantAmountStr;


                var amtStrArray = amtStr.split(",");
                for(var j=0;j<amtStrArray.length;j++){
                    var participantAndAmountArray = amtStrArray[j].split("|");
                    dashBoard.participants[participantAndAmountArray[0]].isDeletable = 0;
                    dashBoard.participants[participantAndAmountArray[0]].totalSpent = dashBoard.getFormatedAmountDB(parseFloat(dashBoard.participants[participantAndAmountArray[0]].totalSpent) + parseFloat(participantAndAmountArray[2]));
                    dashBoard.participants[participantAndAmountArray[0]].balance = dashBoard.getFormatedAmountDB(parseFloat(dashBoard.participants[participantAndAmountArray[0]].balance) - parseFloat(participantAndAmountArray[2]));

                }

            } else {
                totalCost =  dashBoard.getFormatedAmountDB(parseFloat(totalCost) + parseFloat(amount));
            }

            dashBoard.participants[paidBy].isDeletable = 0;
            dashBoard.participants[paidBy].totalPaid = dashBoard.getFormatedAmountDB(parseFloat(dashBoard.participants[paidBy].totalPaid) + parseFloat(amount));
            dashBoard.participants[paidBy].balance = dashBoard.getFormatedAmountDB(parseFloat(dashBoard.participants[paidBy].balance) + parseFloat(amount));

        }
        //calculate per meal cost
        if(parseFloat(totalMeal)>0){
            perMealCost = dashBoard.getFormatedAmountDB(parseFloat(totalCost)/parseFloat(totalMeal));
        }


        //reset balance by deducting (permeal cost * meal amount)
        for (var index in dashBoard.participants) {
            dashBoard.participants[index].mealCost = dashBoard.getFormatedAmountDB(parseFloat(perMealCost) * parseFloat(dashBoard.participants[index].numberOfMeal));
            dashBoard.participants[index].totalSpent = dashBoard.getFormatedAmountDB(parseFloat(dashBoard.participants[index].totalSpent) + parseFloat(dashBoard.participants[index].mealCost));
            dashBoard.participants[index].balance = dashBoard.getFormatedAmountDB(parseFloat(dashBoard.participants[index].balance) - (parseFloat(perMealCost) * parseFloat(dashBoard.participants[index].numberOfMeal))) ;
        }


        dashBoard.totalMeal = totalMeal;
        dashBoard.yourMeal = yourMeal;
        dashBoard.totalCost = totalCost;
        dashBoard.yourCost = dashBoard.getFormatedAmountDB(parseFloat(perMealCost)* parseFloat(yourMeal));

    }





    this.resetParticipantMeal = function resetParticipantMeal(){
        var mealStr = "";


        for (var index in dashBoard.participants) {
            dashBoard.participants[index].numberOfMeal = dashBoard.showMealFormatedAmount(parseFloat(0));
        }

        //for(var i=0;i<dashBoard.meals.length;i++){
        for (var id in dashBoard.meals) {
            mealStr =  dashBoard.meals[id].participantMealStr;



            var mealStrArray = mealStr.split(",");
            for(var j=0;j<mealStrArray.length;j++){

                var participantAndMealArray = mealStrArray[j].split("|");

                dashBoard.participants[participantAndMealArray[0]].numberOfMeal = dashBoard.showMealFormatedAmount(parseFloat(dashBoard.participants[participantAndMealArray[0]].numberOfMeal) + parseFloat(participantAndMealArray[1]) + parseFloat(participantAndMealArray[2]) + parseFloat(participantAndMealArray[3]));

            }
        }

    }


    this.processParticipantDataByPopup = function processParticipantDataByPopup (participantObj){

        dashBoard.participants[participantObj.id] =  participantObj;
        dashBoard.addParticipantToList();
        sendDataToServer(participantObj,"#participantForm");
    }

    this.updateParticipantBalance = function updateParticipantBalance(){
        var balanceEntryParticipantBalance = [];
        var balanceString = "";

        var positiveParticipantBalance = [];
        var negativeParticipantBalance = [];

        //reset all participant balance
        for (var index in dashBoard.participants) {
            positiveParticipantBalance[index] = dashBoard.getFormatedAmountDB(parseFloat(0));
            negativeParticipantBalance[index] = dashBoard.getFormatedAmountDB(parseFloat(0));
        }

        dashBoard.resetParticipantBalance();
        //assign negative and posi
        for (var index in dashBoard.participants) {
            if(parseFloat(dashBoard.participants[index].balance) > 0){
                positiveParticipantBalance[index] = dashBoard.participants[index].balance;
            } else if(parseFloat(dashBoard.participants[index].balance) < 0) {
                negativeParticipantBalance[index] = dashBoard.participants[index].balance;
            }
        }

        //sort postivie and negative


        //add balance amount in positive and negative


        //if pos and neg values are same, then direct exchange payment

        for (var posIndex in positiveParticipantBalance) {

            if(dashBoard.showFormatedAmount(parseFloat(positiveParticipantBalance[posIndex])) > dashBoard.showFormatedAmount(parseFloat(0))){

                for (var negIndex in negativeParticipantBalance) {
                    if(dashBoard.showFormatedAmount(parseFloat(positiveParticipantBalance[posIndex])) == dashBoard.showFormatedAmount(parseFloat(negativeParticipantBalance[negIndex])*(-1))
                        && dashBoard.showFormatedAmount(parseFloat(positiveParticipantBalance[posIndex])) > dashBoard.showFormatedAmount(parseFloat(0))){

                        if(balanceString == ""){
                            balanceString = balanceString + negIndex +"|" + posIndex +"|" + dashBoard.showFormatedAmount(parseFloat(negativeParticipantBalance[negIndex])*(-1));
                        } else{
                            balanceString = balanceString+"," + negIndex +"|" + posIndex +"|" + dashBoard.showFormatedAmount(parseFloat(negativeParticipantBalance[negIndex])*(-1));
                        }
                        //update array amount
                        positiveParticipantBalance[posIndex] = 0;
                        negativeParticipantBalance[negIndex] = 0;
                    }
                }

            }
        }



        //distribute amount among pos values
        var maxPartIndex = dashBoard.getMaxMinParticipantId(positiveParticipantBalance,1);
        var minPartIndex = dashBoard.getMaxMinParticipantId(negativeParticipantBalance,2);


        while(maxPartIndex != "" && minPartIndex != ""){

            var maxVal = parseFloat(positiveParticipantBalance[maxPartIndex]);


            if(minPartIndex != ""){

                var decrementalVal = parseFloat(negativeParticipantBalance[minPartIndex]) *(-1);
                if(parseFloat(decrementalVal) >parseFloat(maxVal)){
                    decrementalVal = dashBoard.getFormatedAmountDB(maxVal);
                }

                //update array
                positiveParticipantBalance[maxPartIndex] = dashBoard.getFormatedAmountDB(parseFloat(positiveParticipantBalance[maxPartIndex]) - parseFloat(decrementalVal));
                negativeParticipantBalance[minPartIndex] = dashBoard.getFormatedAmountDB(parseFloat(negativeParticipantBalance[minPartIndex]) + parseFloat(decrementalVal));

                if(balanceString == ""){
                    balanceString = balanceString + minPartIndex +"|" + maxPartIndex +"|" + decrementalVal;
                } else{
                    balanceString = balanceString+"," + minPartIndex +"|" + maxPartIndex +"|" + decrementalVal;
                }

            }


            //check equal
            for (var posIndex in positiveParticipantBalance) {

                if(dashBoard.showFormatedAmount(parseFloat(positiveParticipantBalance[posIndex])) > dashBoard.showFormatedAmount(parseFloat(0))){

                    for (var negIndex in negativeParticipantBalance) {

                        if(dashBoard.showFormatedAmount(parseFloat(positiveParticipantBalance[posIndex])) == dashBoard.showFormatedAmount(parseFloat(negativeParticipantBalance[negIndex])*(-1))
                            && dashBoard.showFormatedAmount(parseFloat(positiveParticipantBalance[posIndex])) > dashBoard.showFormatedAmount(parseFloat(0))){

                            if(balanceString == ""){
                                balanceString = balanceString + negIndex +"|" + posIndex +"|" + dashBoard.showFormatedAmount(parseFloat(negativeParticipantBalance[negIndex])*(-1));
                            } else{
                                balanceString = balanceString+"," + negIndex +"|" + posIndex +"|" + dashBoard.showFormatedAmount(parseFloat(negativeParticipantBalance[negIndex])*(-1));
                            }
                            //update array amount
                            positiveParticipantBalance[posIndex] = 0;
                            negativeParticipantBalance[negIndex] = 0;
                        }
                    }

                }
            }

            maxPartIndex = dashBoard.getMaxMinParticipantId(positiveParticipantBalance,1);
            minPartIndex = dashBoard.getMaxMinParticipantId(negativeParticipantBalance,2);

        }

        return balanceString;


    }

    this.getMaxMinParticipantId = function getMaxMinParticipantId(balanceList,ind){

        var result  = 0;
        var participantIndex='';
        for (var index in balanceList) {

            if(ind == 1){
                if(dashBoard.showFormatedAmount(parseFloat(balanceList[index])) > parseFloat(result)){
                    participantIndex = index;
                    result = parseFloat(balanceList[index]);
                }
            } else {

                if(dashBoard.showFormatedAmount(parseFloat(balanceList[index])) < parseFloat(result)){
                    participantIndex = index;
                    result = parseFloat(balanceList[index]);
                }

            }
        }

        return participantIndex;

    }

    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");
        $("#balance_chart_image").html(imgElem);
        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.showBalanceDisposalMessage = function showBalanceDisposalMessage(){

        var result = false;
        var hasMeal = false;
        var hasMealExpense = false;

        for (var index in dashBoard.meals) {
            hasMeal = true;
            break;
        }

        for (var index in dashBoard.groupExpenses) {
            if(dashBoard.groupExpenses[index].expenseType == "2"){
                hasMealExpense = true;
                break;
            }
        }


        if(hasMeal == false && hasMealExpense == true){
            result = true;
            $("#balanceDivErrorId").show();
            $("#balanceDivId").hide();
            $("#balanceSummaryDivId").hide();

        }


        return result;

    }

    this.drawGraph = function drawGraph(){

        $("#balanceDivErrorId").hide();
        $("#balanceDivId").show();
        $("#balanceSummaryDivId").show();



        if(dashBoard.showBalanceDisposalMessage() == true){

            return;
        }
        if(plot1){

            plot1.destroy();
        }

        var balanceString = dashBoard.updateParticipantBalance();
        var data = [];
        var barLabel = [];
        var ticks = [];

        var noOfParticipant = 0;

        for (var index in dashBoard.participants) {

            data.push(parseFloat(dashBoard.showFormatedAmount(dashBoard.participants[index].balance)));
            barLabel.push(dashBoard.showFormatedAmount(parseFloat(dashBoard.participants[index].balance)));
            ticks.push(dashBoard.participants[index].name);
            noOfParticipant++;
        }



        // Can specify a custom tick Array.
        // Ticks should match up one for each y value (category) in the series.


        $("#balance_chart").css("width", (noOfParticipant*100)+"px");

        var options = {
            // The "seriesDefaults" option is an options object that will
            // be applied to all series in the chart.
            seriesDefaults:{
                renderer:$.jqplot.BarRenderer,
                rendererOptions: {fillToZero: true}
            },
            // Custom labels for the series are specified with the "label"
            // option on the series option.  Here a series option object
            // is specified for each series.
            series:[
                {

                    color: '#008000',
                    showMarker: true,
                    pointLabels:{
                        show: true,
                        labels:barLabel
                    }

                }


            ],
            // Show the legend and put it outside the grid, but inside the
            // plot container, shrinking the grid to accomodate the legend.
            // A value of "outside" would not shrink the grid and allow
            // the legend to overflow the container.


            negativeSeriesColors: ["#FF0000"],
            axes: {
                // Use a category axis on the x axis and use our custom ticks.
                xaxis: {
                    renderer: $.jqplot.CategoryAxisRenderer,
                    ticks: ticks
                },
                // Pad the y axis just a little so bars can get close to, but
                // not touch, the grid boundaries.  1.2 is the default padding.
                yaxis: {
                    pad: 1.18,
                    tickOptions: {formatString: '%d '+dashBoard.expense.currency}
                }
            },
            title: {
                text: 'Balance of "'+dashBoard.expense.title+'"'

            },

        };


        plot1 = $.jqplot('balance_chart', [data],options);

        dashBoard.showBalanceDetails(balanceString);


    }


    this.showBalanceDetails = function showBalanceDetails(balanceString){

        var balancePaymentHtml = "";
        var balanceSummaryHtml = "";
        var perMealCost = 0;

        if(balanceString != ""){

            var balanceStringArr = balanceString.split(",");


            for (var index in balanceStringArr) {

                var balanceStringval = balanceStringArr[index].split("|");
                balancePaymentHtml = balancePaymentHtml + '<p><b>'+dashBoard.participants[balanceStringval[0]].name+'</b> <I>'+lblShouldPayTo+'</I> <b>'+dashBoard.participants[balanceStringval[1]].name+'</b><span><b>'+dashBoard.showFormatedAmount(parseFloat(balanceStringval[2]))+'</b> '+dashBoard.expense.currency+'<a onClick="dashBoard.insertBalanceEntry('+"'"+balanceStringval[0]+"'"+','+"'"+balanceStringval[1]+"'"+','+balanceStringval[2]+')" style="cursor: pointer;"> <img title="'+lblClickTransactionMadeAlready+'" src="/cdn/images/tick-icon.png" alt=""/></a></span></p>';
            }
        }

        if(parseFloat(dashBoard.totalMeal)>0){
            perMealCost = dashBoard.getFormatedAmountDB(parseFloat(dashBoard.totalCost)/parseFloat(dashBoard.totalMeal));
        }


        balanceSummaryHtml = "*"+lblMealsForYou+": <b>"+dashBoard.showMealFormatedAmount(dashBoard.yourMeal)+"</b>( "+lblOutOf +dashBoard.showMealFormatedAmount(dashBoard.totalMeal)+")"+lblAndCost+": <b>"+dashBoard.showFormatedAmount(dashBoard.yourCost)+"</b> "+dashBoard.expense.currency+"("+lblOutOf +dashBoard.showFormatedAmount(dashBoard.totalCost)+" "+dashBoard.expense.currency+")."+lblHencePerCost+"<b>"+dashBoard.showFormatedAmount(perMealCost)+"</b> "+dashBoard.expense.currency;


        $("#balance_payment_div").html(balancePaymentHtml);
        $("#balanceSummaryDivId").html(balanceSummaryHtml);
    }


    this.insertBalanceEntry = function insertBalanceEntry(payerId,paytoId,amount){

        dashBoard.isAddMode = true;

        groupExpenseObj= new GroupExpense();

        groupExpenseObj.id = dashBoard.getExpenseUniqueId();
        groupExpenseObj.expenseId = dashBoard.expense.id;
        groupExpenseObj.isAdd = "1";

        groupExpenseObj.type = 2; //1=normal expense,2=balance expense
        groupExpenseObj.paidBy = payerId;
        groupExpenseObj.expenseName = "Balance Expense";
        groupExpenseObj.amount = amount;
        groupExpenseObj.expenseDate =   dashBoard.currentDate;
        groupExpenseObj.isDetails = 0;
        groupExpenseObj.participantAmountStr = paytoId+'|'+'1'+'|'+amount;


        groupExpenseObj.isreimburse = 0;

        groupExpenseObj.expenseType = 1;


        dashBoard.processExpenseData(groupExpenseObj);
        dashBoard.drawGraph();
    }














    ///////////////////////////////////////////////////////////////// Participant section ////////////////////////////////////////////

    this.validParticipantInputForm = function validParticipantInputForm(name,skipPartId){
        var errorMessage = "";

        //validate participant name
        if (!name.trim()) {
            errorMessage = lblEnterParticipantName;
        } else if (name.trim().length>12){
            errorMessage = lblExpenseNameLessChar;
        }

        if(errorMessage == ""){
            //check the participant name already exist or not
            for (var index in dashBoard.participants) {

                if(skipPartId != dashBoard.participants[index].id){
                    if(dashBoard.participants[index].name.toLowerCase() == name.trim().toLowerCase()){
                        errorMessage = lblParticipantAlreadyExist;
                        break;
                    }
                }
            }
        }

        if(errorMessage == ""){
            //check the participant name already exist or not
            if( name.trim().indexOf(',') === -1 && name.trim().indexOf('|') === -1){


            } else {
                errorMessage = lblParticipantShouldNotContain;

            }
        }


        return errorMessage;

    }

    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.addParticipant = function addParticipant(participantName,source){

        //generate auto ID for new participant

        var participantObj = new Participant();
        participantObj.id =   dashBoard.getParticipantId();

        participantObj.name = participantName;
        participantObj.isCreator = 0;
        participantObj.create_date = Math.round(+new Date()/1000);
        participantObj.balance = 0;
        participantObj.isFreeze = 0;
        participantObj.expense_id = dashBoard.expense.id;
        participantObj.isAdd = 1;
        participantObj.isDeletable = 1;

        //participants.push(participantObj);
        //insert into grid
        if(source == "1"){
            dashBoard.processParticipantDataByPopup(participantObj);
        } else {
            dashBoard.processParticipantData(participantObj);
        }
        //send to database

    }

    this.getParticipantId = function getParticipantId(){


        //dashBoard.loginParticipantId
        var SI= 1;
        var maxId = 0;
        var participantIdStrArry ;

        for (var index in dashBoard.participants) {
            if(dashBoard.participants[index].id == dashBoard.loginParticipantId){

                break;

            }
            SI++;
        }

        //var participantLoginStrArr = dashBoard.loginParticipantId.split("_");

        for (var index in dashBoard.participants) {

            participantIdStrArry = dashBoard.participants[index].id.split("_");

            if(SI == participantIdStrArry[0]){
                if(parseInt(participantIdStrArry[1]) > parseInt(maxId)){

                    maxId = parseInt(participantIdStrArry[1]);
                }
            }
        }
        maxId++;

        return SI+"_"+maxId;
    }

    this.processParticipantData = function processParticipantData(participantObj){

        dashBoard.participants[participantObj.id] =  participantObj;

        if(typeof  participantObj.numberOfMeal == "undefined"){

            participantObj.numberOfMeal = 0;
        }

        if(typeof  participantObj.mealCost == "undefined"){

            participantObj.mealCost = 0;
        }


        if(typeof  participantObj.totalSpent == "undefined"){

            participantObj.totalSpent = 0;
        }


        if(typeof  participantObj.totalPaid == "undefined"){

            participantObj.totalPaid = 0;
        }


        var data = [];
        data.push([participantObj.id, participantObj.name,dashBoard.showMealFormatedAmount(participantObj.numberOfMeal),dashBoard.showFormatedAmount(participantObj.mealCost)+" "+dashBoard.expense.currency,dashBoard.showFormatedAmount(participantObj.totalSpent)+" "+dashBoard.expense.currency,dashBoard.showFormatedAmount(participantObj.totalPaid)+" "+dashBoard.expense.currency,dashBoard.showFormatedAmount(participantObj.balance)+" "+dashBoard.expense.currency,""]);


        //go to the last page after adding record

        $('#grid').jqGrid('GridUnload');
        dashBoard.showExpenseList();

        dashBoard.addRowsToParticipantGrid(data,true);
        dashBoard.setParticipantGridExtension();


        dashBoard.setPageAfterAdd('#participant_grid');

        sendDataToServer(participantObj,"#participantForm");


    }

    this.updateParticipant = function updateParticipant(participantId,oldName,newName){

        var participantObj = new Participant();
        participantObj.id =  participantId;

        participantObj.name = newName;
        participantObj.expense_id = dashBoard.expense.id;
        participantObj.isAdd = 2;



        //update participant array;
        var existingPartcipantObj = dashBoard.participants[participantId];
        existingPartcipantObj.name = newName;
        dashBoard.participants[participantId] = existingPartcipantObj;



        //update grid
        var data = [];
        data.push([existingPartcipantObj.id, existingPartcipantObj.name,dashBoard.showMealFormatedAmount(existingPartcipantObj.numberOfMeal),dashBoard.showFormatedAmount(existingPartcipantObj.mealCost)+" "+dashBoard.expense.currency,dashBoard.showFormatedAmount(existingPartcipantObj.totalSpent)+" "+dashBoard.expense.currency,dashBoard.showFormatedAmount(existingPartcipantObj.totalPaid)+" "+dashBoard.expense.currency,dashBoard.showFormatedAmount(existingPartcipantObj.balance)+" "+dashBoard.expense.currency,""]);

        dashBoard.addRowsToParticipantGrid(data,false);


        $('#grid').jqGrid('GridUnload');
        dashBoard.showExpenseList();

        $("#participant_grid").trigger("reloadGrid");
        dashBoard.setParticipantGridExtension();



        sendDataToServer(participantObj,"#participantForm");

    }

    this.deleteParticipant = function deleteParticipant(index){

        var rowId =$("#participant_grid").jqGrid('getGridParam','selrow');


        var i;
        var rowData = jQuery("#participant_grid").getRowData(rowId);

        //prepare delete object
        var participantObj = new Participant();
        participantObj.id =   rowData['SI'];
        participantObj.name = rowData['Name'];
        participantObj.expense_id = dashBoard.expense.id;
        participantObj.isAdd = 3;

        $('#participant_grid').jqGrid('delRowData', rowId);

        delete dashBoard.participants[ participantObj.id];

        $('#grid').jqGrid('GridUnload');
        dashBoard.showExpenseList();


        dashBoard.setParticipantGridExtension();

        dashBoard.setPageAfterDelete('#participant_grid');

        sendDataToServer(participantObj,"#participantForm");
        $(".ui-icon-closethick").trigger('click');
    }


    this.displayParticipantList = function displayParticipantList(){

        var partNameBeforeEdit = "";

        var maxRowNum = 0;

        for(var index in  dashBoard.participants){
            maxRowNum++;
        }

        if(maxRowNum<51){
            maxRowNum = 50;
        }

        $("#participant_grid").jqGrid({
                datatype: "local",
                height: 232,
                colNames: ['SI', lblName, lblTotalMeal, lblMealCharge, lblTotalCharge, lblTotalPaid, lblBalance,''],
                colModel: [
                    {
                        name: 'SI',
                        index: 'SI',
                        width: 0,
                        sorttype: "int",
                        hidden:true
                    },
                    {
                        name: 'Name',
                        index: 'Name',
                        width: 120 ,
                        align:'center',
                        editable: true

                    } ,
                    {
                        name: 'Total Meal',
                        index: 'Total Meal',
                        width: 70 ,
                        align:'center',


                    } ,
                    {
                        name: 'Meal Charge',
                        index: 'Meal Charge',
                        width: 110 ,
                        align:'center',


                    } ,
                    {
                        name: 'Total Charge',
                        index: 'Total Charge',
                        width: 110 ,
                        align:'center',


                    } ,
                    {
                        name: 'Total Paid',
                        index: 'Total Paid',
                        width: 110 ,
                        align:'center',


                    } ,
                    {
                        name: 'Balance',
                        index: 'Balance',
                        width: 130 ,
                        align:'center',


                    } ,
                    {
                        name: 'Action',
                        index: 'Action',
                        width: 60 ,
                        align:'center',

                        formatter:  function(cellvalue,options,rowObject) {
                            return dashBoard.inlineNavAction(cellvalue,options,rowObject, (options.rowId!='new_row'));
                        },
                        formatoptions:{
                            keys:true,
                            onSuccess : function(){

                                var rowId =$("#participant_grid").jqGrid('getGridParam','selrow');

                                var rowData = jQuery("#participant_grid").getRowData(rowId);

                                var inputVal = $("#"+rowData['SI']+"_Name").val().trim();

                                if(dashBoard.participants[rowData['SI']].name != inputVal){

                                    var errorMsg = dashBoard.validParticipantInputForm(inputVal,rowData['SI']);
                                    if( errorMsg == ""){

                                        dashBoard.updateParticipant(rowData['SI'],dashBoard.participants[rowData['SI']].name,inputVal);

                                    } else {

                                        $("#"+rowData['SI']+"_Name").focus();
                                        jQuery.fn.fmatter.rowactions.call(this,'edit');

                                    }

                                }

                            }

                        }

                    }

                ],

                rowNum      : maxRowNum,
                rowList:[6,10,20,maxRowNum],
                pager: '#participant_pager',
                gridview:true,
                rownumbers:true,
                autoencode:true,
                ignoreCase:true,

                viewrecords: true,
                sortorder: 'desc',
                caption:lblParticipantList,
                loadComplete: function(){
                    dashBoard.setParticipantGridExtension();
                }
            }

        );




        $("#participant_grid").jqGrid('navGrid','#participant_pager',{
                add:true,addtitle: lblAddParticipant,
                edit:false,edittitle: lblEditParticipant,
                del:false,deltitle: lblDeleteParticipant ,
                search:true,searchtitle: lblFindParticipant},
            { // Edit
                recreateForm: true,
                beforeInitData: function () {
                }
            },
            { // Add
                recreateForm: true,
                beforeInitData: function () {

                }
            }

        );

        $("#participant_grid").jqGrid('setGridParam', {ondblClickRow: function(rowid,iRow,iCol,e){

            jQuery.fn.fmatter.rowactions.call(document.getElementById("jEditButton_"+rowid),'edit');

        }});



        var data = [];

        $("#participant_grid").jqGrid("clearGridData", true).trigger("reloadGrid");

        for (var index in dashBoard.participants) {
            data.push([dashBoard.participants[index].id, dashBoard.participants[index].name,dashBoard.showMealFormatedAmount(dashBoard.participants[index].numberOfMeal),dashBoard.showFormatedAmount(dashBoard.participants[index].mealCost)+" "+dashBoard.expense.currency,dashBoard.showFormatedAmount(dashBoard.participants[index].totalSpent)+" "+dashBoard.expense.currency,dashBoard.showFormatedAmount(dashBoard.participants[index].totalPaid)+" "+dashBoard.expense.currency,dashBoard.showFormatedAmount(dashBoard.participants[index].balance)+" "+dashBoard.expense.currency,""]);

        }

        dashBoard.addRowsToParticipantGrid(data,true);

    }




    this.inlineNavAction = function inlineNavAction(cellvalue, options, rowObject, isSavedRow){

        var rowid = options.rowId;

        var ocl = "id='jEditButton_"+rowid+"' onclick=jQuery.fn.fmatter.rowactions.call(this,'edit'); onmouseover=jQuery(this).addClass('ui-state-hover'); onmouseout=jQuery(this).removeClass('ui-state-hover'); ";
        var str = "<div title='"+lblEditParticipant+"' style='float:left;cursor:pointer;' class='ui-pg-div ui-inline-edit' "+ocl+"><span class='ui-icon ui-icon-pencil'></span></div>";

        if(dashBoard.participants[rowObject['SI']].isDeletable == 1
            && dashBoard.participants[rowObject['SI']].isCreator != "1"
            && rowObject['SI'] != dashBoard.loginParticipantId){
            ocl = "id='jDeleteButton_"+rowid+"' onclick=jQuery.fn.fmatter.rowactions.call(this,'del'); onmouseover=jQuery(this).addClass('ui-state-hover'); onmouseout=jQuery(this).removeClass('ui-state-hover'); ";
            str += "<div title='"+lblDeleteParticipant+"' style='float:left;cursor:pointer;margin-left:5px;' class='ui-pg-div ui-inline-del' "+ocl+"><span class='ui-icon ui-icon-trash'></span></div>";
        }


        ocl = "id='jSaveButton_"+rowid+"' onclick=jQuery.fn.fmatter.rowactions.call(this,'save'); onmouseover=jQuery(this).addClass('ui-state-hover'); onmouseout=jQuery(this).removeClass('ui-state-hover'); ";
        str += "<div title='"+$.jgrid.edit.bSubmit+"' style='float:left;display:none' class='ui-pg-div ui-inline-save' "+ocl+"><span class='ui-icon ui-icon-disk'></span></div>";
        ocl = "id='jCancelButton_"+rowid+"' onclick=jQuery.fn.fmatter.rowactions.call(this,'cancel'); onmouseover=jQuery(this).addClass('ui-state-hover'); onmouseout=jQuery(this).removeClass('ui-state-hover'); ";
        str += "<div title='"+$.jgrid.edit.bCancel+"' style='float:left;margin-left:5px;;display:none' class='ui-pg-div ui-inline-cancel' "+ocl+"><span class='ui-icon ui-icon-cancel'></span></div>";

        return "<div style='margin-left:8px;'>" + str + "</div>";
    }


    this.setParticipantGridExtension = function setParticipantGridExtension(){
        $.extend($.jgrid.edit, {
            addCaption: lblAddParticipant,
            editCaption: lblEditParticipant,
            bSubmit: lblSave,
            bCancel: lblCancel,
            width:300,

            recreateForm: true,
            beforeShowForm: function () {

            },

            beforeSubmit: function(response, postData) {
                dashBoard.processAfterValidation(dashBoard.validParticipantInputForm($('#Name').val(),-1))

            }

        });

        $.extend($.jgrid.del, {

            caption: lblDeleteParticipant,
            msg: lblWantDeleteParticipant,
            beforeSubmit: function(response, postData) {
                dashBoard.deleteParticipant();
            }

        });
    }



    this.addRowsToParticipantGrid = function addRowsToParticipantGrid(data,isAdd){
        var names = ['SI', 'Name', 'Total Meal','Meal Charge','Total Charge','Total Paid','Balance',''];
        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(isAdd == true){
            for (var i = 0; i < mydata.length; i++) {


                $("#participant_grid").jqGrid('addRowData',data[i][0], mydata[i]);
            }
            //Set the page to the last page
        } else {


            $("#participant_grid").jqGrid('setRowData', data[0][0], mydata[0]);

        }


    }

    this.printExpense = function printExpense(){
        var data =[];
        var createdBy;

        for (var id in dashBoard.groupExpenses) {
            data.push(dashBoard.getFilteredExpenseObjPrint(dashBoard.groupExpenses[id]));

        }


        var balanceString = dashBoard.updateParticipantBalance();
        var balancePaymentHtml = "";
        if(balanceString != ""){

            var balanceStringArr = balanceString.split(",");


            for (var index in balanceStringArr) {

                var balanceStringval = balanceStringArr[index].split("|");
                balancePaymentHtml = balancePaymentHtml + dashBoard.participants[balanceStringval[0]].name+"|"+dashBoard.participants[balanceStringval[1]].name+"|"+dashBoard.showFormatedAmount(parseFloat(balanceStringval[2]))+",";
            }
        }

        for (var index in dashBoard.participants) {

            if(dashBoard.participants[index].isCreator == "1"){
                createdBy = dashBoard.participants[index].name;
                break;
            }
        }


        $("#printExpense").val(JSON.stringify(dashBoard.expense));
        $("#printExpenseList").val(JSON.stringify(data));
        $("#printBalance").val(JSON.stringify(balancePaymentHtml));
        $("#printNames").val(JSON.stringify(dashBoard.loginParticipantName+","+createdBy+","+dashBoard.getFormatedDbDate(dashBoard.expense.create_date)));
        $("#printOption").val(JSON.stringify("1"));
        $("#printForm").submit();

    }

    this.printMeals = function printMeals(){
        var data =[];
        var createdBy;

        for (var id in dashBoard.meals) {
            data.push(dashBoard.getFilteredMealObj(dashBoard.meals[id]));

        }


        var balanceString = dashBoard.resetParticipantBalance();
        var balancePaymentHtml = "";


        for (var index in dashBoard.participants) {

            if(dashBoard.participants[index].isCreator == "1"){
                createdBy = dashBoard.participants[index].name;
                break;
            }
        }


        $("#printExpense").val(JSON.stringify(dashBoard.expense));
        $("#printExpenseList").val(JSON.stringify(data));
        $("#printBalance").val(JSON.stringify(dashBoard.showMealFormatedAmount(dashBoard.totalMeal)+","+dashBoard.showMealFormatedAmount(dashBoard.yourMeal)+","+dashBoard.showFormatedAmount(dashBoard.totalCost)+","+dashBoard.showFormatedAmount(dashBoard.yourCost)));
        $("#printNames").val(JSON.stringify(dashBoard.loginParticipantName+","+createdBy+","+dashBoard.getFormatedDbDate(dashBoard.expense.create_date)));
        $("#printOption").val(JSON.stringify("2"));
        $("#printForm").submit();

    }


    this.printMyMeals = function printMyMeals(){
        var data =[];
        var createdBy;

        for (var id in dashBoard.meals) {
            data.push(dashBoard.getFilteredMyMealObj(dashBoard.meals[id]));

        }


        var balanceString = dashBoard.resetParticipantBalance();
        var balancePaymentHtml = "";


        for (var index in dashBoard.participants) {

            if(dashBoard.participants[index].isCreator == "1"){
                createdBy = dashBoard.participants[index].name;
                break;
            }
        }


        $("#printExpense").val(JSON.stringify(dashBoard.expense));
        $("#printExpenseList").val(JSON.stringify(data));
        $("#printBalance").val(JSON.stringify(dashBoard.showMealFormatedAmount(dashBoard.totalMeal)+","+dashBoard.showMealFormatedAmount(dashBoard.yourMeal)+","+dashBoard.showFormatedAmount(dashBoard.totalCost)+","+dashBoard.showFormatedAmount(dashBoard.yourCost)));
        $("#printNames").val(JSON.stringify(dashBoard.loginParticipantName+","+createdBy+","+dashBoard.getFormatedDbDate(dashBoard.expense.create_date)));
        $("#printOption").val(JSON.stringify("3"));
        $("#printForm").submit();

    }

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////




    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


    this.loadMealGrid = function loadMealGrid(){

        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.globalMealIndex;

        if(maxRowNum<101){
            maxRowNum = 100;
        }


        $("#meal_grid").jqGrid({
                datatype: "local",
                height: 232,
                title:false,
                colNames: ['SI', lblDate, lblDay, lblBreakfast, lblLunch, lblDinner, lblInvoles],
                colModel: [
                    {
                        name: 'SI',
                        index: 'SI',
                        width: 0,
                        sorttype: "int",
                        hidden:true,
                        key:true
                    },
                    {
                        name: 'Date',
                        index: 'Date',
                        width: 80,
                        align:'center',
                        sorttype:'date',
                        formoptions:{rowpos:3},
                        editable:true,
                        editrules:{required:true},
                        editoptions: {dataInit:initDateEdit}

                    },
                    {
                        name: 'Day',
                        index: 'Day',
                        align:'center',
                        width: 120,
                        editable: false,
                    },
                    {
                        name: 'Breakfast',
                        index: 'Breakfast',
                        align:'center',
                        width: 190,
                        formoptions:{rowpos:1},
                        editable: false,
                        sorttype: "float"

                    },
                    {
                        name: 'Lunch',
                        index: 'Lunch',
                        width: 90 ,
                        align:'center',

                        editable: false,


                    },
                    {
                        name: 'Dinner',
                        index: 'Dinner',
                        align:'center',
                        width: 150,
                        sorttype: "float"
                    },
                    {
                        name: 'Involves',
                        index: 'Involves',
                        align:'center',
                        width: 100,
                        sorttype: "float"
                    }
                ],
                rowNum      : maxRowNum,
                rowList:[10,20,50,maxRowNum],
                pager: '#meal_expense_pager',
                gridview:true,
                rownumbers:true,
                autoencode:true,
                ignoreCase:true,

                viewrecords: true,
                sortorder: 'desc',
                caption:lblMealList

            }



        );


        if(dashBoard.isMealGridLoadedAlready == 0){
            var mealData = [];
            for (var index in dashBoard.meals) {
                mealData.push(dashBoard.getDataByMeal(dashBoard.meals[index]));
            }

            dashBoard.addMealRowsToGrid(mealData);
            dashBoard.isMealGridLoadedAlready =1;
        }





        $("#meal_grid").jqGrid('setGridParam', {
                onSelectRow: function(rowid,iRow,iCol,e){

                    if(!iCol){

                        dashBoard.isAddMode = false;
                        dashBoard.loadForEdit();

                    }

                }
            }
        );

        $("#meal_grid").jqGrid('setGridParam', {ondblClickRow: function(rowid,iRow,iCol,e){
            dashBoard.isAddMode = false;
            jQuery(this).jqGrid('editGridRow', rowid);

        }});

        $("#meal_grid").jqGrid('navGrid','#meal_expense_pager',{
                add:true,addtitle: lblAddMealInformation,
                edit:true,edittitle: lblEditMealInformation,
                del:true,deltitle: lblDeleteMealInformation ,
                search:true,searchtitle: lblFindMealInformation
            },
            { // Edit
                recreateForm: true,
                beforeInitData: function () {

                    dashBoard.isAddMode = false;

                }
            },
            { // Add
                recreateForm: true,
                beforeInitData: function () {
                    dashBoard.isAddMode = true;

                }
            }

        );

        dashBoard.setMealAmtHtmlFormat();
        dashBoard.setMealGridExtension();


        jQuery("#meal_grid").setGridParam({rowNum:maxRowNum}).trigger("reloadGrid");

        $('.ui-jqgrid-bdiv').scrollTop($('#meal_grid')[0].scrollHeight);

    }

    this.setMealGridExtension = function setMealGridExtension(){

        $.extend($.jgrid.edit, {
            addCaption: lblAddMealInformation,
            editCaption: lblEditMealInformation,
            bSubmit: lblSave,
            bCancel: lblCancel,
            width:300,

            recreateForm: true,
            beforeShowForm: function () {

                if(dashBoard.isAddMode == true){

                    $('#tr_Date>td.DataTD>input').insertAfter( '   ');

                    $(dashBoard.mealAmtHtmlFormat).insertAfter("#tr_Date");

                    $('<a >'+lblSaveContinue+'<span class="ui-icon ui-icon-disk"></span></a>')
                        .click(function() {
                            dashBoard.validateMealAddForm(0);
                        })
                        .addClass("fm-button ui-state-default ui-corner-all fm-button-icon-left")
                        .prependTo("#Act_Buttons>td.EditButton");


                    dashBoard.refreshParticipantsMealProperties();
                    dashBoard.setAllCheckImpactMeal();
                    dashBoard.setUIMealDate();

                    $("#Date").val(dashBoard.maxMealDate);
                } else {
                    dashBoard.loadForEditMeal();

                }
            },

            beforeSubmit: function(response, postData) {

                dashBoard.validateMealAddForm(1);

            }

        });

        $.extend($.jgrid.del, {

            caption: lblDeleteMeal,
            msg: lblWantDeleteMeal,
            beforeSubmit: function(response, postData) {
                dashBoard.deleteMeal();
            }

        });
    }


}


function isValidDate(dateArray){

    var errorMessage = "";
    var error = lblDateNotValid;

    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];
    }
    //Jan/2017/25 12:44:33 UTC
    var formatedDateStr = dateArray[1]+"/"+dateArray[2]+"/"+dateArray[0]+" "+"00:00:00"+ " UTC"  ;
    return (new Date(formatedDateStr).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 addMeal(){

    if(dashBoard.isAddMode == true){
        dashBoard.addMealToGrid();


    } else {
        dashBoard.addMealToGrid();


    }

}



function sendDataToServer(formData,formName){


    var formUrl = $(formName).attr('action');

    $.ajax({
        type: 'POST',
        url: formUrl,
        data: formData,
        success: function(data,textStatus,xhr){

            if(data.trim()  == "+000"){

            } else{

                alert(lblDataSavingFailed);
            }
        },
        error: function(xhr,textStatus,error){

        }
    });

}

function loadData(formData,formName){


    //get form action

    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"){


            } else{

            }
        },
        error: function(xhr,textStatus,error){

        }
    });

}



$('#sendEmailForm').submit(function(){

    

    return false;
});


$('#viewLogForm').submit(function(){

    $("#ExpenseLogExpenseId").val(dashBoard.expense.id);
    $(".submit").css("float", "left");
    document.getElementById('loadImg').style.display='inline-block'

    //serialize form data
    var formData = $(this).serialize();

    //get form action
    var formUrl = $(this).attr('action');


    $.ajax({
        type: 'POST',
        url: formUrl,
        data: formData,
        success: function(data,textStatus,xhr){
            $('#log_grid').jqGrid('GridUnload');
            dashBoard.generateLogList(data,2);
            document.getElementById("loadImg").style.display = "none";
        },
        error: function(xhr,textStatus,error){

        }
    });

    return false;
});




$('#updateGroupExpenseForm').submit(function(){


    return false;
});

function showMessage(message){
    $("#error_dialog" ).html(message);
    $("#error_dialog" ).dialog();
}

function sendEmail(formData,formName){



}





function Expense(){
    this.id;
    this.unique_url;
    this.title;
    this.currency;
    this.description;
    this.create_date;
    this.defaultMeal;
    this.version
}



function Meal(){
    this.id;
    this.expenseId;
    this.date;
    this.oldDate;
    this.isAdd;
    this.participantMealStr;

}



function GroupExpense(){

    this.id;
    this.expenseType;
    this.expenseId;
    this.isAdd;
    this.paidBy;
    this.expenseName;
    this.amount;
    this.participantAmountStr;
    this.expenseDate;
    this.participantAmtHtml;
    this.noOfNotes;
    this.noOfModification;
    this.isDetails;
    this.isreimburse;
    this.previousDesc;
    this.newDesc;
    this.previousPaidBy;
    this.type;//1=normal expense,2=balance entry
}

function FilteredGroupExpense(){
    this.id;
    this.expenseType;
    this.paidBy;
    this.amount;
    this.expenseName;
    this.expenseDate;
    this.involves;
    this.forYou;
    this.noOfNotes;
    this.noOfModification;
}

function FilteredMeal(){
    this.id;
    this.date;
    this.day;
    this.breakfast;
    this.lunch;
    this.dinner;
    this.involves;
}

function Log(){
    this.expenseId;
    this.fromDate;
    this.toDate;
}
function Email(){
    this.email;
    this.uniqueURL;
    this.title;
}



function Participant(){
    this.id;
    this.name;
    this.isCreator;
    this.create_date;
    this.balance;
    this.numberOfMeal;
    this.mealCost;
    this.totalPaid;
    this.totalSpent;
    this.isFreeze;
    this.currentInputExpensePart;
    this.currentInputExpenseFreezeAmt;
    this.breakfast;
    this.lunch;
    this.dinner;
    this.expense_id;
    this.isAdd;
    this.isDeletable;

}
