using System;
using System.Data;
using System.Globalization;
using System.IO;
using System.Resources;
using System.Threading;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using DevExpress.Web;
using System.Configuration;
using System.Text;

public partial class Masters_Landmarks : Base.BasePage
{
    #region VariableDeclaration
    ResourceManager rm;
    CultureInfo ci;
    EmployeeEventData objEmployee = new EmployeeEventData();
    cls_Common objcommon = new cls_Common();
    Cls_CheckUser objCheckUser = new Cls_CheckUser();
    DemoVersion objDemoVersion = new DemoVersion();
    DataSet ds_Checkuser = new DataSet();
    int EmployeeID = 0;
    string source_Language;
    LeaveEventData objLeave = new LeaveEventData();
    Licensing objLicense = new Licensing();
    string strScript = string.Empty;
    ResetPwd obj_ResetPwd = new ResetPwd();
    int isTriggered = 0;
    Email_Triggering objEmail = new Email_Triggering();
    Geofencing objgeo = new Geofencing();
    int intIndividualUser = 0;
    Int64 geoLandMarkID = 0;
    string gstrUserGroupName = string.Empty;
    #endregion    
    protected override void Page_Load(object sender, EventArgs e)
    {
        base.Page_Load(sender, e);
        source_Language = Convert.ToString(Session["Session_ActiveLanguage"]);
        rm = new ResourceManager(source_Language, System.Reflection.Assembly.Load("App_GlobalResources"));
        ci = Thread.CurrentThread.CurrentCulture;
        site.SiteMapProvider = Convert.ToString(Session["SiteMapProvider"]);
        EmployeeID = Convert.ToInt32(Session["EmpAutoID"]);
        grvLandmarks.Styles.CssFilePath = Convert.ToString(Session["GridCSS"]);
        if (!Page.IsPostBack)
        {
            //Set UserRights
            base.CheckPages(18);
            UserRights();
            LoadStrings(ci);
            Session["Level"] = string.Empty;
            Session["EmployeeData"] = null;
            objcommon.menu("Configuration", "286");
            StringBuilder map = new StringBuilder();
            StringBuilder sb = new StringBuilder();
            sb.Append("<script type='text/javascript' src='" + ConfigurationManager.AppSettings["googleMapKey"].ToString() + "'></script>");
            Page.ClientScript.RegisterStartupScript(this.GetType(), "scriptsKey", sb.ToString());
            string strSetAlert = "";
            strSetAlert = strSetAlert + "<script language='javascript'>";
            strSetAlert = strSetAlert + "loadMapControl();";
            strSetAlert = strSetAlert + "</script>";
            Page.RegisterStartupScript("MaxLengthh", strSetAlert);
            GetLandmarkStatus();
            ClearFields(this);
        }
        BindGridview(0);
        gstrUserGroupName = Convert.ToString(Session["UserGroupName"]);
    }
    /// <summary>
    /// To check rights for the logged in user
    /// </summary>
    private void UserRights()
    {
        if (ViewState["vs_ds_Checkuser"] == null)
        {
            ds_Checkuser = objCheckUser.checkRights(286, Convert.ToInt32(Session["userGroup_Id"]), "");
            ViewState["vs_ds_Checkuser"] = ds_Checkuser;
        }
        else
            ds_Checkuser = (DataSet)ViewState["vs_ds_Checkuser"];
        if (ds_Checkuser.Tables[0].Rows.Count > 0)
        {
            if (ds_Checkuser.Tables[0].Rows[0]["addPrv"] != DBNull.Value && Convert.ToInt32(ds_Checkuser.Tables[0].Rows[0]["addPrv"]) == 1)
            {
                this.lnkbtnSave.Visible = true;
                ViewState["CanAdd"] = true;
            }
            else
            {
                this.lnkbtnSave.Visible = false;
                ViewState["CanAdd"] = false;
            }
            if (ds_Checkuser.Tables[0].Rows[0]["viewPrv"] != DBNull.Value && Convert.ToInt32(ds_Checkuser.Tables[0].Rows[0]["viewPrv"]) == 1)
            {
                ViewState["CanView"] = true;
            }
            else
            {
                ViewState["CanView"] = false;
                grvLandmarks.Visible = false;
            }
            if (ds_Checkuser.Tables[0].Rows[0]["modifyPrv"] != DBNull.Value && Convert.ToInt32(ds_Checkuser.Tables[0].Rows[0]["modifyPrv"]) == 1)
            {
                this.grvLandmarks.Columns[12].Visible = true;
            }
            else
                this.grvLandmarks.Columns[12].Visible = false;
            if (ds_Checkuser.Tables[0].Rows[0]["deletePrv"] != DBNull.Value && Convert.ToInt32(ds_Checkuser.Tables[0].Rows[0]["deletePrv"]) == 1)
            {
                this.lnkbtnDelete.Visible = true;
                this.grvLandmarks.Columns[13].Visible = true;
            }
            else
            {
                this.lnkbtnDelete.Visible = false;
                this.grvLandmarks.Columns[13].Visible = false;
            }
        }
        else
        {
            Response.Redirect("MasterLandingPage.aspx");
        }
    }
    /// <summary>
    /// Getting Information from resource file and display it in label
    /// </summary>
    /// <param name="ci"></param>
    private void LoadStrings(CultureInfo ci)
    {
        lblfenchType.Text = rm.GetString("fenchType", ci);
        lblLocat.Text = rm.GetString("LocationName", ci);
        lblDescript.Text = rm.GetString("Description", ci);
        lblAddress.Text = rm.GetString("Address", ci);
        lbllatelng.Text = rm.GetString("LatLng", ci);
        btnAddress.Text = rm.GetString("LocateMe", ci);
        lnkbtnSave.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Add", ci);
        lbl_IndicatesMandatoryFields.Text = rm.GetString("IndicatesMandatoryFields", ci);
        btnCancel.Text = rm.GetString("btn_Cancel", ci);
    }

    protected void lnkbtnSave_Click(object sender, EventArgs e)
    {
        if (txtLocationName.Text == string.Empty)
        {
            Message("Enter Location Name");
            return;
        }
        if (ddlType.SelectedItem.Value == "1")
        {
            if (txtstreet.Text == string.Empty)
            {
                Message("Enter Address");
                return;
            }
        }
        else if (ddlType.SelectedItem.Value == "1")
        {
            if (txtlat.Text == string.Empty)
            {
                Message("Enter Address");
                return;
            }
            else if (txtlong.Text == string.Empty)
            {
                Message("Enter Address");
                return;
            }
        }
        bool isDuplicate = objgeo.CheckDuplicateLandmarkName((ViewState["Id"] != null) ? "" : txtLocationName.Text.Trim());

        if (isDuplicate)
        {
            string alertMsg = "<script>alert('Given Location Name is already available, please give some other name');showControls(document.getElementById('ctl00_BodyContentPH_ddlType').selectedIndex);SetCenter();</script>";
            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "regJSDupLandmark", alertMsg, false);
            txtLocationName.Focus();
            return;
        }
        Int32 radius = (Convert.ToString(txtRadius.Text) == "") ? 0 : Convert.ToInt16(txtRadius.Text);
        objgeo.InsertGeoLocationDetails(Convert.ToString(ddlType.SelectedItem.Text), Convert.ToString(txtLocationName.Text), radius, Convert.ToString(txtLocationDesc.Text), Convert.ToString(txtstreet.Text), Convert.ToString(txtcity.Text), Convert.ToString(txtstate.Text), Convert.ToString(txtCountry.Text), Convert.ToString(txtlat.Text), Convert.ToString(txtlong.Text), Convert.ToString(Session["EmpAutoID"]), (ViewState["Id"] == null) ? "I" : "U", (ViewState["strEditLandMarkId"] == null) ? 0 : Convert.ToInt64(ViewState["strEditLandMarkId"]));
        if (ViewState["Id"] == null)
        {
            Altermessage("add");
        }
        else
        {
            Altermessage("modify");
        }
        BindGridview(0);
        ClearFields(this);
    }

    private void Altermessage(string isAddOrupdate)
    {
        string strScript = "";
        strScript = strScript + "<script language='javascript'>";
        string alertmsg = (isAddOrupdate == "add") ? "Location Details Saved Successfully" : "Location Details Modified Successfully";
        strScript = strScript + "showControls(document.getElementById('ctl00_BodyContentPH_ddlType').selectedIndex);alert('" + alertmsg + "');";
        strScript = strScript + "</script>";
        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strScript, false);
    }

    public void BindGridview(int landMarkID)
    {
        if (ViewState["CanView"] != null)
        {
            if (Convert.ToBoolean(ViewState["CanView"]) == false)
            {
                grvLandmarks.Visible = false;
                return;
            }
        }
        DataSet dslandmarkDetails = new DataSet();
        dslandmarkDetails = objgeo.GetLandmarkDetails(landMarkID);
        if (dslandmarkDetails.Tables.Count > 0)
        {
            if (dslandmarkDetails.Tables[0].Rows.Count > 0)
            {
                grvLandmarks.Visible = true;
                grvLandmarks.DataSource = dslandmarkDetails;
                grvLandmarks.DataBind();
            }
        }
    }
    /// <summary>
    /// Multilingual for Landmark type
    /// </summary>
    public void GetLandmarkStatus()
    {
        if (ddlType.Items.Count == 0)
        {
            ListItem liAll = new ListItem();
            liAll.Text = "Street Address";
            liAll.Value = "addr";
            ddlType.Items.Add(liAll);
            ListItem liMessages = new ListItem();
            liMessages.Text = "Map Coordinates";
            liMessages.Value = "ltlng";
            ddlType.Items.Add(liMessages);
            ddlType.SelectedIndex = 0;
        }
    }
    protected void btnAddress_Click(object sender, EventArgs e)
    {
        string jsScript = string.Empty;
        string viewLandmark = "<script>";
        viewLandmark += "showControls(document.getElementById('ctl00_BodyContentPH_ddlType').selectedIndex);";
        viewLandmark += "showAddress(); ";
        viewLandmark += "</script>";
        ScriptManager.RegisterStartupScript(grvLandmarks, this.GetType(), "viewLandmark", viewLandmark, false);
    }

    protected void ibEdit_Click(object sender, EventArgs e)
    {
        LinkButton btnEdit = (LinkButton)sender;
        string strLandMarkId = btnEdit.CommandArgument.ToString();
        if (ViewState["strEditLandMarkId"] == null || ViewState["strEditLandMarkId"].ToString() != strLandMarkId)
        {
            ClearFields(this);
            string strLandmarkType = Convert.ToString(grvLandmarks.GetRowValuesByKeyValue(strLandMarkId, "Options"));
            string strLandMark = Convert.ToString(grvLandmarks.GetRowValuesByKeyValue(strLandMarkId, "LocationName"));
            string strRadius = Convert.ToString(grvLandmarks.GetRowValuesByKeyValue(strLandMarkId, "Radius"));
            string strLandMarkDesc = Convert.ToString(grvLandmarks.GetRowValuesByKeyValue(strLandMarkId, "Description"));
            string strAddress = Convert.ToString(grvLandmarks.GetRowValuesByKeyValue(strLandMarkId, "Address")).Replace("\r\n", "");
            string strLat = Convert.ToString(grvLandmarks.GetRowValuesByKeyValue(strLandMarkId, "latitude"));
            string strLong = Convert.ToString(grvLandmarks.GetRowValuesByKeyValue(strLandMarkId, "longitude"));
            ViewState["Id"] = strLandMarkId;
            ddlType.SelectedIndex = (strLandmarkType == "addr") ? Convert.ToInt16(0) : 1;
            txtLocationName.Text = strLandMark;
            txtRadius.Text = strRadius;
            txtLocationDesc.Text = strLandMarkDesc;
            txtstreet.Text = strAddress;
            txtlat.Text = strLat;
            txtlong.Text = strLong;
            string editLandmark = "<script>showControls(document.getElementById('ctl00_BodyContentPH_ddlType').selectedIndex);";
            if (ddlType.SelectedIndex == 0)
            {
                editLandmark += "loadMapControl(); showAddress();";
            }
            else
            {
                //editLandmark += "showAddress('" + "" + "','" + ViewState["MapPositionImage"].ToString() + "','" + strAddress.Replace("\n", "") + "'); chkValue = 0;";
                editLandmark += "showAddress();";
            }
            editLandmark += "</script>";
            ScriptManager.RegisterStartupScript(grvLandmarks, this.GetType(), Guid.NewGuid().ToString(), editLandmark, false);
            updPanel.Update();
            ViewState["strEditLandMarkId"] = strLandMarkId;
            BindGridview(0);
        }
    }

    protected void ibDelete_Click(object sender, EventArgs e)
    {
        LinkButton btnDelete = (LinkButton)sender;
        string strLandMarkId = btnDelete.CommandArgument.ToString();
        if (strLandMarkId != null)
        {
            objgeo.DeleteGEOLocationDetails(Convert.ToString(strLandMarkId));
            BindGridview(0);
            updPanel.Update();
            ClearFields(this);
            string strScript = "";
            strScript = strScript + "<script language='javascript'>";
            strScript = strScript + "alert('Location Details Deleted Successfully');";
            strScript = strScript + "</script>";
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strScript, false);
        }
    }
    public void ClearFields(Control ctrl)
    {
        txtcity.Text = string.Empty;
        txtCountry.Text = string.Empty;
        txtlat.Text = string.Empty;
        txtLocationDesc.Text = string.Empty;
        txtLocationName.Text = string.Empty;
        txtlong.Text = string.Empty;
        txtRadius.Text = string.Empty;
        txtstate.Text = string.Empty;
        txtstreet.Text = string.Empty;
        ddlType.SelectedIndex = 0;
        updPanel.Update();
        //modified on 03-Aug-2010 for showing Map for read only users
        //ScriptManager.RegisterStartupScript(btnCancel, this.GetType(), Guid.NewGuid().ToString(), "loadForLandMark();" + ((!IsPostBack) ?
        //  (hdnCanAddLandmarks.Value.ToString().Equals("true")? "document.getElementById('ddlType').focus();":"") : ""), true);
        //if (ViewState["CanAdd"] != null && Convert.ToBoolean(ViewState["CanAdd"]) == false)
        //{
        ScriptManager.RegisterStartupScript(btnCancel, this.GetType(), Guid.NewGuid().ToString(), "loadMapControl();", true);
        //}
        //else
        //{
        //    ScriptManager.RegisterStartupScript(btnCancel, this.GetType(), Guid.NewGuid().ToString(), "loadMapControl();", true);
        //}
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        ViewState["strEditLandMarkId"] = null;
        if (ViewState["CanAdd"] != null && Convert.ToBoolean(ViewState["CanAdd"]) == false)
        {
            ControlVisibility(false);
        }
        else
        {
            ControlVisibility(true);
        }
        //End
        grvLandmarks.Selection.UnselectAll();
        ClearFields(btnCancel);

        ScriptManager.RegisterClientScriptBlock(ddlType, this.GetType(), Guid.NewGuid().ToString(),
            "showControls(" + ddlType.SelectedIndex + ");", true);
    }
    /// <summary>
    /// Function to enable/disable & show/hide controls
    /// </summary>
    /// <param name="isEnable"></param>
    private void ControlVisibility(bool isEnable)
    {
        ddlType.Enabled = isEnable;
        txtLocationName.Enabled = isEnable;
        txtRadius.Enabled = isEnable;
        txtLocationDesc.Enabled = isEnable;
        txtstreet.Enabled = isEnable;
        txtcity.Enabled = isEnable;
        txtstate.Enabled = isEnable;
        txtCountry.Enabled = isEnable;
        txtlat.Enabled = isEnable;
        txtlong.Enabled = isEnable;
        btnAddress.Enabled = isEnable;
        updPanel.Update();
    }

    protected void lnkbtnDelete_Click(object sender, EventArgs e)
    {
        string[] ChkBoxIDs;
        if (hdnSelectRow.Value != string.Empty && hdnSelectRow.Value != null)
        {
            ChkBoxIDs = objLeave.commaStringToArray(hdnSelectRow.Value);
            for (int i = 0; i < ChkBoxIDs.Length; i++)
            {
                int Count = objgeo.CheckGEOLocationUtilization(Convert.ToInt32(ChkBoxIDs[i]));
                if (Count > 0)
                {
                    base.Message("Location cant be deleted");
                    return;
                }
            }
            objgeo.DeleteGEOLocationDetails(Convert.ToString(hdnSelectRow.Value));
            BindGridview(0);
            updPanel.Update();
            Message("Location details was deleted Successfully");
        }
        else
        {
            Message(rm.GetString("DeletionRecordAlert", ci));
            return;
        }
    }

    protected void grvLandmarks_HtmlRowCreated(object sender, ASPxGridViewTableRowEventArgs e)
    {
        if (e.RowType == GridViewRowType.Data)
        {
            HtmlInputCheckBox deleteChkBxItem = (HtmlInputCheckBox)grvLandmarks.FindRowCellTemplateControl(e.VisibleIndex, null, "chkSelect");

            if (deleteChkBxItem != null)
            {
                geoLandMarkID = Convert.ToInt16(e.GetValue("id"));
                int Count = objgeo.CheckGEOLocationUtilization(geoLandMarkID);
                LinkButton LnkbtnDelete = (LinkButton)grvLandmarks.FindRowCellTemplateControl(e.VisibleIndex, null, "ibDelete");
                if (Count > 0)
                {
                    deleteChkBxItem.Disabled = true;
                    if (LnkbtnDelete != null)
                    {
                        LnkbtnDelete.Enabled = false;
                        LnkbtnDelete.OnClientClick = null;
                    }
                }
                else
                {
                    deleteChkBxItem.Disabled = false;
                    if (LnkbtnDelete != null)
                    {
                        LnkbtnDelete.Enabled = true;
                    }
                }
            }
        }
    }
    #region ICallbackEventHandler Members

    string callbackResult;

    /// <summary>
    /// Gets the callback result.
    /// </summary>
    /// <returns></returns>
    public string GetCallbackResult()
    {
        return callbackResult;
    }

    /// <summary>
    /// Raises the callback event.
    /// </summary>
    /// <param name="eventArgument">The event argument.</param>
    public void RaiseCallbackEvent(string eventArgument)
    {

    }

    #endregion
}