protected void Page_Load(object sender, EventArgs e)
 {
     Shows shows = new Shows();
     DataSet ds = shows.GetAllShows();
     showPicker.DataSource = ds;
     showPicker.DataTextField = "Name";
     showPicker.DataValueField = "ShowID";
     showPicker.DataBind();
 }
        public void ProcessRequest(HttpContext context)
        {
            int ShowID = Convert.ToInt32(context.Request["showid"]);
            String userIDs = context.Request["ids"].ToString();
            String[] IDsList = userIDs.Split(',');

            Shows show = new Shows(ShowID);

            Document doc = new Document(PageSize.A4.Rotate(), 10, 10, -5, -5);
            Stream output = new MemoryStream();

            var writer = PdfWriter.GetInstance(doc, output);
            StyleSheet sheet = new StyleSheet();

            doc.Open();
            int pageCount = 0;
            foreach (String id in IDsList)
            {
                List<int> defaultUsers = new List<int>();

                int UserID = Convert.ToInt32(id);
                UserShows userShow = new UserShows(UserID, ShowID);
                printRingForUser(userShow, UserID, doc, ref defaultUsers, ref pageCount);

                List<int> tmp = null;
                foreach (int defid in defaultUsers)
                {
                    if (pageCount % 2 != 0)
                    {
                        doc.NewPage();
                    }
                    pageCount = 0;
                    printRingForUser(userShow, defid, doc, ref tmp, ref pageCount);
                }
                if (pageCount % 2 != 0)
                {
                    doc.NewPage();
                }
                pageCount = 0;

            }
            doc.Close();
            context.Response.ClearContent();
            context.Response.ContentType = "application/pdf";
            context.Response.AddHeader("content-disposition", String.Format("inline;filename=PreviewSchedule.pdf"));
            context.Response.BinaryWrite((output as MemoryStream).ToArray());
        }
 protected void Page_Load(object sender, EventArgs e)
 {
     String cmd = Request["cmd"];
     int iShowID = Convert.ToInt32(Request["showid"]);
     Shows show = new Shows(iShowID);
     ShowID.Value = iShowID.ToString();
     showName = show.ShowName;
     adminMenu.ClosingDate = "(not set)";
     DateTime tmp = new DateTime();
     if (show.ClosingDate.CompareTo(tmp) != 0)
     {
         adminMenu.ClosingDate = show.ClosingDate.ToString("dd MMM yyyy");
     }
     adminMenu.ShowDate = show.ShowDate.ToString("dd MMM yyyy");
     adminMenu.Venue = (!DBNull.Value.Equals(show.Venue) ? show.Venue : "");
     adminMenu.VenuePostcode = (!DBNull.Value.Equals(show.VenuePostcode) ? show.VenuePostcode : "");
     adminMenu.ShowName = show.ShowName;
 }
        protected void Page_Load(object sender, EventArgs e)
        {
            int showid = 0;

            if (Request["showid"] != null)
            {
                showid = Convert.ToInt32(Request["showid"]);
            } else
            {
                showid = Convert.ToInt32(Session["showid"]);
            }
            ShowID.Value = showid.ToString();
            show = new Shows(showid);
            DataSet ds = UserShows.getAllUserShowDetails(showid);
            String html = "";
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                int contactStatus = Convert.ToInt32(row["ContactStatus"]);
                String dtstr = "";
                if (row["ContactDate"] != DBNull.Value)
                {
                    DateTime dt = Convert.ToDateTime(row["ContactDate"]);
                    if (dt.Year != 1970)
                    {
                        dtstr = dt.ToString("dd-MMM hh:mm:ss");
                    }
                }
                String contactStatusStr = "Not Sent";

                if (contactStatus == 1)
                {
                    contactStatusStr = "Sent";
                }

                html += String.Format("<div usershowid='{3}' contactstatus='{4}' class='bulkitem'><div class='cb'><input type='checkbox' /></div><div class='userShowName' >{0}</div><div class='contactStatus'>{1}</div><div class='contactDate'>{2}</div></div>",
                            row["Name"], contactStatusStr, dtstr, row["UserShowsID"], contactStatus
                    );
            }

            userShowList.InnerHtml = html;
        }
        public void ProcessRequest(HttpContext context)
        {
            int ShowID = Convert.ToInt32(context.Request["showid"]);
            Shows show = new Shows(ShowID);

            String sortby = Convert.ToString(context.Request["sortby"]);

            ShowDetails sd = new ShowDetails();
            DataTable table = sd.GetShowDetails(ShowID).Tables[0];

            Document doc = new Document(PageSize.A4, -10, -50, 2, 2);
            Stream output = new MemoryStream();
            var writer = PdfWriter.GetInstance(doc, output);
            StyleSheet sheet = new StyleSheet();

            doc.Open();
            Font smallFont = new Font(Font.COURIER, 8, Font.NORMAL, Color.BLACK);
            Font normalFont = new Font(Font.COURIER, 8, Font.NORMAL, Color.BLACK);
            Font normalFontBold = new Font(Font.COURIER, 8, Font.BOLD, Color.BLACK);
            Font headerFont = new Font(Font.HELVETICA, 12, Font.BOLD, Color.BLACK);
            Font ClassTitleFont = new Font(Font.HELVETICA, 16, Font.NORMAL, Color.BLACK);
            Font bigFont = new Font(Font.HELVETICA, 25, Font.NORMAL, Color.BLACK);
            Font mediumFont = new Font(Font.HELVETICA, 20, Font.NORMAL, Color.BLACK);

            PdfPTable ptable = new PdfPTable(1);
            PdfPCell cell;

            cell = new PdfPCell();
            cell.FixedHeight = 150;
            cell.BorderWidth = 0;
            ptable.AddCell(cell);

            cell = new PdfPCell(new Phrase(new Chunk("Master List", bigFont)));
            cell.HorizontalAlignment = Element.ALIGN_CENTER;
            cell.BorderWidth = 0;
            cell.FixedHeight = 100;
            ptable.AddCell(cell);

            cell = new PdfPCell(new Phrase(new Chunk(show.ShowName, bigFont)));
            cell.HorizontalAlignment = Element.ALIGN_CENTER;
            cell.BorderWidth = 0;
            ptable.AddCell(cell);

            cell = new PdfPCell(new Phrase(new Chunk(show.ShowDate.ToString("dd MMM yyyy"), bigFont)));
            cell.BorderWidth = 0;
            cell.HorizontalAlignment = Element.ALIGN_CENTER;
            ptable.AddCell(cell);
            doc.Add(ptable);
            doc.NewPage();

            float[] colWidths = { 100, 40, 175, 200};
            int count = 0;
            String lastName = "";
            DataSet masterList = DogClasses.getMasterList(ShowID, sortby);
            String tmp = "";

            ptable = new PdfPTable(colWidths);
            cell = new PdfPCell(new Phrase(new Chunk("Handler Name", headerFont)));
            cell.BorderWidth = 0;
            ptable.AddCell(cell);

            cell = new PdfPCell(new Phrase("Ring No", headerFont));
            cell.BorderWidth = 0;
            ptable.AddCell(cell);

            cell = new PdfPCell(new Phrase("Dog Name", headerFont));
            cell.BorderWidth = 0;
            ptable.AddCell(cell);

            cell = new PdfPCell(new Phrase("Class Details", headerFont));
            cell.BorderWidth = 0;
            ptable.AddCell(cell);
            doc.Add(ptable);

            bool topBorder = false;
            Color altLine = new Color(224, 224, 224);
            foreach (DataRow row in masterList.Tables[0].Rows)
            {
                Color altColor = Color.WHITE;
                if (count % 2 == 0 )
                {
                    altColor = altLine;
                }

                MasterList masterListItem = new MasterList(row);
                ptable = new PdfPTable(colWidths);
                if (lastName == masterListItem.Name)
                {
                    cell = new PdfPCell(new Phrase(new Chunk("", normalFont)));
                    topBorder = false;
                }
                else
                {
                    topBorder = true;
                    tmp = masterListItem.Name;
                    //if (masterListItem.AltHandler > 0)
                    //{
                    //    User u = new User(masterListItem.AltHandler);
                    //    tmp = u.Name;
                    //}

                    cell = new PdfPCell(new Phrase(new Chunk(tmp, normalFont)));
                    cell.BorderColorTop = Color.BLACK;
                    cell.BorderWidthTop = 1;
                }
                cell.BorderWidth = 0;
                cell.BackgroundColor = altColor;
                ptable.AddCell(cell);

                cell = new PdfPCell(new Phrase(new Chunk(masterListItem.RingNumber.ToString(), normalFont)));
                cell.BorderWidth = 0;
                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                cell.BackgroundColor = altColor;
                if (topBorder)
                {
                    cell.BorderColorTop = Color.BLACK;
                    cell.BorderWidthTop = 1;
                }
                ptable.AddCell(cell);

                Paragraph p = new Paragraph();
                Phrase ph = new Phrase();
                ph.Add(new Chunk(masterListItem.KCName, normalFont));
                ph.Add(Chunk.NEWLINE);
                ph.Add(new Chunk(masterListItem.KCNumber, normalFont));
                cell = new PdfPCell(ph);
                cell.BorderWidth = 0;
                cell.BackgroundColor = altColor;
                if (topBorder)
                {
                    cell.BorderColorTop = Color.BLACK;
                    cell.BorderWidthTop = 1;
                }
                ptable.AddCell(cell);

                PdfPTable classDetailsTbl = new PdfPTable(1);
                List<DogClasses> dcList = DogClasses.Retrieve(masterListItem.DogID, ShowID);
                p = new Paragraph();
                bool first = true;
                foreach (DogClasses dc in dcList)
                {
                    ShowClasses sc = new ShowClasses(dc.Classid);
                    if (!first)
                    {
                        p.Add(new Chunk(String.Format(",  {0,3}:", sc.ClassNo), normalFont));
                    }
                    else
                    {
                        p.Add(new Chunk(String.Format("{0,3}:", sc.ClassNo), normalFont));
                    }
                    p.Add(new Chunk(String.Format("{0,3}", dc.RO), normalFontBold));
                    first = false;
                }

                cell = new PdfPCell(p);
                cell.BorderWidth = 0;
                classDetailsTbl.AddCell(cell);
                cell = new PdfPCell(classDetailsTbl);
                cell.BorderWidth = 0;
                cell.BackgroundColor = altColor;
                if (topBorder)
                {
                    cell.BorderColorTop = Color.BLACK;
                    cell.BorderWidthTop = 1;
                }
                ptable.AddCell(cell);

                doc.Add(ptable);

                lastName = masterListItem.Name;

                count++;
                //if (count > 100 ) break;
            }

            doc.Close();

            context.Response.ClearContent();
            context.Response.ContentType = "application/pdf";
            context.Response.AddHeader("content-disposition", String.Format("inline;filename=PreviewSchedule.pdf"));
            context.Response.BinaryWrite((output as MemoryStream).ToArray());
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            int OrgID = Convert.ToInt32(Session["OrgID"]);
            int showid = Convert.ToInt32(Session["showid"]);
            ShowID.Value = showid.ToString();
            Shows show = new Shows(showid);
            if (!IsPostBack)
            {
                String deleteCtrl = "<span class='del'>Del</span>";
                String newCtrl = "";
                showPublished = false;
                if (show.Status == (int)Shows.SHOW_STATUS.PUBLISHED)
                {
                    deleteCtrl = "";
                    newCtrl = "style='display:none;'";
                    showPublished = true;
                }

                String html = "<table id='classTypes' style='width:550px' data-type='charges'><tbody><tr class='tableHeader'><td class='itemName'>Charge Name</td><td class='itemCharge'>Charge</td><td><input class='newEntry' id='btnNewClass' type='button' value='New' "+ newCtrl + " ></td></tr>";
                List<ShowCharges> list = ShowCharges.getShowCharges(showid);
                foreach (ShowCharges sc in list)
                {
                    html += String.Format("<tr class='tableItem' data-id='{3}' ><td class='itemName'>{0}</td><td class='itemCharge'>{1:0.00}</td><td class='classControls'>{4}</td></tr>",
                                    sc.ChargeName, sc.ChargeRate, sc.Name, sc.ID, deleteCtrl);
                }
                html += "</table>";

                classChargesArea.InnerHtml = html;

                html = "<table id='classTypes' style='width:550'  data-type='classTypes'><tbody><tr class='tableHeader'><td class='longname'>Long Name</td><td class='shortname'>Short</td><td class='chargetype'>Charge Type</td><td class='entrytype'>Entry Type</td><td><input  class='newEntry' id='btnNewClass' type='button' value='New' " + newCtrl + " ></td>";
                List<ClassTypes> classTypeList = ClassTypes.GetClassTypesForShow(showid);
                //list = ShowCharges.getClassChargeDetails(showid);
                foreach (ClassTypes sc in classTypeList)
                {
                    html += String.Format("<tr data-id='{3}' data-chargetype='{5}' data-entrytype='{6}' class='tableItem'><td class='longname'>{0}</td><td class='shortname'>{1}</td><td class='chargetype'>{2}</td><td class='entrytype'>{4}</td><td class='classControls'>{7}</td></tr>",
                                    sc.LongName, sc.ShortName, sc.ChargeName, sc.ID, sc.EntryTypeName, sc.ChargeType, sc.EntryTypeID, deleteCtrl );
                }
                html += "</table>";
                classDetailsArea.InnerHtml = html;

                html = "<table id='showDiscounts' style='width:550px'  data-type='discounts'><tbody><tr class='tableHeader'><td class='height'>Discount Type</td><td class='cat'>Type</td><td class='name'>Amount</td><td class='chargetype'>Charge Type</td><td><input  class='newEntry' id='btnNewClass' type='button' value='New' " + newCtrl + " ></td>";
                List<ShowDiscounts> discountList = ShowDiscounts.getClassChargeDetails(showid);
                foreach (ShowDiscounts sc in discountList)
                {
                    String tmpCharge = "(" + sc.Charge.ToString("0.00") + ")";
                    if (sc.ChargeName.Length == 0)
                    {
                        tmpCharge = "";
                    }
                    html += String.Format("<tr data-id='{8}'   class='tableItem' data-chargetype='{3}' data-subtype='{4}' data-discounttype='{7}'  ><td class='itemName'>{0}</td><td class='subType'>{1}</td><td class='itemAmount'>{2}</td><td class='chargeType'>{5} {6}</td><td class='classControls'>{9}</td></tr>",
                                    sc.DiscountName, sc.SubTypeName, sc.Amount, sc.ChargeType, sc.Subtype, sc.ChargeName, tmpCharge, sc.DiscountType, sc.ID, deleteCtrl);
                }
                html += "</table>";
                showDiscountsArea.InnerHtml = html;

                List<EntryType> entryTypeList = EntryType.getAllEntryTypes();
                entryTypesStr = "";
                foreach (EntryType et in entryTypeList)
                {
                    if (entryTypesStr.Length > 0) entryTypesStr += ",";
                    entryTypesStr += String.Format("{{ name:'{0}', value:'{1}'  }}", et.Name, et.ID);
                }
                entryTypesStr = "[" + entryTypesStr + "]";

                List<ChargeSubTypes> subTypeList = ChargeSubTypes.getChargeSubTypes();
                subTypesStr  = "";
                foreach (ChargeSubTypes et in subTypeList)
                {
                    if (subTypesStr.Length > 0) subTypesStr += ",";
                    subTypesStr += String.Format("{{ name:'{0}', value:'{1}'  }}", et.SubTypeName.Replace("'", "&#39;"), et.ID);
                }
                subTypesStr = "[" + subTypesStr + "]";

                chargeTypesStr = "{ name:'', value: 0 }";
                foreach (ShowCharges sc in list)
                {
                    if (chargeTypesStr.Length > 0) chargeTypesStr += ",";
                    chargeTypesStr += String.Format("{{ name:'{0}', value:'{1}'  }}", sc.ChargeName,sc.ID);
                }
                chargeTypesStr = "[" + chargeTypesStr + "]";

                discountTypeStr = "";
                List<DiscountType> disTyps = DiscountType.getDiscountTypes();
                foreach (DiscountType dt in disTyps)
                {
                    if (discountTypeStr.Length > 0) discountTypeStr += ",";
                    discountTypeStr += String.Format("{{ name:'{0}', value:'{1}' }}", dt.DiscountName, dt.ID);
                }
                discountTypeStr = "[" + discountTypeStr + "]";

            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            FormsIdentity identity = (FormsIdentity)HttpContext.Current.User.Identity;
            FormsAuthenticationTicket ticket = identity.Ticket;
            // get the roles stored as UserData into the ticket
            String[] userData = ticket.UserData.Split(':');
            String[] roles = userData[0].Split(',');
            int id = Convert.ToInt32(userData[1]);
            String html = "";

            Fpp.WebModules.Business.User currentUser = new User(id);
            int ShowID = Convert.ToInt32(Request["showid"]);
            Shows show = new Shows(ShowID);

            List<ShowDetails> showDetailsList = ShowDetails.GetShowDaysList(ShowID);
            html += "<h2>" + show.ShowName + "</h2>";

            Rings r = new Rings();
            DataSet ringList = r.GetAllRingsForShow(ShowID, "ShowDate");

            Dogs d = new Dogs();

            DogClasses dc = new DogClasses();
            DateTime dt = DateTime.Now;
            Boolean newday = false;
            int currentRingID = 0;
            foreach (DataRow ringRow in ringList.Tables[0].Rows)
            {
                int RingID = Convert.ToInt32(ringRow["RingID"]);
                if (ringRow.IsNull("ClassID") )
                {
                    continue;
                }
                int ClassID = Convert.ToInt32(ringRow["ClassID"]);
                DateTime rowDT = Convert.ToDateTime(ringRow["ShowDate"]);
                if (rowDT != dt)
                {
                    newday = true;
                    if (currentRingID != 0)
                    {
                        html += "</table></div>";
                        html += "<div class='pagebreak'></div>";
                    }
                    html += "<div class='clsDate'>" + rowDT.ToString("dddd d MMM") + "</div>";
                    dt = rowDT;
                }

                if (currentRingID != RingID)
                {
                    List<Judge> judgeList = Judge.getJudgesForRingList(RingID);

                    if (currentRingID != 0 && !newday)
                    {
                        html += "</table></div>";
                    }
                    html += "<div class='Ring'>";
                    html += "<table class='roClassesTbl'>";
                    html += "<tr class='ringInfo'>";
                    html += "<td colspan='3'>" +
                                "<div class='roTitle centered'>Ring No " + ringRow["RingNo"].ToString() + "</div>";
                    foreach (Judge judge in judgeList)
                    {
                        html += "<div class='roTitle centered'>" + judge.Name + "</div>";
                    }
                    html += "</td></tr>";
                    currentRingID = RingID;
                }

                html += "<tr>";
                DataSet dogsList = d.GetDogsInClass(currentUser.UserID, ClassID);
                int DogsInClass = d.dogsInClassCount(ClassID);

                String clsName = ShowClasses.expandCatagory(ringRow) + " " + ShowClasses.expandHeight(ringRow) + ringRow["name"].ToString();
                String grades = ShowClasses.shortenGrades(ringRow);
                int ix = clsName.IndexOf("Grd");
                if (ix == -1) ix = clsName.IndexOf("Cmb");
                if (ix > -1)
                {
                    clsName = clsName.Substring(0, ix + 3) + " (" + grades + ") " + clsName.Substring(ix + 4);
                }
                else
                {
                    ix = clsName.IndexOf(" ");
                    clsName = clsName.Substring(0, ix) + " (" + grades + ") " + clsName.Substring(ix + 1);
                }

                if (dogsList.Tables[0].Rows.Count > 0)
                {
                    html += "<td valign='top' class='clsRing InClass'>" + ringRow["ClsNo"] + "</td>";
                    html += "<td  valign='top' class='clsDetails InClass'><div>" + clsName  + "</div>";
                    foreach (DataRow dogRow in dogsList.Tables[0].Rows)
                    {
                        String img = "<img src='data:image/gif;base64," + CreateImage(dogRow["DogColour"].ToString()) + "' />";

                        html += String.Format("<div class='dogInClass'><div style='background:{2};' class='dogIcon'>{3}</div>[{1}] {0}</div>", dogRow["DogName"], dogRow["RO"], dogRow["DogColour"], img);
                    }
                    html += "</td>";
                    html += "<td valign='top' class='clsEntry'><div>(" + DogsInClass+ ")</div></td>";
                }
                else
                {
                    html += "<td valign='top' class='clsRing notInClass'>" + ringRow["ClsNo"] + "</td>";
                    html += "<td valign='top' class='clsDetails notInClass'>" + clsName + "</td>";
                    html += "<td valign='top' class='clsEntry notInClass'><div>(" + DogsInClass + ")</div></td>";
                }

                html += "</tr>";
                newday = false;

            }
            html += "</table>";
            html += "</div>";
            ringPlanContainer.InnerHtml = html;
        }
        public void ProcessRequest(HttpContext context)
        {
            int ShowID = Convert.ToInt32(context.Request["showid"]);
            int RingID = Convert.ToInt32(context.Request["ringid"]);
            String cmd = context.Request["doc"].ToString();
            Shows show = new Shows(ShowID);

            ShowDetails sd = new ShowDetails();
            DataTable table = sd.GetShowDetails(ShowID).Tables[0];
            String pdfPath = context.Server.MapPath(cmd + ".pdf");
            Boolean publish = false;
            if (!String.IsNullOrEmpty(context.Request["publish"]) && context.Request["publish"].ToString() == "1") publish = true;

            Document doc = new Document(PageSize.A6, 35, 0, 20, 2);
            Stream output;
            if (publish)
            {
                String path = context.Server.MapPath(@"..\schedules\");
                path += DateTime.Today.ToString("yyyy");
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                path += String.Format("\\{0:yyyyMM}_{1}.pdf", show.ShowDate, show.ShowName);
                output = new FileStream(path, FileMode.Create);
            }
            else
            {
                output = new MemoryStream();
            }
            var writer = PdfWriter.GetInstance(doc, output);
            StyleSheet sheet = new StyleSheet();

            doc.Open();
            Font font = new Font(Font.HELVETICA, 10, Font.NORMAL, Color.BLACK);
            Font smallFont = new Font(Font.HELVETICA, 8, Font.NORMAL, Color.BLACK);
            Font notSoBigFont = new Font(Font.HELVETICA, 11, Font.BOLD, Color.BLACK);
            Font fontWhite = new Font(Font.HELVETICA, 10, Font.NORMAL, Color.WHITE);
            Font headerFont = new Font(Font.HELVETICA, 12, Font.BOLD, Color.BLACK);
            Font spaceFont = new Font(Font.HELVETICA, 40, Font.BOLD, Color.WHITE);
            Font totalsFont = new Font(Font.HELVETICA, 14, Font.BOLD, Color.BLACK);
            Font bigBoyFont = new Font(Font.HELVETICA, 20, Font.BOLD, Color.BLACK);
            Font bigBoyFont2 = new Font(Font.HELVETICA, 25, Font.BOLD, Color.BLACK);
            PdfPCell blankCell = new PdfPCell(new Phrase(new Chunk("", font)));
            ShowClasses sc = new ShowClasses();
            Rings currentRing = new Rings(RingID);
            List<ShowClasses> showClasses = ShowClasses.GetAllClassesForShowRing(ShowID, RingID);
            String tmp;
            foreach (ShowClasses showClass in showClasses)
            {
                PdfPCell cell;
                DataSet callingList = sc.getCallingList(ShowID, showClass.ID);

                String grades = showClass.Grades;
                if (grades.Length == 1)
                {
                    grades = "Grade " + grades;
                }
                else
                {
                    grades = "Grades " + grades[0] + "-" + grades[grades.Length - 1];
                }
                PdfPTable ptable = new PdfPTable(1);
                tmp = String.Format("Class {0}", showClass.ClassNo);
                cell = new PdfPCell(new Phrase(new Chunk(tmp, bigBoyFont2)));
                cell.BorderWidth = 0;
                cell.Padding = 5;
                cell.HorizontalAlignment = Element.ALIGN_MIDDLE;
                cell.VerticalAlignment = Element.ALIGN_CENTER;
                ptable.AddCell(cell);

                tmp = String.Format("{0} {1} {2} {3}", showClass.longHeight, showClass.longCatagory, showClass.LongClassName, showClass.ClassName);
                cell = new PdfPCell(new Phrase(new Chunk(tmp, totalsFont)));
                cell.BorderWidth = 0;
                cell.Padding = 5;
                cell.HorizontalAlignment = Element.ALIGN_MIDDLE;
                cell.VerticalAlignment = Element.ALIGN_CENTER;
                ptable.AddCell(cell);

                tmp = String.Format("{0}", grades);
                cell = new PdfPCell(new Phrase(new Chunk(tmp, totalsFont)));
                cell.BorderWidth = 0;
                cell.Padding = 5;
                cell.FixedHeight = 100f;
                cell.HorizontalAlignment = Element.ALIGN_MIDDLE;
                cell.VerticalAlignment = Element.ALIGN_CENTER;
                ptable.AddCell(cell);

                tmp = String.Format("Ring {0}", currentRing.RingNo);
                cell = new PdfPCell(new Phrase(new Chunk(tmp, totalsFont)));
                cell.BorderWidth = 0;
                cell.Padding = 5;
                cell.FixedHeight = 30f;
                cell.HorizontalAlignment = Element.ALIGN_MIDDLE;
                ptable.AddCell(cell);

                tmp = String.Format("Ring Order = {0}", showClass.Position + 1);
                cell = new PdfPCell(new Phrase(new Chunk(tmp, totalsFont)));
                cell.BorderWidth = 0;
                cell.Padding = 5;
                cell.FixedHeight = 30f;
                cell.HorizontalAlignment = Element.ALIGN_MIDDLE;
                ptable.AddCell(cell);

                doc.Add(ptable);
                doc.NewPage();

                foreach (DataRow row in callingList.Tables[0].Rows)
                {
                    int Cat = Convert.ToInt32(row["Catagory"]);
                    if (Cat == 0)
                    {
                        PdfPTable tbl = new PdfPTable(1);
                        int dogGrade = Convert.ToInt32(row["Grade"]);
                        if (dogGrade == 99 ) {
                            tmp = "Veteran";
                        } else {
                            tmp = String.Format("Grade {0}", row["Grade"]);
                        }
                        cell = new PdfPCell(new Phrase(new Chunk(tmp, bigBoyFont2)));
                        cell.BackgroundColor = CMYKColor.LIGHT_GRAY;
                        cell.BorderWidth = 2;
                        cell.Padding = 9;
                        cell.PaddingTop = 4;
                        cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                        tbl.AddCell(cell);
                        doc.Add(tbl);

                    }

                    float[] colWidths = { 300, 150 };
                    PdfPTable callingListTbl = new PdfPTable(colWidths);
                    tmp = String.Format("Class {0}: {1} {2} {3} {4}", showClass.ClassNo, showClass.longHeight, showClass.LongClassName, grades, showClass.ClassName);
                    cell = new PdfPCell(new Phrase(new Chunk(tmp, notSoBigFont)));
                    cell.BorderWidth = 2;
                    cell.BorderColorRight = Color.BLACK;
                    cell.BorderColorBottom = Color.BLACK;
                    cell.Padding = 5;
                    cell.PaddingTop = 1;
                    cell.PaddingLeft = 2;
                    cell.FixedHeight = 50f;
                    callingListTbl.AddCell(cell);

                    tmp = String.Format("{0}", row["RO"]);
                    cell = new PdfPCell(new Phrase(new Chunk(tmp, bigBoyFont)));
                    cell.BorderWidth = 2;
                    cell.BorderColorLeft = Color.BLACK;
                    cell.BorderColorBottom = Color.BLACK;
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    cell.Padding = 5;
                    callingListTbl.AddCell(cell);

                    cell = new PdfPCell(new Phrase(new Chunk("Course Time", notSoBigFont)));
                    cell.BorderWidth = 2;
                    cell.Padding = 5;
                    cell.BorderColorRight = Color.BLACK;
                    cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                    callingListTbl.AddCell(cell);

                    cell = new PdfPCell(new Phrase(new Chunk("", notSoBigFont)));
                    cell.BorderWidth = 2;
                    cell.Padding = 5;
                    cell.BorderColorBottom = Color.BLACK;
                    callingListTbl.AddCell(cell);

                    int DefaultHandler = Convert.ToInt32(row["DefaultHandler"]);
                    int AltHandler = Convert.ToInt32(row["AltHandler"]);
                    String handlerName = row["Name"].ToString();
                    User user;
                    if (DefaultHandler > 0)
                    {
                        user = new User(DefaultHandler);
                        handlerName = user.Name;
                    }
                    if (AltHandler > 0)
                    {
                        user = new User(AltHandler);
                        handlerName = user.Name;
                    }

                    if (showClass.EntryType == 5)
                    {
                        cell = new PdfPCell(new Phrase(new Chunk(String.Format("{0}", handlerName), smallFont)));
                        cell.BorderWidth = 0;
                        cell.Colspan = 1;
                        cell.HorizontalAlignment = Element.ALIGN_LEFT;
                        callingListTbl.AddCell(cell);

                        cell = new PdfPCell(new Phrase(new Chunk(String.Format("{0,-10}", row["KCName"]), smallFont)));
                        cell.Colspan = 1;
                        cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                        cell.BorderWidth = 0;
                    }
                    else
                    {
                        cell = new PdfPCell(new Phrase(new Chunk(String.Format("{0}", handlerName), notSoBigFont)));
                        cell.BorderWidth = 0;
                        cell.Colspan = 2;
                        callingListTbl.AddCell(cell);

                        cell = new PdfPCell(new Phrase(new Chunk(String.Format("{0,-10} {1}", row["RingNumber"], row["KCName"]), notSoBigFont)));
                        cell.BorderWidth = 0;
                    }
                    if (showClass.EntryType < 4)
                    {
                        cell.FixedHeight = 170f;
                    }
                    cell.Colspan = 2;
                    callingListTbl.AddCell(cell);

                    if (showClass.EntryType == 4 || showClass.EntryType == 5 )
                    {
                        int UserID = Convert.ToInt32(row["UserID"]);
                        int DogID = Convert.ToInt32(row["DogID"]);
                        List<MultiDog> otherHandlers = MultiDog.getMultiDog(UserID, DogID, showClass.ID);

                        int dogCnt = 0;
                        foreach (MultiDog md in otherHandlers)
                        {

                            if (dogCnt < 3)
                            {
                                //html += String.Format("<div class='dogInClass'><div style='width:8px;height:10px;' class='dogIcon'></div>[{1}] {0}</div>", md.Dogname, dogRow["RO"]);
                                if (showClass.EntryType == 4)
                                {
                                    cell = new PdfPCell(new Phrase(new Chunk(String.Format("{0}", md.Handlername), notSoBigFont)));
                                    cell.BorderWidth = 0;
                                    cell.Colspan = 2;
                                    callingListTbl.AddCell(cell);
                                    cell = new PdfPCell(new Phrase(new Chunk(String.Format("{0,-10} {1}", "", md.Dogname), notSoBigFont)));
                                    cell.BorderWidth = 0;
                                    cell.FixedHeight = 160f;
                                    cell.Colspan = 2;
                                }
                                else
                                {
                                    cell = new PdfPCell(new Phrase(new Chunk(String.Format("{0}", md.Handlername), smallFont)));
                                    cell.BorderWidth = 0;
                                    cell.Colspan = 1;
                                    cell.HorizontalAlignment = Element.ALIGN_LEFT;
                                    callingListTbl.AddCell(cell);
                                    cell = new PdfPCell(new Phrase(new Chunk(String.Format("{0,-10} {1}", "", md.Dogname), smallFont)));
                                    cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                                    cell.BorderWidth = 0;
                                    cell.Colspan = 1;

                                }
                                callingListTbl.AddCell(cell);
                            }
                            dogCnt++;
                        }

                        if (showClass.EntryType == 5)
                        {
                            cell = new PdfPCell(new Phrase(new Chunk("", smallFont)));
                            cell.BorderWidth = 0;
                            cell.FixedHeight = 140f;
                            cell.Colspan = 2;
                            callingListTbl.AddCell(cell);

                        }
                    }

                    cell = new PdfPCell(new Phrase(new Chunk("Time", notSoBigFont)));
                    cell.BorderWidth = 2;
                    cell.BorderColorRight = Color.BLACK;
                    cell.BorderColorBottom = Color.BLACK;
                    cell.Padding = 5;
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    callingListTbl.AddCell(cell);
                    callingListTbl.AddCell(blankCell);

                    cell = new PdfPCell(new Phrase(new Chunk("Course Faults", notSoBigFont)));
                    cell.BorderWidth = 2;
                    cell.BorderColorRight = Color.BLACK;
                    cell.BorderColorBottom = Color.BLACK;
                    cell.Padding = 5;
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    callingListTbl.AddCell(cell);
                    callingListTbl.AddCell(blankCell);

                    cell = new PdfPCell(new Phrase(new Chunk("Time Faults", notSoBigFont)));
                    cell.BorderWidth = 2;
                    cell.BorderColorRight = Color.BLACK;
                    cell.BorderColorBottom = Color.BLACK;
                    cell.Padding = 5;
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    callingListTbl.AddCell(cell);
                    callingListTbl.AddCell(blankCell);

                    cell = new PdfPCell(new Phrase(new Chunk("Totals Faults", notSoBigFont)));
                    cell.BorderWidth = 2;
                    cell.BorderColorRight = Color.BLACK;
                    cell.BorderColorBottom = Color.BLACK;
                    cell.Padding = 5;
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    callingListTbl.AddCell(cell);
                    callingListTbl.AddCell(blankCell);
                    doc.Add(callingListTbl);
                    doc.NewPage();

                }
            }

            doc.Close();

            if (publish)
            {

            }
            else
            {
                context.Response.ClearContent();
                context.Response.ContentType = "application/pdf";
                context.Response.AddHeader("content-disposition", String.Format("inline;filename=PreviewSchedule.pdf"));
                context.Response.BinaryWrite((output as MemoryStream).ToArray());
            }
        }
        public void ProcessRequest(HttpContext context)
        {
            //PDFBuilder.HtmlToPdfBuilder builder = new HtmlToPdfBuilder(PageSize.A4);
            //builder.AddPage();
            //builder.ImportStylesheet(context.Server.MapPath("pdfstylesheet.css"));

            int ShowID = Convert.ToInt32(context.Request["showid"]);

            Shows show = new Shows(ShowID);

            ShowDetails sd = new ShowDetails();
            DataTable table = sd.GetShowDetails(ShowID).Tables[0];
            String pdfPath = context.Server.MapPath("PreviewSchedule.pdf");
            String contents = File.ReadAllText(context.Server.MapPath("schedule1FrontPage.html"));
            Boolean publish = false;
            if (!String.IsNullOrEmpty(context.Request["publish"]) && context.Request["publish"].ToString() == "1") publish = true;

            String logoImg = context.Server.MapPath("FirstContactAgility.png") ;
            contents = contents.Replace("[CLUBLOGO]", "src='" + logoImg + "'");
            contents = contents.Replace("[SHOWDATES]", show.ShowDate.ToString("dddd, dd MMM yyyy"));
            contents = contents.Replace("[CLUBNAME]", show.ShowName);
            contents = contents.Replace("[SHOWVENUE]", show.Venue  + ", " + show.VenuePostcode);
            contents = contents.Replace("[OPENTIME]", "8:00am");
            contents = contents.Replace("[BRIEFING]", "8:15am");
            contents = contents.Replace("[JUDGINGSTARTS]", "8:30am");
            contents = contents.Replace("[SdHOWVENUE]", show.Venue + "," + show.VenuePostcode);
            contents = contents.Replace("[CLOSINGDATE]", show.ClosingDate.ToString("dd MMM yyyy"));
            contents = contents.Replace("[CHAIRMANNAME]", show.Chairman.Name);
            contents = contents.Replace("[CHAIRMANADDRESS]", show.Chairman.AddressDetails);
            contents = contents.Replace("[SECRETARYNAME]", show.Secretary.Name);
            contents = contents.Replace("[SECRETARYADDRESS]", show.Secretary.AddressDetails);
            contents = contents.Replace("[TREASURERNAME]", show.Treasurer.Name);
            contents = contents.Replace("[TREASURERADDRESS]", show.Treasurer.AddressDetails);
            contents = contents.Replace("[SHOWSECNAME]", show.ShowSec.Name);
            contents = contents.Replace("[SHOWSECADDRESS]", show.ShowSec.AddressDetails);
            contents = contents.Replace("[SHOWMANAGERNAME]", show.ShowManager.Name);
            contents = contents.Replace("[SHOWMANAGERADDRESS]", show.ShowManager.AddressDetails);
            contents = contents.Replace("[EQUIPMENTNAME]", show.Equipment.Name);
            contents = contents.Replace("[EQUIPMENTADDRESS]", show.Equipment.AddressDetails);
            contents = contents.Replace("[VETNAME]", show.Vet.Name);
            contents = contents.Replace("[VETADDRESS]", show.Vet.AddressDetails);
            contents = contents.Replace("[SHOWENTRIESNAME]", show.ShowEntries.Name);
            contents = contents.Replace("[SHOWENTRIESADDRESS]", show.ShowEntries.AddressDetails);
            contents = contents.Replace("[PAYABLENAME]", show.Payable.Name);
            contents = contents.Replace("[PAYABLEADDRESS]", show.Payable.AddressDetails);

            Document doc = new Document(PageSize.A4, 25, 10, 10, 10);
            Stream  output ;
            if (publish)
            {
                String path = context.Server.MapPath(@"..\schedules\");
                path += DateTime.Today.ToString("yyyy");
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                path += String.Format("\\{0:yyyyMMM}_{1}.pdf", show.ShowDate, show.ShowName);
                output = new FileStream(path, FileMode.Create);

                show.setStatus(Shows.SHOW_STATUS.PUBLISHED);
            } else {
                output = new MemoryStream();
            }
            var writer = PdfWriter.GetInstance(doc, output);
            StyleSheet sheet = new StyleSheet();

            doc.Open();
            var parsedHTML = HTMLWorker.ParseToList(new StringReader(contents), sheet);
            foreach (var htmlElement in parsedHTML)
            {
                doc.Add(htmlElement as IElement);
            }
            doc.NewPage();
            foreach (DataRow row in table.Rows)
            {
                ShowDetails _showDetails = new ShowDetails(row);
                DataTable showDayTable = _showDetails.GetDayData(true);

                String dayHtml = generateClassesForDay(_showDetails.ShowDetailsID, showDayTable);
                doc.NewPage();
                var dayClasses = HTMLWorker.ParseToList(new StringReader(dayHtml), sheet);
                foreach (var htmlElement in dayClasses)
                {
                    doc.Add(htmlElement as IElement);
                }
            };

            doc.NewPage();
            contents = File.ReadAllText(context.Server.MapPath("schedule2RulesNRegs.html"));
            parsedHTML = HTMLWorker.ParseToList(new StringReader(contents), sheet);
            foreach (var htmlElement in parsedHTML)
            {
                doc.Add(htmlElement as IElement);
            }

            #if TEST
            foreach (DataRow row in table.Rows)
            {
                PdfPTable pdfTable = new PdfPTable(5);
                ShowDetails _showDetails = new ShowDetails(row);
                DataTable showDayTable = _showDetails.GetDayData(true);
                String dateThing = getDateOrdinalSuffix(_showDetails.ShowDate.Day);
                String datestr = _showDetails.ShowDate.ToString("dddd MMM d").ToUpper() + dateThing;

                PdfPCell pdfCell = new PdfPCell();
                pdfCell = new PdfPCell(new Phrase(datestr ));
                pdfCell.Colspan = 5;
                pdfTable.AddCell(pdfCell);

                pdfTable.AddCell("ClsNo");
                pdfCell = new PdfPCell(new Phrase("Name"));
                pdfCell.Colspan = 3;
                pdfTable.AddCell(pdfCell);
                pdfTable.AddCell("Grades");

                pdfTable = new PdfPTable(5);
                foreach (DataRow clsRow in showDayTable.Rows)
                {
                    PdfPTable grades = new PdfPTable(7);
                    String str = clsRow["grades"].ToString();
                    for (int i = 1; i <= 7; i++)
                    {
                        if (str.IndexOf((char)(i + 48)) > -1)
                        {
                            grades.AddCell(i.ToString());
                        }
                        else
                        {
                            grades.AddCell(" ");
                        }
                    }
                    pdfTable.AddCell(clsRow["ClsNo"].ToString() );

                    pdfCell = new PdfPCell(new Phrase(clsRow["Name"].ToString()));
                    pdfCell.Colspan = 3;
                    pdfTable.AddCell(pdfCell);
                    pdfTable.AddCell(grades);
                    doc.Add(pdfTable);
                }
                doc.NewPage();
            }
            #endif
            doc.Close();

            if (publish)
            {

            }
            else
            {
                context.Response.ClearContent();
                context.Response.ContentType = "application/pdf";
                context.Response.AddHeader("content-disposition", String.Format("inline;filename=PreviewSchedule.pdf"));
                context.Response.BinaryWrite( (output as MemoryStream).ToArray());
            }
        }
        private static String readTemplate(String templateName, String type, Shows show, String UserRefNo)
        {
            String template = HttpContext.Current.Server.MapPath(@"..\Templates\" + templateName + "." + type);

            String contents = File.ReadAllText(template);
            contents = contents.Replace("[DATE_ENTERED]", DateTime.Now.ToString("dd MMM yyyy hh:mm:ss"));
            contents = contents.Replace("[SHOWNAME]", show.ShowName);
            contents = contents.Replace("[SHOWDATE]", show.ShowDate.ToString("dd MMM yyyy"));

            contents = contents.Replace("[USERREFNO]", UserRefNo);

            return contents;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            FormsIdentity identity = (FormsIdentity)HttpContext.Current.User.Identity;
            FormsAuthenticationTicket ticket = identity.Ticket;
            // get the roles stored as UserData into the ticket
            String[] userData = ticket.UserData.Split(':');
            String[] roles = userData[0].Split(',');
            int id = Convert.ToInt32(userData[1]);
            Fpp.WebModules.Business.User currentUser = new User(id);
            int ShowID = Convert.ToInt32(Request["showid"]);
            Shows show = new Shows(ShowID);

            List<ShowDetails> showDetailsList = ShowDetails.GetShowDaysList(ShowID);

            Dogs d = new Dogs();
            List<Dogs> dogsList = Dogs.GetAllDogsForHandler(currentUser.UserID, show.ShowDate);

            DogClasses dc =new DogClasses();
            String html = "";
            foreach (Dogs dog in dogsList)
            {
                html += "<div class='RunningOrder'>";
                html += "<div class='roTitle'>" + show.ShowName + " " + show.ShowDate.ToString("dd MMM yyyy") + "</div>";
                html += "<div class='bigText rightSide'>Ring No:" + dog.ID + "</div>";
                html += "<div class='bigText leftSide'>" + currentUser.Name + "</div>";
                String tmp = "Grade " + dog.Grade;
                if (dog.Grade == 99)
                {
                    tmp = "Veteran";
                }
                html += String.Format("<div class='roTitle'>({0}) {1}</div>",tmp, dog.KCName );

                DataSet runningOrders = dc.getRunningOrders(ShowID, dog.ID);
                if (runningOrders.Tables.Count > 0)
                {
                    html += "<table class='roClassesTbl'>";
                    html += "<tr class='tblHeader'>";
                    html += "<td class='clsDetails'>Class</td><td class='clsRO'>RO</td><td class='clsEntry'>Entries</td><td class='clsRing'>Ring No</td></tr>";
                    DateTime dt = DateTime.Now;
                    foreach (DataRow row in runningOrders.Tables[0].Rows)
                    {
                        html += "<tr class='tblDetails'>";
                        DateTime rowDT = Convert.ToDateTime(row["ShowDate"]);
                        if (rowDT !=  dt )
                        {
                            html += "<td colspan='4' class='clsDate'>" + rowDT.ToString("dddd") + "</td>";
                            dt = rowDT;
                            html += "</tr>";
                            html += "<tr class='tblDetails'>";
                        }
                        html += "<td class='clsDetails'>" +
                            "<span class='clsNo'>" + row["clsno"] + "</span>" +
                            row["Name"].ToString() +
                            "</td>";
                        html += "<td class='clsRO'>" + row["RO"] + "</td>";
                        html += "<td class='clsEntry'>(" + row["DogsInClass"] + ")</td>";
                        html += "<td class='clsRing'>"+  row["RingNo"] + "</td>";
                        html += "</tr>";
                    }
                    html += "</table>";
                }

                html += "</div>";
            }
            runningOrdersContainer.InnerHtml = html;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                testing = Config.GetInt("testing");

                String cmd = Request["cmd"];
                int iShowID = Convert.ToInt32(Request["showid"]);
                Shows show = new Shows(iShowID);
                ShowID.Value = iShowID.ToString();
                showName = show.ShowName;

                int startingID = -1;
                if (!String.IsNullOrEmpty(Request["ShowDetailsID"])) startingID = Convert.ToInt32(Request["ShowDetailsID"]);

                UserShows us = new UserShows();
                DataSet ds = us.getAllUsersForShow(iShowID);

                String html = "";
                html = "<input type='button' id='btnAdd' value='Add Entry' />";
                html += "<input type='button' id='btnBulkEmail' value='Email Everyone!' />";
                html += "<div class='innerContainer'>";
                int online = 0;
                int offline = 0;

                int Entries = ds.Tables[0].Rows.Count;

                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    UserShows usdetails = new UserShows(row);
                    User u = new User(usdetails.Userid);
                    //Transaction.ENTERED_BY EnteredBy = Transaction.hasShowAdminUpdateEntry(iShowID, usdetails.Userid);
                    Transaction trans = new Transaction(usdetails.Userid, iShowID);
                    Transaction.ENTERED_BY EnteredBy = (Transaction.ENTERED_BY )trans.EnteredBy;
                    String EntryType = "";
                    if (EnteredBy == Transaction.ENTERED_BY.ONLINE_ENTRY)
                    {
                        EntryType = "O";
                        online++;
                        //onlineDogs += DogClasses.countDogsInClassForShow(usdetails.Userid, iShowID);
                    }
                    else
                    {
                        EntryType = "A";
                        offline++;
                        //offlineDogs += DogClasses.countDogsInClassForShow(usdetails.Userid, iShowID);
                    }

                    String tmp = "";
                    if (usdetails.Status == 2 ) {
                        tmp = "NotPaid";
                    } else {
                        tmp = (EnteredBy == 0 ? "OnlineEntry" : "");
                    }

                    String ht = " ";
                    if (usdetails.HandlerType == 1)
                    {
                        ht = "M";
                    }
                    else if (usdetails.HandlerType == 2)
                    {
                        ht = "J";
                    }
                    /*
                    String ps = " ";
                    if (usdetails.Status == (int)UserShows.UserStatus.STATUS_SAVED)
                    {
                        ps = "S";
                    }
                    else if (usdetails.Status == (int)UserShows.UserStatus.STATUS_ENTERED_NOT_PAID)
                    {
                        ps = "N";
                    }
                     * */

                    String showRef = usdetails.ID.ToString("000000");
                    html += "<div userid='" + usdetails.Userid.ToString() + "' class='user " + tmp + "'><div class='printRP'>P</div><div class='showref'>" + showRef + "</div><div class='userShowDetails'>" + EntryType + "</div><div class='handlerType'>" + ht + "</div><div class='userName'>" + u.Name + "</div><div class='delete'>x</div></div>";
                }
                html += "</tbody></table></div>";
                handlerList.InnerHtml = html;

                showStatus = String.Format("Online Entries:{0}    Offline Entries:{1}", online, offline);
                strClassNosGradeList = fastJSON.JSON.Instance.ToJSON(ShowClasses.GetAllClassesForShow(iShowID));
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                FormsIdentity identity = (FormsIdentity)HttpContext.Current.User.Identity;
                // get the forms authetication ticket of the user
                FormsAuthenticationTicket ticket = identity.Ticket;
                // get the roles stored as UserData into the ticket
                String[] userData = ticket.UserData.Split(':');
                String[] roles = userData[0].Split(',');
                int id = Convert.ToInt32(userData[1]);
                Fpp.WebModules.Business.User currentUser = new User(id);

                UserID.Value = currentUser.ID.ToString();
                UserName.Value = currentUser.Name;

                String cmd = Request["cmd"];
                int showid = Convert.ToInt32(Request["showid"]);
                ShowID.Value = showid.ToString();
                if (cmd == "edit")
                {
                    Shows show = new Shows(showid);
                    ShowDetails showDetails = new ShowDetails();
                    showDetails.GetFrom(showid);

                    ShowDetailsID.Value = showDetails.ShowDetailsID.ToString();
                    edtClosingDate.Value = show.ClosingDate.ToString("dd MMM yyyy");
                    edtShowDate.Value = show.ShowDate.ToString("dd MMM yyyy");
                    edtVenue.Value = show.Venue;
                    edtVenuePostcode.Value = show.VenuePostcode;

                    edtShowName.Value = show.ShowName;

                    initialShowDate.Value = String.Format("{0:dd MMM yyyy}", showDetails.ShowDate);

                    System.Web.UI.HtmlControls.HtmlTableRow row = new HtmlTableRow();
                    System.Web.UI.HtmlControls.HtmlTableCell cell = new HtmlTableCell();

                    row.Attributes.Add("class", "tableHeader");

                    cell.InnerHtml = "Show Day";
                    cell.Attributes.Add("class", "showDate");
                    row.Cells.Add(cell);

                    cell = new HtmlTableCell();
                    cell.InnerHtml = "Classes";
                    cell.Attributes.Add("class", "classSummary");
                    row.Cells.Add(cell);

                    cell = new HtmlTableCell();
                    cell.InnerHtml = "<input id='btnNewDay' type='button' value='New Day' />";
                    row.Cells.Add(cell);
                    classSummary.Rows.Add(row);

                    DataTable table = showDetails.GetAllShows().Tables[0];

                    if (table != null)
                    {

                        foreach (DataRow dataRow in table.Rows)
                        {
                            row = new HtmlTableRow();
                            row.Attributes.Add("class", "tableDetails");
                            row.Attributes.Add("showdate", String.Format("{0:yyyy-MM-dd}", dataRow["ShowDate"]));
                            row.Attributes.Add("id", String.Format("{0}", dataRow["ShowDetailID"]));

                            cell = new HtmlTableCell();
                            cell.InnerHtml = String.Format("{0:dddd, dd MMM}", dataRow["ShowDate"]);
                            cell.Attributes.Add("class", "showDate");
                            row.Cells.Add(cell);

                            cell = new HtmlTableCell();
                            cell.InnerHtml = String.Format("({0} Classes)", dataRow["Classes"]);
                            cell.Attributes.Add("class", "classNumber");
                            row.Cells.Add(cell);

                            cell = new HtmlTableCell();
                            cell.Attributes.Add("class", "classControls");
                            cell.InnerHtml = "<span class='del'>DEL</span>";
                            row.Cells.Add(cell);
                            classSummary.Rows.Add(row);
                        }
                    }

                }
            }
        }
        public static UserShows SaveEntry(HttpContext context, String data, Fpp.WebModules.Business.User currentUser, Shows thisShow)
        {
            DogClasses dc = new DogClasses();
            int handlertype = Convert.ToInt32(context.Request["handlertype"]);
            String[] dogs = data.Split(',');
            String[] altHandlersList = context.Request["althandlerslist"].Split(',');
            int waitingList = Convert.ToInt32(context.Request["waitinglist"]);

            //
            //  Multidog format is packed as
            //  <dogid>@<clsid>:<handlername>.<dogname>[;<handlername>.<dogname>][,<dogid>#<clsid>:<handlername>.<dogname>[;<handlername>.<dogname>]]
            //
            MultiDog.DeleteUserFromShow(currentUser.ID, thisShow.ID);
            String[] pairTeams = context.Request["pairteams"].Split(',');
            if (!String.IsNullOrEmpty(context.Request["pairteams"])) {
                foreach (String pairTeam in pairTeams)
                {
                    String[] pt = pairTeam.Split(';');
                    int DogID = -1;
                    int ClsID = -1; ;

                    foreach (String p in pt)
                    {
                        String[] dogcls;
                        String[] otherHandlerDog;
                        if (p.IndexOf(':') > 0)
                        {
                            dogcls = p.Split(':')[0].Split('@');
                            DogID = Convert.ToInt32(dogcls[0]);
                            ClsID = Convert.ToInt32(dogcls[1]);
                            otherHandlerDog = p.Split(':')[1].Split('.');

                            String []handlerDetails = otherHandlerDog[0].Split('-');
                            if (handlerDetails.Length > 1)
                            {
                                String handlerName = handlerDetails[0];
                                int handlerID = -1;
                                int.TryParse(handlerDetails[1], out handlerID);

                                String[] dogDetails = otherHandlerDog[1].Split('-');
                                String dogName = dogDetails[0];
                                int dogID = -1;
                                int.TryParse(dogDetails[1], out  dogID );

                                MultiDog.Add(currentUser.ID, DogID, ClsID, thisShow.ID, handlerName, dogName, handlerID, dogID);
                            }
                            else
                            {
                                MultiDog.Add(currentUser.ID, DogID, ClsID, thisShow.ID, otherHandlerDog[0], otherHandlerDog[1]);
                            }
                        }
                        else
                        {
                            otherHandlerDog = p.Split('.');
                            String[] handlerDetails = otherHandlerDog[0].Split('-');
                            if (handlerDetails.Length > 1)
                            {
                                String handlerName = handlerDetails[0];
                                int handlerID = -1;
                                int.TryParse(handlerDetails[1], out handlerID);

                                String[] dogDetails = otherHandlerDog[1].Split('-');
                                String dogName = dogDetails[0];
                                int dogID = -1;
                                int.TryParse(dogDetails[1], out  dogID);

                                MultiDog.Add(currentUser.ID, DogID, ClsID, thisShow.ID, handlerName, dogName, handlerID, dogID);
                            }
                        }
                    }
                }
            }

            foreach (String dog in dogs)
            {
                String[] details = dog.Split(':');
                int dogid = Convert.ToInt32(details[0]);

                String[] clslist = details[1].Split('.');
                List<int> classes = new List<int>();
                List<int> altHandlers = new List<int>();
                foreach (String clsid in clslist)
                {
                    if (clsid.Length > 0)
                    {
                        int altid = 0;
                        classes.Add(Convert.ToInt32(clsid));
                        for (int ii = 0; ii < altHandlersList.Length; ii++)
                        {
                            String[] kvPairs = altHandlersList[ii].Split(':');
                            if (kvPairs[0] == clsid && kvPairs[2] == details[0])
                            {
                                altid = Convert.ToInt32(kvPairs[1]);
                            }
                        }
                        altHandlers.Add(altid);
                    }
                }
                dc.Save(dogid, thisShow.ID, classes, altHandlers);
            }

            UserShows us = new UserShows(currentUser.ID, thisShow.ID);
            us.Status = us.Status = (int)UserShows.UserStatus.STATUS_SAVED ;

            //
            // add check to see if this person is on the judging list.
            if (Judge.isJudgeAtShow(currentUser.ID, thisShow.ID))
            {
                us.HandlerType = (int)UserShows.HandlerTypes.JUDGE;
            }
            else
            {
                us.HandlerType = handlertype;
            }
            if ( !String.IsNullOrEmpty(context.Request["optout"] )  ) {
                us.Optout = Convert.ToInt32(context.Request["optout"]);
            }
            us.Save();

            Camping camping = new Camping(thisShow.ID);
            if (camping.ID > -1)
            {
                String campParty = "";
                String campDays = "";
                String campComments = "";
                if (!String.IsNullOrEmpty(context.Request["campingdays"])) campDays = context.Request["campingdays"];
                if (!String.IsNullOrEmpty(context.Request["campingparty"])) campParty = context.Request["campingparty"];
                if (!String.IsNullOrEmpty(context.Request["campcomments"])) campComments = context.Request["campcomments"];
                if (campDays.Length > 0)
                {
                    UserCamping.Add(us.ID, campParty, campComments, campDays);
                }
            }

            if (waitingList == 1)
            {
                WaitingList.Add(us.ShowID, us.Userid);

            }

            return us;
        }
        public void ProcessRequest(HttpContext context)
        {
            //PDFBuilder.HtmlToPdfBuilder builder = new HtmlToPdfBuilder(PageSize.A4);
            //builder.AddPage();
            //builder.ImportStylesheet(context.Server.MapPath("pdfstylesheet.css"));

            int ShowID = Convert.ToInt32(context.Request["showid"]);

            Shows show = new Shows(ShowID);

            ShowDetails sd = new ShowDetails();
            DataTable table = sd.GetShowDetails(ShowID).Tables[0];
            String pdfPath = context.Server.MapPath("PreviewSchedule.pdf");
            Boolean publish = false;
            if (!String.IsNullOrEmpty(context.Request["publish"]) && context.Request["publish"].ToString() == "1") publish = true;

            Document doc = new Document(PageSize.A4, 25, 10, 10, 10);
            Stream  output ;
            if (publish)
            {
                String path = context.Server.MapPath(@"..\schedules\");
                path += DateTime.Today.ToString("yyyy");
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                path += String.Format("\\{0:yyyyMM}_{1}.pdf", show.ShowDate, show.ShowName);
                output = new FileStream(path, FileMode.Create);
            } else {
                output = new MemoryStream();
            }
            var writer = PdfWriter.GetInstance(doc, output);
            StyleSheet sheet = new StyleSheet();

            doc.Open();

            int clsNo = 0;
            ShowClasses sc = new ShowClasses();
            DataSet callingList = sc.getCallingList(ShowID);
            foreach (DataRow row in callingList.Tables[0].Rows)
            {
                if (clsNo > 0 && clsNo != Convert.ToInt32( row["ClsNo"]))  {
                    doc.NewPage();
                }

                var dayClasses = HTMLWorker.ParseToList(new StringReader(dayHtml), sheet);
                foreach (var htmlElement in dayClasses)
                {
                    doc.Add(htmlElement as IElement);
                }
            };

            doc.NewPage();
            contents = File.ReadAllText(context.Server.MapPath("schedule2RulesNRegs.html"));
            parsedHTML = HTMLWorker.ParseToList(new StringReader(contents), sheet);
            foreach (var htmlElement in parsedHTML)
            {
                doc.Add(htmlElement as IElement);
            }

            doc.Close();

            if (publish)
            {

            }
            else
            {
                context.Response.ClearContent();
                context.Response.ContentType = "application/pdf";
                context.Response.AddHeader("content-disposition", String.Format("inline;filename=PreviewSchedule.pdf"));
                context.Response.BinaryWrite( (output as MemoryStream).ToArray());
            }
        }
        public void ProcessRequest(HttpContext context)
        {
            int ShowID = Convert.ToInt32(context.Request["showid"]);
            int RingID = Convert.ToInt32(context.Request["ringid"]);
            String cmd = context.Request["doc"].ToString();
            Shows show = new Shows(ShowID);

            ShowDetails sd = new ShowDetails();
            DataTable table = sd.GetShowDetails(ShowID).Tables[0];
            String pdfPath = context.Server.MapPath(cmd + ".pdf");
            Boolean publish = false;
            if (!String.IsNullOrEmpty(context.Request["publish"]) && context.Request["publish"].ToString() == "1") publish = true;

            Document doc = new Document(PageSize.A4, -50, -50, 2, 2);
            Stream output;
            if (publish)
            {
                String path = context.Server.MapPath(@"..\schedules\");
                path += DateTime.Today.ToString("yyyy");
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                path += String.Format("\\{0:yyyyMM}_{1}.pdf", show.ShowDate, show.ShowName);
                output = new FileStream(path, FileMode.Create);
            }
            else
            {
                output = new MemoryStream();
            }
            var writer = PdfWriter.GetInstance(doc, output);
            StyleSheet sheet = new StyleSheet();

            doc.Open();
            Font font = new Font(Font.COURIER, 10, Font.NORMAL, Color.BLACK);
            Font resFont = new Font(Font.COURIER, 9, Font.ITALIC, Color.BLACK);
            Font headerFont = new Font(Font.COURIER, 10, Font.BOLD, Color.BLACK);
            Font headerFont2 = new Font(Font.HELVETICA, 12, Font.BOLD, Color.BLACK);
            Font ClassTitleFont = new Font(Font.HELVETICA, 16, Font.NORMAL, Color.BLACK);
            ShowClasses sc = new ShowClasses();
            Rings currentRing = new Rings(RingID);
            List<ShowClasses> showClasses = ShowClasses.GetAllClassesForShowRing(ShowID, RingID);
            foreach (ShowClasses showClass in showClasses)
            {
                PdfPTable ptable = new PdfPTable(3);
                PdfPCell cell;

                String grades = showClass.Grades;
                if (grades.Length == 1)
                {
                    grades = "Grade " + grades;
                }
                else
                {
                    grades = "Grades " + grades[0] + "-" + grades[grades.Length - 1];
                }
                String tmp = String.Format("Ring No:{5}   Class No:{0} {1} {2} {3} ({4})", showClass.ClassNo, showClass.longHeight, showClass.longCatagory, showClass.LongClassName, grades, currentRing.RingNo);
                cell = new PdfPCell(new Phrase(new Chunk(tmp, ClassTitleFont)));
                cell.Colspan = 3;
                cell.BorderWidth = 0;
                ptable.AddCell(cell);
                cell = new PdfPCell(new Phrase(new Chunk("", ClassTitleFont)));
                cell.Colspan = 3;
                cell.BorderWidth = 0;
                ptable.AddCell(cell);
                ptable.AddCell(cell);
                ptable.AddCell(cell);
                doc.Add(ptable);

                DataSet callingList = sc.getCallingList(ShowID, showClass.ID);
                float[] colWidths = { 35, 50, 200, 200 };
                PdfPTable callingListTbl = new PdfPTable(colWidths);

                cell = new PdfPCell(new Phrase(new Chunk("RO", headerFont)));
                cell.BorderWidth = 0;
                callingListTbl.AddCell(cell);

                cell = new PdfPCell(new Phrase(new Chunk("Ring No", headerFont)));
                cell.BorderWidth = 0;
                callingListTbl.AddCell(cell);

                cell = new PdfPCell(new Phrase(new Chunk("Handler", headerFont)));
                cell.BorderWidth = 0;
                callingListTbl.AddCell(cell);

                cell = new PdfPCell(new Phrase(new Chunk("Dog Name", headerFont)));
                cell.BorderWidth = 0;
                callingListTbl.AddCell(cell);
                int altFlag = 0;
                Color altLine = Color.LIGHT_GRAY;
                foreach (DataRow row in callingList.Tables[0].Rows)
                {
                    Color altColor = Color.WHITE;
                    if (altFlag % 2 == 0 && showClass.EntryType != 5)
                    {
                        altColor = altLine;
                    }

                    cell = new PdfPCell(new Phrase(new Chunk(row["RO"].ToString(), font)));
                    cell.BorderWidth = 0;
                    cell.BorderWidth = 2;
                    cell.BorderColor = Color.RED;
                    cell.BackgroundColor = altColor;
                    cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                    callingListTbl.AddCell(cell);

                    if (showClass.EntryType == 5)
                    {
                        cell = new PdfPCell(new Phrase(new Chunk("Team Name:", headerFont2)));
                        cell.BackgroundColor = altColor;
                        cell.BorderWidth = 1;
                        cell.Colspan = 2;
                        cell.FixedHeight = 30F;
                        callingListTbl.AddCell(cell);

                        cell = new PdfPCell(new Phrase(new Chunk(ShowClasses.expandHeight(row), headerFont2)));
                        cell.BackgroundColor = altColor;
                        cell.BorderWidth = 1;
                        cell.FixedHeight = 30F;
                        cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                        callingListTbl.AddCell(cell);

                        cell = new PdfPCell(new Phrase(new Chunk("", font)));
                        cell.BackgroundColor = altColor;
                        cell.Colspan = 1;
                        cell.BorderWidth = 0;
                        cell.FixedHeight = 30F;
                        callingListTbl.AddCell(cell);
                    }

                    int borderWidth = 0;
                    if (showClass.EntryType == 5) borderWidth = 1;
                    cell = new PdfPCell(new Phrase(new Chunk(row["RingNumber"].ToString(), font)));
                    cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                    cell.BackgroundColor = altColor;
                    cell.BorderWidth = borderWidth;
                    callingListTbl.AddCell(cell);

                    int DefaultHandler = Convert.ToInt32(row["DefaultHandler"]);
                    int AltHandler = Convert.ToInt32(row["AltHandler"]);
                    String handlerName = row["Name"].ToString();
                    User user;
                    if (DefaultHandler > 0) {
                        user = new User(DefaultHandler);
                        handlerName = user.Name;
                    }
                    if (AltHandler > 0)
                    {
                        user = new User(AltHandler);
                        handlerName = user.Name;
                    }

                    cell = new PdfPCell(new Phrase(new Chunk(handlerName, font)));
                    cell.BackgroundColor = altColor;
                    cell.BorderWidth = borderWidth;
                    callingListTbl.AddCell(cell);

                    cell = new PdfPCell(new Phrase(new Chunk(row["KCName"].ToString(), font)));
                    cell.BackgroundColor = altColor;
                    cell.BorderWidth = borderWidth;
                    callingListTbl.AddCell(cell);

                    if (showClass.EntryType == 4 || showClass.EntryType == 5)
                    {
                        int UserID = Convert.ToInt32(row["UserID"]);
                        int DogID = Convert.ToInt32(row["DogID"]);
                        //MultiDog md = new MultiDog(UserID, DogID, showClass.ID);

                        List<MultiDog> otherHandlers = MultiDog.getMultiDog(UserID, DogID, showClass.ID);

                        String reserves = "";
                        int dogCnt = 0;
                        foreach (MultiDog md in otherHandlers)
                        {
                            String res = "";
                            if (dogCnt > 2 && md.Handlername.Length > 0)
                            {
                                if (reserves.Length > 0) reserves += "; ";
                                reserves += String.Format("{0} & {1}", md.Handlername, md.Dogname);
                            }

                            if (dogCnt < 3)
                            {

                                cell = new PdfPCell(new Phrase(new Chunk("", font)));
                                cell.BorderWidth = 0;
                                cell.BackgroundColor = altColor;
                                cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                                callingListTbl.AddCell(cell);

                                cell = new PdfPCell(new Phrase(new Chunk(res, font)));
                                cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                                cell.BackgroundColor = altColor;
                                cell.BorderWidth = 1;
                                callingListTbl.AddCell(cell);

                                cell = new PdfPCell(new Phrase(new Chunk(md.Handlername, font)));
                                cell.BackgroundColor = altColor;
                                cell.BorderWidth = 1;
                                callingListTbl.AddCell(cell);

                                cell = new PdfPCell(new Phrase(new Chunk(md.Dogname, font)));
                                cell.BackgroundColor = altColor;
                                cell.BorderWidth = 1;
                                callingListTbl.AddCell(cell);
                            }
                            dogCnt++;

                        }

                        cell = new PdfPCell(new Phrase(new Chunk("", font)));
                        cell.BackgroundColor = altColor;
                        cell.BorderWidth = 0;
                        cell.FixedHeight = 30F;
                        callingListTbl.AddCell(cell);

                        cell = new PdfPCell(new Phrase(new Chunk("Reserves: " + reserves, resFont)));
                        cell.BackgroundColor = altColor;
                        cell.Colspan = 3;
                        cell.BorderWidth = 1;
                        cell.FixedHeight = 30F;
                        callingListTbl.AddCell(cell);
                    }
                    altFlag++;

                }
                doc.Add(callingListTbl);
                doc.NewPage();
            }

            doc.Close();

            if (publish)
            {

            }
            else
            {
                context.Response.ClearContent();
                context.Response.ContentType = "application/pdf";
                context.Response.AddHeader("content-disposition", String.Format("inline;filename=PreviewSchedule.pdf"));
                context.Response.BinaryWrite((output as MemoryStream).ToArray());
            }
        }
        public static void Cancel(User currentUser, int showid)
        {
            DogClasses dc = new DogClasses();

            Shows show = new Shows(showid);
            UserShows us = new UserShows(currentUser.ID, showid);
            UserCamping.DeleteForUser(us.ID);

            String refcode = us.ID.ToString("000000");
            us.Delete();
            //us.Status =(int) UserShows.UserStatus.STATUS_PENDING_REFUND;
            //us.Save();

            DogClasses.deleteUserDogs(currentUser.ID, showid);
            MultiDog.DeleteUserFromShow(currentUser.ID, showid);

            if (us.Status != (int)UserShows.UserStatus.STATUS_SAVED)
            {
                String htmlContents = readTemplate("CancelledEntry", "html", show, refcode);
                String plainContents = readTemplate("CancelledEntry", "txt", show, refcode);

                List<Transaction> transList = Transaction.getTransactionForUserRefCode(showid, currentUser.ID, us.ID);
                if (us.Status == (int)UserShows.UserStatus.STATUS_ENTERED_NOT_PAID)
                {
                    htmlContents = htmlContents.Replace("[PAYMENT_NOTE]", "");
                    plainContents = plainContents.Replace("[PAYMENT_NOTE]", "");
                    Transaction.Add(refcode, 4, -transList[0].Amount, "Entry Fee Returned", showid, currentUser.ID, DateTime.Now);
                }
                else
                {
                    if (transList.Count > 0)
                    {
                        //
                        // if handler is cancelling the show and there have paid, then
                        // mark in their account history that there have a refund

                        htmlContents = htmlContents.Replace("[PAYMENT_NOTE]", "Your payment will be refunded in the next 24 - 48 hours");
                        plainContents = plainContents.Replace("[PAYMENT_NOTE]", "Your payment will be refunded in the next 24 - 48 hours");

                        int transid = Transaction.Add(refcode, 2, -transList[0].Amount, "Refund Requested", showid, currentUser.ID, DateTime.Now);
                        Transaction.SetEnteredBy(transid, Transaction.ENTERED_BY.ONLINE_ENTRY);
                    }
                    else
                    {
                        htmlContents = htmlContents.Replace("[PAYMENT_NOTE]", "");
                        plainContents = plainContents.Replace("[PAYMENT_NOTE]", "");
                    }
                }

                MailMessage mm = new MailMessage();
                AlternateView htmlView = AlternateView.CreateAlternateViewFromString(htmlContents, null, MediaTypeNames.Text.Html);
                LinkedResource logoImage = new LinkedResource(HttpContext.Current.Server.MapPath("~/Assets/logo.gif"), MediaTypeNames.Image.Gif);
                logoImage.ContentId = "LogoImage";
                //htmlView.LinkedResources.Add(logoImage);
                AlternateView plainView = AlternateView.CreateAlternateViewFromString(plainContents, null, MediaTypeNames.Text.Plain);

                mm.AlternateViews.Add(plainView);
                mm.AlternateViews.Add(htmlView);

                SmtpClient client = new SmtpClient("localhost");
                mm.From = new MailAddress("*****@*****.**", "First Place Processing");
                mm.To.Add(new MailAddress(currentUser.EmailAddress, currentUser.Name));
                mm.Subject = String.Format("Entry Cancellation {0} ({1:dd MMM yyyy})", show.ShowName, show.ShowDate);
                client.Send(mm);

                if (us.Status == (int)UserShows.UserStatus.STATUS_ENTERED_AND_PAID)
                {
                    mm = new MailMessage();
                    mm.From = new MailAddress("*****@*****.**", "First Place Processing");
                    mm.To.Add(new MailAddress("*****@*****.**", "First Place Processing"));
                    mm.Subject = "Entry Cancellation Request";
                    mm.Body = String.Format("Refund Request from {0}\r\n\r\nRefcode: {1}\r\n\r\nEmail: {2}\r\n\r\nShow: {3}\r\n",
                                            currentUser.Name, refcode, currentUser.EmailAddress, show.ShowName);
                    client.SendAsync(mm, null);
                }
            }
        }
        private String printRingForUser(UserShows userShow, int UserID, ref List<int> defaultUsers)
        {
            String html = "";

            Fpp.WebModules.Business.User currentUser = new User(userShow.Userid);
            Shows show = new Shows(userShow.ShowID);

            List<ShowDetails> showDetailsList = ShowDetails.GetShowDaysList(userShow.ShowID);
            html += "<h2>" + show.ShowName + "</h2>";

            Rings r = new Rings();
            DataSet ringList = r.GetAllRingsForShow(userShow.ShowID, "ShowDate");

            Dogs d = new Dogs();

            DogClasses dc = new DogClasses();
            DateTime dt = DateTime.Now;
            Boolean newday = false;
            int currentRingID = 0;
            int ShowDetailsID = -1;
            int PrevShowDetailsID = -1;
            foreach (DataRow ringRow in ringList.Tables[0].Rows)
            {
                try
                {
                    int RingID = Convert.ToInt32(ringRow["RingID"]);
                    int EntryType = Convert.ToInt32(ringRow["EntryType"]);
                    ShowDetailsID = Convert.ToInt32(ringRow["ShowDetailsID"]);
                    if (ringRow.IsNull("ClassID"))
                    {
                        continue;
                    }
                    int ClassID = Convert.ToInt32(ringRow["ClassID"]);
                    DateTime rowDT = Convert.ToDateTime(ringRow["ShowDate"]);
                    if (rowDT != dt)
                    {
                        newday = true;
                        if (currentRingID != 0)
                        {
                            html += "</table></div></div>";
                            if (currentUser.UserID == UserID)
                            {
                                html += getHandlerDetails(userShow, currentUser, PrevShowDetailsID);
                            }
                            else
                            {
                                User defaultHandler = new User(UserID);
                                html += getHandlerDetails(userShow, defaultHandler, PrevShowDetailsID);
                            }
                            html += "<div class='pagebreak'></div>";
                        }
                        html += "<div class='day group'>";
                        html += "<div class='clsDate'>" + rowDT.ToString("dddd d MMM") + "</div>";
                        dt = rowDT;
                    }

                    if (currentRingID != RingID)
                    {
                        List<Judge> judgeList = Judge.getJudgesForRingList(RingID);

                        if (currentRingID != 0 && !newday)
                        {
                            html += "</table></div>";
                        }
                        html += "<div class='Ring'>";
                        html += "<table class='roClassesTbl'>";
                        html += "<tr class='ringInfo'>";
                        html += "<td colspan='3'>" +
                                    "<div class='roTitle centered'>Ring No " + ringRow["RingNo"].ToString() + "</div>";
                        foreach (Judge judge in judgeList)
                        {
                            html += "<div class='roTitle centered'>" + judge.Name + "</div>";
                        }
                        html += "</td></tr>";
                        currentRingID = RingID;
                    }

                    html += "<tr>";
                    DataSet dogsList = d.GetDogsInClass(userShow.Userid, ClassID);
                    int DogsInClass = d.dogsInClassCount(ClassID);

                    String clsName = String.Format("{0} {1} {2} {3}",
                                    ShowClasses.expandCatagory(ringRow),
                                    ShowClasses.expandHeight(ringRow),
                                    ringRow["LongName"],
                                    ringRow["name"]);
                    String grades = ShowClasses.shortenGrades(ringRow);
                    int ix = clsName.IndexOf("Grd");
                    if (ix == -1) ix = clsName.IndexOf("Cmb");
                    if (ix > -1)
                    {
                        clsName = clsName.Substring(0, ix + 3) + " " + grades + " " + clsName.Substring(ix + 4);
                    }
                    else
                    {
                        ix = clsName.IndexOf(" ");
                        clsName = clsName.Substring(0, ix) + " " + grades + " " + clsName.Substring(ix + 1);
                    }

                    if (dogsList.Tables[0].Rows.Count > 0)
                    {
                        String tmphtml = "<td valign='top' class='clsRing InClass'>" + ringRow["ClsNo"] + "</td>" +
                                            "<td  valign='top' class='clsDetails InClass'><div>" + clsName + "</div>";
                        int countDogs = 0;
                        int DefaultHandler;
                        foreach (DataRow dogRow in dogsList.Tables[0].Rows)
                        {
                            int DogID = Convert.ToInt32(dogRow["DogID"]);
                            DefaultHandler = Convert.ToInt32(dogRow["DefaultHandler"]);
                            if (DefaultHandler == 0) DefaultHandler = -1;
                            if ((DefaultHandler == -1 && currentUser.UserID == UserID) ||
                                (DefaultHandler == UserID)
                                )
                            {
                                html += tmphtml;
                                tmphtml = "";

                                String img = "<img src='data:image/gif;base64," + CreateImage(dogRow["DogColour"].ToString()) + "' />";
                                String dogName = dogRow["DogName"].ToString();
                                if (dogName.Length == 0)
                                {
                                    dogName = dogRow["KCName"].ToString();
                                }
                                html += String.Format("<div class='dogInClass'><div style='background:{2};' class='dogIcon'>{3}</div>[{1}] {0}</div>", dogName, dogRow["RO"], dogRow["DogColour"], img);

                                int AltHandler = Convert.ToInt32(dogRow["AltHandler"]);
                                String HandlerName = "";
                                if (AltHandler > 0)
                                {
                                    User u = new User(AltHandler);
                                    HandlerName = u.Name;

                                    html += "<div class='altHandler'>Handler:" + AltHandler + "</div>";
                                }

                                // Pairs
                                if (EntryType == 4)
                                {

                                    MultiDog md = new MultiDog(UserID, DogID, ClassID);
                                    html += String.Format("<div class='dogInClass'><div style='width:8px;height:10px;' class='dogIcon'></div>[{1}] {0}</div>", md.Dogname, dogRow["RO"]);
                                }

                                countDogs++;
                            }
                            else
                            {
                                if (defaultUsers != null && defaultUsers.IndexOf(DefaultHandler) == -1)
                                {
                                    defaultUsers.Add(DefaultHandler);
                                }
                            }
                        }
                        if (countDogs == 0)
                        {
                            html += "<td valign='top' class='clsRing notInClass'>" + ringRow["ClsNo"] + "</td>";
                            html += "<td valign='top' class='clsDetails notInClass'>" + clsName + "</td>";
                            html += "<td valign='top' class='clsEntry notInClass'><div>(" + DogsInClass + ")</div></td>";
                        }
                        else
                        {
                            html += "</td>";
                            html += "<td valign='top' class='clsEntry'><div>(" + DogsInClass + ")</div></td>";
                        }
                    }
                    else
                    {
                        html += "<td valign='top' class='clsRing notInClass'>" + ringRow["ClsNo"] + "</td>";
                        html += "<td valign='top' class='clsDetails notInClass'>" + clsName + "</td>";
                        html += "<td valign='top' class='clsEntry notInClass'><div>(" + DogsInClass + ")</div></td>";
                    }

                    html += "</tr>";
                    newday = false;
                    PrevShowDetailsID = ShowDetailsID;
                }
                catch (Exception e)
                {
                    AppException.LogEvent("Printing Ring Plan:  " + e.Message);
                }
            }
            html += "</table>";
            html += "</div>";
            html += "</div>";

            if (currentUser.UserID == UserID)
            {
                html += getHandlerDetails(userShow, currentUser, PrevShowDetailsID);
            }
            else
            {
                User defaultHandler = new User(UserID);
                html += getHandlerDetails(userShow, defaultHandler, PrevShowDetailsID);
            }
            html += "<div class='pagebreak'></div>";

            return html;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                JumpHeights = "";
                foreach (String s in ShowClasses.HEIGHTNAMES) {
                    if (JumpHeights.Length > 0) JumpHeights += ",";
                    JumpHeights += String.Format("'{0}'", s);
                }
                JumpHeights = "[" + JumpHeights + "]";

                String cmd = Request["cmd"];

                if (Session["showid"] != null)
                {
                    _showid = Convert.ToInt32(Session["showid"]);
                }
                else
                {
                    _showid = Convert.ToInt32(Request["showid"]);
                    Session["showid"] = _showid.ToString();
                }
                _orgID = Convert.ToInt32(Session["OrgID"]);
                ShowID.Value = _showid.ToString();
                if (cmd == "edit")
                {
                    Shows show = new Shows(_showid);
                    _showStatus = show.Status;
                    ShowDetails showDetails = new ShowDetails();
                    showDetails.GetFrom(_showid);

                    ShowDetailsID.Value = showDetails.ShowDetailsID.ToString();
                    edtClosingDate.Value = "(not set)";
                    DateTime tmp = new DateTime();
                    if (show.ClosingDate.CompareTo(tmp) != 0)
                    {
                        edtClosingDate.Value = show.ClosingDate.ToString("dd MMM yyyy");
                    }

                    edtShowDate.Value = show.ShowDate.ToString("dd MMM yyyy");
                    dspShowDate.Value = edtShowDate.Value;
                    edtVenue.Value = (!DBNull.Value.Equals(show.Venue) ? show.Venue : "");
                    edtVenuePostcode.Value = (!DBNull.Value.Equals(show.VenuePostcode) ? show.VenuePostcode : "");

                    edtShowName.Value = show.ShowName;

                    initialShowDate.Value = String.Format("{0:dd MMM yyyy}", show.ShowDate);

                    System.Web.UI.HtmlControls.HtmlTableRow row = new HtmlTableRow();
                    System.Web.UI.HtmlControls.HtmlTableCell cell = new HtmlTableCell();

                    row.Attributes.Add("class", "tableHeader");

                    cell.InnerHtml = "Show Day";
                    cell.Attributes.Add("class", "showDate");
                    row.Cells.Add(cell);

                    cell = new HtmlTableCell();
                    cell.InnerHtml = "Classes";
                    cell.Attributes.Add("class", "classSummary");
                    row.Cells.Add(cell);

                    cell = new HtmlTableCell();
                    cell.InnerHtml = "<input id='btnNewDay' type='button' value='New Day' /><input id='btnRenumber' type='button' value='Renumber' />";
                    row.Cells.Add(cell);
                    summaryDetails.Rows.Add(row);

                    DataTable table = showDetails.GetAllShows().Tables[0];
                    if (table != null)
                    {
                        foreach (DataRow dataRow in table.Rows)
                        {
                            row = new HtmlTableRow();
                            row.Attributes.Add("class", "tableDetails");
                            row.Attributes.Add("showdate", String.Format("{0:yyyy-MM-dd}", dataRow["ShowDate"]));
                            row.Attributes.Add("id", String.Format("day_{0}", dataRow["ShowDetailID"]));
                            row.Attributes.Add("classdaylimit", String.Format("{0}", dataRow["ClassLimit"]));

                            cell = new HtmlTableCell();
                            cell.InnerHtml = String.Format("{0:dddd, dd MMM}", dataRow["ShowDate"]);
                            cell.Attributes.Add("class", "showDate");
                            row.Cells.Add(cell);

                            cell = new HtmlTableCell();
                            cell.InnerHtml = String.Format("({0} Classes)", dataRow["Classes"]);
                            cell.Attributes.Add("class", "classNumber");
                            row.Cells.Add(cell);

                            cell = new HtmlTableCell();
                            cell.Attributes.Add("class", "classControls");
                            cell.InnerHtml = "<span class='del'>Del</span><span class='copy'>Copy</span>";
                            row.Cells.Add(cell);
                            summaryDetails.Rows.Add(row);
                        }
                    }

                }
            }
        }
        private void printRingForUser(UserShows userShow, int UserID, Document doc, ref List<int> defaultUsers, ref int pageCount)
        {
            String html = "";
            float[] ringColumns = new float[] { 300, 300, 300, 300};

            Font pageFont = FontFactory.GetFont("Arial", 22, Font.NORMAL);
            Font headerFont = new Font(Font.HELVETICA, 16, Font.BOLD, Color.BLACK);
            Font judgeFont = FontFactory.GetFont("Arial", 9, Font.BOLD);
            Font notInClassFont = new Font(Font.HELVETICA, 6, Font.NORMAL, Color.BLACK);
            Font inClassFont = new Font(Font.HELVETICA, 9, Font.NORMAL, Color.BLACK);
            Font font = new Font(Font.HELVETICA, 10, Font.NORMAL, Color.BLACK);
            Font font1 = FontFactory.GetFont("Arial", 18, Font.BOLD);
            Font dogNotInClass = new Font(Font.HELVETICA, 6, Font.NORMAL, Color.BLACK);
            Font dogInClass = new Font(Font.HELVETICA, 9, Font.NORMAL, Color.BLACK);
            Font dogDetailsInClass = new Font(Font.HELVETICA, 9, Font.BOLD, Color.BLACK);
            Fpp.WebModules.Business.User currentUser = new User(userShow.Userid);
            Shows show = new Shows(userShow.ShowID);

            List<ShowDetails> showDetailsList = ShowDetails.GetShowDaysList(userShow.ShowID);
            doc.Add(new Paragraph(show.ShowName, pageFont));

            Rings r = new Rings();
            DataSet ringList = r.GetAllRingsForShow(userShow.ShowID, "ShowDate");

            Dogs d = new Dogs();

            DogClasses dc = new DogClasses();
            DateTime dt = DateTime.Now;
            int currentRingID = 0;
            int ShowDetailsID = -1;
            int PrevShowDetailsID = -1;
            PdfPTable rings = new PdfPTable(ringColumns);

            int ringCnt = 0;
            PdfPCell cell = null;
            PdfPTable ringDetails = null;
            PdfPTable classDetailsTable = null;
            List<int> dogsRunningToday = new List<int>();
            foreach (DataRow ringRow in ringList.Tables[0].Rows)
            {
                int RingID = Convert.ToInt32(ringRow["RingID"]);
                ShowDetailsID = Convert.ToInt32(ringRow["ShowDetailsID"]);

                if (ringRow.IsNull("ClassID"))
                {
                    continue;
                }
                int ClassID = Convert.ToInt32(ringRow["ClassID"]);
                DateTime rowDT = Convert.ToDateTime(ringRow["ShowDate"]);
                if (rowDT != dt)
                {
                    if (currentRingID != 0)
                    {
                        if (ringCnt % 4 != 0)
                        {
                            var remind = ringCnt % 4;
                            while (remind-- > 0)
                            {
                                cell = new PdfPCell(new Phrase(new Chunk(" ", pageFont)));
                                cell.BorderWidth = 0;
                                rings.AddCell(cell);
                            }
                        }

                        doc.Add(rings);
                        if (currentUser.UserID == UserID)
                        {
                            doc.Add(getHandlerDetails(userShow, currentUser, PrevShowDetailsID, dogsRunningToday));
                        }
                        else
                        {
                            User defaultHandler = new User(UserID);
                            doc.Add(getHandlerDetails(userShow, defaultHandler, PrevShowDetailsID, dogsRunningToday));
                        }
                        doc.NewPage();
                        if (dogsRunningToday.Count > 0)
                        {
                            pageCount++;
                        }
                    }
                    dogsRunningToday.Clear();
                    doc.Add(new Paragraph(rowDT.ToString("dddd d MMM"), headerFont));
                    doc.Add(new Paragraph("  ", judgeFont));
                    dt = rowDT;
                    rings = new PdfPTable(ringColumns);
                    rings.WidthPercentage = 100;
                    ringCnt = 0;
                }

                if (currentRingID != RingID)
                {
                    ringCnt++;
                    ringDetails = new PdfPTable(1);
                    rings.AddCell(new PdfPCell( ringDetails));

                    List<Judge> judgeList = Judge.getJudgesForRingList(RingID);

                    cell = new PdfPCell(new Phrase(new Chunk("Ring No " + ringRow["RingNo"].ToString(), judgeFont)));
                    cell.BorderWidth = 0;
                    cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                    ringDetails.AddCell(cell);

                    foreach (Judge judge in judgeList)
                    {
                        cell = new PdfPCell(new Phrase(new Chunk(judge.Name, judgeFont)));
                        cell.BorderWidth = 0;
                        cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                        ringDetails.AddCell(cell);
                    }
                    currentRingID = RingID;
                    classDetailsTable = new PdfPTable(new float[] { 50, 225, 100 });
                    classDetailsTable.DefaultCell.BorderWidth = 0;
                    ringDetails.AddCell(classDetailsTable);
                }
                html += "<tr>";
                DataSet dogsList = d.GetDogsInClass(userShow.Userid, ClassID);
                int DogsInClass = d.dogsInClassCount(ClassID);

                String clsName = String.Format("{0} {1} {2} {3}",
                                ShowClasses.expandCatagory(ringRow),
                                ShowClasses.expandHeight(ringRow),
                                ringRow["LongName"],
                                ringRow["name"]);
                String grades = ShowClasses.shortenGrades(ringRow);
                int ix = clsName.IndexOf("Grd");
                if (ix == -1) ix = clsName.IndexOf("Cmb");
                if (ix > -1)
                {
                    clsName = clsName.Substring(0, ix + 3) + " " + grades + " " + clsName.Substring(ix + 4);
                }
                else
                {
                    ix = clsName.IndexOf(" ");
                    clsName = clsName.Substring(0, ix) + " " + grades + " " + clsName.Substring(ix + 1);
                }

                if (dogsList.Tables[0].Rows.Count > 0)
                {
                    Phrase[] tmpCells = new Phrase[3];
                    tmpCells[0] = new Phrase(new Chunk(ringRow["ClsNo"].ToString(), dogInClass));
                    tmpCells[1] = new Phrase(new Chunk(clsName, dogInClass));
                    tmpCells[2] = new Phrase(new Chunk(String.Format("({0})", DogsInClass), dogInClass));

                    int countDogs = 0;
                    int DefaultHandler;
                    Paragraph p = new Paragraph();
                    foreach (DataRow dogRow in dogsList.Tables[0].Rows)
                    {
                        int DogID = Convert.ToInt32(dogRow["DogID"]);
                        DefaultHandler = Convert.ToInt32(dogRow["DefaultHandler"]);
                        if (DefaultHandler == 0) DefaultHandler = -1;
                        if ((DefaultHandler == -1 && currentUser.UserID == UserID) ||
                            (DefaultHandler == UserID)
                            )
                        {
                            if (countDogs == 0)
                            {
                                cell = new PdfPCell(tmpCells[0]);
                                cell.BorderWidth = 0;
                                cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                                classDetailsTable.AddCell(cell);
                                p.Add(tmpCells[1]);
                                p.Add(Chunk.NEWLINE);
                            }
                            if (!dogsRunningToday.Contains(DogID))
                            {
                                dogsRunningToday.Add(DogID);
                            }
                            String img = "<img src='data:image/gif;base64," + CreateImage(dogRow["DogColour"].ToString()) + "' />";
                            String dogName = dogRow["DogName"].ToString();
                            if (dogName.Length == 0)
                            {
                                dogName = dogRow["KCName"].ToString();
                            }
                            var chunk = new Chunk("   ", dogDetailsInClass);
                            chunk.SetBackground(new Color( System.Drawing.ColorTranslator.FromHtml(dogRow["DogColour"].ToString())  ));
                            p.Add(new Phrase(chunk));
                            p.Add(new Phrase(new Chunk(String.Format(" [{1}] {0}", dogName, dogRow["RO"]), dogDetailsInClass)));
                            p.Add(Chunk.NEWLINE);

                            int AltHandler = Convert.ToInt32(dogRow["AltHandler"]);
                            String HandlerName = "";
                            if (AltHandler > 0)
                            {
                                User u = new User(AltHandler);
                                HandlerName = u.Name;

                                html += "<div class='altHandler'>Handler:" + AltHandler + "</div>";
                                p.Add(Chunk.NEWLINE);
                                p.Add(new Phrase(new Chunk(String.Format("Handler:", AltHandler),dogInClass)));
                            }
                            countDogs++;
                        }
                        else
                        {
                            if (defaultUsers != null && defaultUsers.IndexOf(DefaultHandler) == -1)
                            {
                                defaultUsers.Add(DefaultHandler);
                            }
                        }
                    }
                    if (countDogs == 0)
                    {
                        cell = new PdfPCell(new Phrase(new Chunk(ringRow["ClsNo"].ToString(), dogNotInClass)));
                        cell.BorderWidth = 0;
                        cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                        classDetailsTable.AddCell(cell);

                        cell = new PdfPCell(new Phrase(new Chunk(clsName, dogNotInClass)));
                        cell.BorderWidth = 0;
                        cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                        cell.NoWrap = true;
                        classDetailsTable.AddCell(cell);

                        cell = new PdfPCell(new Phrase(new Chunk(String.Format("({0})", DogsInClass), dogNotInClass)));
                        cell.BorderWidth = 0;
                        cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                        classDetailsTable.AddCell(cell);
                    }
                    else
                    {

                        cell = new PdfPCell(p);
                        cell.BorderWidth = 0;
                        cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                        cell.NoWrap = true;
                        classDetailsTable.AddCell(cell);

                        cell = new PdfPCell(tmpCells[2]);
                        cell.BorderWidth = 0;
                        cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                        classDetailsTable.AddCell(cell);
                    }
                }
                else
                {
                    cell = new PdfPCell(new Phrase(new Chunk(ringRow["ClsNo"].ToString(), dogNotInClass)));
                    cell.BorderWidth = 0;
                    cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    classDetailsTable.AddCell(cell);

                    cell = new PdfPCell(new Phrase(new Chunk(clsName, dogNotInClass)));
                    cell.BorderWidth = 0;
                    cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    classDetailsTable.AddCell(cell);

                    cell = new PdfPCell(new Phrase(new Chunk(String.Format("({0})", DogsInClass), dogNotInClass)));
                    cell.BorderWidth = 0;
                    cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    classDetailsTable.AddCell(cell);
                }

                PrevShowDetailsID = ShowDetailsID;
            }

            if (ringCnt % 4 != 0)
            {
                var remind = ringCnt % 4;
                while (remind-- > 0)
                {
                    cell = new PdfPCell(new Phrase(new Chunk(" ", pageFont)));
                    cell.BorderWidth = 0;
                    rings.AddCell(cell);

                }
            }

            if (currentUser.UserID == UserID)
            {
                doc.Add(getHandlerDetails(userShow, currentUser, PrevShowDetailsID, dogsRunningToday));
            }
            else
            {
                User defaultHandler = new User(UserID);
                doc.Add(getHandlerDetails(userShow, defaultHandler, PrevShowDetailsID, dogsRunningToday));
            }
            doc.NewPage();
        }
        public void ProcessRequest(HttpContext context)
        {
            int ShowID = Convert.ToInt32(context.Request["showid"]);
            int RingID = Convert.ToInt32(context.Request["ringid"]);
            String cmd = context.Request["doc"].ToString();

            Shows show = new Shows(ShowID);
            ShowDetails sd = new ShowDetails();
            DataTable table = sd.GetShowDetails(ShowID).Tables[0];
            String pdfPath = context.Server.MapPath(cmd + ".pdf");
            Boolean publish = false;
            if (!String.IsNullOrEmpty(context.Request["publish"]) && context.Request["publish"].ToString() == "1") publish = true;

            Document doc = new Document(PageSize.A4, -50, -50, 2, 2);
            Stream output;
            if (publish)
            {
                String path = context.Server.MapPath(@"..\schedules\");
                path += DateTime.Today.ToString("yyyy");
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                path += String.Format("\\{0:yyyyMM}_{1}.pdf", show.ShowDate, show.ShowName);
                output = new FileStream(path, FileMode.Create);
            }
            else
            {
                output = new MemoryStream();
            }
            var writer = PdfWriter.GetInstance(doc, output);
            StyleSheet sheet = new StyleSheet();

            doc.Open();
            Font smallFont = new Font(Font.COURIER, 8, Font.NORMAL, Color.BLACK);
            Font normalFont = new Font(Font.COURIER, 10, Font.NORMAL, Color.BLACK);
            Font headerFont = new Font(Font.HELVETICA, 12, Font.BOLD, Color.BLACK);
            Font ClassTitleFont = new Font(Font.HELVETICA, 16, Font.NORMAL, Color.BLACK);
            Font bigFont = new Font(Font.HELVETICA, 25, Font.NORMAL, Color.BLACK);
            Font mediumFont = new Font(Font.HELVETICA, 20, Font.NORMAL, Color.BLACK);
            ShowClasses sc = new ShowClasses();
            Rings currentRing = new Rings(RingID);
            List<ShowClasses> showClasses = ShowClasses.GetAllClassesForShowRing(ShowID, RingID);
            PdfPTable callingListTbl = null;
            foreach (ShowClasses showClass in showClasses)
            {
                List<int> resultCnts = ShowClasses.getDogsInClass(showClass.ID, (showClass.Catagory == 0));

                int gradeidx = 0;
                foreach (int dogCounts in resultCnts)
                {
                    PdfPTable ptable = new PdfPTable(3);
                    PdfPCell cell;

                    String grades;
                    String subTitle;
                    if (showClass.Catagory == 0)
                    {
                        if (gradeidx < showClass.Grades.Length)
                        {
                            grades = "Grade " + showClass.Grades[gradeidx];
                        }
                        else
                        {
                            grades = showClass.Grades;
                        }
                        subTitle = String.Format("{0} {1} {2} {3} - Judge: {4}", showClass.longHeight, showClass.longCatagory, showClass.LongClassName, grades, Judge.getJudgeForClass(showClass.ID));
                    }
                    else
                    {
                        if (showClass.Grades.Length == 1)
                        {
                            grades = showClass.Grades;
                        }
                        else
                        {
                            grades = showClass.Grades[0] + " - " + showClass.Grades[showClass.Grades.Length - 1];
                        }
                        subTitle = String.Format("{0} {1} {3} {2} - Judge: {4}", showClass.longHeight, showClass.longCatagory, showClass.LongClassName, grades, Judge.getJudgeForClass(showClass.ID));

                    }
                    String tmp = String.Format("Result Sheet - Ring No:{0}", currentRing.RingNo);
                    cell = new PdfPCell(new Phrase(new Chunk(tmp, bigFont)));
                    cell.Colspan = 2;
                    cell.BorderWidth = 0;
                    ptable.AddCell(cell);

                    tmp = String.Format("Class No:{0}", showClass.ClassNo);
                    cell = new PdfPCell(new Phrase(new Chunk(tmp, bigFont)));
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    cell.BorderWidth = 2;
                    cell.Padding = 5;
                    ptable.AddCell(cell);

                    cell = new PdfPCell(new Phrase(new Chunk(subTitle, mediumFont)));
                    cell.Colspan = 3;
                    cell.BorderWidth = 0;
                    ptable.AddCell(cell);

                    cell = new PdfPCell(new Phrase(new Chunk("", ClassTitleFont)));
                    cell.Colspan = 3;
                    cell.BorderWidth = 0;
                    ptable.AddCell(cell);
                    ptable.AddCell(cell);
                    ptable.AddCell(cell);
                    doc.Add(ptable);

                    float[] colWidths = { 75, 75, 200, 200, 50, 75 };
                    callingListTbl = new PdfPTable(colWidths);

                    cell = new PdfPCell(new Phrase(new Chunk("Place", headerFont)));
                    cell.BorderWidth = 1;
                    cell.BorderWidthBottom = 0;
                    cell.FixedHeight = 35f;
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    callingListTbl.AddCell(cell);

                    cell = new PdfPCell(new Phrase(new Chunk("Ring Number", headerFont)));
                    cell.BorderWidth = 1;
                    cell.BorderWidthBottom = 0;
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    callingListTbl.AddCell(cell);

                    cell = new PdfPCell(new Phrase(new Chunk("Handler", headerFont)));
                    cell.BorderWidth = 1;
                    cell.BorderWidthBottom = 0;
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    callingListTbl.AddCell(cell);

                    cell = new PdfPCell(new Phrase(new Chunk("Dog Name", headerFont)));
                    cell.BorderWidth = 1;
                    cell.BorderWidthBottom = 0;
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    callingListTbl.AddCell(cell);

                    cell = new PdfPCell(new Phrase(new Chunk("Clear/ Faults", headerFont)));
                    cell.BorderWidth = 1;
                    cell.BorderWidthBottom = 0;
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    callingListTbl.AddCell(cell);

                    cell = new PdfPCell(new Phrase(new Chunk("Time", headerFont)));
                    cell.BorderWidth = 1;
                    cell.BorderWidthBottom = 0;
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    callingListTbl.AddCell(cell);

                    int maxRosettes = calcRosettes(dogCounts);
                    int maxTrophies = calcTrophies(dogCounts);
                    float rowHeight = 25f;
                    if (showClass.EntryType == 4)
                    {
                        rowHeight = 65f;
                    }
                    else if (showClass.EntryType == 5)
                    {
                        rowHeight = 120f;
                    }

                    for (int resultRow = 0; resultRow < maxRosettes; resultRow++)
                    {
                        int bwb = 0;
                        if (resultRow == maxRosettes - 1)
                        {
                            bwb = 1;
                        }
                        Color background = Color.WHITE;
                        if (maxTrophies > 0)
                        {
                            background = Color.LIGHT_GRAY;
                        }
                        maxTrophies--;

                        cell = new PdfPCell(new Phrase(new Chunk(calcPlace(resultRow + 1), normalFont)));
                        cell.BorderWidth = 1;
                        cell.BorderWidthBottom = bwb;
                        cell.FixedHeight = rowHeight;
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.BackgroundColor = background;
                        callingListTbl.AddCell(cell);

                        cell = new PdfPCell(new Phrase(new Chunk("", normalFont)));
                        cell.BorderWidth = 1;
                        cell.BackgroundColor = background;
                        cell.BorderWidthBottom = bwb;

                        callingListTbl.AddCell(cell);
                        callingListTbl.AddCell(cell);
                        callingListTbl.AddCell(cell);
                        callingListTbl.AddCell(cell);
                        callingListTbl.AddCell(cell);
                    }
                    doc.Add(callingListTbl);
                    doc.NewPage();
                    gradeidx++;
                }
            }

            doc.Close();

            if (publish)
            {

            }
            else
            {
                context.Response.ClearContent();
                context.Response.ContentType = "application/pdf";
                context.Response.AddHeader("content-disposition", String.Format("inline;filename=PreviewSchedule.pdf"));
                context.Response.BinaryWrite((output as MemoryStream).ToArray());
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            siteDetails.InnerHtml = "<span class='lolight'>&#169; First Place Processing</span>  *  " +
                                     "<a href='/docs/?_=cpf'>Card Payment Fees</a>  *  " +
                                     "<a href='/docs/?_=tandc'>Terms &amp; Conditions</a>  *  " +
                                     "<a href='/docs/?_=pp'>Privacy Policy</a>";

            String paymentReturnStatus = "";
            if (Context.Session["paymentStatus"] != null)
            {
                paymentReturnStatus = Context.Session["paymentStatus"].ToString();
                Context.Session["paymentStatus"] = "";
            };
            if (paymentReturnStatus == "cancelled")
            {
                paymentStatus = "<div class='paymentStatus'>Your last payment was cancelled</div>";
            }
            else if (paymentReturnStatus == "paysuccess") {
                if (Context.Session["paymentStatusShowName"] != null)
                {
                    String showName = Context.Session["paymentStatusShowName"].ToString();
                    Context.Session["paymentStatus"] = "";
                    Context.Session["paymentStatusShowName"] = "";
                    paymentStatus = "<h2><div class='paymentStatus'>Your Payment has been gratefully received for " + showName + "</div><br><div>Thank you.</div></h2>";
                }
                else
                {
                    Context.Session["paymentStatus"] = "";
                    Context.Session["paymentStatusShowName"] = "";
                    paymentStatus = "<h2><div class='paymentStatus'>Your Payment has been gratefully received.</div><br><div>Thank you.</div></h2>";
                }
            }

            if (!String.IsNullOrEmpty(Request["_"] ) )
            {
                sectionDisplay = Request["_"];
            }

            HttpCookie cookie = Context.Request.Cookies[".FPPAUTH"];
            if (cookie != null)
            {
                FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);

                String[] lists = ticket.UserData.Split(':');
                int userid = Convert.ToInt32(lists[1]);
                UserID.Value = userid.ToString();
                showadmin = (lists[0].Contains("showadmin"));

                user = new User(userid);
                List<Dogs> userDogs = Dogs.GetAllDogsForHandler(userid, DateTime.Now);
                handlerDogs = userDogs.Count;
                FirstTime = user.firstTime;
                loginInUser.InnerHtml = user.Name;

                String enteredShows = "";
                Shows shows = new Shows();
                DataSet ds = shows.GetAllEnteredShows(userid);
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    var show = new Shows(row);
                    var us = new UserShows(userid, show.ID);
                    var notPaid = "";
                    if (us.Status == (int)UserShows.UserStatus.STATUS_ENTERED_NOT_PAID)
                    {
                        notPaid = " <div class='flagUnpaid'></div>";
                    }
                    enteredShows += String.Format("<div class='showsEnteredItem'><div class='ShowDetails ' data-showtype='2' status='{6}'  showid='{5}' showdate='{2:dd MMM yyyy}' closingdate='{1:dd MMM yyyy}' venue='{3}' venuepostcode='{4}'>{0}{7}</div></div>",
                                row["Name"], DateCheck(row, "ClosingDate"), DateCheck(row, "ShowDate"), row["Venue"], row["VenuePostcode"], row["showid"], row["status"], notPaid);
                    // + "<div class='ShowDate'>" + String.Format("{0:dd MMM yyyy}", Convert.ToDateTime(row["ShowDate"]))  + "</div>";
                }
                lstEnteredShows.InnerHtml = enteredShows;

                SavedList= "";
                ds = shows.GetAllSavedShows(userid);
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    SavedList += String.Format("<div class='ShowDetails' data-showtype='1' showid='{5}' showdate='{2:dd MMM yyyy}' closingdate='{1:dd MMM yyyy}' venue='{3}' venuepostcode='{4}'>{0}</div>",
                                row["Name"], DateCheck(row, "ClosingDate"), DateCheck(row, "ShowDate"), row["Venue"], row["VenuePostcode"], row["showid"]);
                    // + "<div class='ShowDate'>" + String.Format("{0:dd MMM yyyy}", Convert.ToDateTime(row["ShowDate"]))  + "</div>";
                }
                lstSavedShows.InnerHtml = SavedList;

                lstAvailableShows.InnerHtml = "";
                List<Shows> showsList = Shows.getPublishedShows(userid);
                if (showsList.Count > 0)
                {
                    foreach (Shows show in showsList)
                    {
                        List<ShowDetails> showDetailsList = ShowDetails.GetShowDaysList(show.ShowID);
                        String classLimit = "";
                        if (showDetailsList.Count > 0) {
                            classLimit = String.Format(" classlimit='{0}' ", showDetailsList[0].ClassLimit);
                        }
                        lstAvailableShows.InnerHtml += String.Format("<div data-showtype='0'  data-dvshow='{7}' data-auto='false' class='ShowDetails' {6} showid='{5}' showdate='{2:dd MMM yyyy}' closingdate='{1:dd MMM yyyy}' venue='{3}' venuepostcode='{4}'>{0}</div>",
                                    show.ShowName, show.ClosingDate, show.ShowDate, show.Venue, show.VenuePostcode, show.ShowID, classLimit, (show.OrgID == 1));
                    }
                }
                else
                {
                    lstAvailableShows.InnerHtml = "<div class='noshowsavailable'>No Shows Available</div>";
                }
                user.firstTime = true;
            }
            else
            {
                Response.Redirect("~/");
            }
        }