﻿var InfiniteScroll = function(ID, tableID, statusPanelID, messageDivID, orderBy, viewMode) 
{
    this._ID = ID;
    this._tableID = tableID;
    
    this._statusPanelID = statusPanelID;
    this._messageDivID = messageDivID;
    this._orderBy = orderBy;    
    this._viewMode = viewMode;       
    
    this._tag = null;
    this._searchString = null;
    this._isPaused = false;      
        
    this._isBusy = false;
        
    this._timer = null;
    this._timer2 = null;
}

InfiniteScroll.prototype = 
{  
    start: function() 
    {                       
        document.getElementById(this._statusPanelID).innerHTML = "Please wait..";               
        
        if(this._timer != null)
            clearTimeout(this._timer);

        if(this._timer2 != null)
            clearTimeout(this._timer2);
                        
        if(this._isBusy)
        {
            this._timer2 = setTimeout(createObjectCallback(this, this.start), 100);         
            return;
        }            
            
        this._initializeLayout();                      
        this._clear();    
        this._isPaused = false;    
        window.scroll(0,0);       
        
        this._getImages(true);                
    },    
    
    pause: function()
    {
        this._isPaused = true;
    },    

    resume: function()
    {
        this._isPaused = false;
    },    
    
    _initializeLayout: function() 
    {
        var pTable = document.getElementById(this._tableID);
    
        if(this._viewMode == 0)
        {
            this._itemsPerRow = 4;
            pTable.align = "";
            pTable.style.marginLeft = "";
            pTable.style.marginRight = "";            
        }
        else
        {
            this._itemsPerRow = 1;    
            pTable.align = "center";
            pTable.style.marginLeft = "auto";
            pTable.style.marginRight = "auto";
        }
        
        document.getElementById(this._messageDivID).innerHTML = "";
    },
    
    _clear: function() 
    {
        var pTable = document.getElementById(this._tableID);
        for (var i = pTable.rows.length; i > 0; i--)
            pTable.deleteRow(i-1); 
        this._totalItemsCount = 0;           
    },
    
    _getImages: function(reset) 
    {               
        this._isBusy = true;               
        ImageServices.GetImages(this._orderBy, this._tag, this._searchString, reset, createObjectCallback(this, this._succeededCallback), createObjectCallback(this, this._errorCallBack));                
    },
    
    _succeededCallback: function (result)
    {                         
        if(result.SessionExpired)
        {
            alert("Your session has expired. Please refresh the page.");
            this._isBusy = false;
            return;
        }
        
        var pTable = document.getElementById(this._tableID);
                        
        if(pTable.rows.length == 0)
        {            
            var msg = "";
            
            if(this._tag != null)
            {
                if(result.ResultsCount == 0)
                    msg = "No results found for tag \"" + htmlEncode(this._tag) +  "\"";                    
                else
                    msg = result.ResultsCount + " result" + ((result.ResultsCount != 1)?"s":"") + " found for tag \"" + htmlEncode(this._tag) + "\"";
            }
            else if(this._searchString != null)
            {
                if(result.ResultsCount == 0)
                    msg = "No results found for \"" + htmlEncode(this._searchString) +  "\"";
                else
                    msg = result.ResultsCount + " result" + ((result.ResultsCount != 1)?"s":"") + " found for \"" + htmlEncode(this._searchString) + "\"";         
            }
            
            if(!msg.isEmpty())
                document.getElementById(this._messageDivID).innerHTML = msg + "<br><a href='#' onclick='" + this._ID + "._tag = null;" + this._ID + "._searchString = null;" + this._ID + ".start();return false;'>Clear search</a>";
        }
        
                            
        if(result.Images.length == 0)
        {   
            document.getElementById(this._statusPanelID).innerHTML = "Showing&nbsp;<b>"+(this._totalItemsCount)+"</b>&nbsp;images";         
            this._isBusy = false;
            return;
        }
        else
        {
            this._totalItemsCount += result.Images.length;
                        
            var lastRow;
            
            if((pTable.rows.length - 1) > 0 && pTable.rows[pTable.rows.length - 1] != null)
                lastRow = pTable.rows[pTable.rows.length - 1];
            else
                lastRow = pTable.insertRow(pTable.rows.length);              
             
            var i = 0;                                                         
            
            for(i = 0; i < result.Images.length; i++)
            {                
                if(lastRow.cells.length >= this._itemsPerRow)
                    lastRow = pTable.insertRow(pTable.rows.length);                
                
                var cell1 = lastRow.insertCell(lastRow.cells.length);                
                                
                cell1.innerHTML = this._getItemHTML(result.Images[i]);                               
            }                                                        
            
            document.getElementById(this._statusPanelID).innerHTML = "Showing&nbsp;<b>"+(this._totalItemsCount)+"</b>&nbsp;images, scroll down to view more";              

            if(result.Images.length < 8)
                document.getElementById(this._statusPanelID).innerHTML = "Showing&nbsp;<b>"+(this._totalItemsCount)+"</b>&nbsp;images";
            
            this._timer = setTimeout(createObjectCallback(this, this._detectScroll), 300);         
        }   
        
        this._isBusy = false;                   
    },    
        
    _errorCallBack: function (error)
    {        
        this._isBusy = false;
    },    
    
    _detectScroll: function()
    {              
        if(this._isPaused)
        {
            this._timer = setTimeout(createObjectCallback(this, this._detectScroll), 300);
            return;
        }
            
        var intElemScrollHeightOuter = this._getWindowHeight();                          
        var intElemScrollHeightInner = document.getElementById(this._tableID).clientHeight;
        var intElemScrolled = this._getScrollY();      

        var height = intElemScrollHeightInner - intElemScrollHeightOuter;                  
        
        if (intElemScrolled >= height-20)    
            this._getImages(false);                    
        else
            this._timer = setTimeout(createObjectCallback(this, this._detectScroll), 300);         
        return true;
    },     
    
    _getItemHTML: function(item)
    {
        var eltHTML = "";
        if(this._viewMode == 0) 
            eltHTML += "<div id='box" + item.ID + "' style='text-align: center; border: solid 1px #FFF; height: 300px; width: 175px;' onmouseover=\"this.style.border = 'solid 1px #BCC6D3'\" onmouseout=\"this.style.border = 'solid 1px #FFF'\">";        
        else
            eltHTML += "<div id='box" + item.ID + "' style='text-align: center; border: solid 1px #FFF; width: 700px; padding-bottom: 20px; padding-top: 20px;' onmouseover=\"this.style.border = 'solid 1px #BCC6D3'\" onmouseout=\"this.style.border = 'solid 1px #FFF'\">";        
                
        if(item.Title != null)
            eltHTML += "<strong>" + htmlEncode(item.Title) + "</strong><br />";
        else
            eltHTML += "<strong>No Title</strong><br />";
            
        eltHTML += "<center><table><tr><td><div class='img-shadow'>";
        
        if(this._viewMode == 0)        
            eltHTML += "<img id='img" + item.ID + "' src='userimages/" + item.Hash + "_thumb.jpg' style='cursor: pointer;width: " + item.ThumbWidth + "px; height: " + item.ThumbHeight + "px;' onclick='showFullViewImage(" + item.ID + ");' onmouseover='ShowDescriptionTip(" + ((item.Description != null)?"\""+ replaceLineBreaks(replaceQuotes(htmlEncode(item.Description)))+"\"":"null") + ");'/>";        
        else
            eltHTML += "<img id='img" + item.ID + "' src='userimages/" + item.Hash + ".jpg' style='cursor: pointer;width: " + item.ImageWidth + "px; height: " + item.ImageHeight + "px;' onclick='showFullViewImage(" + item.ID + ");' onmouseover='ShowDescriptionTip(" + ((item.Description != null)?"\""+replaceLineBreaks(replaceQuotes(htmlEncode(item.Description)))+"\"":"null") + ");'/>";        
        
        
        eltHTML += "</div></td></tr></table></center>";        
        
        eltHTML += "<img src='images/thumb_up.gif' style='vertical-align: middle;' title='Thumbs up' onmouseover='ShowTip(\"Number of thumbs up votes\")' />&nbsp;<span id='trueVotesCount" + item.ID + "'>" + item.TrueVotesCount + "</span>&nbsp;&nbsp;&nbsp;";
        eltHTML += "<img src='images/thumb_down.gif' style='vertical-align: middle;' title='Thumbs down' onmouseover='ShowTip(\"Number of thumbs down votes\")' />&nbsp;<span id='falseVotesCount" + item.ID + "'>" + item.FalseVotesCount + "</span>&nbsp;&nbsp;&nbsp;";        
        eltHTML += "<img id='comments" + item.ID + "' src='images/comments.gif' style='vertical-align: middle;cursor: pointer;' title='Comments' onmouseover='ShowTip(\"Comments\")' onclick='showFullViewImage(" + item.ID + ");' />&nbsp;" + item.CommentsCount + "&nbsp;&nbsp;&nbsp;";        
        eltHTML += "<img src='images/bury.gif' style='vertical-align: middle;' title='Buries' onmouseover='ShowTip(\"Buries\")' />&nbsp;<span id='buriesCount" + item.ID + "'>" + item.BuriesCount + "</span>&nbsp;&nbsp;&nbsp;";        
        eltHTML += "<a id='newWindow" + item.ID + "' href='image.aspx?id=" + item.ID + "' target='_blank'><img src='images/new_window.gif' style='vertical-align: middle;' title='Open image in new window' onmouseover='ShowTip(\"Open image in new window\")' /></a><br /><br />";
                
        if(item.IsAddedBySameUser)
        {
            eltHTML += "Added by: You";
            
            if(item.UserName != null)
                eltHTML += " (" + htmlEncode(item.UserName) + ")";
            
            eltHTML += "<br />";
        }
        else
        {
            if(item.UserName != null)
                eltHTML += "Added by: " + htmlEncode(item.UserName) + "<br />";
        }
        
        eltHTML += item.DateAdded + "<br />";
        
        if(!item.IsAddedBySameUser)
        {
            if(item.HasVoted)
            {
                if(item.UserVote)
                    eltHTML += "<div>You voted: <img src='images/thumb_up.gif' style='vertical-align: middle;' title='You already voted with thumbs up' onmouseover='ShowTip(\"You already voted with thumbs up\")' /></div>";    
                else
                    eltHTML += "<div>You voted: <img src='images/thumb_down.gif' style='vertical-align: middle;' title='You already voted with thumbs down' onmouseover='ShowTip(\"You already voted with thumbs down\")' /></div>";                
            }
            else
            {
                eltHTML += "<div id='vote" + item.ID + "'>Your vote:&nbsp;"
                eltHTML += "<img src='images/thumb_up.gif' style='vertical-align: middle;cursor: pointer;' title='Vote with thumbs up' onmouseover='ShowTip(\"Vote with thumbs up\")' onclick='voteForImage(" + item.ID + ",true);'  />&nbsp;";
                eltHTML += "<img src='images/thumb_down.gif' style='vertical-align: middle;cursor: pointer;' title='Vote with thumbs down' onmouseover='ShowTip(\"Vote with thumbs down\")' onclick='voteForImage(" + item.ID + ",false);'  />";
                eltHTML += "</div>";                
            }
            
            if(item.HasBuried)
            {
                eltHTML += "<div>You buried this image</div>";
            }
            else
            {
                eltHTML += "<div id='bury" + item.ID + "'><a href='' onclick='showBuryPopup(event, " + item.ID + ");return false;'>Bury this image?</a></div>";
            }
        }
        else
        {
            eltHTML += "<div id='delete" + item.ID + "'>(<a href='' onclick='confirmDelete(" + item.ID + ");return false;'>Delete it!</a>)</div>";
        }                                
        
        eltHTML += "</div>";

        return eltHTML;
    },
    
    _getWindowHeight: function() 
    {
        var myHeight = 0;

        if( typeof( window.innerWidth ) == 'number' ) //Non-IE    
            myHeight = window.innerHeight;
        else if (document.documentElement && document.documentElement.clientHeight)  //IE 6+ in 'standards compliant mode'
            myHeight = document.documentElement.clientHeight;
        else if(document.body && document.body.clientHeight) //IE 4 compatible    
            myHeight = document.body.clientHeight;

        return myHeight;
    },

    _getScrollY: function() 
    {
        var scrOfY = 0;

        if(typeof(window.pageYOffset) == 'number' ) //Netscape compliant    
            scrOfY = window.pageYOffset;
        else if( document.body && document.body.scrollTop) //DOM compliant    
            scrOfY = document.body.scrollTop;
        else if( document.documentElement && document.documentElement.scrollTop) //IE6 standards compliant mode    
            scrOfY = document.documentElement.scrollTop;

        return scrOfY;
    },
    
    dispose: function() { 
        if(this._timer != null)
            clearTimeout(this._timer);        
    }    
}

function createObjectCallback(obj, fn)
{
    return function() { fn.apply(obj, arguments); };
}


 