SlidingBuilder = Class.create({
    initialize: function(options){
        if(options!=null && options.kindOfEffect != null){
            this.scrollForFirstRow = options.scrollForFirstRow || 300
            this.scrollForSecondRow = options.scrollForSecondRow || -300
            this.direction = options.direction || "right"
            this.elementForPage = options.elementForPage || 6
            this.containerChildElement = null
            this.containerParentElement = null
            this.secondRowElement = null
            this.firstRowElement = null
            this.secondsForFade = options.secondsForFade || 1
            this.alreadyLoadedTab = false
            this.canClickFromScroll = true
            this.canClickFromRequest = true
            this.whatData =  options.whatData
            this.roomId = options.roomId
            this.nrRequest = 0;
            this.range1 = 0;
            this.startAfterClick = options.startAfterClick
            this.userSelectorObject = options.userSelectorObject
            this.expandableObject = options.expandableObject
            this.elementAlreadyLoaded = options.elementAlreadyLoaded || false
            this.classForSpinner = options.classForSpinner || "spinnerBox"
            if(options.objectForRequest){
                this.range2 = options.objectForRequest._object.limit || 6
                this.friendVisible= options.objectForRequest._object.friendVisible || 6
            }
            this.objectForRequest = options.objectForRequest ||
                                new Hash({
                                            action:    "getUserPage",
                                            url:        "/commons/json_request_for_user.php",
                                            room_id:    this.roomId
                                        })
            this.numberOfItem = 0
            this.functionNameForUserSelector = options.functionNameForUserSelector
            switch(options.kindOfEffect) {
                case "scrolling":
                    this.containerChildElement = options.elementsContainer
                    this.atLessAPage = this.containerChildElement.childElements()[0].hasClassName('singlepage')
                    this.containerParentElement = options.parentContainer
                    //this.containerParentElement.onclick = this.launchRequest.bindAsEventListener(this,true)
                    this.firstRowElement = options.rowSx
                    this.secondRowElement = options.rowDx
                    this.currentPosition = 0
                    this.currentPage = Math.ceil(this.currentPosition / this.scrollForSecondRow)
                    break;
                }
            if(this.startAfterClick)
                ;//this.launchRequest(true)
            else{
                if(!this.elementAlreadyLoaded)
                    this.launchRequest(true)
                else{
                    this.atLessAPage = true
                    this.bindForScrollElements()
                }
            }
        }
    },
    launchRequest: function(bindRow){
        if(this.atLessAPage){
            this.objectForRequest.set('string_for_limit', " limit "+ this.range1+","+(this.range2+1));
            this.requester = new Requester({
                            object: this.objectForRequest,
                            callBackAfterRequest: this.buildNewElements.bind(this,bindRow)
                        })
                this.requester.sendRequest()
                this.nrRequest++;
        }
    },
    externalLaunchRequest: function(bindRow){
        if(this.atLessAPage && !this.alreadyLoadedTab){
            this.alreadyLoadedTab = true
            this.objectForRequest.set('string_for_limit', " limit "+ this.range1+","+(this.range2+1));
            this.requester = new Requester({
                            object: this.objectForRequest,
                            callBackAfterRequest: this.buildNewElements.bind(this,bindRow)
                        })
                this.requester.sendRequest()
                this.nrRequest++;
        }
    },
    getElementsToCheck: function(){
        return this.containerChildElement.childElements()[Math.abs(this.currentPage)]
    },
    checkLoadedClassNameInDiv: function(){
        var nrElement = this.containerChildElement.childElements()[Math.abs(this.currentPage)].childElements().size() - 1
        //if(this.containerChildElement.childElements()[nrElement].hasClassName('other')){
        if(this.containerChildElement.childElements()[Math.abs(this.currentPage)].childElements()[nrElement].hasClassName('other')){
            return true
        }
        return false
    },
    removeLoadedClassNameInDiv: function(){
        var currentPage = this.containerChildElement.childElements()[Math.abs(this.currentPage)];
        currentPage.childElements()
    },
    calculateRange: function(){
        if(this.nrRequest ){
            this.range1 = this.range2
            this.range2 = this.range2 + this.friendVisible
        }
    },
    pageAlreadyLoaded: function(){
         if(this.containerChildElement.childElements()[Math.abs(this.currentPage+1)].childElements()[0].className.split("spinnerBox").size() > 1)
             return false
         else
             return true;
    },
    secondRowClicked: function(){
        if( this.secondRowElement.style.display != "none"){
            if( this.canClickFromScroll && this.canClickFromRequest){
                this.canClickFromScroll = false
                this.scroll(this.scrollForSecondRow);
                if(this.checkLoadedClassNameInDiv() && !this.elementAlreadyLoaded && !this.pageAlreadyLoaded()){
                    this.calculateRange()
                    this.canClickFromRequest = false
                    this.objectForRequest.set('string_for_limit', " limit "+ this.range1+","+(this.range2+1));
                    this.launchRequest(false)
                }else{
                    this.initializeScrollForSecondRow()
                }
            }
        }
    },
    buildNewElements: function(bindRow,request){
        var html =""
        for(var i = 0; i < request.serverObject.users.size();i++)
            html +=  request.serverObject.users[i]
        if(this.atLessAPage){
            this.canClickFromRequest = true
            html  = this.sobstituteString(html,"tagA", "<a ")
            html  = this.sobstituteString(html ,"closeTagA", "</a>")
            html  = this.sobstituteString(html  ,"closeTag", ">")
            this.containerChildElement.childElements()[this.nrRequest-1].update(html)
            var nrElement = this.containerChildElement.childElements()[Math.abs(this.currentPage)].childElements().length
            if(!this.containerChildElement.childElements()[Math.abs(this.currentPage)].childElements()[nrElement-1].hasClassName('nomore')){
                this.containerChildElement.insert({
                    bottom:"<div class='page_"+(this.nrRequest+1)+" singlepage communityBox'><img src='/img/ajax-loader.gif' class='"+this.classForSpinner+"loading' style='position: absolute; left: 180px; top: 55px;'/></div>"
                })
            }/*
            if(html == ""){
                this.containerChildElement.insert({
                    bottom:"<div class='page_"+(this.nrRequest+1)+" singlepage communityBox'><span>Nessun utente disponibile in questa classifica</span></div>"
                })
            }*/
            if(this.userSelectorObject != null){
                if(!this.functionNameForUserSelector){
                    this.userSelectorObject.unBindElements()
                    this.userSelectorObject.bindElements()
                }else
                    this.userSelectorObject.bindSingleBtnChallenge(this.roomId)
            }
            if(this.expandableObject != null)
                this.expandableObject.bindObject()
            FB.XFBML.parse();
            this.initializeScrollForSecondRow()
        }
        this.numberOfItem = this.containerChildElement.childElements().size() //conto le pagine non appena posso
        if(bindRow)
            this.bindForScrollElements()
    },
    initializeScrollForSecondRow: function(){
        if( this.secondRowElement.style.display != "none"){
            if(this.checkLoadedClassNameInDiv()){
                this.removeLoadedClassNameInDiv(Math.abs(this.currentPage)+1)
            }
            this.currentPage = Math.ceil(this.currentPosition / this.scrollForSecondRow)
            var nrElement = this.containerChildElement.childElements()[Math.abs(this.currentPage)].childElements().length
            if(this.containerChildElement.childElements()[Math.abs(this.currentPage)].childElements()[nrElement-1].hasClassName('nomore')){
                this.secondRowElement.style.visibility = 'hidden'
            }
            this.firstRowElement.style.visibility= 'visible'
        }
    },
    firstRowClicked: function(){
        if( this.firstRowElement.style.display != "none"){
            if( this.canClickFromScroll ){
                this.canClickFromScroll = false
                this.scroll(this.scrollForFirstRow)
                this.currentPage = Math.ceil(this.currentPosition / this.scrollForFirstRow)
                if(-this.currentPage < 2-1){
                    this.firstRowElement.style.visibility= 'hidden'
                }
                this.secondRowElement.style.visibility= 'visible'
            }
        }
    },
    removeEventForFirstRow: function(){
        Event.stopObserving(this.firstRowElement)
    },
    removeEventForSecondRow: function(){
        Event.stopObserving(this.secondRowElement)
    },
    addEventForFirstRow: function(){
        Event.observe(this.firstRowElement,'click',this.firstRowClicked.bindAsEventListener(this,this.scrollForFirstRow))
    },
    addEventForSecondRow: function(){
        Event.observe(this.secondRowElement,'click',this.secondRowClicked.bindAsEventListener(this,this.scrollForSecondRow))
    },
    removeEventForRows: function(){
        if( this.containerChildElement != null){
            this.removeEventForFirstRow()
            this.removeEventForSecondRow()
        }
    },
    bindRows: function(){
        this.addEventForFirstRow()
        this.addEventForSecondRow()
    },
    bindForScrollElements: function(){
        if(this.atLessAPage){
                this.removeEventForRows()
                this.currentPosition = 0
                this.scroll(0)
                this.firstRowElement.style.visibility= 'hidden'
                
                /*if(this.elementAlreadyLoaded){

                    if( !this.containerChildElement.childElements().size() )
                        this.secondRowElement.style.visibility= 'hidden'
                    else
                        this.secondRowElement.style.visibility= 'visible'
                }*/
                this.bindRows()
                var nrElement = this.containerChildElement.childElements()[Math.abs(this.currentPage)].childElements().length
                if(this.containerChildElement.childElements()[Math.abs(this.currentPage)].childElements()[nrElement-1].hasClassName('nomore')){
                    this.secondRowElement.style.visibility = 'hidden'
                }
        }else{
            this.secondRowElement.style.visibility= 'hidden';
            this.firstRowElement.style.visibility= 'hidden'
        }
    },
    countItemInChildDiv: function(){
        var nrElement = Math.abs(this.currentPage)+this.elementForPage-1
        if(this.containerChildElement.childElements()[Math.abs(this.currentPage)].childElements()[nrElement] ? this.containerChildElement.childElements()[Math.abs(this.currentPage)].childElements()[nrElement].hasClassName('other') : null){
            return true
        }
        return false
    },
    scroll: function(deltaPixel) {
        var totalScroll = this.currentPosition + deltaPixel
        this.currentPosition = totalScroll
        this.canClickScroll = false
        var that = this;
        this.containerChildElement.morph(that.direction +": " + totalScroll  + "px",{
            duration: 0.2,
            delay: 0.2,
            afterFinish: function(){
                that.canClickFromScroll = true
            }
        });
    },
    sobstituteString: function(string, pattern, replacement){
      //String.prototype.replace = function(pattern, replacement) {
          return string.split(pattern).join(replacement);
      //}
    }
})

