﻿    function CleanWordHTML( str )
    {
        str = str.replace(/<o:p>\s*<\/o:p>/g, "") ;
        str = str.replace(/<o:p>.*?<\/o:p>/g, "&nbsp;") ;
        str = str.replace( /\s*mso-[^:]+:[^;"]+;?/gi, "" ) ;
        str = str.replace( /\s*MARGIN: 0cm 0cm 0pt\s*;/gi, "" ) ;
        str = str.replace( /\s*MARGIN: 0cm 0cm 0pt\s*"/gi, "\"" ) ;
        str = str.replace( /\s*TEXT-INDENT: 0cm\s*;/gi, "" ) ;
        str = str.replace( /\s*TEXT-INDENT: 0cm\s*"/gi, "\"" ) ;
        str = str.replace( /\s*TEXT-ALIGN: [^\s;]+;?"/gi, "\"" ) ;
        str = str.replace( /\s*PAGE-BREAK-BEFORE: [^\s;]+;?"/gi, "\"" ) ;
        str = str.replace( /\s*FONT-VARIANT: [^\s;]+;?"/gi, "\"" ) ;
        str = str.replace( /\s*tab-stops:[^;"]*;?/gi, "" ) ;
        str = str.replace( /\s*tab-stops:[^"]*/gi, "" ) ;
        str = str.replace( /\s*face="[^"]*"/gi, "" ) ;
        str = str.replace( /\s*face=[^ >]*/gi, "" ) ;
        str = str.replace( /\s*FONT-FAMILY:[^;"]*;?/gi, "" ) ;
        str = str.replace(/<(\w[^>]*) class=([^ |>]*)([^>]*)/gi, "<$1$3") ;
        str = str.replace( /<(\w[^>]*) style="([^\"]*)"([^>]*)/gi, "<$1$3" ) ;
        str = str.replace( /\s*style="\s*"/gi, '' ) ; 
        str = str.replace( /<SPAN\s*[^>]*>\s*&nbsp;\s*<\/SPAN>/gi, '&nbsp;' ) ; 
        str = str.replace( /<SPAN\s*[^>]*><\/SPAN>/gi, '' ) ; 
        str = str.replace(/<(\w[^>]*) lang=([^ |>]*)([^>]*)/gi, "<$1$3") ; 
        str = str.replace( /<SPAN\s*>(.*?)<\/SPAN>/gi, '$1' ) ; 
        str = str.replace( /<FONT\s*>(.*?)<\/FONT>/gi, '$1' ) ;        
        str = str.replace(/<\\?\?xml[^>]*>/gi, "") ; 
        str = str.replace(/<\/?\w+:[^>]*>/gi, "") ; 
        str = str.replace( /<(U|I|STRIKE)>&nbsp;<\/\1>/g, '&nbsp;' ) ;
        str = str.replace( /<(B|b)>&nbsp;<\/\b|B>/g, '' ) ;
        str = str.replace( /<([^\s>]+)[^>]*>\s*<\/\1>/g, '' ) ;
        str = str.replace( /<([^\s>]+)[^>]*>\s*<\/\1>/g, '' ) ;
        str = str.replace( /<([^\s>]+)[^>]*>\s*<\/\1>/g, '' ) ;     
        
        var re2 = new RegExp("(<font|<FONT)([^*>]*>.*?)(<\/FONT>|<\/font>)","gi") ; 
        str = str.replace( re2, "<div$2</div>") ;
        str = str.replace( /size|SIZE = ([\d]{1})/g, '' ) ;           
        
        var re = new RegExp("(<META .*?>)","gi");
        str=str.replace(re,"");
        var re1 = new RegExp("(<link .*?>)","gi");
        str=str.replace(re1,"");    
           
        str = str.replace( /<STYLE\s*>(.*?)<\/STYLE>/gi, '$1' ) ;            
        return str ;
    }
    
    function ShowMonthOfYear(numbOfMonth)
    {
        var arrNames = new Array();
        arrNames[0] = "January";
        arrNames[1] = "February";
        arrNames[2] = "March";
        arrNames[3] = "April";
        arrNames[4] = "May";
        arrNames[5] = "June";
        arrNames[6] = "July";
        arrNames[7] = "August";
        arrNames[8] = "September";
        arrNames[9] = "October";
        arrNames[10] = "November";
        arrNames[11] = "December";
        
        return arrNames[numbOfMonth];
    }


    $(document).ready(function () {

        // make sure that the thread link is available, but only if we are looking at a thread
        if (threadID == 0) {
            $("#ThreadsLink").css("display", "none");
        }
        // save a comment    
        $("#CommentSectionSaveLink a").click(function (e) {
            e.preventDefault();
            var comment = $("#AddYourComment #CommentSection").html();
            var InitialString = InitialComment;

            if (comment != InitialString) {
                var strTest = $("#AddYourComment #CommentSection").html();
                comment = CleanWordHTML(comment);

                // send the details to an ajax query and shove back to start page
                $.post("_admin/__InsertComment.aspx", { thID: threadID, comM: comment }, function (xml) {
                    var res = $("Result", xml).text();

                    if (res > 0) {
                        var dte = new Date();
                        // as this is my own entry, I can delete it             
                        var DivToAdd = "<div class=\"ForumComment\" id=\"ForumComment" + res + "\" style=\"display:none\">";
                        DivToAdd += "<div class=\"ForumCommentNickname\">I added this comment - ";
                        DivToAdd += dte.getDate() + " ";
                        DivToAdd += ShowMonthOfYear(dte.getMonth()) + " ";
                        DivToAdd += dte.getFullYear() + " ";
                        DivToAdd += dte.getHours() + ":";
                        DivToAdd += dte.getMinutes() + " ";
                        DivToAdd += "</div>";
                        DivToAdd += "<div class=\"ForumCommentComment\"><p>" + comment + "</p></div>";
                        DivToAdd += "<div class=\"CommentLinks\"><ul><li><a class=\"DeleteComment\" href=\"#\" id=\"" + res + "\" >Delete My Comment</a></li></ul></div>";
                        DivToAdd += "</div>";
                        $("#AddYourComment").before(DivToAdd);
                        $("#AddYourComment #CommentSection").html(InitialString);
                        $("#ForumComment" + res).slideDown();
                        NumberOfComments += 1;
                        ticks = NumberOfComments;
                    };
                });
            };
        });



        // edit a comment    
        $("#EditCommentSectionSaveLink a.Save").click(function (e) {
            e.preventDefault();
            var comment = $("#EditComment #CommentSection").html();
            var commentID = $("#CommentID").val();
            var Subject = $("#CommentSubject").val();

            if ((comment != "") & (commentID > 0) & (Subject != "")) {
                comment = CleanWordHTML(comment);

                // send the details to an ajax query and shove back to start page
                $.post("_admin/__UpdateComment.aspx", { cmID: commentID, comM: comment, subJ: Subject }, function (xml) {
                    var res = $("Result", xml).text();

                    if (res > 0) {
                        top.location = ForumURL + "?thID=" + $("#returnThread").val();
                    };
                });
            };
        });

        // if someone clicks within or without the comment section, the text may need to change 
        $("#AddYourComment #CommentSection").focus(function () {
            var InitialString = InitialComment;
            if ($("#AddYourComment #CommentSection").text() == InitialString) {
                $("#AddYourComment #CommentSection").html("");
            };
        });
        // if someone clicks within or without the comment section, the text may need to change 
        $("#AddYourComment #CommentSection").blur(function () {
            var InitialString = InitialComment;
            if ($("#AddYourComment #CommentSection").text() == "") {
                $("#AddYourComment #CommentSection").html(InitialString);
            };
        });

        // if someone clicks within or without the comment section, the text may need to change 
        $("#ThreadAddComment").focus(function () {
            var InitialString = InitialComment;
            if ($("#ThreadAddComment").text() == InitialString) {
                $("#ThreadAddComment").html("");
            };
        });
        // if someone clicks within or without the comment section, the text may need to change  
        $("#ThreadAddComment").blur(function () {
            var InitialString = InitialComment;
            if ($("#ThreadAddComment").text() == "") {
                $("#ThreadAddComment").html(InitialString);
            };
        });



        // save the thread
        $("#ThreadAddButtons .Save").click(function (e) {
            e.preventDefault();
            // get the subject and the comment
            var subject = $("#tbxSubject").val();
            var comment = $("#ThreadAddComment").html();

            if ((subject != "") & (comment != "") & (comment != InitialComment)) {
                // send the details to an ajax query and shove back to start page
                $.post("_admin/__InsertThread.aspx", { subJ: subject, comM: comment }, function (xml) {
                    var res = $("Result", xml).text();

                    if (res > 0) {
                        top.location = ForumURL;
                    };
                });
            };
        });

        $(".AbuseComment").live("click", function (e) {
            e.preventDefault();
            var commentID = $(this).attr("id");
            $.post("_admin/__ReportAbuse.aspx", { thID: threadID, frID: commentID }, function (xml) {
                var res = $("Result", xml).text();
                if (res > 0) {
                    if (res == 1) {

                        if (commentID == threadID) {
                            top.location = ForumURL;
                        }

                        $("#ForumComment" + commentID).slideUp();
                        NumberOfComments -= 1;
                        ticks = NumberOfComments;
                    }
                    else if (res == 2) {
                        top.location = ForumURL + "?thID=" + threadID;
                    }
                };
            });


        });

        // delete a comment
        $(".DeleteComment").live("click", function (e) {
            e.preventDefault();
            var commentID = $(this).attr("id");
            $.post("_admin/__DeleteComment.aspx", { thID: threadID, cmID: commentID }, function (xml) {
                var res = $("Result", xml).text();
                if (res > 0) {
                    $("#ForumComment" + commentID).slideUp();
                    NumberOfComments -= 1;
                    ticks = NumberOfComments;

                    if (commentID == threadID) {
                        top.location = ForumURL;
                    }
                };
            });
        });

        // Find the initial number of comments
        NumberOfComments = $("div .ForumComment").length + 1;
        ticks = NumberOfComments;

        // start the ticker thread  

        var chkSignIn = $(".UserSignIn").val();

        if (chkSignIn != "N") {
            if (threadID > 0) {
                ThreadTicker();
            }
            else {
                ThreadReaderTimer();
            }
        }

        // reorder the page
        $(".PageOrder").click(function (e) {
            e.preventDefault();
            // change the page order
            // try and remove any up/donw images
            $("#imgPageOrder").remove();
            $(".PageOrder").css("color", "#000");
            // get the new page order
            po = $(this).attr("id");
            // see if we are desc?
            if (PageOrder == po) {
                PageOrder += " desc";
                $(this).append("<img id=\"imgPageOrder\" border=\"0\" src=\"img/forum_down.gif\">");
                $(this).css("color", "#FFF");
            }
            else {
                PageOrder = po;
                $(this).append("<img id=\"imgPageOrder\" border=\"0\" src=\"img/forum_up.gif\">");
                $(this).css("color", "#FFF");
            }
            // start from the first page
            PageNumber = 1;
            // remove all the position divs
            $("div [id^='Position']").css("display", "none");
            // remove any forum threads
            $("div [id^='ForumThreadHeader']").remove();
            // get the page
            ThreadReader();

        });

        // change the page number
        $(".PageLinks a").live("click", function (e) {
            e.preventDefault();
            PageNumber = $(this).attr("id");
            $("div [id^='Position']").css("display", "none");
            $(".PageLinks a").remove();
            $("div [id^='ForumThreadHeader']").remove();
            // get the page
            ThreadReader();
        });

    });
     
     
     ////////////////////////////////
     ////////////////////////////////
     ////////////////////////////////
     ////////////////////////////////
     // Non page load functions
     
     function CheckUserDetails()
     {
         var res=-2;
         $.post("_admin/__IsUserBlocked.aspx", function(xml) {
            res = $("Result", xml).text();
            if (res==0)
            { 
                top.location=ForumURL;                        
            }             
         });     
     }
     
     function ThreadTicker(){
        CheckUserDetails();
        // a function to check to see if the page has been updated elsewhere
        // get the current number of comments        
        $.post("_admin/__ThreadCounter.aspx", {thID: threadID}, function(xml) {
            var res = $("Result", xml).text();
            ticks = res;
        });     
        // if the number of comments is different then add a refresh link
        if (NumberOfComments!=ticks)
        {
            if ($("#ThreadCounter").css("display")=="none")
            {            
                $("#ThreadCounter").html("<a href=" + ForumURL + "?thID=" + threadID + ">Comments have been updated, click here to refresh this thread</a>"    );
                $("#ThreadCounter").slideDown();
            }
        }
        setTimeout("ThreadTicker()", 20000);
      }  
      
     function ThreadReaderTimer(){
        CheckUserDetails();
        ThreadReader();     
        setTimeout("ThreadReaderTimer()", 20000);
     } 
      
     function ThreadReader(){
        // a function to check to see if the page has been updated elsewhere
        // get the current number of comments
        $.post("_admin/__Threads.aspx", {po: PageOrder, pg: PageNumber}, function(xml) {
            var TotalNumberOfPages = $("TotalNumberOfPages", xml).text();
            
            var position=1; 
            var arr = new Array();
            
            if (TotalNumberOfPages>=0)
            {               
            
                $(".PageLinks a").remove();
                // add some links for the pages
                
                // we only want to show a limited number of links                 
                var StartPaging = 1 + (NumberOfPagesThatCanBeShown * (~~((PageNumber-1)/NumberOfPagesThatCanBeShown)));
                               
                var EndPaging = StartPaging + (NumberOfPagesThatCanBeShown-1);
                
                if (EndPaging>TotalNumberOfPages)
                {
                    EndPaging = TotalNumberOfPages;
                }
                // do we need to add a "earlier" link to the paging
                if (StartPaging-NumberOfPagesThatCanBeShown>0)                
                {
                    $(".PageLinks").append("<a href=\"#\" id=\"" + (StartPaging-1) + "\">..</a>");                    
                }
                // now add the page links                
                for (i=StartPaging;i<=EndPaging;i++)
                {
                    if (i==PageNumber)
                    {
                        $(".PageLinks").append("<a class=\"selected\" href=\"#\" id=\"" + i + "\">" + i + "</a>");
                    }
                    else
                    {
                        $(".PageLinks").append("<a href=\"#\" id=\"" + i + "\">" + i + "</a>");
                    }
                    
                }           
                // do we need to add a "later" link?
                if (EndPaging<TotalNumberOfPages)
                {
                    $(".PageLinks").append("<a href=\"#\" id=\"" + (EndPaging+1) + "\">..</a>");
                }
                
                
                $("ForumThread",xml).each(function() {
                
                    var id =  $("ID",this).text();
                    var CounterToCheck = $("#sCounter" + id).text();
                    var Counter = $("CommentCounter",this).text();
                    // change the details for the threads
                    if (CounterToCheck!=Counter)
                    {
                        $("#sCounter" + id).hide();
                        $("#sCounter" + id).text(Counter);
                        $("#sCounter" + id).slideDown();
                        $("#sDateLastModified" + id).hide();
                        $("#sDateLastModified" + id).text($("DateLastModified",this).text());
                        $("#sDateLastModified" + id).slideDown();
                    }
                    
                    // see if the div is on the page
                    var GetTheDiv = $("#sPosition" + id);
                    
                    if (GetTheDiv.length>0) {
                   
                        // check the div's position
                        var DivPosition = $("#sPosition" + id).text();
                        
                        if (DivPosition!=position)
                        {
                            // if it is different then delete the div and reinsert in the correct row    
                            // get the row
                            var divThreadRow = $("#ForumThreadHeader" + id);
                            var divSwapThreadRow = $("#Postition" + position + " div[id^='ForumThreadHeader'");
                            // change the counter
                            $("#ForumThreadHeader" + id + " span[id^='sPosition']").text(position);
                            //$("#Postition" + position + " div[id^='ForumThreadHeader' span[id^='sPosition']").text(DivPosition);                            
                            // remove the old row
                            $("#ForumThreadHeader" + id).remove();
                            $("#Postition" + position + " div[id^='ForumThreadHeader'").remove();

                            // insert in the correct place
                            $("#Position" + position).append(divThreadRow);
                            $("#Position" + DivPosition).append(divSwapThreadRow);
     
                        }
                        // final we need to tidy up and divs which do not exsist on the page
                        // aha this is what I've missed!!!!!
                        
                    }
                    else
                    {
                        // insert the div                        
                        var divPosition="<div class=\"ForumThreadHeader\" id=\"ForumThreadHeader"+id+"\">";
                        divPosition+="<div class=\"cPosition\"><span id=\"sPosition"+id+"\">";
                        divPosition+=position;
                        divPosition+="</span></div><div class=\"cLink\"><a href=\""+ ForumURL + "?thID=" + id + "\">";
                        divPosition+=$("Title",this).text();
                        divPosition+="</a></div>";
                        divPosition+="<div class=\"cNickName\">";
                        divPosition+=$("Nickname",this).text();
                        divPosition+="</div>";
                        divPosition+="<div class=\"cDateLastModified\"><span id=\"sDateLastModified" + id + "\">";
                        divPosition+=$("DateLastModified",this).text();                            
                        divPosition+="</span></div><div class=\"cCounter\"><span id=\"sCounter"+id+"\">";
                        divPosition+=$("CommentCounter",this).text();  
                        divPosition+="</span></div></div>";
                        
                        // now find where we need to insert the div
                        $("#Position" + position).append(divPosition);
                        //$("#Position" + position).slideDown();
                        
                        

                    }
                    arr[position] = id;
                    position+=1;
                });

                // now add some colour
                var lst = $("[id^='ForumThreadHeader']");
                
                for (i=0;i<lst.length;i++)
                {
                    var chk=1;
                    
                    for (x in arr)
                    {
                        var strArr = "ForumThreadHeader" + arr[x];
                        var strLst = $(lst[i]).attr("id");
                    
                        if (strArr==strLst)
                        {
                            chk=0;
                        }
                    }
                    
                    if (chk==1)
                    {
                        $(lst[i]).remove();
                    }
                }
                 
                $("[id^='Position']:even").css("background-color", "#E8E8E9");                
                $("[id^='Position']:lt(" + (position-1) + ")").slideDown();
                //$("[id^='Position']:lt(" + (position-1) + ")").css("display","block");
                
            }
        });     
         
      }          
