/* Minification failed. Returning unminified contents.
(3,1): run-time error CSS1019: Unexpected token, found '/'
(3,2): run-time error CSS1019: Unexpected token, found '/'
(3,80): run-time error CSS1031: Expected selector, found '('
(3,80): run-time error CSS1025: Expected comma or open brace, found '('
(28,1): run-time error CSS1019: Unexpected token, found '/'
(28,2): run-time error CSS1019: Unexpected token, found '/'
(28,77): run-time error CSS1030: Expected identifier, found ' '
(29,10): run-time error CSS1031: Expected selector, found 'getFeatureLayerInfoWindowContent('
(29,10): run-time error CSS1025: Expected comma or open brace, found 'getFeatureLayerInfoWindowContent('
(85,1): run-time error CSS1019: Unexpected token, found '/'
(85,2): run-time error CSS1019: Unexpected token, found '/'
(86,10): run-time error CSS1031: Expected selector, found 'deleteFeatureLayerTypePoint('
(86,10): run-time error CSS1025: Expected comma or open brace, found 'deleteFeatureLayerTypePoint('
(213,10): run-time error CSS1031: Expected selector, found 'deleteBldgStagingTable_Success('
(213,10): run-time error CSS1025: Expected comma or open brace, found 'deleteBldgStagingTable_Success('
(217,10): run-time error CSS1031: Expected selector, found 'deleteBldgStagingTable_Failure('
(217,10): run-time error CSS1025: Expected comma or open brace, found 'deleteBldgStagingTable_Failure('
(221,10): run-time error CSS1031: Expected selector, found 'updateLayerAttributes('
(221,10): run-time error CSS1025: Expected comma or open brace, found 'updateLayerAttributes('
(253,10): run-time error CSS1031: Expected selector, found 'hideAttributes('
(253,10): run-time error CSS1025: Expected comma or open brace, found 'hideAttributes('
(260,1): run-time error CSS1019: Unexpected token, found '/'
(260,2): run-time error CSS1019: Unexpected token, found '/'
(260,71): run-time error CSS1030: Expected identifier, found ' '
(261,10): run-time error CSS1031: Expected selector, found 'setFeatureAttributesValues('
(261,10): run-time error CSS1025: Expected comma or open brace, found 'setFeatureAttributesValues('
(277,1): run-time error CSS1019: Unexpected token, found '/'
(277,2): run-time error CSS1019: Unexpected token, found '/'
(277,57): run-time error CSS1031: Expected selector, found '('
(277,57): run-time error CSS1025: Expected comma or open brace, found '('
(379,10): run-time error CSS1031: Expected selector, found 'openDeletePointConfirmationDialogue('
(379,10): run-time error CSS1025: Expected comma or open brace, found 'openDeletePointConfirmationDialogue('
(501,10): run-time error CSS1031: Expected selector, found 'addNewPointOnMap('
(501,10): run-time error CSS1025: Expected comma or open brace, found 'addNewPointOnMap('
(543,90): run-time error CSS1002: Unterminated string: 's get that templates and use it  
(591,1): run-time error CSS1019: Unexpected token, found '/'
(591,2): run-time error CSS1019: Unexpected token, found '/'
(591,71): run-time error CSS1030: Expected identifier, found ' '
(592,10): run-time error CSS1031: Expected selector, found 'OpenFeatureLayerTypeInfoWindow('
(592,10): run-time error CSS1025: Expected comma or open brace, found 'OpenFeatureLayerTypeInfoWindow('
(631,10): run-time error CSS1031: Expected selector, found 'updateStagingTable_Success('
(631,10): run-time error CSS1025: Expected comma or open brace, found 'updateStagingTable_Success('
(635,10): run-time error CSS1031: Expected selector, found 'updateStagingTable_Failure('
(635,10): run-time error CSS1025: Expected comma or open brace, found 'updateStagingTable_Failure('
(643,1): run-time error CSS1019: Unexpected token, found '/'
(643,2): run-time error CSS1019: Unexpected token, found '/'
(644,1): run-time error CSS1031: Expected selector, found '/'
(644,1): run-time error CSS1025: Expected comma or open brace, found '/'
(656,10): run-time error CSS1031: Expected selector, found 'addGradingFeaturePoint('
(656,10): run-time error CSS1025: Expected comma or open brace, found 'addGradingFeaturePoint('
(756,90): run-time error CSS1002: Unterminated string: 's get that templates and use it  
(867,10): run-time error CSS1031: Expected selector, found 'showGradingFeatureAttributes('
(867,10): run-time error CSS1025: Expected comma or open brace, found 'showGradingFeatureAttributes('
(933,1): run-time error CSS1019: Unexpected token, found '/'
(933,2): run-time error CSS1019: Unexpected token, found '/'
(933,77): run-time error CSS1030: Expected identifier, found ' '
(934,10): run-time error CSS1031: Expected selector, found 'getGradingFeatureLayerInfoWindowContent('
(934,10): run-time error CSS1025: Expected comma or open brace, found 'getGradingFeatureLayerInfoWindowContent('
(939,1): run-time error CSS1019: Unexpected token, found '/'
(939,2): run-time error CSS1019: Unexpected token, found '/'
(940,10): run-time error CSS1031: Expected selector, found 'deleteGradingPoint('
(940,10): run-time error CSS1025: Expected comma or open brace, found 'deleteGradingPoint('
(961,10): run-time error CSS1031: Expected selector, found 'addGradingPoint_Success('
(961,10): run-time error CSS1025: Expected comma or open brace, found 'addGradingPoint_Success('
(965,10): run-time error CSS1031: Expected selector, found 'deleteGrading_Failure('
(965,10): run-time error CSS1025: Expected comma or open brace, found 'deleteGrading_Failure('
(969,10): run-time error CSS1031: Expected selector, found 'deleteGradingPoint_Success('
(969,10): run-time error CSS1025: Expected comma or open brace, found 'deleteGradingPoint_Success('
(973,10): run-time error CSS1031: Expected selector, found 'addGrading_Failure('
(973,10): run-time error CSS1025: Expected comma or open brace, found 'addGrading_Failure('
(977,10): run-time error CSS1031: Expected selector, found 'getGradingPoint_Success('
(977,10): run-time error CSS1025: Expected comma or open brace, found 'getGradingPoint_Success('
(982,10): run-time error CSS1031: Expected selector, found 'getGradingPoint_Failure('
(982,10): run-time error CSS1025: Expected comma or open brace, found 'getGradingPoint_Failure('
(986,10): run-time error CSS1031: Expected selector, found 'IsGradingLogPointAlreadyExists_Success('
(986,10): run-time error CSS1025: Expected comma or open brace, found 'IsGradingLogPointAlreadyExists_Success('
(990,10): run-time error CSS1031: Expected selector, found 'IsGradingLogPointAlreadyExists_Failure('
(990,10): run-time error CSS1025: Expected comma or open brace, found 'IsGradingLogPointAlreadyExists_Failure('
(995,10): run-time error CSS1031: Expected selector, found 'deleteFeatureLayer('
(995,10): run-time error CSS1025: Expected comma or open brace, found 'deleteFeatureLayer('
 */
/************Functions for adding and editing facility for feature layers****************/

//This function is getting invoked when user clicks on the feature layer point (This opens up infowindow which contains the point information)
function showFeatureAttributes(event) {
    hideAttributes();
    map.graphics.clear();
    var eventFeatureLayer = event.graphic.getLayer();
    var query = new Query();
    query.objectIds = [event.graphic.attributes.OBJECTID];

    eventFeatureLayer.selectFeatures(query, esri.layers.FeatureLayer.SELECTION_NEW, function (features) {
        if (features.length > 0) {
            updateFeature = features[0];
            $("#btnDeleteBuilding").removeAttr("disabled");
            //Set the Feature Layer InfoWindow content and open the InfoWindow
            getFeatureLayerInfoWindowContent(event, eventFeatureLayer);

            //Set the date format 
            $('#txtDate').datepicker({ dateFormat: 'mm/dd/yy' });
        }
        else {
            map.infoWindow.hide();
        }
    });

}

// Opens up the Info Window when user clicks on the feature point on the Map.
function getFeatureLayerInfoWindowContent(event, featureLayer) {  
    var date = null;
    var formatteddate = null;
    if (event.graphic.attributes.DATE_ != null) {
        date = new Date(event.graphic.attributes.DATE_);
        formatteddate = (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear()
    }

    var featurediv = document.createElement("div");
    featurediv.id = "infoContDiv";

    var content = '<table><tr><td><b>Building ID</b>:</td><td><input type="text" class="editorInput" id="txtBldId" readonly="readonly"  value=' + (event.graphic.attributes.BLD_ID != null ? event.graphic.attributes.BLD_ID : '') + '  ></td></tr>'
                             + '<tr><td><b>Date</b>:</td><td><input type="text" class="editorInput" id="txtDate" readonly="readonly"  value=' + (event.graphic.attributes.DATE_ != null ? formatteddate : '') + ' ></td></tr>'
                         + '<tr><td><b>Author</b>:</td><td><input type="text" class="editorInput" id="txtAuthor" readonly="readonly"  value=' + (event.graphic.attributes.AUTHOR != null ? event.graphic.attributes.AUTHOR : '') + ' ></td></tr>'
                         //+ '<tr><td><b>PER_FLAG</b>:</td><td><select name="txtPerFlag" id="txtPerFlag" disabled    class="editorInput"><option value="2" ></option><option value="0"  ' + (event.graphic.attributes.PER_FLAG != null && event.graphic.attributes.PER_FLAG == 0 ? "Selected" : '') + '>Yes</option><option value="1" ' + (event.graphic.attributes.PER_FLAG != null && event.graphic.attributes.PER_FLAG == 1 ? "Selected" : '') + '>No</option></select> </td></tr>'
                         //+ '<tr><td><b>B1_PER_ID1</b>:</td><td><input type="text" class="editorInput" id="txtPerId1" readonly="readonly"  value=' + (event.graphic.attributes.B1_PER_ID1 != null ? event.graphic.attributes.B1_PER_ID1 : '') + ' ></td></tr>'
                         //+ '<tr><td><b>B1_PER_ID2</b>:</td><td><input type="text" class="editorInput" id="txtPerId2" readonly="readonly" value=' + (event.graphic.attributes.B1_PER_ID2 != null ? event.graphic.attributes.B1_PER_ID2 : '') + ' ></td></tr>'
                         //+ '<tr><td><b>B1_PER_ID3</b>:</td><td><input type="text" class="editorInput" id="txtPerId3" readonly="readonly" value=' + (event.graphic.attributes.B1_PER_ID3 != null ? event.graphic.attributes.B1_PER_ID3 : '') + ' ></td></tr>'
                         + '<tr><td><b>Permit #</b>:</td><td><input type="text" class="editorInput" id="txtPerId" readonly="readonly"  value=' + (event.graphic.attributes.PERMIT_ID != null ? event.graphic.attributes.PERMIT_ID.match(/\d{5}(?=\d{2,5})|\d+/g).join("-") : '') + ' ></td></tr>';


    content += '</table>';
    content += '<table><tr><td>' + (permitid != "" && IsRequestFromPCIS == true && isClickHereForExistingBldg ? '<a onclick ="AssignPermitNumberToBuilding(\'' + (event.graphic.attributes.BLD_ID != null ? event.graphic.attributes.BLD_ID : '') + '\', \'' + '' + '\', \'' + '' + '\');" class="buttonAssignPermit" title="Assign Permit to this Structure">Assign Permit</a>' : "") + '</td><td ><input type="Submit" class="buttonAssignPermit" id="btnDelete" value="Delete Building" onclick="deleteFeatureLayer(\'' + event.graphic.attributes.TYPE + '\');"></td></tr></table>';

    /*Show delete button only if temporary building id from pcis url matches with feature layer temporary building id and pcis url contains buildingid as New*/
    //if (bldg_ID.toString().length < 12 && event.graphic.attributes.BLD_ID == PCIS_bld_id && userid.toLowerCase() == event.graphic.attributes.AUTHOR.toLowerCase()) {
    //    //content += '<tr><td colspan="2"><input type="Submit"  class="ui-dialog-buttonset btn" id="btnDelete" value="Delete" onclick="deleteFeatureLayerTypePoint(\'' + event.graphic.attributes.TYPE + '\');"></td></tr></table>';
    //}
    //else {
    //    content += '</table>';
    //}

    var symbol = new SimpleMarkerSymbol().setStyle(
     SimpleMarkerSymbol.STYLE_SQUARE).setColor(
     new Color([0, 255, 255, 0.25])
   ).setSize("35");

    /*Clear graphics from the Map*/
    map.graphics.clear();

    /*Set feature layer symbol*/
    //features[k].setSymbol(symbol);
    
    graphic = new Graphic(event.graphic.geometry, symbol);
    map.graphics.add(graphic);
    
    //content += (permitid != "" && IsRequestFromPCIS == true && isClickHereForExistingBldg ? '<br/><a onclick ="AssignPermitNumberToBuilding(\'' + (event.graphic.attributes.BLD_ID != null ? event.graphic.attributes.BLD_ID : '') + '\', \'' + '' + '\', \'' + '' + '\');" class="buttonAssignPermit" title="Assign Permit to this Structure">Assign Permit</a>' : "");
    featurediv.innerHTML = content;
    map.infoWindow.setTitle(event.graphic.attributes.TYPE);
    map.infoWindow.setContent(featurediv);
    map.infoWindow.resize(350, 400);
    map.infoWindow.show(event.screenPoint);
    setDraggableInfoWindow();

}

// Deletes the feature layer point from the Map as well as from staging table T_BLDG2PERMIT_STG
function deleteFeatureLayerTypePoint(featureLayerID) {
    /***Disconnect the Show feature attributes event ***/
    dojo.disconnect(selectFeaturePoint);
    
    if ((updateFeature != "" && updateFeature != undefined && updateFeature != null) || deleteExistingBuilding) {
        var ad_user = AD_Username;        
        
        if (deleteExistingBuilding) {
            var queryTask = new QueryTask(getUrlByName("js_searchFeatureUrl"));
            query = new esri.tasks.Query();
            query.returnGeometry = false;
            query.Format = "JSON";

            query.outFields = ["*"];
            query.where = "PERMIT_ID  = '" + permit_id + "'";

            queryTask.execute(query,
            function (fset) {
                
                var resultFeatures = fset.features;
                for (var i = 0; i < resultFeatures.length; i++) {
                    if (resultFeatures[i] !== undefined) {
                        var featureAttributes = resultFeatures[i].attributes;
                        updateFeature = resultFeatures[i];
                        jQuery.support.cors = true;
                        $.ajax({
                            url: DeleteNewFeatureActionUrl,
                            type: 'POST',
                            data: { BLD_ID: updateFeature.attributes.BLD_ID, B1_PER_ID1: updateFeature.attributes.B1_PER_ID1, B1_PER_ID2: updateFeature.attributes.B1_PER_ID2, B1_PER_ID3: updateFeature.attributes.B1_PER_ID3, BLDG_TYPE: featureLayerID, AD_USER: ad_user, PCIS_USER: userid, PIN: pin, OPERATION: "D" },
                            dataType: 'json',
                            async: false,
                            success: deleteBldgStagingTable_Success,
                            error: deleteBldgStagingTable_Failure
                        });
                        
                        if (isTempBuildingDeleted) {
                             searchFeatureLayer.applyEdits(null, null, [updateFeature]);
                        }
                        else {
                            alertMessage = "Building can’t be deleted due to locked record";
                            $('#pContent').empty();
                            $('#pContent').append("<span id='spIcon' class='ui-icon ui-icon-alert' style='float: left; margin: 0 7px 7px 0;'></span>" + alertMessage);

                            $("#dialog-confirm").dialog({
                                resizable: false,
                                height: "auto",
                                width: "auto",
                                modal: true,
                                open: function (event, ui) {
                                    $(".ui-dialog-titlebar-close").blur();
                                },
                                close: function (event, ui) {

                                },
                                buttons: [{
                                    text: "OK",
                                    tabIndex: -1,
                                    "class": 'ui-dialog-buttonset btn',
                                    click: function () {
                                        $(this).dialog("close");

                                    }
                                }]
                            });
                            return false;
                        }


                    }
                }

            });
        }
        else {
            jQuery.support.cors = true;
            $.ajax({
                url: DeleteNewFeatureActionUrl,
                type: 'POST',
                data: { BLD_ID: updateFeature.attributes.BLD_ID, B1_PER_ID1: updateFeature.attributes.B1_PER_ID1, B1_PER_ID2: updateFeature.attributes.B1_PER_ID2, B1_PER_ID3: updateFeature.attributes.B1_PER_ID3, BLDG_TYPE: featureLayerID, AD_USER: ad_user, PCIS_USER: userid, PIN: pin, OPERATION: "D" },
                dataType: 'json',
                async: false,
                success: deleteBldgStagingTable_Success,
                error: deleteBldgStagingTable_Failure
            });
            
            if (isTempBuildingDeleted) {
                   searchFeatureLayer.applyEdits(null, null, [updateFeature]);
            }
            else {
                
                confirmDialog("Building can’t be deleted due to locked record", "ok", false)
                return false;
            }

        }

       
        //remove the feature from the feature layer 
        $("#btnClickHereToAddNewBuilding").removeAttr("disabled");
        if (featureLayerID == residentialFeatureType) {
            $('.residStyle').css('background', '');
            doIdentify = true;
            isFeatureLayerClicked = true;
        }
        else if (featureLayerID == apartmentFeatureType) {
            $('.multiStyle').css('background', '');
            doIdentify = true;
            isFeatureLayerClicked = true;
        }
        else if (featureLayerID == commercialFeatureType) {
            $('.commStyle').css('background', '');
            doIdentify = true;
            isFeatureLayerClicked = true;

        }
        hideAttributes();
        if (isTempBuildingDeleted) {
            confirmDialog(ValidationMessages.existingFeaturePointDeleteMsg, "ok", false)
        }
    }
    else {

        confirmDialog("Building can’t be deleted due to locked record", "ok", false)

    }
}

function deleteBldgStagingTable_Success(data) {    
    isTempBuildingDeleted = data;
}

function deleteBldgStagingTable_Failure(x, y, z) {

}

function updateLayerAttributes() {
    var timeStamp = null;
    var newDate = null;
    var currentDate = null;
    if (document.getElementById("txtDate").value != "") {
        currentDate = document.getElementById("txtDate").value.split("/");
        newDate = currentDate[0] + "," + currentDate[1] + "," + currentDate[2];
        timeStamp = new Date(newDate).getTime();
    }
    var buildingID = (document.getElementById("txtBldId").value != "" ? document.getElementById("txtBldId").value : null);
    var date = (document.getElementById("txtDate").value != "" ? timeStamp : null);
    var author = (document.getElementById("txtAuthor").value != "" ? document.getElementById("txtAuthor").value : null);
    var per_flag = (document.getElementById("txtPerFlag").value != "2" ? document.getElementById("txtPerFlag").value : null);
    var b1_per_id1 = (document.getElementById("txtPerId1").value != "" ? document.getElementById("txtPerId1").value : null);
    var b1_per_id2 = (document.getElementById("txtPerId2").value != "" ? document.getElementById("txtPerId2").value : null);
    var b1_per_id3 = (document.getElementById("txtPerId3").value != "" ? document.getElementById("txtPerId3").value : null);
    var permit_id = (document.getElementById("txtPerId").value != "" ? document.getElementById("txtPerId").value : null);

    //Update Map Layers Fields
    updateFeature.attributes["BLD_ID"] = buildingID;
    updateFeature.attributes["DATE_"] = date;
    updateFeature.attributes["AUTHOR"] = author;
    updateFeature.attributes["PER_FLAG"] = per_flag;
    updateFeature.attributes["B1_PER_ID1"] = b1_per_id1;
    updateFeature.attributes["B1_PER_ID2"] = b1_per_id2;
    updateFeature.attributes["B1_PER_ID3"] = b1_per_id3;
    updateFeature.attributes["PERMIT_ID"] = permit_id;

    updateFeature.getLayer().applyEdits(null, [updateFeature], null);

}

function hideAttributes() {
    if (map.infoWindow.isShowing) {
        map.infoWindow.hide();
    }

}

//This function sets the values to the attributes of the feature layer.
function setFeatureAttributesValues(feature, tempBuildingID, author, b1_per_id1, b1_per_id2, b1_per_id3, permit_id, timeStamp, per_flag, featureType) {

    //Add Map feature layers Fields
    feature.attributes["BLD_ID"] = (tempBuildingID != null && tempBuildingID != "" ? tempBuildingID : null);
    feature.attributes["DATE_"] = (timeStamp != null && timeStamp != "" ? timeStamp : null);
    feature.attributes["AUTHOR"] = (author != null && author != "" ? author : null);
    feature.attributes["PER_FLAG"] = (per_flag != null && per_flag != "" ? per_flag : null);
    feature.attributes["B1_PER_ID1"] = (b1_per_id1 != null && b1_per_id1 != "" ? b1_per_id1 : null);
    feature.attributes["B1_PER_ID2"] = (b1_per_id2 != null && b1_per_id2 != "" ? b1_per_id2 : null);
    feature.attributes["B1_PER_ID3"] = (b1_per_id3 != null && b1_per_id3 != "" ? b1_per_id3 : null);
    feature.attributes["PERMIT_ID"] = (permit_id != null && permit_id != "" ? permit_id : null);
    feature.attributes["TYPE"] = (featureType != null && featureType != "" ? featureType : null);

    updateFeature = feature;
}

//This function adds the feature layer point on the Map (This adds New Building to the Map which is of type Residential/Apartment/Commercial).
function addFeaturePoint(geometry) {

    var IsPermitNumberAlreadyExists = $('#IsPermitNumberAlreadyExists').val();
    /**Building ID associated with Permit Number*/
    var permitBuildingID = null;
    var alertMessage = null;
    var successMessage = null;
    var buildingID;
    var b1_per_id1 = "";
    var b1_per_id2 = "";
    var b1_per_id3 = "";

    if (permitid != null && permitid != "" && permitid != 0) {
        permit_id = permitid;
        b1_per_id1 = permitid.substring(0, 5);
        b1_per_id2 = permitid.substring(5, 10);
        b1_per_id3 = permitid.substring(10, 15);
    }


    /****Format the permit number for showing in messages****/
    if (permitid != "" && permitid.length == 15) {
        formattedPermitNumber = permitid.match(/\d{5}(?=\d{2,5})|\d+/g).join("-");
    }

    var Parameters = { B1_PER_ID1: b1_per_id1, B1_PER_ID2: b1_per_id2, B1_PER_ID3: b1_per_id3 }

    var IsPermitNumberExistInT_DATA_SRC_INFO = $('#IsPermitNoExistInT_DATA_SRC_INFO').val();


    $.ajax({
        url: IsPermitNumberExistInT_DATA_SRC_INFO,
        dataType: "json",
        data: Parameters,
        async: false,
        cache: false,
        success: function (buildingID) {
            /*******returns building ID*******/
            /***********If building ID is present then the permit number is assigned to that building ID***********/
            if (buildingID != "") {

                alertMessage = "This Permit " + formattedPermitNumber + " is already assigned to building ID " + buildingID + ".";
                $('#pContent').empty();
                $('#pContent').append("<span id='spIcon' class='ui-icon ui-icon-alert' style='float: left; margin: 0 7px 82px 0;'></span>" + alertMessage);

                $("#dialog-confirm").dialog({
                    resizable: false,
                    height: "auto",
                    width: 500,
                    modal: true,
                    open: function (event, ui) {
                        $(".ui-dialog-titlebar-close").blur();
                    },
                    close: function (event, ui) {
                        removeAddPointFunctionalityForFeatureClass();
                    },
                    buttons: [{
                        text: "OK",
                        tabIndex: -1,
                        "class": 'ui-dialog-buttonset btn',
                        click: function () {
                            $(this).dialog("close");
                            removeAddPointFunctionalityForFeatureClass();
                        }
                    }]
                });


            }
            else {


                var permitParameters = { PermitNumber: formattedPermitNumber }
                /*******************Check if given permit number is already assigned to any building**********************/
                $.ajax({
                    url: IsPermitNumberAlreadyExists,
                    dataType: "json",
                    data: permitParameters,
                    async: false,
                    cache: false,
                    success: function (buildingID) {
                        /*******returns building ID*******/
                        /***********If building ID is present then the permit number is assigned to that building ID***********/
                        if (buildingID != "") {
                            permitBuildingID = buildingID;
                            alertMessage = "This Permit " + formattedPermitNumber + " is already assigned to building ID " + buildingID + ". <br/><br/>Do you want to delete the existing point and add new point?";
                            openDeletePointConfirmationDialogue(alertMessage, permitBuildingID)
                        }
                        else {
                            addNewPointOnMap(geometry);
                        }

                    }
                });

            }
        }
    });

}

function openDeletePointConfirmationDialogue(alertMessage, permitBuildingID) {

    var date = new Date();
    var author = userid;
    var ad_user = AD_Username;
    var PIN = pin;
    var per_flag = "";
    var b1_per_id1 = "";
    var b1_per_id2 = "";
    var b1_per_id3 = "";
    var permit_id = "";
    var template = "";
    var buildingID = permitBuildingID;


    var timeStamp = new Date().getTime();

    if (permitid != null && permitid != "" && permitid != 0) {
        permit_id = permitid;
        b1_per_id1 = permitid.substring(0, 5);
        b1_per_id2 = permitid.substring(5, 10);
        b1_per_id3 = permitid.substring(10, 15);
    }

    var dbOperationsforExistingPermit = $('#dbOperationsforExistingPermit').val();

    /*********disconnect the point draw functionality**************/
    dojo.disconnect(pointDrawEnd);

    $('#pContent').empty();
    $('#pContent').append("<span id='spIcon' class='ui-icon ui-icon-alert' style='float: left; margin: 0 7px 82px 0;'></span>" + alertMessage);

    $("#dialog-confirm").dialog({
        resizable: false,
        height: "auto",
        width: 500,
        modal: true,
        open: function (event, ui) {
            $(".ui-dialog-titlebar-close").blur();
        },
        close: function (event, ui) {
            removeAddPointFunctionalityForFeatureClass();
        },
        buttons: [{
            text: "No",
            "class": 'ui-dialog-buttonset btn',
            tabIndex: -1,
            click: function () {
                removeAddPointFunctionalityForFeatureClass();
                $(this).dialog("close");
            }
        },
                {
                    text: "Yes",
                    "class": 'ui-button-left ui-dialog-buttonset btn',
                    tabIndex: -1,
                    click: function () {

                        InitializeDialog('#requestViewModal', authenticationURL, 'Authentication', 'auto', 400);

                        $("#requestViewModal").dialog("option", "dialogClass", "AuthenticationView");
                        /* Open dialog box */
                        $('#requestViewModal').dialog("open");

                        $(this).dialog("close");
                        deleteExistingBuilding = true;
                        return false;

                        ///************Delete feature point from feature layer************/
                        //var isDeleted = false;
                        //var queryTask = new QueryTask(getUrlByName("js_searchFeatureUrl"));
                        //query = new esri.tasks.Query();
                        //query.returnGeometry = false;
                        //query.Format = "JSON";

                        //query.outFields = ["*"];
                        //query.where = "PERMIT_ID  = '" + permit_id + "'";

                        //queryTask.execute(query,
                        //function (fset) {                            
                        //    var resultFeatures = fset.features;
                        //    for (var i = 0; i < resultFeatures.length; i++) {                              
                        //        if (resultFeatures[i] !== undefined) {                                    
                        //            var featureAttributes = resultFeatures[i].attributes;
                        //            searchFeatureLayer.applyEdits(null, null, [resultFeatures[i]]);
                        //            isDeleted = true;

                        //        }
                        //    }

                        //});

                        //setTimeout(function () {
                        //    //if (isDeleted) {                                
                        //        //remove record from the staging table T_BLDG2PERMIT_STG  and PCIS.bldg2permit
                        //        jQuery.support.cors = true;
                        //        $.ajax({
                        //            url: DeleteNewFeatureActionUrl,
                        //            type: 'POST',
                        //            data: { BLD_ID: buildingID, B1_PER_ID1: b1_per_id1, B1_PER_ID2: b1_per_id2, B1_PER_ID3: b1_per_id3, BLDG_TYPE: featureType, AD_USER: ad_user, PCIS_USER: userid, PIN: PIN, OPERATION: "D" },
                        //            dataType: 'json',
                        //            async: false,
                        //            cache: false,
                        //            success: deleteBldgStagingTable_Success,
                        //            error: deleteBldgStagingTable_Failure
                        //        });

                        //        confirmDialog(ValidationMessages.existingFeaturePointDeleteMsg, "ok", false)
                        //    //}
                        //    //else {
                        //     //   $(this).dialog("close");
                        //   // }

                        //}, 200);
                    }
                }]

    });

}

/*******************Function to add new feature point on Map*********************/
function addNewPointOnMap(geometry) {

    var date = new Date();
    var author = userid;
    var ad_user = AD_Username;
    var PIN = pin;
    var per_flag = "";
    var b1_per_id1 = "";
    var b1_per_id2 = "";
    var b1_per_id3 = "";
    var permit_id = "";
    var template = "";
    var buildingID = PCIS_bld_id;


    var timeStamp = new Date().getTime();

    if (permitid != null && permitid != "" && permitid != 0) {
        permit_id = permitid;
        b1_per_id1 = permitid.substring(0, 5);
        b1_per_id2 = permitid.substring(5, 10);
        b1_per_id3 = permitid.substring(10, 15);
    }


    //Call method which add record to the staging table T_BLDG2PERMIT_STG
    jQuery.support.cors = true;
    $.ajax({
        url: AddNewFeatureActionUrl,
        type: 'POST',
        data: { BLD_ID: buildingID, DATE: date, PCIS_USER: author, PER_FLAG: per_flag, B1_PER_ID1: b1_per_id1, B1_PER_ID2: b1_per_id2, B1_PER_ID3: b1_per_id3, PERMIT_ID: permit_id, BLDG_TYPE: featureType, AD_USER: ad_user, PIN: PIN, OPERATION: "A" },
        dataType: 'json',
        async: false,
        cache: false,
        success: updateStagingTable_Success,
        error: updateStagingTable_Failure
    });

    if (tempBuildingID != null && tempBuildingID != "") {
        //add a new feature to the feature layer   
        drawToolbar.deactivate();
        
        //feature templates in this feature layer so let's get that templates and use it  
        //the template gets us access to things like the attribute info so we can populate  
        //the new feature with the default attributes.   
        for (i = 0; i <= searchFeatureLayer.types.length - 1; i++) {
            if (searchFeatureLayer.types[i].id == featureType) {
                template = searchFeatureLayer.types[i].templates[0];
            }
        }


        //lets setup the attributes for the new feature  
        var attributes = dojo.mixin({}, template.prototype.attributes);
        //now create the feature and add it to the layer  
        var feature = new Graphic(geometry, null, attributes);

        //Adding and Setting the Feature layer attributes values
        setFeatureAttributesValues(feature, tempBuildingID, author, b1_per_id1, b1_per_id2, b1_per_id3, permit_id, timeStamp, per_flag, featureType);

        //Add record to the feature layer        
        searchFeatureLayer.applyEdits([feature]);

        $("#btnDeleteBuilding").removeAttr("disabled");

        setFeatureLayerBackground();
        doIdentify = true;
        isFeatureLayerClicked = true;

        //Set the content for InfoWindow after adding the record to the database.
        OpenFeatureLayerTypeInfoWindow(tempBuildingID, date, author, b1_per_id1, b1_per_id2, b1_per_id3, permit_id, timeStamp, per_flag, featureType, geometry);

        $('#txtDate').datepicker({ dateFormat: 'mm/dd/yy' }).datepicker("setDate", new Date());
        $("#btnClickHereToAddNewBuilding").attr("disabled", "disabled");

    }
    else {
        doIdentify = true;
        drawToolbar.deactivate();
        isFeatureLayerClicked = !isFeatureLayerClicked;
        confirmDialog(ValidationMessages.validDuplicatePermitNo, "ok", false)
        setFeatureLayerBackground();
    }

    dojo.disconnect(pointDrawEnd);

}



// Opens up the Info Window when user add the feature point on the Map.
function OpenFeatureLayerTypeInfoWindow(tempBuildingID, date, author, b1_per_id1, b1_per_id2, b1_per_id3, permit_id, timeStamp, per_flag, featureType, geometry) {    
    var infocontdiv = document.createElement("div");
    infocontdiv.id = "infoContDiv";

    var content = '<table><tr><td><b>Building ID</b>:</td><td><input type="text" class="editorInput" id="txtBldId" readonly="readonly"  value=' + (tempBuildingID != null && tempBuildingID != "" ? tempBuildingID : '') + '  ></td></tr>'
                         + '<tr><td><b>Date</b>:</td><td><input type="text" class="editorInput" id="txtDate" readonly="readonly"  value=' + (date != null && date != "" ? date : '') + ' ></td></tr>'
                         + '<tr><td><b>Author</b>:</td><td><input type="text" class="editorInput" id="txtAuthor" readonly="readonly"  value=' + (author != null && author != "" ? author : '') + '></td></tr>'
                         //+ '<tr><td><b>PER_FLAG</b>:</td><td><select name="txtPerFlag" id="txtPerFlag"  disabled class="editorInput"><option value="2" ></option><option value="0">Yes</option><option value="1">No</option></select> </td></tr>'
                         //+ '<tr><td><b>B1_PER_ID1</b>:</td><td><input type="text" class="editorInput" id="txtPerId1" readonly="readonly"   value=' + (b1_per_id1 != null && b1_per_id1 != "" ? b1_per_id1 : '') + ' ></td></tr>'
                         //+ '<tr><td><b>B1_PER_ID2</b>:</td><td><input type="text" class="editorInput" id="txtPerId2" readonly="readonly"  value=' + (b1_per_id2 != null && b1_per_id2 != "" ? b1_per_id2 : '') + ' ></td></tr>'
                         //+ '<tr><td><b>B1_PER_ID3</b>:</td><td><input type="text" class="editorInput" id="txtPerId3" readonly="readonly"  value=' + (b1_per_id3 != null && b1_per_id3 != "" ? b1_per_id3 : '') + ' ></td></tr>'
                         + '<tr><td><b>Permit #</b>:</td><td><input type="text" class="editorInput" id="txtPerId" readonly="readonly"    value=' + (permit_id != null && permit_id != "" ? permit_id.match(/\d{5}(?=\d{2,5})|\d+/g).join("-") : '') + '></td></tr></table>';
    //+ '<tr><td colspan="2"><input type="Submit" class="ui-dialog-buttonset btn"  id="btnDelete" value="Delete" onclick="deleteFeatureLayerTypePoint(\'' + featureType + '\');"></td></tr></table>';

    //content += (permitid != "" && IsRequestFromPCIS == true && isClickHereForExistingBldg ? '<br/><a onclick ="AssignPermitNumberToBuilding(\'' + (tempBuildingID != null && tempBuildingID != "" ? tempBuildingID : '') + '\', \'' + '' + '\', \'' + '' + '\');" class="buttonAssignPermit" title="Assign Permit to this Structure">Assign Permit</a>' : "");
    content += '<table><tr><td>' + (permitid != "" && IsRequestFromPCIS == true && isClickHereForExistingBldg ? '<a onclick ="AssignPermitNumberToBuilding(\'' + (tempBuildingID != null && tempBuildingID != "" ? tempBuildingID : '') + '\', \'' + '' + '\', \'' + '' + '\');" class="buttonAssignPermit" title="Assign Permit to this Structure">Assign Permit</a>' : "") + '</td><td ><input type="Submit" class="buttonAssignPermit" id="btnDelete" value="Delete Building" onclick="deleteFeatureLayer(\'' + (featureType != null && featureType  != '' ? featureType : '') + '\');"></td></tr></table>';

    var symbol = new SimpleMarkerSymbol().setStyle(
     SimpleMarkerSymbol.STYLE_SQUARE).setColor(
     new Color([0, 255, 255, 0.25])
   ).setSize("35");

    /*Clear graphics from the Map*/
    map.graphics.clear();

    /*Set feature layer symbol*/
    //features[k].setSymbol(symbol);

    graphic = new Graphic(geometry, symbol);
    map.graphics.add(graphic);

    infocontdiv.innerHTML = content;
    map.infoWindow.setTitle(featureType);
    map.infoWindow.setContent(infocontdiv);
    map.infoWindow.resize(350, 400);
    map.infoWindow.show(map.toScreen(geometry));
    setDraggableInfoWindow();
}

function updateStagingTable_Success(data) {
    tempBuildingID = data;
}

function updateStagingTable_Failure(x, y, z) {

}

/************Functions for adding and editing facility for feature layers****************/


/**********************Functions for grading applications******************************/
//Commenting for production release
//This function sets the values to the attributes of the feature layer.
function setGradingFeatureAttributesValues(feature, parcelLON, parcelLAT, logID, pin, pointX, pointY) {

    //Add Map feature layers Fields    
    feature.attributes["LOG_ID"] = (logID != null && logID != "" ? logID : null);
    feature.attributes["PIN"] = (pin != null && pin != "" ? pin : null);
    feature.attributes["POINT_X"] = (pointX != null && pointX != "" ? pointX : null);
    feature.attributes["POINT_Y"] = (pointY != null && pointY != "" ? pointY : null);

    updateFeature = feature;
}

function addGradingFeaturePoint(geometry) {    
    var pin = "";
    var parcelLON = "";
    var parcelLAT = "";
    var logID = "";

    pointX = geometry.x;
    pointY = geometry.y;
    pin = gradingPIN;
    logID = getURLVars()["LogNo"] !== undefined ? getURLVars()["LogNo"] : '';

    if (gradingParcels != null && gradingParcels != undefined && gradingParcels.length == 0) {
        //$('#tools').find('.dropdown-toggle').html('<img src="/StructuralInventory/Images/tools.png" width="27" height="20">&nbsp;&nbsp;' + "Tools" + ' <span class="caret"></span>');
        confirmDialog("Please select a parcel to drop the pin", "ok", false)
        $("#btnDeleteLogPoint").attr("disabled", "disabled");
        doIdentify = false;
        drawToolbar.deactivate();
        isFeatureLayerClicked = !isFeatureLayerClicked;
        isAddGradingPointClicked = true;
        isSelectedParcelClicked = false;
        dojo.disconnect(pointDrawEnd);

    }
    else if (isSelectedParcelClicked) {        

        /********Check if grading point selected from map*******/
        if(isGradingPointClicked)
        {            
            logID = featureLogID;
        }

        jQuery.support.cors = true;
        $.ajax({
            url: IsGradingLogPointAlreadyExists,
            type: 'POST',
            data: { LogID: logID},
            dataType: 'json',
            async: false,
            success: IsGradingLogPointAlreadyExists_Success,
            error: IsGradingLogPointAlreadyExists_Failure
        });

        if (isGradingPointAlreadyExists) {         

            alertMessage = "This log point " + logID + " is already assigned to parcel. Are you sure you want to modify this log point? ";
            $('#pContent').empty();
            $('#pContent').append("<span id='spIcon' class='ui-icon ui-icon-alert' style='float: left; margin: 0 7px 82px 0;'></span>" + alertMessage);

            $("#dialog-confirm").dialog({
                resizable: false,
                height: "auto",
                width: 500,
                modal: true,
                open: function (event, ui) {
                    $(".ui-dialog-titlebar-close").blur();
                },
                close: function (event, ui) {
                    
                },
                buttons: [{
                    text: "No",
                    "class": 'ui-dialog-buttonset btn',
                    tabIndex: -1,
                    click: function () {                        
                        $(this).dialog("close");
                        drawToolbar.deactivate();
                    }
                },
                 {
                     text: "Yes",
                     "class": 'ui-button-left ui-dialog-buttonset btn',
                     tabIndex: -1,
                     click: function () {                         
                         if (LOG_ID != "") {

                             var query = new Query();
                             query.where = "LOG_ID =" + LOG_ID;

                             gradingFeatureLayer.selectFeatures(query, esri.layers.FeatureLayer.SELECTION_NEW, function (features) {
                                 if (features.length > 0) {
                                     addedGradingPointFeature = features[0];
                                 }
                             });
                         }

                         modifyLogPoint();
                         //add a new feature to the feature layer   
                         drawToolbar.deactivate();

                         $(this).dialog("close");                                                  
                     }
                 }]
            });

            return false;
        }
        
        //add a new feature to the feature layer   
        drawToolbar.deactivate();

        //feature templates in this feature layer so let's get that templates and use it  
        //the template gets us access to things like the attribute info so we can populate  
        //the new feature with the default attributes.   
        template = gradingFeatureLayer.templates[0];


        //lets setup the attributes for the new feature  
        var attributes = dojo.mixin({}, template.prototype.attributes);
        //now create the feature and add it to the layer  
        var feature = new Graphic(geometry, null, attributes);
                
        if (gradingParcels != null && gradingParcels != undefined) {
            gradingPointParcelIDs = "";
            for (var i = 0; i <= gradingParcels.length - 1; i++) {
                gradingPointParcelIDs += gradingParcels[i] + ",";
            }
        }

        
        gradingPointParcelIDs = gradingPointParcelIDs.replace(/,\s*$/, "");
        

        //Adding and Setting the Feature layer attributes values
        setGradingFeatureAttributesValues(feature, parcelLON, parcelLAT, logID, pin, pointX, pointY);

        addedGradingPointFeature = feature;

        jQuery.support.cors = true;
        $.ajax({
            url: AddGradingPointUrl,
            type: 'POST',
            data: { LogID: logID, PIN: gradingPointParcelIDs },
            dataType: 'json',
            async: false,
            success: addGradingPoint_Success,
            error: addGrading_Failure
        });
                
        //Add record to the feature layer       
        if (isGradingPointAdded) {
            gradingFeatureLayer.applyEdits([feature]);
            addAddressMarker(feature.geometry);
            /********Enabled delete log point button**********/
            $("#btnDeleteLogPoint").removeAttr("disabled");
            $("#btnAddPoint").attr("disabled", "disabled");


            //$('#tools').find('.dropdown-toggle').html('<img src="/StructuralInventory/Images/tools.png" width="27" height="20">&nbsp;&nbsp;' + "Tools" + ' <span class="caret"></span>');

            setFeatureLayerBackground();
            //map.graphics.clear();
            //gradingParcels.length = 0
            doIdentify = false;
            isAddGradingPointClicked = true;
            isSelectedParcelClicked = false;
            isFeatureLayerClicked = !isFeatureLayerClicked;
            isGradingPointAdded = true;
        }

        //$('#pContent').empty();
        //$('#pContent').append("Continue to save the selected pin location and back to the log profile page. <br/><br/> Click \"Proceed\" to continue");

        //$("#dialog-confirm").dialog({
        //    resizable: false,
        //    height: "auto",
        //    width: 500,
        //    modal: true,
        //    open: function (event, ui) {
        //        $(".ui-dialog-titlebar-close").blur();
        //    },
        //    close: function (event, ui) {
        //        removeAddPointFunctionalityForGradingFeatureClass();
        //    },
        //    buttons: [{
        //        text: "Cancel",
        //        "class": 'ui-dialog-buttonset btn',
        //        tabIndex: -1,
        //        click: function () {
        //            $(this).dialog("close");
        //            //Remove record from the feature layer        
        //            gradingFeatureLayer.applyEdits(null, null, [feature]);
        //        }
        //    },
        //            {
        //                text: "Proceed",
        //                "class": 'ui-button-left ui-dialog-buttonset btn',
        //                tabIndex: -1,
        //                click: function () {
        //                    //window.location = gradingAppURL + logID + "/0/" + parcelIDs + "/" + pointX + "/" + pointY;                            
        //                    window.open(gradingAppURL + logID + "/0/" + gradingPointParcelIDs + "/" + pointX + "/" + pointY, "_blank");
        //                    $(this).dialog("close");
        //                }
        //            }]

        //});

        dojo.disconnect(pointDrawEnd);

    }
    else {
        confirmDialog("Please drop a point on the selected parcel", "ok", false)
        drawToolbar.deactivate();
        isFeatureLayerClicked = !isFeatureLayerClicked;
        $("#btnDeleteLogPoint").attr("disabled", "disabled");
        //doIdentify = true;
        isAddGradingPointClicked = true;
        isSelectedParcelClicked = false;
        dojo.disconnect(pointDrawEnd);
    }
}

function showGradingFeatureAttributes(event) {    
    gradingParcels.length = 0;
   
    hideAttributes();    
    if (graphicsArray.length > 0) {
        for (i = 0; i <= graphicsArray.length - 1; i++) {
            map.graphics.remove(graphicsArray[i]);
        }
    }
    
    graphicsArray.length = 0;
    // map.graphics.clear();
    var eventFeatureLayer = event.graphic.getLayer();
    var query = new Query();
    query.objectIds = [event.graphic.attributes.OBJECTID];

    map.graphics.clear();
    eventFeatureLayer.selectFeatures(query, esri.layers.FeatureLayer.SELECTION_NEW, function (features) {
        if (features.length > 0) {
            updateFeature = features[0];            
            isGradingPointClicked = true;
            //Set the Feature Layer InfoWindow content and open the InfoWindow
            getGradingFeatureLayerInfoWindowContent(event, updateFeature);

        }
        else {
            map.infoWindow.hide();
        }
    });
    
    
    jQuery.support.cors = true;
    $.ajax({
        url: GetGradingPointDataUrl,
        type: 'GET',
        data: { LogID: event.graphic.attributes.LOG_ID },
        dataType: 'json',
        async: false,
        success: getGradingPoint_Success,
        error: getGradingPoint_Failure
    });

    
    for (i = 0; i < gradingLogPointData.length; i++) {        
        var query = new Query();
        query.where = "PIN  = '" + gradingLogPointData[i].PIN + "'";
        gradingParcels.push(gradingLogPointData[i].PIN);

        parcelFeatureLayer.selectFeatures(query, (gradingLogPointData.length == 1 ? esri.layers.FeatureLayer.SELECTION_NEW : (i == 0 ? esri.layers.FeatureLayer.SELECTION_ADD : esri.layers.FeatureLayer.SELECTION_NEW)), function (features) {            
            if (features.length > 0) {
                updateFeature = features[0];
                /*Set feature layer symbol*/
                updateFeature.setSymbol(parcelSymbol);
                /*add feature in the graphics of the map*/
                map.graphics.add(updateFeature);
            }
            else {
                map.infoWindow.hide();
            }
        });
    }

    $("#spLogNo").html(event.graphic.attributes.LOG_ID);
    $("#selectedParcelCount").html(gradingParcels.length);
}

// Opens up the Info Window when user clicks on the feature point on the Map.
function getGradingFeatureLayerInfoWindowContent(event, feature) {    
    showGradingQuickViewDetail(event, feature);
    
}

// Deletes the feature layer point from the Map as well as from staging table T_BLDG2PERMIT_STG
function deleteGradingPoint() {
    
    if (addedGradingPointFeature != null && addedGradingPointFeature != undefined && addedGradingPointFeature != "") {        
        jQuery.support.cors = true;
        $.ajax({
            url: DeleteGradingPointUrl,
            type: 'POST',
            data: { LogID: addedGradingPointFeature.attributes.LOG_ID },
            dataType: 'json',
            async: false,
            success: deleteGradingPoint_Success,
            error: deleteGrading_Failure
        });

        
        if (isGradingPointDeleted) {
            gradingFeatureLayer.applyEdits(null, null, [addedGradingPointFeature]);            
        }
    }
}

function addGradingPoint_Success(data) {
    isGradingPointAdded = data;
}

function deleteGrading_Failure(x, y, z) {
    isGradingPointAdded = false;
}

function deleteGradingPoint_Success(data) {
    isGradingPointDeleted = data;
}

function addGrading_Failure(x, y, z) {
    isGradingPointDeleted = false;
}

function getGradingPoint_Success(data) {
    
    gradingLogPointData = data;
}

function getGradingPoint_Failure(x, y, z) {

}

function IsGradingLogPointAlreadyExists_Success(data) {
    isGradingPointAlreadyExists = data;
}

function IsGradingLogPointAlreadyExists_Failure(x, y, z) {
}
/**********************Functions for grading applications******************************/


function deleteFeatureLayer(featureLayerID) {
    featureType = featureLayerID;
    InitializeDialog('#requestViewModal', authenticationURL, 'Authentication', 'auto', 400);

    $("#requestViewModal").dialog("option", "dialogClass", "AuthenticationView");
    /* Open dialog box */
    $('#requestViewModal').dialog("open");
    return false;
}
