protected void Page_Load(object sender, EventArgs e)
        {
            // validate module
            // load module
            ModuleInfo _mod = null;
            PortalSettings portalSettings = DotNetNuke.Entities.Portals.PortalController.GetCurrentPortalSettings();

            try {
                ModuleController modCtrl = new ModuleController();
                int mid = Convert.ToInt32(Request.Params["mid"]);

                ArrayList mods = modCtrl.GetModuleTabs(mid);
                if (mods == null || mods.Count == 0) {
                    throw new Exception();
                }

                _mod = (ModuleInfo)mods[0];
                if (_mod == null || _mod.ModuleID <= 0) {
                    throw new Exception();
                }
            } catch (Exception ex) {
                _mod = null;
            }

            if (_mod == null) {
                Response.Write("Invalid Module!");
            } else {


                if (Request.Files != null && Request.Files.Count > 0) {
                    try {
                        string parentFolder = uploadPath.Value;
                        if (parentFolder.Length > 0 && parentFolder[parentFolder.Length - 1] != '\\')
                            parentFolder += '\\';

                        string path = portalSettings.HomeDirectoryMapPath + parentFolder + Path.GetFileName(Request.Files[0].FileName);
                        if (File.Exists(path)) {
                            if (cbUploadOverwrite.Checked) {
                                File.Delete(path);
                            } else {
                                throw new Exception("A file with the same name already exists. ");
                            }
                        }

                        Request.Files[0].SaveAs(path);
                        Response.Write(uploadPath.Value);
                    } catch (Exception ex) {
                        Response.Write("Error uploading file (Server response: " + ex.Message + ")");
                    }

                    Response.End();
                }



                if (!Page.IsPostBack) {

                    try {
                        // load module settings
                        ModuleController modCtrl = new ModuleController();
                        int mid = Convert.ToInt32(Request.Params["mid"]);

                        ArrayList mods = modCtrl.GetModuleTabs(mid);
                        if (mods == null || mods.Count == 0) {
                            throw new Exception();
                        }

                        ModuleInfo mod = (ModuleInfo)mods[0];
                        if (mod == null || mod.ModuleID <= 0) {
                            throw new Exception();
                        }

                        FastShotSettings fsSettings = new FastShotSettings();
                        fsSettings.Load(mod.ModuleID);

                        // load templates
                        List<string> templates = new List<string>();
                        foreach (string dir in System.IO.Directory.GetDirectories(Server.MapPath(TemplateSourceDirectory + "/templates/"))) {
                            if (System.IO.Path.GetFileName(dir)[0] == '.') {
                                continue;
                            }
                            foreach (string subDir in System.IO.Directory.GetDirectories(dir)) {
                                if (System.IO.Path.GetFileName(subDir)[0] == '.') {
                                    continue;
                                }
                                templates.Add(JsonEncode(System.IO.Path.GetFileName(dir) + "/" + System.IO.Path.GetFileName(subDir)));
                            }
                        }

                        Page.ClientScript.RegisterStartupScript(GetType(), "initSettings", "avt.fs.settings = {mid: " + fsSettings.ModuleId.ToString() + ", title: '" + JsonEncode(mod.ModuleTitle) + "', template: '" + JsonEncode(fsSettings.Template) + "', thumb_w: " + fsSettings.ThumbWidth + ", thumb_h: " + fsSettings.ThumbHeight + "};", true);
                        Page.ClientScript.RegisterStartupScript(GetType(), "initTemplates", "avt.fs.templates = [\"" + string.Join("\",\"", templates.ToArray()) + "\"];", true);
                        Page.ClientScript.RegisterStartupScript(GetType(), "initReturnUrl", "avt.fs.returnUrl = \"" + DotNetNuke.Common.Globals.NavigateURL(mod.TabID) + "\";", true);
                        
                    } catch {
                        Page.ClientScript.RegisterStartupScript(GetType(), "initSettings", "avt.fs.settings = {mid: -1, title = 'Invalid Module'};", true);
                    }

                    FastShotController fsCtrl = new FastShotController();
                    if (fsCtrl.IsActivated()) {
                        btnActivate.Visible = false;
                    } else {
                        btnActivate.Attributes["onclick"] = "window.location='" + TemplateSourceDirectory + "/Activation.aspx?rurl=" + Server.UrlEncode(Request.Url.OriginalString) + "';";
                    }
                }
            }

            //AJAX.RegisterScriptManager();
            //SearchBoostController sbCtrl = new SearchBoostController();
            //PortalController portalCtrl = new PortalController();

            //// init instances
            //if (DotNetNuke.Entities.Users.UserController.GetCurrentUserInfo().IsSuperUser) {
            //    ScriptManager.RegisterStartupScript(this, GetType(), "initInstAll", "avt.sb.inst = " + GetInstAllJson() + "; avt.sb.inst.byPortal = {};", true);
            //    foreach (PortalInfo portaInfo in portalCtrl.GetPortals()) {
            //        ScriptManager.RegisterStartupScript(this, GetType(), "initInstP" + portaInfo.PortalID.ToString(), "avt.sb.inst.byPortal[" + portaInfo.PortalID.ToString() + "] = {caption: '"+ portaInfo.PortalName +" (Id: "+ portaInfo.PortalID.ToString() +")', data: " + GetInstJson(portaInfo.PortalID) + "};", true);
            //    }
            //} else {
            //    ScriptManager.RegisterStartupScript(this, GetType(), "initInstAll", "avt.sb.inst = " + GetInstAllJson(DotNetNuke.Entities.Portals.PortalController.GetCurrentPortalSettings().PortalId) + ";", true);
            //}

            //// init instances on current portal
            //ScriptManager.RegisterStartupScript(this, GetType(), "initInstC", "avt.sb.inst.cPortal = " + GetInstJson(DotNetNuke.Entities.Portals.PortalController.GetCurrentPortalSettings().PortalId) + ";", true);

            //// init custom rules
            //ScriptManager.RegisterStartupScript(this, GetType(), "initSearchTargets", "avt.sb.targets = " + GetRulesJson() + ";", true);

            //// set return url
            //if (Request.UrlReferrer != null && !string.IsNullOrEmpty(Request.UrlReferrer.ToString()) && !Request.UrlReferrer.ToString().Contains("SearchBoostStudio.aspx") && !Request.UrlReferrer.ToString().Contains("/avt.SearchBoost/Activation.aspx")) {
            //    ScriptManager.RegisterStartupScript(this, GetType(), "initReturnUrl", "avt.sb.returnUrl = '" + Request.UrlReferrer.ToString() + "';", true);
            //} else {
            //    ScriptManager.RegisterStartupScript(this, GetType(), "initReturnUrl", "avt.sb.returnUrl = '" + HttpRuntime.AppDomainAppVirtualPath + "';", true);
            //}

            //// set if superuser
            //if (DotNetNuke.Entities.Users.UserController.GetCurrentUserInfo().IsSuperUser) {
            //    ScriptManager.RegisterStartupScript(this, GetType(), "initSuperUSer", "avt.sb.isSuperUser = true;", true);
            //}

            //// check if we need to load an instance on startup
            //if (!string.IsNullOrEmpty(Request.QueryString["iinst"])) {
            //    SearchInstance searchInst = sbCtrl.GetInstance(Request.QueryString["iinst"]);
            //    if (searchInst != null) {
            //        ScriptManager.RegisterStartupScript(this, GetType(), "initCurrentInstance", "avt.sb.current = '" + Request.QueryString["iinst"] + "';", true);
            //    }
            //}

            //if (sbCtrl.IsActivated()) {
            //    btnActivate.Visible = false;
            //} else {
            //    btnActivate.Attributes["onclick"] = "window.location='" + TemplateSourceDirectory + "/Activation.aspx?rurl=" + Server.UrlEncode(Request.Url.OriginalString) + "';";
            //}
        }
        protected void OnActivate(Object Sender, EventArgs args)
        {
            txtRegistrationCode.Text = txtRegistrationCode.Text.Trim();

            FastShotController redirCtrl = new FastShotController();
            AvtRegCoreClient regClient = redirCtrl.GetRegCoreClient();

            AvtActivation act;
            try {
                act = regClient.Activate(txtRegistrationCode.Text, FastShotController.ProductCode, FastShotController.Version, ddHosts.SelectedValue, FastShotController.ProductKey);
            } catch (Exception ex) {
                // error
                validateActivation.Text = ex.Message;
                validateActivation.IsValid = false;
                return;
            }

            // activation succesfull
            pnlSuccess.Visible = true;
            pnlActivateForm.Visible = false;
            btnClose.Text = "Close";
            lnkPurchase.Visible = false;

        }
        public void RenderItems()
        {
            FastShotController fShotCtrl = new FastShotController();

            FastShotSettings FsSettings = new FastShotSettings();
            FsSettings.Load(ModuleId);

            bool isActivated = false;
            try {
                isActivated = fShotCtrl.IsActivated();
            } catch (System.Net.WebException) {
                isActivated = false;
            }

            List<ItemInfo> items = fShotCtrl.GetItems(ModuleId);

            StringBuilder strXML = new StringBuilder();
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.OmitXmlDeclaration = true;
            XmlWriter Writer = XmlWriter.Create(strXML, settings);

            Writer.WriteStartElement("fastshot");
            Writer.WriteElementString("root", TemplateSourceDirectory + "/");
            Writer.WriteElementString("mid", ModuleId.ToString());


            if (!isActivated) {
                Random rand = new Random();
                if (rand.Next(0, 20) == 1) {
                    items = new List<ItemInfo>();
                    items.Add(new ItemInfo() {
                        ImageUrl = "http://www.avatar-soft.ro/portals/0/product_logo/fastshot_large.png",
                        ThumbnailUrl = "http://www.avatar-soft.ro/portals/0/product_logo/fastshot_medium.png",
                        Title = "FastShot Demo",
                        Description = "This copy of FastShot is not activated! Visit <a href = 'http://www.avatar-soft.ro' style = 'font-weight: bold;'>www.avatar-soft.ro</a> to read more about FastShot.",
                        ThumbWidth = 115,
                        ThumbHeight = 110,
                        AutoGenerateThumb = false
                    });
                }
            }

            int maxThumbWidth = 0;
            int maxThumbHeight = 0;
            foreach (ItemInfo item in items) {
                if (item.ThumbWidth > maxThumbWidth) maxThumbWidth = item.ThumbWidth;
                if (item.ThumbHeight > maxThumbHeight) maxThumbHeight = item.ThumbHeight;
            }

            Writer.WriteElementString("max_thumb_width", maxThumbWidth.ToString());
            Writer.WriteElementString("max_thumb_height", maxThumbHeight.ToString());

            foreach (ItemInfo item in items) {
                Writer.WriteStartElement("img");
                Writer.WriteElementString("id", item.ItemId.ToString());
                Writer.WriteElementString("title", fShotCtrl.Tokenize(item.Title, ModuleConfiguration));
                Writer.WriteElementString("desc", fShotCtrl.Tokenize(item.Description, ModuleConfiguration));
                Writer.WriteElementString("thumburl", ResolveUrl(item.ThumbnailUrl));
                Writer.WriteElementString("imgurl", ResolveUrl(item.ImageUrl));
                Writer.WriteElementString("thumb_width", item.ThumbWidth.ToString());
                Writer.WriteElementString("thumb_height", item.ThumbHeight.ToString());
                Writer.WriteElementString("tplParams", item.TplParams);
                Writer.WriteEndElement(); //img
            }

            Writer.WriteEndElement(); // fastshot
            Writer.Close();

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(strXML.ToString());

            XslCompiledTransform transform = new XslCompiledTransform();
            transform.Load(Server.MapPath(TemplateSourceDirectory + "/templates/"+ FsSettings.Template +"/main.xsl"));
            System.IO.StringWriter output = new System.IO.StringWriter();

            transform.Transform(doc, null, output);
            itemContainer.InnerHtml = "";
            itemContainer.InnerHtml += output.ToString();
        }