protected void DisplayMode_Click(object sender, EventArgs e)
    {
        Util util = new Util();
        Hashtable State = (Hashtable)HttpRuntime.Cache[Session.SessionID];
        if (util.CheckSessionTimeout(State, Response, "Default.aspx")) return;

        if (State["SelectedApp"] == null || State["SelectedApp"].ToString().Contains("->"))
            return;

        int index = DisplayModeButton.SelectedToggleStateIndex;

        if (index == 0)//design mode
        {
             State["WebAppMode"] = null;//design mode is the default
            canvas.Attributes["src"] = "canvas.aspx";
            DesignMessage.Text = "";
            QRCode.Src = "";
            QRCode.Style.Value = "display:none";
            QRCodeLabel.Style.Value = "display:none";
            CurrentAppContainer.Style.Value = CurrentAppContainerStyle;
            TestAppURL.Text = "";
            ShowAppControls();
        }
        else //preview mode
        {
            //save Page first
            if (SavedCanvasHtml.Text.Length > 0)
                SavePage();

            HideAppControls();
            DisplayModeButton.Style.Value = "";//don't hide the toggle button
            CurrentAppContainer.Style.Value = "display:none";

            State["WebAppMode"] = "preview";
            WebAppsUtil web_util = new WebAppsUtil();
            AmazonS3 s3 = new AmazonS3();
            State["IsProduction"] = false;
            string file_name =  State["SelectedApp"].ToString().Replace(" ", "_") + Constants.WEB_APP_TEST_SUFFIX +"/index.html";

            string save_file_path =  HttpRuntime.Cache["TempFilesPath"].ToString() + State["Username"].ToString() + "." + file_name.Replace(Constants.WEB_APP_TEST_SUFFIX + "/index.html", ".html");

            string ret = web_util.GetWebApp(State, util.GetStagingAppXml(State), 1.0D,1.0D);
            if (ret.StartsWith("Error:"))
            {
                Message.Text = ret;
                DisplayMode_Click(null, null);
                return;
            }
            File.WriteAllText(save_file_path, ret);

            if ( State["UrlAccountIdentifier"] == null)
            {
                Message.Text = "The Account Identifier has not been set.";
                return;
            }
            string key =  State["UrlAccountIdentifier"].ToString() + "/" + file_name;
            s3.UploadFileWithKey(State, file_name, save_file_path,key);
            string url = "http://viziapps.s3-website-us-east-1.amazonaws.com/" +  State["UrlAccountIdentifier"].ToString() + "/" +  State["SelectedApp"].ToString().Replace(" ", "_") + Constants.WEB_APP_TEST_SUFFIX;
            canvas.Attributes["src"] = url;

            if (File.Exists(save_file_path))
                File.Delete(save_file_path);

            BitlyData.LoginName = ConfigurationManager.AppSettings["BitlyLoginName"];
            BitlyData.APIKEY = ConfigurationManager.AppSettings["BitlyAPIKey"];
            String bitly_url = Bitly.ShortURL(url, Bitly.Format.TXT);
            QRCode.Src = Bitly.GetQRCodeURL(bitly_url);

            TestAppURL.Text = "Test App URL: " + bitly_url;
            QRCode.Style.Value = "";
            QRCodeLabel.Style.Value = "";
            QRCodeLabel.Text = "QR Code for Test Web App: " +  State["SelectedApp"].ToString() + ". Capture the URL from this image with any app that reads QR codes and you will see your app on your device in seconds." ;
            DisplayModeValue.Text = "";
            SavedCanvasHtml.Text = "";
        }
    }
    protected void ShowPublishedWebApp()
    {
        Util util = new Util();
        Hashtable State = (Hashtable)HttpRuntime.Cache[Session.SessionID];
        if (util.CheckSessionTimeout(State, Response, "Default.aspx")) return;

        if (State["SelectedApp"] == null || State["SelectedApp"].ToString().Contains("->"))
            return;

        WebAppsUtil web_util = new WebAppsUtil();
        AmazonS3 s3 = new AmazonS3();
        State["IsProduction"] = true;

        string file_name = State["SelectedApp"].ToString().Replace(" ", "_") + Constants.WEB_APP_TEST_SUFFIX + "/index.html";
        string save_file_path =  HttpRuntime.Cache["TempFilesPath"].ToString() + State["Username"].ToString() + "." + file_name.Replace(Constants.WEB_APP_TEST_SUFFIX + "/index.html", ".html");

        string ret = web_util.GetWebApp(State, util.GetStagingAppXml(State),1.0D, 1.0D);
        if (ret.StartsWith("Error:"))
        {
            PublishMessage.Text = ret;
             return;
        }
        File.WriteAllText(save_file_path, ret);

        if (State["UrlAccountIdentifier"] == null)
        {
            PublishMessage.Text = "The Account Identifier has not been set.";
            return;
        }
        string key = State["UrlAccountIdentifier"].ToString() + "/" + file_name;
        s3.UploadFileWithKey(State, file_name, save_file_path, key);
        string url = "http://viziapps.s3-website-us-east-1.amazonaws.com/" + State["UrlAccountIdentifier"].ToString() + "/" + State["SelectedApp"].ToString().Replace(" ", "_") ;

        if (File.Exists(save_file_path))
            File.Delete(save_file_path);

        BitlyData.LoginName = ConfigurationManager.AppSettings["BitlyLoginName"];
        BitlyData.APIKEY = ConfigurationManager.AppSettings["BitlyAPIKey"];
        String bitly_url = Bitly.ShortURL(url, Bitly.Format.TXT);
        QRCode.Src = Bitly.GetQRCodeURL(bitly_url);

        PublishedAppURL.Text = "Published App URL: " + bitly_url;
        QRCode.Style.Value = "";
        QRCodeLabel.Style.Value = "";
        QRCodeLabel.Text = "QR Code for Published Web App: " + State["SelectedApp"].ToString() + ". Capture the URL from this image with any app that reads QR codes and you will see your app on your device in seconds.";
    }
    protected XmlDocument GetDesign(string application_id, string user_id, string customer_id,
        int device_display_width, int device_display_height, string app_status, string time_stamp)
    {
        XmlUtil x_util = new XmlUtil();
        Util util = new Util();
        DB db = new DB();
        Hashtable State = (Hashtable)HttpRuntime.Cache[Session.SessionID];
        string sql = "SELECT application_name,application_type FROM applications WHERE application_id='" + application_id + "'";
        DataRow[] rows = db.ViziAppsExecuteSql(State, sql);
        DataRow row = rows[0];
        string application_name = row["application_name"].ToString();
        string application_type = row["application_type"].ToString();
        State["SelectedApp"] = application_name;

        XmlDocument Design = null;
        if (app_status == "staging")
        {
            Design = util.GetStagingAppXml(State, application_name);
        }
        else
        {
            Design = util.GetProductionAppXml(State, application_name);
        }

        if (Design == null)
            return null;

        if (application_type == Constants.HYBRID_APP_TYPE)
        {
            WebAppsUtil w_util = new WebAppsUtil();
            State["SelectedAppType"] = Constants.HYBRID_APP_TYPE;
             HttpRuntime.Cache["NewWebAppHtml"] = File.ReadAllText(Server.MapPath(".") + @"\App_Data\NewViziAppsWebApp.txt");
             HttpRuntime.Cache["NewHybridAppXml"] = File.ReadAllText(Server.MapPath(".") + @"\App_Data\NewViziAppsHybridApp.xml");
             HttpRuntime.Cache["ShareThisScripts"] = File.ReadAllText(Server.MapPath(".") + @"\App_Data\ShareThisScripts.txt");
             HttpRuntime.Cache["TempFilesPath"] = Server.MapPath(".") + @"\temp_files\";

            State["Username"] = util.GetUsernameFromCustomerID(State, customer_id);
            //get original design display width and height
            string device_design_width = Design.SelectSingleNode("//configuration/device_design_width").InnerText;
            string device_design_height = Design.SelectSingleNode("//configuration/device_design_height").InnerText;
            double x_size_factor = 1.0D;
            double y_size_factor = 1.0D;
            if (device_display_width > 600)
            {
                x_size_factor = Convert.ToDouble(device_display_width) / Convert.ToDouble(device_design_width);
                y_size_factor = Convert.ToDouble(device_display_height) / Convert.ToDouble(device_design_height);
            }
            if (app_status == "production")
                State["IsProduction"] = true;
            else
                State["IsProduction"] = false;
            string html = w_util.GetWebApp(State, Design, x_size_factor, y_size_factor);
            Design = x_util.GenerateHybridAppXml(State, Design, device_display_width.ToString(), device_display_height.ToString(), html);
        }
        XmlNode configuration = Design.SelectSingleNode("//configuration");

        if (user_id != null && user_id.Length > 0)
            x_util.CreateNode(Design, configuration, "user_id", user_id);
        x_util.CreateNode(Design, configuration, "customer_id", customer_id);
        XmlNode app_node = Design.SelectSingleNode("//application");
        if (time_stamp == null)
        {
            if (app_status == "staging")
            {
                time_stamp = util.GetStagingAppTimeStamp(State, application_id);
            }
            else
            {
                time_stamp = util.GetProductionAppTimeStamp(State, application_id);
            }
        }

        x_util.CreateNode(Design, app_node, "time_stamp", time_stamp);
        XmlNode id_node = app_node.SelectSingleNode("id");
        if (id_node == null)
            x_util.CreateNode(Design, app_node, "id", application_id);
        else
            id_node.InnerText = application_id;

        XmlNode root = Design.SelectSingleNode("app_project");
        if (root == null)
            root = Design.SelectSingleNode("mobiflex_project");

        XmlNode status_node = x_util.CreateNode(Design, root, "status", "OK");

        return Design;
    }
    protected void Publish_Click(object sender, EventArgs e)
    {
        Util util = new Util();
        Hashtable State = (Hashtable)HttpRuntime.Cache[Session.SessionID];
        if (util.CheckSessionTimeout(State, Response, "../../Default.aspx")) return;

        //check if entries were set
        DB db = new DB();
        StringBuilder b_sql = new StringBuilder("SELECT * FROM applications ");
        b_sql.Append("WHERE application_name='" + State["SelectedApp"].ToString() + "'");
        b_sql.Append(" AND customer_id='" +  State["CustomerID"].ToString() + "'");
        DataRow[] rows = db.ViziAppsExecuteSql(State, b_sql.ToString());
        DataRow row = rows[0];
         if (row["production_app_name"] == DBNull.Value || row["production_app_name"].ToString().Length == 0)
         {
             PublishMessage.Text = "The Published App Name needs to be set and saved";
            return;
         }
         if (row["production_app_xml"] == DBNull.Value)
         {
             PublishMessage.Text = "The Publish Design needs to be saved";
            return;
         }

        string icon_url = util.GetApplicationLargeIcon(State,  State["ApplicationID"].ToString());
        if (icon_url == null || icon_url.Length == 0)
        {
            PublishMessage.Text = "The Icon image needs to be uploaded";
            return;
        }
        string splash_url = util.GetApplicationSplashImage(State,  State["ApplicationID"].ToString());
        if (splash_url == null || splash_url.Length == 0)
        {
            PublishMessage.Text = "The splash image needs to be uploaded";
            return;
        }

        //check on paid service
        //is payment current
        XmlUtil x_util = new XmlUtil();
        Hashtable features = util.IsProductionAppPaid(State);
        if (features == null)
        {
            PublishMessage.Text = "A production service needs to be paid for your app.";
            return;
        }
        else //check number of pages
        {
            int page_count = x_util.GetProductionAppPageCount(State);
            int sku_page_count = (int)features["max_pages"];
            if (page_count > sku_page_count)
            {
                PublishMessage.Text = "Your production app of " + page_count.ToString() + " pages exceeds the page limit of " + sku_page_count .ToString() + " for the production service you paid for.";
                return;
            }
        }

        State["UrlAccountIdentifier"] = util.GetUrlAccountIdentifier(State);
        if (State["UrlAccountIdentifier"].ToString().Length == 0)
        {
            PublishMessage.Text = "The Account Identifier has not been set. Go the Design Page and set the Account Identifier in the app properties";
            return;
        }

        WebAppsUtil web_util = new WebAppsUtil();
        AmazonS3 s3 = new AmazonS3();
        State["IsProduction"] = true;

        string file_name = State["SelectedApp"].ToString() + "/index.html";
        file_name = file_name.Replace(" ", "_");
        string save_file_path =  HttpRuntime.Cache["TempFilesPath"].ToString() + State["Username"].ToString() + "." + file_name.Replace("/index.html", ".html");

        if (File.Exists(save_file_path))
            File.Delete(save_file_path);

        string html = web_util.GetWebApp(State,util.GetStagingAppXml(State),1.0D,1.0D);
        File.WriteAllText(save_file_path, html);
         string key =  State["UrlAccountIdentifier"].ToString() + "/" + file_name;
        s3.UploadFileWithKey(State, file_name, save_file_path, key);

        if (File.Exists(save_file_path))
            File.Delete(save_file_path);

        string filename =  State["SelectedApp"].ToString().Replace(" ", "_") + "_qrcode.png";

        string url = "http://viziapps.s3-website-us-east-1.amazonaws.com/" +  State["UrlAccountIdentifier"].ToString() + "/" +  State["SelectedApp"].ToString().Replace(" ", "_");
        PublishMessage.Text = "Pulished App URL: " + url;

        BitlyData.LoginName = ConfigurationManager.AppSettings["BitlyLoginName"];
        BitlyData.APIKEY = ConfigurationManager.AppSettings["BitlyAPIKey"];
        String bitly_url = Bitly.ShortURL(url, Bitly.Format.TXT);
        QRCode.Src = Bitly.GetQRCodeURL(bitly_url);
        PublishedAppURL.Text = "Short-length published App URL: " + bitly_url;

        QRCode.Style.Value = "";
        QRCodeLabel.Style.Value = "";
        QRCodeLabel.Text = "QR Code for Published Web App: " + State["SelectedApp"].ToString() + ". Capture the URL from this image with any app that reads QR codes and you will see your app on your device in seconds.";
    }
    /* protected void GoToWebAppDesign_Click(object sender, EventArgs e)
    {
        Util util = new Util();
        Hashtable State = (Hashtable)HttpRuntime.Cache[Session.SessionID];
        if (util.CheckSessionTimeout(State, Response, "Default.aspx")) return;

        if (SavedCanvasHtml.Text.Length > 0)
            SavePage();
        if (State["SelectedApp"] != null &&
            !State["SelectedApp"].ToString().Contains("->") &&
            SaveBeforeChangingAppType.Text.Length > 0)
        {
            SaveBeforeChangingAppType.Text = "";
           // util.SetAppType(State, Constants.WEB_APP_TYPE);
        }
        else
        {
            InitCurrentApp("->");
        }
        Response.Redirect("TabDesignWeb.aspx", false);
    }*/
    protected void DisplayMode_Click(object sender, EventArgs e)
    {
        Util util = new Util();
        Hashtable State = (Hashtable)HttpRuntime.Cache[Session.SessionID];
        if (util.CheckSessionTimeout(State, Response, "Default.aspx")) return;

        if (State["SelectedApp"] == null || State["SelectedApp"].ToString().Contains("->"))
            return;

        int index = DisplayModeButton.SelectedToggleStateIndex;

        if (index == 0)//design mode
        {
             State["WebAppMode"] = null;//design mode is the default
            canvas.Attributes["src"] = "canvas.aspx";
            DesignMessage.Text = "";
            CurrentAppContainer.Style.Value = CurrentAppContainerStyle;
            PreviewNote.Text = "";
            ShowAppControls();
        }
        else //preview mode
        {
            //save Page first
            if (SavedCanvasHtml.Text.Length > 0)
                SavePage();

            HideAppControls();
            DisplayModeButton.Style.Value = "";//don't hide the toggle button
            CurrentAppContainer.Style.Value = "display:none";
            State["WebAppMode"] = "preview";

            //validate fields next
            XmlUtil x_util = new XmlUtil();
            Message.Text = "";
            x_util.ValidateFieldNames(State, Message);
            if (Message.Text != "All fields have been validated")
            {
                PreviewNote.Text = "There were errors in generating your app. Return to design mode to fix the errors.";
                DisplayModeValue.Text = "";
                SavedCanvasHtml.Text = "";
                return;
            }
            Message.Text = "";
            WebAppsUtil web_util = new WebAppsUtil();
            AmazonS3 s3 = new AmazonS3();

            State["IsProduction"] = false;
            string file_name =  State["SelectedApp"].ToString().Replace(" ", "_") + Constants.WEB_APP_TEST_SUFFIX +"/index.html";
            string save_file_path =  HttpRuntime.Cache["TempFilesPath"].ToString() + State["Username"].ToString() + "." + file_name.Replace(Constants.WEB_APP_TEST_SUFFIX + "/index.html", ".html");

            if (State["UrlAccountIdentifier"] == null)
            {
                Message.Text = "The Account Identifier has not been set.";
                return;
            }

            string html = web_util.GetWebApp(State,util.GetStagingAppXml(State),1.0D, 1.0D);
            if (html.StartsWith("Error:"))
            {
                Message.Text = html;
                DisplayMode_Click(null, null);
                return;
            }
            File.WriteAllText(save_file_path, html);

            string key =  State["UrlAccountIdentifier"].ToString() + "/" + file_name;
            s3.UploadFileWithKey(State, file_name, save_file_path,key);
            string url = "http://viziapps.s3-website-us-east-1.amazonaws.com/" +  State["UrlAccountIdentifier"].ToString() + "/" +  State["SelectedApp"].ToString().Replace(" ", "_") + Constants.WEB_APP_TEST_SUFFIX;
            canvas.Attributes["src"] = url;

            if (File.Exists(save_file_path))
                File.Delete(save_file_path);

            PreviewNote.Text = "This preview cannot show actions with native device resources. To test those actions, go to design mode and select this app for testing on your device.";
            DisplayModeValue.Text = "";
            SavedCanvasHtml.Text = "";
        }
    }