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>"+lblExpenseNotFound+"</h3></center>");
        $("#create-participant").hide();
        return;
    }


    var loadTabs = new LoadTabs();
    loadTabs.startLoading( $.parseJSON($("#expenseData").val()));
    //  alert("hello");

    //''alert($("#expenseData").val());

    // $("#dvLoading").show();

    //var expenseObj = new Expense();
    //expenseObj.unique_url = $("#unique_url").val();

    // loadData(expenseObj,"#loadForm");



//	var loadTabs = new LoadTabs();


    // loadTabs.startLoading();
});



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();
        //var participantIndex = 0;
        //var groupExpenseIndex = 0


        $.each( expenseInfoObj, function( key, val ) {
            //alert(key);
            if(key == "Expense"){

                var expenseObj = new Expense();
                expenseObj.id = val.id;
                expenseObj.unique_url = val.unique_url;
                expenseObj.title = val.title;
                expenseObj.currency= val.currency;
                expenseObj.description = val.description;
                expenseObj.create_date = val.create_date;
                expenseObj.version = val.version;


                dashBoard.expense = expenseObj;


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

                // $(document.body).append(object.id);


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

                     expObj.id =



                     $(document.body).append(i+"="+object);
                    });
                 */
            } 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.totalPaid = 0;
                    participantObj.totalSpent = 0;
                    participantObj.balance = 0;

                    //set login participant Id and name
                    /* if(participantObj.isCreator == "1"){
                         dashBoard.loginParticipantId = participantObj.id;
                         dashBoard.loginParticipantName = participantObj.name;
                     }*/

                    dashBoard.participants[participantObj.id] = participantObj;
                    // $(document.body).append(i+"="+object);
                });

                /* $.each(val, function (i, object) {
                     $(document.body).append(i+"="+object);
                    });*/
                //participantObj.push(val);
            } else if(key === "GroupExpense"){
                $.each(val, function (i, object) {
                    // alert("hello");
                    //  alert(object.expense_date_new);
                    var groupExpense = new GroupExpense();
                    //  groupExpense.index = dashBoard.globalExpenseIndex;
                    groupExpense.id = object.id;
                    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;
                    // alert(object.type);

                    dashBoard.groupExpenses[groupExpense.id] = groupExpense;
                    dashBoard.globalExpenseIndex++;
                    // alert(dashBoard.groupExpenses[object.id]);

                    // $(document.body).append(i+"="+object);
                });
            }


        });


        dashBoard.displayCovePage();

        /* for (var index in dashBoard.groupExpenses) {
         alet( dashBoard.groupExpenses[index].id);
         break;
         }*/



        //dashBoard.showExpenseList();

        dashBoard.setCurrentDate();

    }
}





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

    this.gridData = [];

    this.participantAmtHtmlFormat = "";

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

    this.paidByHtml = "";

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

    this.currentDate ;

    this.isAddMode = true;
    //this.isParticipantAddMode = true;

    this.globalExpenseIndex = 0;



    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(lblCreatedBy+createdBy+lblOn+dashBoard.getFormatedDbDate(dashBoard.expense.create_date));

            $("#tabs" ).tabs( { active: 2 } );
            dashBoard.resetParticipantBalance();
            dashBoard.displayParticipantList();
            dashBoard.setParticipantGridExtension();
        } else{

            //hide loading
            $("#dvLoading").hide();
            //show list of participant

            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 + '<tr><td><a href="#" style="cursor:pointer;" onClick=dashBoard.loginParticipant('+"'"+dashBoard.participants[index].id+"'"+')>'+dashBoard.participants[index].name+'</a></td></tr>';
        }

        participantListHtml = participantListHtml + "</table>" ;


        $("#expenseCreatedByDiv").html("Created By "+createdBy+" on "+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(lblLoggedInAs+"<b>"+dashBoard.loginParticipantName+"</b> <a  style= \"cursor:pointer;	color: #0757A4\" onClick=\"dashBoard.logout()\">[Quit]</a>");

        dashBoard.showExpenseList();
        //show print options
        $("#printOptionId").show();

        $("#participantBox").hide();
        $("#tabs").show();
        // $("#basic_Info").html("login as "+ dashBoard.loginParticipantName+ " &nbsp;&nbsp; <a   onClick='dashBoard.printExpense()' style=cursor:pointer>Print</a>");
        dashBoard.setPaidBy(dashBoard.loginParticipantId);
    }

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

    /*
    this.getParticipantNameById = function getParticipantNameById(id){
         return dashBoard.participants[id].name;
    }
    */
    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(["Record Not Found"]);

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

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

                        }

                    ],



                    gridview:true,

                    viewrecords: true,

                    caption:'Expense Log'
                }

            );





            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,
                    // sortname: 'invdate',
                    viewrecords: true,
                    sortorder: 'desc',
                    caption:'Expense Log'
                }

            );


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

            );


            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]);
            }

        }

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

    }


    this.showExpenseList = function showExpenseList(){


        //	alert(this.groupExpenses.length)
        dashBoard.gridData = [];
        dashBoard.isAddMode = true;
        //var data = [];
        //$.each(this.groupExpenses, function( key, value ) {

        //var filteredGroupExpenseObj = dashBoard.getFilteredExpenseObj(key,value);

        //dashBoard.filteredGroupExpenses[key] = filteredGroupExpenseObj;
        for (var index in dashBoard.groupExpenses) {
            dashBoard.gridData.push(dashBoard.getDataByExpense(dashBoard.groupExpenses[index]));
        }

        // alert(value);
        //	data.push([value.id,  dashBoard.getParticipantNameById(value.paidBy), dashBoard.getFormatedAmount(value.amount), value.expenseName, dashBoard.getFormatedDate(value.expenseDate),dashBoard.getInvolveString(value.involves),dashBoard.getForYouString(value.involves)]);
        //data[]
        //});

        //alert(dashBoard.gridData[0]);

        dashBoard.setParticipantAmtHtmlFormat();

        dashBoard.reloadGrid();


        /*data.sort(function(a, b) {
          if(a.value < b.value) return 1;
          if(a.value > b.value) return -1;
          return 0;
        });*/

        //	alert(data);
        //var data = [["48803", "DSK1", "", "02200220", "OPEN","OPEN","OPEN","OPEN","OPEN","OPEN"], ["48804", "DSK1", "", "02200220", "OPEN","OPEN","OPEN",]];
        //(data1);
    }


    this.getDataByExpense = function getDataByExpense(groupExpenseObj){

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

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

    this.getFilteredExpenseObj = function getFilteredExpenseObj(groupExpenseObj){

        var filteredGroupExpenseObj = new FilteredGroupExpense();

        filteredGroupExpenseObj.id = groupExpenseObj.id;
        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);
        filteredGroupExpenseObj.involves=dashBoard.getInvolveString(groupExpenseObj.participantAmountStr);
        filteredGroupExpenseObj.forYou=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.paidBy = dashBoard.participants[groupExpenseObj.paidBy].name;
        filteredGroupExpenseObj.amount = dashBoard.showFormatedAmount(groupExpenseObj.amount);
        filteredGroupExpenseObj.expenseName=groupExpenseObj.expenseName;
        filteredGroupExpenseObj.expenseDate = groupExpenseObj.expenseDate;//dashBoard.getFormatedDate(groupExpenseObj.expenseDate);
        filteredGroupExpenseObj.involves=dashBoard.getInvolveString(groupExpenseObj.participantAmountStr);
        filteredGroupExpenseObj.forYou=dashBoard.getForYouStringPrint(groupExpenseObj.participantAmountStr);
        filteredGroupExpenseObj.noOfNotes=groupExpenseObj.noOfNotes;
        filteredGroupExpenseObj.noOfModification=groupExpenseObj.noOfModification;

        return filteredGroupExpenseObj;
    }

    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);
        };
        //  alert(dashBoard.groupExpenses.length);
        var maxRowNum = dashBoard.globalExpenseIndex;

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


        $("#grid").jqGrid({
                datatype: "local",
                height: 232,
                title:false,
                colNames: ['SI', 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: '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 () {

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

                                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",
                        cellattr: function (rowId, tv, rawObject, cm, rdata) { return 'style="white-space: normal !important;"' }
                    },
                    {
                        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,
                // sortname: 'invdate',
                viewrecords: true,
                sortorder: 'desc',
                caption:lblExpenseList

                // ondblClickRow: function(rowid,iRow,iCol,e){alert('double clicked');}
            }



        );
        //jQuery("#grid").setGridParam({rowNum:10}).trigger("reloadGrid");

        dashBoard.addRowsToGrid(dashBoard.gridData);



        //	$(".ui-jqgrid-titlebar").hide();

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

                    if(!iCol){
                        //alert(rowid);
                        dashBoard.removeParticipantAmtRows();
                        dashBoard.isAddMode = false;
                        dashBoard.loadForEdit();
                        //jQuery(this).jqGrid('editGridRow', rowid);
                    }

                }
            }
        );

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

        }});

        //$("#grid").jqGrid('setGridParam', { onRightClickRow: function(rowid,iRow,iCol,e){alert('Right Click!');}});

        $("#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;
                    // alert("in edit");
                    // inEdit = true;
                }
            },
            { // Add
                recreateForm: true,
                beforeInitData: function () {
                    dashBoard.isAddMode = true;
                    // inEdit = false;
                }
            }

        );


        dashBoard.setExpenseGridExtension();

        //$('html, body').animate({scrollBottom: $("#gbox_grid").offset().bottom}, 2000);

        jQuery("#grid").setGridParam({rowNum:maxRowNum}).trigger("reloadGrid");
        // alert($('#grid')[0].scrollHeight);

        $('.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 parentDiv = dlgDiv.parent(); // div#gbox_list
                     var dlgWidth = dlgDiv.width();
                     var parentWidth = parentDiv.width();
                     var dlgHeight = dlgDiv.height();
                     var parentHeight = parentDiv.height();
                     // TODO: change parentWidth and parentHeight in case of the grid
                     //       is larger as the browser window
                     dlgDiv[0].style.top = Math.round((parentHeight-dlgHeight)/2) + "px";
                     dlgDiv[0].style.left = Math.round((parentWidth-dlgWidth)/2) + "px";


                     alert("hello");*/

                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);
                    $("#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_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");
        //   alert("in LoadForEdit");

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

        //alert(dashBoard.groupExpenses.length);
        var rowData = jQuery("#grid").getRowData(rowId);
        //alert(dashBoard.groupExpenses[rowData['SI']].id);
        dashBoard.showEditUI(dashBoard.groupExpenses[rowData['SI']]);
        $('#PaidBy').find('option').remove().end().append(dashBoard.paidByHtml);
    }

    this.changeSingleInvolve = function changeSingleInvolve(participantId){

        if($("#chkParticipant"+participantId).is(':checked')){

            dashBoard.participants[participantId].currentInputExpensePart = 1;
        } else {
            $("#chkParticipant"+participantId).prop('checked', false);
            $("#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.changeDetailsPart = function changeDetailsPart(participantId){

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

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


        if(filteredValue != "" && parseInt(filteredValue) != dashBoard.participants[participantId].currentInputExpensePart){
            // alert("1");
            dashBoard.participants[participantId].currentInputExpensePart = parseInt(filteredValue);
            dashBoard.participants[participantId].isFreeze = 0;


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

        } else if(originalValue != "") {
            // alert("2");

            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].isFreeze = 0
                dashBoard.participants[participantId].currentInputExpensePart = 0;
            }

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

        }


    }

    this.changeDetailsFreeze = function changeDetailsFreeze(participantId){
        //alert("hello")
        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))){
            //alert("1");
            //validate if all the freeze amount exceed the input amount, set the current freeze amount =  input-(all other freeze amount)
            //filteredValue =
            //dashBoard.setFreezeOnUI(participantId,filteredValue);

            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 == "") {
            //alert("3");
            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(){

        //alert(participantId);
        //alert(dashBoard.participants[participantId].isFreeze);
        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');
                /*if($("#participantTextPart"+participantId).hasProp("background-color")){
                    $("#participantTextPart"+participantId).removeProp("background-color");
                }*/

            }

        }

    }

    /*this.setFreezeOnUI = function setFreezeOnUI(participantId,newValue){
        if(parseFloat(dashBoard.participants[participantId].currentInputExpenseFreezeAmt) != parseFloat(newValue)){
            $("#participantTextPart"+participantId).prop("value", '');
            $("#participantTextPart"+participantId).css('background-color' , '#DEDEDE');
        }
    }*/



    this.scanParticipantCheckBoxs = function scanParticipantCheckBoxs(){

        var isAllCheck = true;
        var numberOfInvolves = 0;
        var totalParticipant = 0;

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

        //dashBoard.participants.length

        if(numberOfInvolves == totalParticipant){
            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) {

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

            noOfParticipant++;

        }

        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;
            //commonValue = dashBoard.getFormatedAmount(dashBoard.currentInputAmount/dashBoard.getNumberOfParticipants());
        }

        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);
            }



            //$("#pamount_"+dashBoard.participants[index].id).html(commonValue+" "+dashBoard.expense.currency);


        }

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

    }



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

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

            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))){
            //if totalFreeze amount exceed expense input reset all the parts and freeze amount equal

            //totalFreezeAmt = dashBoard.getFormatedAmount(0);
            //dashBoard.resetAllPartAndFreezeAmt();
            //totalParts = dashBoard.getNumberOfParticipants();
        } else if(dashBoard.getFormatedAmount(dashBoard.currentInputAmount)>0 && parseFloat(totalFreezeAmt) == parseFloat(dashBoard.currentInputAmount)){
            //if totalFreeze amount is equal to expense input amount,no need to keep part for where isFreeze=0
            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);
                //Freeze amount can not be negative
                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(){
        /*for (var index in dashBoard.participants) {
            if(dashBoard.participants[index].isFreeze == 0){
                //dashBoard.participants[index].currentInputExpensePart = 0;
            }
        }*/
    }

    this.updateBalance = function updateBalance(){
        //balance
    }


    this.setParticipantAmtHtmlFormat = function setParticipantAmtHtmlFormat(){
        dashBoard.paidByHtml = "";
        var 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">All <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>';
        /*var 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">Breakdown</td></tr>';
        result += '<tr id="tr_selectAll" class="FormData" rowpos="6"><td class="CaptionTD"></td><td class="DataTD">&nbsp;<input class="FormElement ui-widget-content ui-corner-all" role="checkbox" name="selectAll" id="selectAll" onClick="dashBoard.setAllCheckImpact()" checked type="checkbox">Check All</td></tr>';

        for (var index in dashBoard.participants) {

            result += '<tr id="tr_Participant'+dashBoard.participants[index].id+'" class="FormData" rowpos="7"><td class="CaptionTD"><input onClick="dashBoard.changeSingleInvolve('+"'"+dashBoard.participants[index].id+"'"+')" class="FormElement ui-widget-content ui-corner-all" role="checkbox" name="Participant'+dashBoard.participants[index].id+'" id="chkParticipant'+dashBoard.participants[index].id+'" type="checkbox">'+ dashBoard.participants[index].name+' </td><td class="DataTD"><div id="pamount_'+dashBoard.participants[index].id+'"></div></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.setPaidBy = function setPaidBy(selectedParticipantId){

        dashBoard.paidByHtml = "";

        for (var index in dashBoard.participants) {
            //alert(dashBoard.participants[index].id);
            //alert(selectedParticipantId);
            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.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);
        }
        dashBoard.setParticipantAmountInfoByAmtStr(expenseObj.participantAmountStr);

        dashBoard.currentInputAmount = expenseObj.amount;

        //hide show details section
        //	alert(expenseObj.isDetails);
        if(expenseObj.isDetails == 1){
            dashBoard.hideShowParticipantDetails(true);
            $("#Details").prop('checked', true);
            dashBoard.setDetailsCheckImpact();
        } else {
            dashBoard.hideShowParticipantDetails(false)
            dashBoard.setDetailsCheckImpact();
        }


        /*		this.isFreeze;
                this.currentInputExpensePart;
                this.currentInputExpenseFreezeAmt;	*/
        //alert(expenseObj.paidBy);
        //alert(expenseObj.paidBy);


        //dashBoard.calculateFinalFreezeExpenseAmount();

        //dashBoard.showFreezeAmount();
        //dashBoard.setShadowOnPartTextBox();
        //alert(dashBoard.paidByHtml);
        /*for (var index in dashBoard.participants) {

            $("#chkParticipant"+dashBoard.participants[index].id).check(true);
        }*/
    }

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

        var dateObj = new Date((new Date(date*1000)).toUTCString());
        //return date.getdays()+"/"+date.getMonths()+"/"+date.getYears(); var a = new Date(UNIX_timestamp*1000);
        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("-");
            //return date.getdays()+"/"+date.getMonths()+"/"+date.getYears(); var a = new Date(UNIX_timestamp*1000);
            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();
        //return date.getdays()+"/"+date.getMonths()+"/"+date.getYears(); var a = new Date(UNIX_timestamp*1000);
        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.getForYouStringPrint = function getForYouStringPrint(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.showFormatedAmount(participantAndAmountArray[2]);
            }
        }

        if(forYou==""){
            forYou = dashBoard.showFormatedAmount(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(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 = lblDateNotValid;
                } else {
                    errorMessage = isValidDate(dateArray);
                }
            }
        }


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

            dashBoard.clearErrorMessage();
            addExpense();
            if(source == 1){
                $(".ui-icon-closethick").trigger('click');
            } else {
                dashBoard.clearAddForm();
            }
        }

    }

    this.showErrorMessage = function showErrorMessage(msg){
        $("#FormError").show();
        $(".ui-state-error").html(msg);
    }

    this.clearErrorMessage = function clearErrorMessage(){
        $("#FormError").hide();
        $(".ui-state-error").html("");
    }

    this.clearAddForm = function clearAddForm(){
        $('#Reason').val("");
        $('#Amount').val("");
        $("#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', '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++) {

                //alert(i + 1);
                //alert(mydata[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.getExpenseUniqueId = function getExpenseUniqueId(){

        var maxExpId = 0;
        var extractedIndex = 0;
        var expenseIdArray;
        //for(var i=0;i<dashBoard.groupExpenses.length;i++){
        for (var id in dashBoard.groupExpenses) {
            //alert("2");
            expenseIdArray = dashBoard.groupExpenses[id].id.split("-");
            //alert("3");
            if(expenseIdArray[0]== dashBoard.loginParticipantId &&  maxExpId < parseInt(expenseIdArray[1])){
                //alert("4");
                maxExpId = parseInt(expenseIdArray[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){
            //alert(oldExpObj.expenseName);
            //alert(newExpObj.expenseName);
            isChanged = true;
        } else if(oldExpObj.paidBy != newExpObj.paidBy){
            //alert("in paid by");
            isChanged = true;
        } else if(oldExpObj.expenseDate != newExpObj.expenseDate){
            ///alert(oldExpObj.expenseDate);
            //	alert(newExpObj.expenseDate);
            //alert("in date");
            isChanged = true;
        } else if(parseFloat(oldExpObj.amount) != parseFloat(newExpObj.amount)){
            isChanged = true;
        } else if(oldExpObj.participantAmountStr != newExpObj.participantAmountStr){
            //	alert(oldExpObj.participantAmountStr);
            //alert(newExpObj.participantAmountStr);
            isChanged = true;
        }

        //alert(isChanged);
        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.index = dashBoard.globalExpenseIndex++;
            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.index  = dashBoard.currentEditGroupExpense.index;
            groupExpenseObj.id = dashBoard.currentEditGroupExpense.id;

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

        }


        groupExpenseObj.isreimburse = 0;


        dashBoard.processExpenseData(groupExpenseObj);

        //alert("changing....");
    }

    this.processExpenseData = function processExpenseData(groupExpenseObj){

        dashBoard.groupExpenses[groupExpenseObj.id] =  groupExpenseObj;

        sendDataToServer(groupExpenseObj,"#expenseForm");


        var data = [];
        //alert(dashBoard.getDataByExpense(groupExpenseObj.index,groupExpenseObj));

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

        dashBoard.addRowsToGrid(data);

        //go to the last page after adding record
        dashBoard.setPageAfterAdd('#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:";

        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;

        return groupExpenseObj;
    }

    this.deleteExpense = function deleteExpense(){

        var rowId =$("#grid").jqGrid('getGridParam','selrow');
        var i;
        /*alert(rowId);
        for(var index in dashBoard.groupExpenses){
            alert(dashBoard.groupExpenses[index].id);
            break;
        }
        */
        $('#grid').jqGrid('delRowData', rowId);
        var deletedExpObj = dashBoard.groupExpenses[rowId];
        //alert(deletedExpObj.expenseName);
        delete dashBoard.groupExpenses[rowId];
        //alert(deletedExpObj.id);
        deletedExpObj.isAdd = "3";

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

        /*for(i=rowId-1;i<dashBoard.groupExpenses.length-1;i++){
            dashBoard.groupExpenses[i] = dashBoard.groupExpenses[i+1];
        }
        */
        //reduce global expense index
        //dashBoard.globalExpenseIndex--;

        //call ajax for DB update

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


    }




    this.resetParticipantBalance = function resetParticipantBalance(){

        var amtStr = "";
        var paidBy ;
        var amount;


        for (var index in dashBoard.participants) {
            dashBoard.participants[index].totalPaid = dashBoard.getFormatedAmountDB(parseFloat(0));
            dashBoard.participants[index].totalSpent = dashBoard.getFormatedAmountDB(parseFloat(0));
            dashBoard.participants[index].balance = dashBoard.getFormatedAmountDB(parseFloat(0));
            dashBoard.participants[index].isDeletable = 1;

        }

        //for(var i=0;i<dashBoard.groupExpenses.length;i++){
        for (var id in dashBoard.groupExpenses) {
            amtStr =  dashBoard.groupExpenses[id].participantAmountStr;
            paidBy =  dashBoard.groupExpenses[id].paidBy;
            amount =  dashBoard.groupExpenses[id].amount;

            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]));
                //participantBalance[participantAndAmountArray[0]] = dashBoard.getFormatedAmountDB(parseFloat(participantBalance[participantAndAmountArray[0]]) - parseFloat(participantAndAmountArray[2]));
            }

            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));

            //participantBalance[paidBy] = dashBoard.getFormatedAmountDB(parseFloat(participantBalance[paidBy]) + parseFloat(amount));
        }

    }

    this.updateParticipantBalance = function updateParticipantBalance(){

        //var isReady = false;
        //	var participantBalance = [];
        var balanceEntryParticipantBalance = [];
        var balanceString = "";

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

        //reset all participant balance
        for (var index in dashBoard.participants) {
            //dashBoard.participants[index].balance = dashBoard.getFormatedAmountDB(parseFloat(0));
            //participantBalance[index] = dashBoard.getFormatedAmountDB(parseFloat(0));
            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


        //scan and shift positive and negative

        //sort positive and negative again

        //calculate who needs to pay whom



        //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);

        }
        //alert(balanceString);
        return balanceString;


    }

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

        var result  = 0;
        var participantIndex='';
        for (var index in balanceList) {
            //alert(dashBoard.showFormatedAmount(parseFloat(balanceList[index])));
            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");
        //	$('#balance_chart_image').append(imgElem);​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
    }


    this.downloadImage = function downloadImage(imageURL) {
        /* var oImage = document.getElementById(imageURL);
         var canvas = document.createElement("canvas");
         document.body.appendChild(canvas);
         if (typeof canvas.getContext == "undefined" || !canvas.getContext) {
             alert("browser does not support this action, sorry");
             return false;
         }*/

        try {
            var img = document.getElementById(imageURL);

            // window.location.href = img.src.replace('image/png', 'image/octet-stream');
            window.open(img.src.replace('image/png', 'image/png'), "_blank");

            /* var context = canvas.getContext("2d");
             var width = oImage.width;
             var height = oImage.height;
             canvas.width = width;
             canvas.height = height;
             canvas.style.width = width + "px";
             canvas.style.height = height + "px";
             context.drawImage(oImage, 0, 0, width, height);
             var rawImageData = canvas.toDataURL("image/png;base64");
             rawImageData = rawImageData.replace("image/png", "image/octet-stream");
             document.location.href = rawImageData;
            // document.location.setAttribute("download", "YourFileName.jpeg");
             document.body.removeChild(canvas);*/
        }
        catch (err) {
            // document.body.removeChild(canvas);
            alert(lblCantDownload);
        }

        return true;
    }



    this.drawGraph = function drawGraph(){

        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++;
        }

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

        var options = {
            seriesDefaults:{
                renderer:$.jqplot.BarRenderer,
                rendererOptions: {fillToZero: true}
            },

            series:[
                {

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

                }


            ],

            negativeSeriesColors: ["#FF0000"],
            axes: {

                xaxis: {
                    renderer: $.jqplot.CategoryAxisRenderer,
                    ticks: ticks
                },

                yaxis: {
                    pad: 1.18,
                    tickOptions: {formatString: '%d '+dashBoard.expense.currency}
                }
            },
            title: {
                text: lblBalanceOf+'"'+dashBoard.expense.title+'"'

            },

        };


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

        dashBoard.showBalanceDetails(balanceString);

        //  dashBoard.createGraphImage();


    }


    this.showBalanceDetails = function showBalanceDetails(balanceString){

        var balancePaymentHtml = "";

        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>should pay to</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>';
            }
        }

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


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


        dashBoard.isAddMode = true;

        groupExpenseObj= new GroupExpense();
        //groupExpenseObj.index = dashBoard.globalExpenseIndex++;
        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;


        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 = LBL_EXPENSE_NAME_LESS_THAN_CHAR;
        }

        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);
        }
    }

    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.totalSpent == "undefined"){

            participantObj.totalSpent = 0;
        }

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

            participantObj.totalPaid = 0;
        }


        var data = [];
        //alert(dashBoard.getDataByExpense(groupExpenseObj.index,groupExpenseObj));
        //alert([participantObj.id, participantObj.name,dashBoard.showFormatedAmount(participantObj.balance)+" "+dashBoard.expense.currency,""]);
        data.push([participantObj.id, participantObj.name,dashBoard.showFormatedAmount(participantObj.totalSpent)+" "+dashBoard.expense.currency,dashBoard.showFormatedAmount(participantObj.totalPaid)+" "+dashBoard.expense.currency,dashBoard.showFormatedAmount(participantObj.balance)+" "+dashBoard.expense.currency,""]);

        //alert(participantObj.name);

        //dashBoard.setParticipantAmtHtmlFormat();

        //go to the last page after adding record

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

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

        //	$('#participant_grid').jqGrid('GridUnload');
        //dashBoard.displayParticipantList();

        dashBoard.setPageAfterAdd('#participant_grid');

        sendDataToServer(participantObj,"#participantForm");


    }

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

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

        //alert(oldName);
        //alert(newName);


        var participantObj = new Participant();
        participantObj.id =  participantId;
        //participantObj.oldName = oldName;
        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 = [];
        // alert([existingPartcipantObj.id, existingPartcipantObj.name,dashBoard.showFormatedAmount(existingPartcipantObj.balance)+" "+dashBoard.expense.currency,""]);
        data.push([existingPartcipantObj.id, existingPartcipantObj.name,dashBoard.showFormatedAmount(existingPartcipantObj.totalSpent)+" "+dashBoard.expense.currency,dashBoard.showFormatedAmount(existingPartcipantObj.totalPaid)+" "+dashBoard.expense.currency,dashBoard.showFormatedAmount(existingPartcipantObj.balance)+" "+dashBoard.expense.currency,""]);
        // alert("helo2");
        dashBoard.addRowsToParticipantGrid(data,false);
        //dashBoard.setParticipantAmtHtmlFormat();
        //alert("helo3");
        //jQuery("#participant_grid").trigger("reloadGrid");
        $('#grid').jqGrid('GridUnload');
        dashBoard.showExpenseList();
        //alert("helo4");
        $("#participant_grid").trigger("reloadGrid");
        dashBoard.setParticipantGridExtension();

        // alert("helo5");
        //dashBoard.setPageAfterAdd('#participant_grid');
        //alert("helo5");
        //$('#participant_grid').jqGrid('GridUnload');
        //dashBoard.displayParticipantList();
        //alert(participantObj.id);


        sendDataToServer(participantObj,"#participantForm");

    }

    this.deleteParticipant = function deleteParticipant(index){
        //alert("hello");
        var rowId =$("#participant_grid").jqGrid('getGridParam','selrow');

        //	alert(rowId);
        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;
        //alert(rowData['SI']);
        //delete record from list
        //dashBoard.participants[participantObj.id]
        //alert(rowId);
        $('#participant_grid').jqGrid('delRowData', rowId);

        delete dashBoard.participants[ participantObj.id];
        //alert(dashBoard.participants[ participantObj.id]);
        //dashBoard.setParticipantAmtHtmlFormat();


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

        //	$('#participant_grid').jqGrid('GridUnload');
        //dashBoard.displayParticipantList();

        dashBoard.setParticipantGridExtension();

        dashBoard.setPageAfterDelete('#participant_grid');
        //alert(participantObj.id);
        //alert(participantObj.name);

        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, lblTotalCharge, lblTotalPaid, lblBalance,''],
                colModel: [
                    {
                        name: 'SI',
                        index: 'SI',
                        width: 0,
                        sorttype: "int",
                        hidden:true
                    },
                    {
                        name: 'Name',
                        index: 'Name',
                        width: 180 ,
                        align:'center',
                        editable: true

                    } ,

                    {
                        name: 'Total Charge',
                        index: 'Total Charge',
                        width: 160 ,
                        align:'center',


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


                    } ,

                    {
                        name: 'Balance',
                        index: 'Balance',
                        width: 170 ,
                        align:'center',


                    } ,
                    {
                        name: 'Action',
                        index: 'Action',
                        width: 90 ,
                        align:'center',
                        //formatter: 'actions',
                        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');
                                //	 alert(rowId);
                                var rowData = jQuery("#participant_grid").getRowData(rowId);
                                //alert(rowData['SI']);
                                var inputVal = $("#"+rowData['SI']+"_Name").val().trim();
                                //alert(dashBoard.participants[rowData['SI']].name);
                                //alert(inputVal);

                                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);
                                        //alert("saved!");
                                        //jQuery.fn.fmatter.rowactions.call(this,'save');
                                    } else {
                                        // $("#error_dialog" ).html(errorMsg);
                                        // $("#error_dialog").message("show");
                                        alert(errorMsg);

                                        /*$("#error_dialog" ).html(errorMsg);
                                        $("#error_dialog" ).dialog();*/
                                        $("#"+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,
                // sortname: 'invdate',
                viewrecords: true,
                sortorder: 'desc',
                caption:lblParticipantList,
                loadComplete: function(){
                    dashBoard.setParticipantGridExtension();
                }
            }

        );



        //$(".ui-jqgrid-titlebar").hide();

        $("#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 () {
                    // isParticipantAddMode = false;
                    ///alert("edit");
                }
            },
            { // Add
                recreateForm: true,
                beforeInitData: function () {
                    // isParticipantAddMode = true;
                    //alert("add");
                }
            }

        );

        $("#participant_grid").jqGrid('setGridParam', {ondblClickRow: function(rowid,iRow,iCol,e){
            //dashBoard.isAddMode = false;
            //jQuery(this).jqGrid('editGridRow', rowid);
            //var object = $("jEditButton_"+rowid);
            //alert(object);
            //	jQuery(this).jqGrid('editGridRow', rowid);
            jQuery.fn.fmatter.rowactions.call(document.getElementById("jEditButton_"+rowid),'edit');
            //alert("hello");
            //alert(rowid);

        }});



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

        //alert("row Id"+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='Edit Participant' 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='Delete Participant' 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 Charge','Total Paid', 'Balance',''];
        var mydata = [];
        // alert("in loop"+data.length);

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

                //alert(i + 1);
                //alert(mydata[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]));

        }

        //echo $this->Form->input('printExpense', array('type' => 'hidden','id'=>'printExpense'));
        //echo $this->Form->input('printBalance', array('type' => 'hidden','id'=>'printBalance'));


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

            var balanceStringArr = balanceString.split(",");
            //alert(balanceStringArr.length);

            for (var index in balanceStringArr) {
                //alert(balanceStringArr[index]);
                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)));

        $("#printForm").submit();

    }


}


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();
        //	sendDataToServer();

    } else {
        dashBoard.addExpenseToGrid();
        //sendDataToServer();

    }

    //ReloadBalance();
    //updateParticipantBalance();
}

function sendDataToServer(formData,formName){


}

function loadData(formData,formName){

    //$("#error_dialog" ).html("");
    // alert(formName);
    //get form action

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



    //alert(formUrl);
    // alert(formData);
    $.ajax({
        type: 'POST',
        url: formUrl,
        data: formData,
        success: function(data,textStatus,xhr){
            // alert(data);
            // $("#tabs").show();
            var loadTabs = new LoadTabs();
            loadTabs.startLoading( $.parseJSON(data));


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

                alert("Success")
            } else{
                //document.write(data);
                //  	alert("Data saving failed!");
            }
        },
        error: function(xhr,textStatus,error){
            //  alert(error);
        }
    });

}



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



    return false;
});


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


    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.version
}

function GroupExpense(){
    //this.index;
    this.id;
    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.paidBy;
    this.amount;
    this.expenseName;
    this.expenseDate;
    this.involves;
    this.forYou;
    this.noOfNotes;
    this.noOfModification;
}

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.totalPaid;
    this.totalSpent;
    this.balance;
    this.isFreeze;
    this.currentInputExpensePart;
    this.currentInputExpenseFreezeAmt;
    this.expense_id;
    this.isAdd;
    this.isDeletable;

}
