﻿/// <reference name="{ViewTopics.js"/>
Type.registerNamespace('InstantASP.InstantForum.UI.Controls');


InstantASP.InstantForum.UI.Controls.ViewTopics = function(element) {

    InstantASP.InstantForum.UI.Controls.ViewTopics.initializeBase(this, [element]);

    this._json = null;
    this._element = element;
    this._pager1 = null;
    this._pager2 = null;
    this._txtChkBoxIds = null;

    this._searchEventArgs = null;
    this._pageSize = null;

    this._enableEditOptions = false;
    this._topicURL = null;
    this._findPostURL = null;
    this._profileURL = null;
    this._callBackURL = null;
    this._readCookieName = null;
    this._emailMembers = false;

    this._useWebService = false;
    this._columns = null;
    this._userCardSector = 1;
    this._defaultNoOfBlocks = 0;
    this._postsPerPage = 0;
    this._enableRank = true;
    

    this._context = null;
    this._commonUI = null;
    this._forumUI = null;
    this._userCard = null;
    
    this._topics = null;
    this._topicsRead = null;
     this._tags = null;
    this._jsonTable = new InstantASPJSONTable(this.getTable().id);
    this._searchArgsArray = null;
    this._xmlHttp = null;
    this._sFloat = null;
    
    this._transition = null;
    this._colCount = null;
    this._currentEditID = null;

    this.__isInitialized = false;


}

InstantASP.InstantForum.UI.Controls.ViewTopics.prototype = {

    // ------------------------------------ properties   

    // json data
    get_json: function() {
        return this._json;
    },

    set_json: function(value) {
        this._json = value;
    },

    // Properties
    get_element: function() {
        return this._element;
    },

    set_element: function(value) {
        this._element = value;
    },

    //pager 1
    get_pager1: function() {
        return this._pager1;
    },

    set_pager1: function(value) {
        this._pager1 = value;
    },

    //pager 2
    get_pager2: function() {
        return this._pager2;
    },

    set_pager2: function(value) {
        this._pager2 = value;
    },


    // hidden textbox to hold checked ids
    get_txtChkBoxIds: function() {
        return this._txtChkBoxIds;
    },

    set_txtChkBoxIds: function(value) {
        this._txtChkBoxIds = value;
    },



    // search event args
    get_searchEventArgs: function() {
        return this._searchEventArgs;
    },

    set_searchEventArgs: function(value) {
        this._searchEventArgs = value;
    },

    // page size
    get_pageSize: function() {
        return this._pageSize;
    },

    set_pageSize: function(value) {
        this._pageSize = value;
    },

    // enableEditOptions
    get_enableEditOptions: function() {
        return this._enableEditOptions;
    },

    set_enableEditOptions: function(value) {
        this._enableEditOptions = value;
    },

    // topic URL
    get_topicURL: function() {
        return this._topicURL;
    },

    set_topicURL: function(value) {
        this._topicURL = value;
    },

    // last post URL
    get_findPostURL: function() {
        return this._findPostURL;
    },

    set_findPostURL: function(value) {
        this._findPostURL = value;
    },

    // profile URL
    get_profileURL: function() {
        return this._profileURL;
    },

    set_profileURL: function(value) {
        this._profileURL = value;
    },

    // callback URL
    get_callBackURL: function() {
        return this._callBackURL;
    },

    set_callBackURL: function(value) {
        this._callBackURL = value;
    },

    // use a web service for initial population
    get_useWebService: function() {
        return this._useWebService;
    },

    set_useWebService: function(value) {
        this._useWebService = value;
    },


    // columns to display
    get_columns: function() {
        return this._columns;
    },

    set_columns: function(value) {
        this._columns = value;
    },

    // sector to display user card
    get_userCardSector: function() {
        return this._userCardSector;
    },

    set_userCardSector: function(value) {
        this._userCardSector = value;
    },

    // default number of user level blocks
    get_defaultNoOfBlocks: function() {
        return this._defaultNoOfBlocks;
    },

    set_defaultNoOfBlocks: function(value) {
        this._defaultNoOfBlocks = value;
    },

    // posts per page
    get_postsPerPage: function() {
        return this._postsPerPage;
    },

    set_postsPerPage: function(value) {
        this._postsPerPage = value;
    },

    // enable rank image?
    get_enableRank: function() {
        return this._enableRank;
    },

    set_enableRank: function(value) {
        this._enableRank = value;
    },

    // get mark all as read cookie name
    get_readCookieName: function() {
        return this._readCookieName;
    },

    set_readCookieName: function(value) {
        this._readCookieName = value;
    },

    // get enable emails
    get_emailMembers: function() {
        return this._emailMembers;
    },

    set_emailMembers: function(value) {
        this._emailMembers = value;
    },
    
    // ------------------------------------ methods

    renderViewTopics: function() {

        var json = this.get_json();

        if (json != null) {

            // setup user card object
            if (this._userCard == null) {

                this._userCard = new InstantForumUserCard(this._element)
                this._userCard._json = this.get_json();
                this._userCard._emailMembers = this.get_emailMembers();
                this._userCard.initialize();

                // add event to hide any active tooltips
                var ctl = this;
                addEvent(document.body, 'click', function() {
                    if (ctl._userCard != null) {
                        ctl._userCard.hideUserCard();
                    }
                }
                );

                addEvent(window, 'resize', function() {
                    if (ctl._userCard != null) {
                        ctl._userCard.hideUserCard();
                    }
                }
                );

                addEvent(document.body, 'mousemove', function(e) {
                    if (ctl._userCard != null) {
                        ctl._userCard.hideUserCardOnMouseOut(e);
                    }
                }
                );

            }

        }

        // setup topics object
        this._topics = new InstantForumTopics(json);
        this._topics.initialize();

        // setup topics read object
        this._topicsRead = new InstantForumTopicsRead(json);
        this._topicsRead.initialize();

        // setup tags object
        this._tags = new InstantASPTags(json);
        this._tags.initialize();

        // setup json table
        this._jsonTable.JSON = json;
        this._jsonTable.Host = this;
        this._jsonTable.BindData = this.selectTopics;
        this._jsonTable.OnHeaderRowAdd = this.buildHeaderRow;
        this._jsonTable.OnRowAdd = this.buildRow;
        this._jsonTable.OnSeperatorRowAdd = this.buildSeperatorRow;
        this._jsonTable.initalize();

        // get pageing controls
        var p1 = this.getPager1();
        var p2 = this.getPager2();

        if (p1 != null) {
            p1.renderAjaxPager();
            p1.enablePager();
        }

        if (p2 != null) {
            p2.renderAjaxPager();
            p2.enablePager();
        }

    },

    // ------------------------------------ data / service

    selectTopics: function(host) {

        // get pageing controls
        var p1 = host.getPager1();
        var p2 = host.getPager2();

        if (host._topics.TopicCollection != null) {

            // get total records
            var intTotalRecords = host._topics.TotalRecords;

            // do we have a limit on results?
            if (host._searchArgsArray != null) {
                if (host._searchArgsArray.MaxResults != null) {
                    if (host._searchArgsArray.MaxResults > 0) {
                        if (intTotalRecords > host._searchArgsArray.MaxResults) {
                            intTotalRecords = host._searchArgsArray.MaxResults;
                        }
                    }
                }
            }


            // update pager total records
            if (p1 != null) { p1.set_totalRecords(intTotalRecords); }
            if (p2 != null) { p2.set_totalRecords(intTotalRecords); }

            // return topics
            return host._topics.TopicCollection;

        } else {

            if (p1 != null) { p1.set_totalRecords(0); }
            if (p2 != null) { p2.set_totalRecords(0); }

        }

        return null;


    },

    // ------------------------------------ search event atgs

    get_searchArgsArray: function() {

        return this._searchArgsArray;

    },

    set_searchArgsInternalArray: function() {

        // get search event args
        var s = new InstantForumSearchEventArgs(this.get_searchEventArgs());
        s.initialize();

        // check for nulls
        if (s.Args.SortBy == null) {
            s.Args["SortBy"] = "LastPosterDate"
        }

        // populate local array
        this._searchArgsArray = s.Args;

    },

    set_searchArgsArray: function(newArr) {

        this._searchArgsArray = newArr;

    },

    pageIndexChanged: function(pageIndex, update) {

        // update json table
        this.fetchData(pageIndex, update);

        // scroll window to top of control        
        if_scrollToDiv(this._element.id);


    },



    // event raised from moderation options button click
    moderationOptionsClick: function(intPageIndex, intAction, intForumID, intNewForumID) {

        // if we don't have selected posts ecit
        var strPostIds = this.get_txtChkBoxIds().value;
        if (strPostIds == "") { return false; }

        // show loader
        this._jsonTable.clearTable();
        this._jsonTable.showLoader();
        this._jsonTable.loading = false;

        // tidy args
        if (intForumID == null || intForumID == "") { intForumID = 0; }
        if (intNewForumID == null || intNewForumID == "") { intNewForumID = 0; }

        var strURL = this._context.CurrentSettings.InstallURL + this.get_callBackURL();

        // call moderation method
        if_modClick(intAction, intForumID, intNewForumID, strPostIds, intPageIndex, strURL, this)

        return false;

    },



    // --------- get paging controls

    getPager1: function() {

        var obj = null;
        if (this._pager1 != null) {
            obj = $find(this._pager1.id);
        }
        return obj;

    },

    getPager2: function() {

        var obj = null;
        if (this._pager2 != null) {
            obj = $find(this._pager2.id);
        }
        return obj;

    },

    // --------- fetch data

    fetchData: function(pageIndex, forceDBLookUp) {

        // if json table is loading exit function, mozilla based browsers seem to
        // fire this event multiple times if you hit enter in a textbox to submit form posts
        if (this._jsonTable.loading == true) { return }

        // tidy arguments
        if (forceDBLookUp == null) { forceDBLookUp = false; }
        if (pageIndex <= 0) { pageIndex = 1; }

        // get pageing controls
        var p1 = this.getPager1();
        var p2 = this.getPager2();

        // did we find paging controls
        if (p1 != null) {
            // ensure we keep within page range
            if (pageIndex > p1._totalPages) { pageIndex = p1._totalPages; }
            p1._pageIndex = pageIndex;
            p1.renderAjaxPager();
            p1.disablePager();
        }

        if (p2 != null) {
            // ensure we keep within page range
            if (pageIndex > p2._totalPages) { pageIndex = p2._totalPages; }
            p2._pageIndex = pageIndex;
            p2.renderAjaxPager();
            p2.disablePager();
        }

        // create context to pass to onComplete, onError etc
        var arrUserContext = new Array();
        arrUserContext[0] = this._element.id;

        // convert search args to xml
        var strXML = "<s>" + ObjToXml(this._searchArgsArray) + "</s>";

        // setup jason table
        this.beginRequest();

        // get data & set async evetns
        var service = new InstantASP.InstantForum.UI.WebServices.Topics();
        service.SelectTopicsPaged(pageIndex, this.get_pageSize(), strXML, true, forceDBLookUp, this.onComplete, this.onError, arrUserContext);

    },

    beginRequest: function() {

        this._jsonTable.clearTable();
        this._jsonTable.showLoader();

    },

    onComplete: function(returndata, userContext) {

        var ctl = $find(userContext[0]);
        ctl._json = returndata;
        ctl.renderViewTopics();

    },

    onError: function(error) {

        if (error != null) {
            alert("Error: " + error.description);
        } else {
            //alert("Error");
        }

    },

    // ------------------------------------ build tabke tows

    buildHeaderRow: function(host) {

        var intCols = 1;
        var imgFolder = host._context.CurrentSettings.InstallImageFolderURL;
        var strImgAsc = "Misc_SortArrowAsc.gif";
        var strImgDesc = "Misc_SortArrowDesc.gif";

        // local vars
        var strCSS = "PanelBar_SubHeader"

        // ------------------- create row

        var row = document.createElement("TR");

        // ------------------- icon

        if (host.showColumn("Icon")) {

            var hyp = document.createElement("A");
            hyp.setAttribute('href', '');
            hyp.appendChild(document.createTextNode(' '));

            var td = host._commonUI.buildTD(strCSS, "3%", null, hyp)
            row.appendChild(td);

        }

        // ------------------- topic title

        var strSortColumn = "Title";
        if (host.showColumn(strSortColumn)) {

            var container = document.createElement("DIV");

            // topic title
            var hyp = document.createElement("A");
            hyp.id = "hypSort_" + strSortColumn
            hyp.setAttribute('href', 'javascript: void(0)');
            hyp.appendChild(document.createTextNode("Topics"));

            container.appendChild(hyp);

            // sort img
            if (host._searchArgsArray.SortBy.toLowerCase().indexOf(strSortColumn.toLowerCase()) > -1) {

                var img = document.createElement("IMG");
                if (host._searchArgsArray.SortOrder == 1) { // desc
                    img.src = imgFolder + strImgDesc;
                    img.alt = iasp_sortDesc;
                } else {
                    img.src = imgFolder + strImgAsc;
                    img.alt = iasp_SortAsc;
                }

                container.appendChild(img);

            }

            var td = host._commonUI.buildTD(strCSS, null, null, container)
            row.appendChild(td);
            intCols += 1;

        }

        // ------------------- replies

        var strSortColumn = "Replies";
        if (host.showColumn(strSortColumn)) {

            var container = document.createElement("DIV");

            var hyp = document.createElement("A");
            hyp.id = "hypSort_" + strSortColumn
            hyp.setAttribute('href', 'javascript: void(0)');
            hyp.appendChild(document.createTextNode(strSortColumn));

            container.appendChild(hyp);

            // sort img
            if (host._searchArgsArray.SortBy.toLowerCase().indexOf(strSortColumn.toLocaleLowerCase()) > -1) {

                var img = document.createElement("IMG");
                if (host._searchArgsArray.SortOrder == 1) { // desc
                    img.src = imgFolder + strImgDesc;
                    img.alt = iasp_sortDesc;
                } else {
                    img.src = imgFolder + strImgAsc;
                    img.alt = iasp_SortAsc;
                }

                container.appendChild(img);

            }

            var td = host._commonUI.buildTD(strCSS, "10%", "center", container)
            row.appendChild(td);
            intCols += 1;

        }

        // ------------------- views

        var strSortColumn = "Views";
        if (host.showColumn(strSortColumn)) {

            var container = document.createElement("DIV");

            var hyp = document.createElement("A");
            hyp.id = "hypSort_" + strSortColumn
            hyp.setAttribute('href', 'javascript: void(0)');
            hyp.appendChild(document.createTextNode(strSortColumn.toLowerCase()));

            container.appendChild(hyp);

            // sort img
            if (host._searchArgsArray.SortBy.toLowerCase().indexOf(strSortColumn.toLocaleLowerCase()) > -1) {

                var img = document.createElement("IMG");
                if (host._searchArgsArray.SortOrder == 1) { // desc
                    img.src = imgFolder + strImgDesc;
                    img.alt = iasp_sortDesc;
                } else {
                    img.src = imgFolder + strImgAsc;
                    img.alt = iasp_SortAsc;
                }

                container.appendChild(img);

            }


            var td = host._commonUI.buildTD(strCSS, "10%", "center", container)
            row.appendChild(td);
            intCols += 1;

        }



        // ------------------- last post by

        var strSortColumn = "LastPosterDate";
        if (host.showColumn(strSortColumn)) {

            var container = document.createElement("DIV");

            var hyp = document.createElement("A");
            hyp.id = "hypSort_" + strSortColumn
            hyp.setAttribute('href', 'javascript: void(0)');
            hyp.appendChild(document.createTextNode("Last Post"));

            container.appendChild(hyp);

            // sort img
            if (host._searchArgsArray.SortBy.toLowerCase().indexOf(strSortColumn.toLocaleLowerCase()) > -1) {

                var img = document.createElement("IMG");
                if (host._searchArgsArray.SortOrder == 1) { // desc
                    img.src = imgFolder + strImgDesc;
                    img.alt = iasp_sortDesc;
                } else {
                    img.src = imgFolder + strImgAsc;
                    img.alt = iasp_SortAsc;
                }

                container.appendChild(img);

            }

            var td = host._commonUI.buildTD(strCSS, "260px", null, container)
            row.appendChild(td);
            intCols += 1;

        }

        // ------------------- select all edit checkbox

        if (host.get_enableEditOptions()) {

            var cb = document.createElement("INPUT");
            cb.setAttribute('type', 'checkbox');
            cb.className = "FormCheckBox";

            // add check all event
            addEvent(cb, 'click', function() {
                checkAll('ckbEdit_', cb.checked);
                host.populateChkBoxInputHidden('ckbEdit_');
            }
            );

            var td = host._commonUI.buildTD(strCSS, null, "center", cb)
            row.appendChild(td);
            intCols += 1;

        }


        // set internal variable to hold column count
        host._colCount = intCols;

        // return row
        return row;


    },

    buildSeperatorRow: function(host, data) {

        // local vars
        var strCSS = "TableCell_Medium"

        // ------------------- create row

        var row = document.createElement("TR");

        // ------------------- create content

        // create title
        var span = document.createElement("SPAN");
        span.className = "SmallTxtBold";
        span.appendChild(document.createTextNode("Topics"));

        // add column to row
        var td = host._commonUI.buildTD(strCSS, null, null, span, host._colCount)
        row.appendChild(td);

        // return row                
        return row;

    },

    buildRow: function(host, data) {

        // local vars
        var strCssDark = "TableCell_Dark";
        var strCssLight = "TableCell_Light";
        var CssSmallTxt = "SmallTxt";
        var CssLargeTxt = "LargeTxt";

        if (data.Queued) {
            strCssDark = "ForumsBodyQueued";
            strCssLight = "ForumsBodyQueued";
        }

        var installURL = host._context.CurrentSettings.InstallURL;
        var imgFolder = host._context.CurrentSettings.InstallImageFolderURL;

        var bolIsRead = false;
        var arrReadIcon = null;
        if (host._topicsRead != null) {
            arrReadIcon = host._topicsRead.Icon(data, host.get_readCookieName())
            bolIsRead = arrReadIcon[2];
        }

        // ------------------- create row

        var row = document.createElement("TR");

        // ------------------- icon

        if (host.showColumn("Icon")) {

            var img = document.createElement("IMG");
            if (arrReadIcon != null) {
                img.src = imgFolder + arrReadIcon[0];
                img.alt = arrReadIcon[1];
                if (data.Queued && iasp_IsIE) {
                    img.style.filter = "alpha(opacity=50); moz-opacity:.50;"
                }
            }

            var td = host._commonUI.buildTD(strCssDark, null, "center", img)
            row.appendChild(td);

        }

        // ------------------- topic cell

        if (host.showColumn("Title")) {

            var strTopicURL = null;
            if (data.ParentID > 0) {
                strTopicURL = host.get_findPostURL().replace("0", data.PostID);
            } else {
                strTopicURL = host.get_topicURL().replace("0", data.PostID);
            }

            var searchArgs = host.get_searchArgsArray();
            if (searchArgs != null) {
                if (searchArgs["Keywords"] != null && searchArgs["Keywords"] != "") {
                    strTopicURL += "?Keywords=" + iasp_EncodeString(searchArgs["Keywords"]);
                }
            }

            var container = document.createElement("div");
            container.style[host._sfloat] = "left";
            container.style.width = "100%";

            var div1 = document.createElement("div");
            div1.style[host._sfloat] = "left";
            div1.className = CssLargeTxt;

            // edit layer

            var spanLiveEdit = document.createElement("DIV");
            spanLiveEdit.style[host._sfloat] = "left";
            spanLiveEdit.style.width = "100%";

            // add events to show edit options

            if (host.get_enableEditOptions()) {

                addEvent(spanLiveEdit, 'mouseover', function() {
                    host.showEditButtons(data.PostID, true);
                }
                );

                addEvent(spanLiveEdit, 'mouseout', function() {
                    host.showEditButtons(data.PostID, false);
                }
                );

            }

            // create span to hold topic link and style based on read status

            var span = document.createElement("SPAN");

            if (bolIsRead) {
                span.className = 'LargeTxt';
            } else {
                span.className = 'LargeTxtBold';
            }

            // create edit textbox for moderators

            if (host.get_enableEditOptions()) {

                var txt = document.createElement("INPUT");
                txt.setAttribute('type', 'text');
                txt.id = "txtEdit_" + data.PostID;
                txt.className = "FormInputText";
                txt.value = data.TitleFull;
                txt.style.width = "100%";
                txt.style.display = "none";

                span.appendChild(txt)

            }

            // add pinned post text

            //            if (data.IsPinned == "true") {

            //                var pinned = document.createElement("SPAN");
            //                pinned.id = "pinnedtext_" + data.PostID;
            //                pinned.className = "LargeTxt";
            //                pinned.appendChild(document.createTextNode("Pinned: "));

            //                span.appendChild(pinned);

            //            }


            // setup topic icon

            if (data.MessageIcon != null) {
                var imgTopicIcon = document.createElement("IMG");
                imgTopicIcon.id = "imgIcon_" + data.PostID;
                imgTopicIcon.src = imgFolder + 'MessageIcons/' + data.MessageIcon;
                imgTopicIcon.alt = data.MessageIconName;
                imgTopicIcon.style.verticalAlign = "middle";
                imgTopicIcon.style.paddingRight = "6px";
                span.appendChild(imgTopicIcon);
            }

            // create link

            var hyp = document.createElement("A");
            hyp.id = "hyp_" + data.PostID;
            hyp.setAttribute('href', strTopicURL);
            hyp.innerHTML = data.Title;
            hyp.style.display = "";

            if (data.Message != null && data.Message != "") {
                hyp.title = data.Message;
            }

            // add link to span

            span.appendChild(hyp);

            // add span to live edit layer

            spanLiveEdit.appendChild(span);

            var spanButtons = document.createElement("SPAN");
            spanButtons.id = "spanButtons_" + data.PostID;
            spanButtons.style.display = "none";

            // live edit

            var hypEdit = document.createElement("A");
            hypEdit.id = "hypEdit_" + data.PostID;
            hypEdit.title = "Edit Topic Title";
            hypEdit.setAttribute('href', "javascript: void(0);");

            var imgEdit = document.createElement("IMG");
            imgEdit.src = imgFolder + 'Misc_Edit.gif';
            imgEdit.style.marginTop = "-2px";
            imgEdit.style.marginBottom = "-2px";
            imgEdit.style.marginLeft = "6px";
            imgEdit.style.verticalAlign = "middle";
            imgEdit.style.padding = "0px";

            imgEdit.alt = "Edit";

            addEvent(hypEdit, 'click', function() {
                host.hypEditMouseClick(data);
            }
            );

            hypEdit.appendChild(imgEdit);

            // live delete

            var hypDelete = document.createElement("A");
            hypDelete.id = "hypDelete_" + data.PostID;
            hypDelete.title = "Delete Topic";
            hypDelete.setAttribute('href', "javascript: void(0);");

            var imgDelete = document.createElement("IMG");
            imgDelete.src = imgFolder + 'Misc_Delete.gif';
            imgDelete.style.marginTop = "-2px";
            imgDelete.style.marginBottom = "-2px";
            imgDelete.style.marginLeft = "2px";
            imgDelete.style.verticalAlign = "middle";
            imgDelete.style.padding = "0px";
            imgDelete.alt = "Delete";

            // add delete event
            addEvent(hypDelete, 'click', function() {
                host.hypDeleteMouseClick(data);
            }
            );

            hypDelete.appendChild(imgDelete);

            // add edit links
            spanButtons.appendChild(hypEdit);
            spanButtons.appendChild(hypDelete);

            spanLiveEdit.appendChild(spanButtons)

            div1.appendChild(spanLiveEdit);

            // posted by

            var strUsername = null;
            if (data.Username != null) {
                strUsername = if_ViewForumGroupsLastPostBy.replace("[0]", data.Username);
            }

            // profile url
            var profileURL = installURL + host.get_profileURL().replace('0', data.UserID);

            // right div

            var bolRenderRight = false;
            var div2 = document.createElement("div");
            div2.style[host._sfloat] = "right";
            div2.style.textAlign = "right"
            div2.style.width = "20%";

            // rank image

            if (data.RankImg != null && host.get_enableRank()) {

                // create rank image
                var imgRank = document.createElement("IMG");
                imgRank.src = imgFolder + data.RankImg;
                imgRank.alt = "Relevancy: " + data.Rank + "%";
                imgRank.title = "Relevancy: " + data.Rank + "%";
                imgRank.style.marginLeft = "6px";
                imgRank.style.verticalAlign = "middle";

                if (data.Queued && iasp_IsIE) {
                    imgRank.style.filter = "alpha(opacity=50); moz-opacity:.50;"
                }

                // add rank image
                div2.appendChild(imgRank);
                bolRenderRight = true;

            } else {

                // show rating

                if (data.Rating > 0) {

                    var strAlt1 = null;
                    if (data.Rating == 1) {
                        strAlt1 = if_RatedStar.replace("[0]", data.Rating);
                    } else {
                        strAlt1 = if_RatedStars.replace("[0]", data.Rating);
                    }

                    var strAlt2 = null;
                    if (data.TotalRatings == 1) {
                        strAlt2 = if_TotalVote.replace("[0]", data.TotalRatings)
                    } else {
                        strAlt2 = if_TotalVotes.replace("[0]", data.TotalRatings)
                    }

                    // create ratomg image
                    var imgRating = document.createElement("IMG");
                    imgRating.src = imgFolder + 'Misc_Rating' + data.Rating + '.gif';
                    imgRating.style.marginTop = "-6px";
                    imgRating.style.verticalAlign = "middle";

                    if (strAlt1 != null && strAlt2 != null) {
                        imgRating.alt = strAlt1 + strAlt2;
                        imgRating.title = strAlt1 + strAlt2; ;
                    }

                    div2.appendChild(imgRating);
                    bolRenderRight = true;

                }

            }
            // attachment icon

            var imgAttachments = document.createElement("IMG");
            if (data.HasAttachments != null) {

                if (data.HasAttachments) {
                    imgAttachments.src = imgFolder + 'Misc_Attachments.gif';
                    imgAttachments.alt = if_HasAttachments;
                    imgAttachments.style.display = '';
                    imgAttachments.style.marginLeft = "6px";
                    div2.appendChild(imgAttachments);
                    bolRenderRight = true;

                }
            }

            // pinned?

            if (data.IsPinned) {

                // create pinned image
                var imgPinned = document.createElement("IMG");
                imgPinned.src = imgFolder + 'Misc_Pinned.gif';
                imgPinned.alt = if_PinnedTopic;
                imgPinned.title = if_PinnedTopic;
                imgPinned.style.marginLeft = "6px";
                imgPinned.style.verticalAlign = "middle";
                if (data.Queued && iasp_IsIE) {
                    imgPinned.style.filter = "alpha(opacity=50); moz-opacity:.50;"
                }

                // add pinned image
                div2.appendChild(imgPinned);
                bolRenderRight = true;

            }

            // do we need to render the right div?

            if (bolRenderRight) {
                div1.style.width = "80%";

            } else {
                div1.style.width = "100%";

            }

            // add left & right layers to container
            container.appendChild(div1);
            if (bolRenderRight) { container.appendChild(div2); }

            // bottom div (Create By & Topic Paging)

            var div3 = document.createElement("div");
            div3.style[host._sfloat] = "left";
            div3.style.textAlign = "left"
            div3.className = CssSmallTxt;
            div3.style.width = "75%";

            // create link
            var hyp = document.createElement("A");
            if (data.UserID > 0) {
                hyp.setAttribute('href', profileURL);
            }
            hyp.appendChild(document.createTextNode(strUsername));

            div3.appendChild(hyp);

            // display tags

            if (host._tags != null) {

                var tags = host._tags.SelectTagsForEntity(data.PostID);

                if (tags != null) {

                    if (tags.length > 0) {

                        // ---------- tags

                        var comma = document.createElement("SPAN");
                        comma.appendChild(document.createTextNode(", "));
                        div3.appendChild(comma);

                        var span = document.createElement("SPAN");
                        span.appendChild(document.createTextNode("Tags: "));
                        div3.appendChild(span);

                        for (var i = 0; i < tags.length; i++) {

                            var tag = tags[i];

                            var tagspan = document.createElement("SPAN");
                            tagspan.innerHTML = tag.TagKeyword;

                            // tag link
                            var hyp = document.createElement("A");
                            hyp.setAttribute('href', "Tags.aspx?Tag=" + tag.TagEncoded);
                            hyp.setAttribute('title', 'Search for posts tagged ' + tag.TagEncoded);
                            hyp.appendChild(tagspan);

                            div3.appendChild(hyp);

                            if (i < tags.length - 1) {
                                var comma = document.createElement("SPAN");
                                comma.appendChild(document.createTextNode(", "));
                                div3.appendChild(comma);
                            }

                        }
                    }
                }
            }

            // paging vars
            var intPageSize = host.get_postsPerPage()
            var intTotalRecords = data.Replies ? parseInt(data.Replies.replace(",", "")) + 1 : 0;
            var div4 = null;

            // should we display pager?
            if (intTotalRecords > intPageSize) {

                div4 = document.createElement("div");
                div4.style[host._sfloat] = "right";
                div4.style.textAlign = "right"
                div4.style.width = "25%";
                div4.className = CssSmallTxt;

                div4.appendChild(host.buildPagingLinks(intPageSize, intTotalRecords, data.PostID));

            }


            if (div4 == null) { div3.style.width = "100%"; }
            container.appendChild(div3);
            if (div4 != null) { container.appendChild(div4); }

            // create cell
            var td = host._commonUI.buildTD(strCssLight, null, null, container)
            row.appendChild(td);

        }

        // ------------------- total replies

        if (host.showColumn("Replies")) {

            var span = document.createElement("SPAN");
            span.className = "ttlPosts";

            if (typeof data.Replies != "undefined") {
                span.appendChild(document.createTextNode(data.Replies));
            } else {
                span.appendChild(document.createTextNode("0"));
            }

            var td = host._commonUI.buildTD(strCssLight, null, "center", span)
            row.appendChild(td);

        }

        // ------------------- total views  

        if (host.showColumn("Views")) {

            var span = document.createElement("SPAN");
            span.className = "ttlPosts";

            if (typeof data.Views != "undefined") {
                span.appendChild(document.createTextNode(data.Views));
            } else {
                span.appendChild(document.createTextNode("0"));
            }

            var td = host._commonUI.buildTD(strCssLight, null, "center", span)
            row.appendChild(td);

        }

        // ------------------- last post

        if (host.showColumn("LastPosterDate")) {

            var strLastPostURL = host.get_findPostURL().replace("0", data.LastPosterPostID ? data.LastPosterPostID : data.PostID);

            var intLastPosterUserID = data.LastPosterUserID;
            var intCardSector = host.get_userCardSector();
            var profileURL = installURL + host.get_profileURL().replace('0', intLastPosterUserID);

            var container = document.createElement("DIV");
            container.style[host._sfloat] = "left";
            container.style.width = "100%";
            container.id = "usercard_main"

            var left = document.createElement("div");
            left.id = "usercard_left"
            left.style[host._sfloat] = "left";

            // create photo image
            var img = document.createElement("IMG");
            if (data.PhotoImage != null && data.PhotoImage != "") {
                if (data.PhotoImage.toLowerCase().indexOf("http://") == -1 && data.PhotoImage.toLowerCase().indexOf("https://") == -1) {
                    img.src = installURL + data.PhotoImage;
                } else {
                    img.src = data.PhotoImage;
                }
            } else {
                img.src = imgFolder + "Misc_NoPhoto.gif";
                img.alt = "No member picture";
            }

            if (data.Queued && iasp_IsIE) {
                img.style.filter = "alpha(opacity=50); moz-opacity:.50;"
            }


            // create photo link
            var hypPhoto = document.createElement("A");
            if (intLastPosterUserID > 0) {
                hypPhoto.setAttribute('href', profileURL);
            }
            hypPhoto.appendChild(img);

            // add mouse over event

            // ensure this is a registered member
            if (intLastPosterUserID > 0) {
                addEvent(hypPhoto, 'mouseover', function() {
                    host._userCard.showUserCard(intLastPosterUserID, intCardSector);
                }
                );
            }

            // B.Marcinkowski Changed 03/30/2010
            // create photo div
            // var div = host._userCard.buildPhotoWithCard(intLastPosterUserID, hypPhoto, intCardSector, "userPictureSmall");


            // add member photo to div
            //left.appendChild(div)
            // B.Marcinkowski Changed 03/30/2010

            // create right div
            var right = document.createElement("div");
            right.style[host._sfloat] = "left";
            right.style.marginTop = "-6px";

            var span = document.createElement("SPAN");
            span.innerHTML = data.LastPosterDate

            var br = document.createElement("SPAN");
            br.innerHTML = "<br />"

            right.appendChild(span);
            right.appendChild(br);

            var hyp1 = document.createElement("A");
            hyp1.setAttribute('href', strLastPostURL);
            hyp1.appendChild(document.createTextNode("Last Post By:"));

            var span = document.createElement("SPAN");
            span.appendChild(document.createTextNode(" "));

            var hyp2 = document.createElement("A");
            if (intLastPosterUserID > 0) {
                hyp2.setAttribute('href', profileURL);
            }
            hyp2.appendChild(document.createTextNode(data.LastPosterUsername));

            right.appendChild(hyp1);
            right.appendChild(span);
            right.appendChild(hyp2);

            // add divs to container
            container.appendChild(left);
            container.appendChild(right);

            // create column
            var td = host._commonUI.buildTD(strCssLight, null, null, container)
            row.appendChild(td);

        }

        // ------------------- topic checkbox

        if (host.get_enableEditOptions()) {

            var cb = document.createElement("INPUT");
            cb.setAttribute('type', 'checkbox');
            cb.id = "ckbEdit_" + data.PostID
            cb.className = "FormCheckBox";

            // add check all event
            addEvent(cb, 'click', function() {
                host.populateChkBoxInputHidden('ckbEdit_');
            }
            );

            var td = host._commonUI.buildTD(strCssDark, "1%", "center", cb)
            row.appendChild(td);

        }


        // add quick edit reset click event
        if (host.get_enableEditOptions()) {

            addEvent(document.body, 'click', function(e) {
                host.detectSave(host._currentEditID, e);
            }
            );

        }

        return row

    },

    // ------------------------------------ topic paging

    buildPagingLinks: function(pageSize, totalRecords, intTopicID) {

        // create container
        var container = document.createElement("div");
        container.id = "pager_" + this._element.id;
        container.style[this._sfloat] = "right";
        container.style.textAlign = "right"

        // create pages label
        var pages = document.createElement("SPAN");
        pages.appendChild(document.createTextNode("Pages: "));

        // div to hold pager
        var div1 = document.createElement("SPAN");

        var strURL = this._context.CurrentSettings.InstallURL + this.get_topicURL().replace("0", intTopicID);

        // create pager
        var pager = new InstantASP.Common.UI.WebControls.AjaxPager(div1);
        pager.set_pageIndex(1);
        pager.set_pageSize(pageSize);
        pager.set_totalRecords(totalRecords);
        pager.set_enablePagesLabel(false);
        pager.set_enablePrevNextButtons(false);
        pager.set_linkClass("SmallTxt");
        pager.set_linkSelectedClass("SmallTxt");
        pager.set_enableDelimiter(true);
        pager.set_enableEndPages(true);
        pager.set_navigateURL(strURL)
        pager.renderAjaxPager();

        // add label & pager to div
        //container.appendChild(pages);
        container.appendChild(div1);

        // return contiainer
        return container;

    },

    // ------------------------------------ helpers

    showColumn: function(colname) {

        var columns = this.get_columns()

        if (columns == "*") {

            return true;

        } else {

            var arrcolumns = columns.split(",");

            for (var i = 0; i < arrcolumns.length; i++) {
                if (colname.toLowerCase() == arrcolumns[i]) {
                    return true;
                }
            }

            return false;
        }

    },

    getTable: function() {

        var container = iasp_FindControl(this.get_element().id);
        var table = container.getElementsByTagName("TABLE")[0]

        if (!table) {
            alert("Could not locate HTML table to render JSON data");
        } else {
            table.id = "tbl_" + container.id;
        }

        return table;

    },

    showEditButtons: function(postID, display) {

        // only display edit options if we are not already editing
        if (this._currentEditID != null) { return false; }

        // get edit buttons
        var spanButtons = iasp_FindControl("spanButtons_" + postID);


        // toggle buttons
        if (spanButtons != null) {
            if (display) {
                spanButtons.style.display = "";
            } else {
                spanButtons.style.display = "none";
            }
        }


    },

    hypEditMouseClick: function(data) {

        // setup current edit identity
        this._currentEditID = data.PostID;

        // initialize edit options
        this.initEditOptions(this._currentEditID);

    },

    hypDeleteMouseClick: function(data) {

        // setup current edit identity
        if (confirm("Are you sure you want to delete this topic?\n\nThis will also delete all replies & attachments.")) {
            this.deleteTopic(data.PostID);
        }

        return false



    },

    initEditOptions: function(id) {

        var pinnedtext = iasp_FindControl("pinnedtext_" + id);
        if (pinnedtext != null) {
            pinnedtext.style.display = "none";
        }

        // get message icon
        var imgIcon = iasp_FindControl("imgIcon_" + id);
        if (imgIcon != null) { imgIcon.style.display = "none"; }

        // get link
        var hyp = iasp_FindControl("hyp_" + id);
        hyp.style.marginLeft = '-1000px'

        var spanButtons = iasp_FindControl("spanButtons_" + id);
        spanButtons.style.display = "none";

        var txt = iasp_FindControl("txtEdit_" + id);
        txt.style.display = "";
        txt.select();

    },

    // event raised when clicking on table cells in edit mode
    detectSave: function(id, e) {

        if (this._currentEditID == null) { return false; }

        var el = null;
        // find the element that was clicked
        if (iasp_IE4 || iasp_IE5 || iasp_Opera) {
            el = window.event.srcElement;
        }
        else {
            // resolve issue with links not working in FF
            if (e.target != null) {
                if (e.target.tagName.toLowerCase() == "a") { return; }
            }
            el = (e.target.tagName ? e.target : e.target.parentNode);
        }

        // if we are clicking the textbox exit
        var tagName = el.tagName.toLowerCase();
        if (tagName == "input" || tagName == "img") {
            return false;
        }

        // else reset out controls

        // reset textbox
        var txt = iasp_FindControl("txtEdit_" + this._currentEditID);

        // save title
        this.saveTitle(this._currentEditID, txt.value)

    },

    saveTitle: function(postID, strTitle) {

        var viewTopics = this;

        // get url
        var strURL = this._context.CurrentSettings.InstallURL + this.get_callBackURL();
        var arrURL = strURL.split("?");

        // setup xmlhttp
        if (this._xmlHttp == null) { this._xmlHttp = new iasp_XmlHttpRequest(); }
        var objXmlHttpHandler = function(obj) {
            if (obj.responseXML != null) {
                var items = obj.responseXML.getElementsByTagName("result");
                if (items.length > 0) {
                    for (var i = 0; i < items.length; i++) {
                        var nd = items[i];
                        // get result
                        var result = nd.getAttribute("title") == null ? "" : nd.getAttribute("title");
                        // end loader
                        iasp_AjaxExtensionsEndRequest();

                        // was everything ok
                        if (result != "") {
                            //alert(result);
                        } else {
                            alert("Problem");
                        }

                        // reset edit controls
                        viewTopics.resetEditControls(postID, result)

                    }
                }
            }
        };

        // setup params
        var strParams = arrURL[1] + "&Action=UpdateTopicTitle&id=" + postID + "&key=" + iasp_EncodeString(strTitle);
        // setup loader
        iasp_AjaxExtensionsInitializeRequest();
        // make request
        this._xmlHttp.Connect(arrURL[0], "GET", strParams, objXmlHttpHandler);


    },

    deleteTopic: function(postID) {

        var viewTopics = this;

        // get url
        var strURL = this._context.CurrentSettings.InstallURL + this.get_callBackURL();
        var arrURL = strURL.split("?");

        // setup xmlhttp
        if (this._xmlHttp == null) { this._xmlHttp = new iasp_XmlHttpRequest(); }
        var objXmlHttpHandler = function(obj) {
            if (obj.responseXML != null) {
                var items = obj.responseXML.getElementsByTagName("result");
                if (items.length > 0) {
                    for (var i = 0; i < items.length; i++) {

                        var nd = items[i];
                        // get result
                        var identity = nd.getAttribute("identity") == null ? 0 : nd.getAttribute("identity");
                        // end loader
                        iasp_AjaxExtensionsEndRequest();
                        // was everything ok
                        if (identity > 0) {
                            viewTopics.pageIndexChanged(1);

                        } else {
                            alert("Problem");
                        }



                    }
                }
            }
        };

        // setup params
        var strParams = arrURL[1] + "&Action=DeleteTopic&id=" + postID;
        // setup loader
        iasp_AjaxExtensionsInitializeRequest();
        // make request
        this._xmlHttp.Connect(arrURL[0], "GET", strParams, objXmlHttpHandler);


    },



    resetEditControls: function(postID, newTitle) {

        var txt = iasp_FindControl("txtEdit_" + postID);
        txt.style.display = "none";

        // get message icon
        var imgIcon = iasp_FindControl("imgIcon_" + postID);
        if (imgIcon != null) { imgIcon.style.display = ""; }


        var hyp = iasp_FindControl("hyp_" + postID);
        hyp.style.dislay = "";
        hyp.style.marginLeft = '0px'
        if (newTitle != "") {
            hyp.innerText = newTitle;
        }

        // reset buttons
        var spanButtons = iasp_FindControl("spanButtons_" + postID);
        spanButtons.style.display = "none";

        var pinnedtext = iasp_FindControl("pinnedtext_" + postID);
        if (pinnedtext != null) {
            pinnedtext.style.display = "";
        }

        // reset internal variable
        this._currentEditID = null;


    },

    populateChkBoxInputHidden: function(ckbId) {

        // reset hidden textbox
        var txtHidden = this.get_txtChkBoxIds();
        txtHidden.value = "";

        // get form
        var form = document.forms[0];

        // loop through elements adding checked ids to hidden input
        for (var i = 0; i < form.length; i++) {
            var objCheckBox = form.elements[i];
            if (objCheckBox.type == 'checkbox' && objCheckBox.id.indexOf(ckbId) >= 0) {
                if (objCheckBox.checked) {
                    if (objCheckBox.id != null && objCheckBox.id != "") {
                        var arrChkBoxId = objCheckBox.id.split("_");
                        txtHidden.value += arrChkBoxId[1] + ",";
                    }
                }

            }
        }

    },

    // ------------------------------------ initialize   

    // Overriden Methods
    initialize: function() {

        InstantASP.InstantForum.UI.Controls.ViewTopics.callBaseMethod(this, 'initialize');

        this.__isInitialized = true;

        // add event  
        $addHandlers(this.get_element(), { 'click': this.onSortChanged }, this);

        if (document.all) {
            this._sfloat = "styleFloat"; //ie
        } else {
            this._sfloat = "cssFloat"; //ff
        }

        // setup page level context object
        if (this._context == null) {

            this._context = new InstantForumContext(this.get_json());
            this._context.initialize();


            // setup common controls
            if (this._context != null) {
                this._commonUI = new InstantASPCommonUI(this._context.CurrentSettings.InstallImageFolderURL);
                this._forumUI = new InstantForumUI(this._context.CurrentSettings.InstallImageFolderURL);
            }

        }

        // setup loval search args array
        if (this.get_searchEventArgs() != null) {
            this.set_searchArgsInternalArray();
        }

        // render control   
        if (this.get_useWebService()) {
            this.fetchData(1);
        } else {
            this.renderViewTopics();
        }



    },

    // ------------------------------------ events

    add_sortChanged: function(handler) {
        this.get_events().addHandler("sortChanged", handler);
    },

    remove_sortChanged: function(handler) {
        this.get_events().removeHandler("sortChanged", handler);
    },

    onSortChanged: function(source, e) {

        if (!this._events) return;

        var handler = this._events.getHandler("sortChanged");

        if (handler) {

            var ele = source.target;
            if (!ele) { return; }

            if (ele.id.toLowerCase().indexOf("hypsort_") > -1) {

                var strSortBy = ele.id.split("_")[1];
                var intSortOrder = this._searchArgsArray.SortOrder;

                // we are sorting a new column
                if (strSortBy != this._searchArgsArray.SortBy) {
                    intSortOrder = 1;
                } else {
                    // we are sorting an existing column          
                    if (intSortOrder == 1) {
                        intSortOrder = 2;
                    } else {
                        intSortOrder = 1;
                    }

                }

                if (this._searchArgsArray.SortBy != null) {
                    this._searchArgsArray.SortBy = strSortBy;
                    this._searchArgsArray.SortOrder = intSortOrder;
                }


                if (ele != null && ele != 'undefined') {
                    if (typeof ele.disabled == 'undefined' || ele.disabled == false) {
                        handler(1);
                    }
                }
            }

        }

    },

    // ------------------------------------ dispose

    dispose: function() {

        $clearHandlers(this.get_element());

        InstantASP.InstantForum.UI.Controls.ViewTopics.callBaseMethod(this, 'dispose');

    }

}

InstantASP.InstantForum.UI.Controls.ViewTopics.registerClass('InstantASP.InstantForum.UI.Controls.ViewTopics', Sys.UI.Control);

if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();