
/*
    Creates a pager
    portletid: the portlet id
    componentname: the name of the global attribute that contains the component
    containerelementId: the html id of the element that will contain the pager
    javascriptVarName: the name of the javacript var that this instance has (used for generated even callbacks)
    size: the pager size
    removeScript (optional): if set allow to call an external script for removal (legacy)

  
  javascript events:
  - selectionChanged
  - row_removed
  - resetCompleted
  - refreshCompleted


  the produced pager has this style info:
  .datapager class for pager table
  .pager_header class for th headers
  .ascending .descending for a tag currently sorting
  .datarow_odd .datarow_even .datarow_selected classes for data row (tr)
  .pager_footer for the footer row under the table
  .first .first_disabled .last .last_disabled .next .next_disabled .previous .previous_disabled .pagelink .pagelink_current classes to control a elements

  locale key used:

  pager_previous,pager_next



*/
function PE_Pager(portletid,attributename,containerElementId,javascriptVarName,size,removeScript) {
    
    this.initialized=false;

    if (arguments.length==0)
        return;
    
    if (removeScript)
        this.removeScript=removeScript;

    this.portletid=portletid;
    this.tablename=attributename;
    this.containerElementId=containerElementId;
    this.containerElement=document.getElementById(containerElementId);
    this.globalVarName=javascriptVarName;
    if (!this.containerElement)
        alert("Container element for id:"+containerElementId+" not present");
    

    /*
    the pager size, after setting this you may call  reset
    */
    this.pagerSize=size;
    //number of elements
    this.length=0;
    
    //first loads the localization map and then resets the pager
    if (!PEAjaxUtils.windowLoaded) {
        Event.observe(window, 'load', function() {
            window.setTimeout((function() {this._init()}).bind(this),100);
        }.bind(this));
    } else
        this._init();

    

}

PE_Pager.Events=new Object();
PE_Pager.Events.SELECTION_CHANGED="selectionChanged";
PE_Pager.Events.ROW_REMOVED="row_removed";
PE_Pager.Events.RESET_COMPLETED="resetCompleted";
PE_Pager.Events.REFRESH_COMPLETED="refreshCompleted";

PE_Pager.prototype._init= function() {
    PEAjaxUtils.scheduleSessionRefresh();
            RemoteProxy.getLocalizationMap(this.portletid,['noimage','detail'], {callback:function(locmap) {
                                                            this.localizationMap=locmap;
                                                            this.reset();
                                                                  }.bind(this)
            });
}

/*
    True if pager is empty
 */   
PE_Pager.prototype.isEmpty= function() {
    if(this.length>0) return false;
    return true;
}

/*
    resets the pager reloading everithing and resetting page, called automatically when the pager is created
*/
PE_Pager.prototype.reset= function() {
   
  
   var params=new Object();
   params.size=this.pagerSize;
   PEAjaxUtils.scheduleSessionRefresh();
   RemoteProxy.call(this.portletid,this.tablename,'reset',params,
                        {callback:function(data) 
                                    {   this.initialized=true;
                                        this.drawPage(data);
                                     PEEventManager.fireEvent(this.portletid,this.tablename,'resetCompleted');
                                    }.bind(this)
                        }
                    );
}

/*
  refreshes the pager reloading data but maintaining selection and sorting
*/
PE_Pager.prototype.refresh= function() {
   if (!this.initialized)
       return;
   
   PEAjaxUtils.scheduleSessionRefresh();
   RemoteProxy.call(this.portletid,this.tablename,'refresh',{},
                        {callback:function(data) 
                                    {
                                     this.drawPage(data);
                                     PEEventManager.fireEvent(this.portletid,this.tablename,'refreshCompleted');
                                    }.bind(this)
                        }
                    );
}

/*
Selects a row in the pager
*/
PE_Pager.prototype.select= function(id) {
    var object=this;
    PEAjaxUtils.scheduleSessionRefresh();
    RemoteProxy.call(this.portletid,this.tablename,'selectRow',{'id':id},
                        {callback:function(data) 
                                    {
                                        object.switchSelection(id);
                                        
                                        object.triggerSelectionChange();
                                    }
                        });
}

/*
go to a page
*/
PE_Pager.prototype.goPage= function(p) {
   var obj=this;
   var params=new Object();
   params.page=p;
   PEAjaxUtils.scheduleSessionRefresh();
   RemoteProxy.call(this.portletid,this.tablename,'selectPage',params,
                        {callback:function(data) 
                                    {
                                        obj.drawPage(data);
                                        
                                    }
                        }
                    );
}

/*
sorts the pager (should not change the selection so no event is triggered)
*/
PE_Pager.prototype.sort= function(property,ascending) {
   var obj=this;
   var params=new Object();
   params.sortproperty=property;
   params.ascending=ascending;
   PEAjaxUtils.scheduleSessionRefresh();
   RemoteProxy.call(this.portletid,this.tablename,'sort',params,
                        {callback:function(data) 
                                    {
                                        obj.drawPage(data);
                                    }
                        }
                    );
}
/*
removes a row
*/
PE_Pager.prototype.remove= function(id, message) {
   
   if (message) {
        var agree=confirm(message);
        if (!agree) {
            return;
        }
   }
    
   var obj=this;
   var params=new Object();
   params.id=id;
   PEAjaxUtils.scheduleSessionRefresh();
   RemoteProxy.call(this.portletid,this.tablename,'remove',params,
                        {callback:function(data) 
                                    {
                                        this.drawPage(data);
                                        
                                        PEEventManager.fireEvent(this.portletid,this.tablename,'row_removed');
                                    }.bind(this)
                        }
                    );
}

/*
private function
*/
PE_Pager.prototype.drawPage= function(data) {
    
    if (data.messageKey)
        alert(data.messageKey);
    
    this.table=$(document.createElement("table"));
    this.table.id=this.containerElementId+"_table";
    this.table.className="data_pager";
    this.table.cellSpacing=0;
    this.table.cellPadding=0;

    var tbody=$(document.createElement("tbody"));
    this.table.appendChild(tbody);
    
    var selectionChange=false;
    if (!this.selectedid || this.selectedid!=data.selectedid) {
        selectionChange=true;
    }
    this.selectedid=data.selectedid;

    //writes headers
    headersrow=$(document.createElement("tr"));
    headersrow.className="pager_header";
    for (fieldidx=0;fieldidx<data.fields.length;fieldidx++) {
        field=data.fields[fieldidx];

        if (field.breakRow)
            break;

        var headelement=$(document.createElement("th"));
        headelement.setAttribute("colspan", field.colSpan);
        
        if (field.canSort) {
            atag=$(document.createElement("a"));
            atag.href="javascript:"+this.globalVarName+".sort('"+field.propertyName+"',"+(!field.asc)+")";
            if (field.sort && field.asc) {
                atag.className="ascending";
            } else if (field.sort && !field.asc) {
                atag.className="descending";
            }
            atag.appendChild(document.createTextNode(field.localizedName));
            headelement.appendChild(atag);
        } else if (field.localizedName)
            headelement.appendChild(document.createTextNode(field.localizedName));
        else {
            headelement.appendChild(document.createTextNode(" "));
        }
        
        if (field.columnClass) 
            headelement.addClassName(field.columnClass);
            
        headersrow.appendChild(headelement);
    }
    tbody.appendChild(headersrow);
    
    //writes data
    stop=false;

    var rownum=0;
    eval("if (!data.row"+rownum+") stop=true;");
    while (!stop) {
        eval("row=data.row"+rownum);
        rowid=row[0];
        

        rowtag=$(document.createElement("tr"));
        if (rowid==data.selectedid)
            rowtag.className="datarow_selected";
        else
            if ((rownum % 2)==0)
                rowtag.className="datarow_even";
            else
                rowtag.className="datarow_odd";
        rowtag.setAttribute("prv_id",rowid);
        for (i=1;i<row.length;i++) {
            field=data.fields[i-1];
            cell=$(document.createElement("td"));
            
            cell.setAttribute("rowspan", field.rowSpan);
            cell.setAttribute("colspan", field.colSpan);
            
            if (field.breakRow) {
                tbody.appendChild(rowtag);
                rowtag=$(document.createElement("tr"));
            }

            //adds a class to modify column behaviour if field has it
            if (data.fields[i-1].columnClass) 
                cell.addClassName(data.fields[i-1].columnClass);
            
            cell.onclick=function() {this.select(arguments[0])}.bind(this,rowid);
            //cell.onclick=function() {alert(arguments[0])}.bind(this,rowid);
            cell.appendChild(this.renderCell(rowid,row[i],field));
            rowtag.appendChild(cell);
        }
        tbody.appendChild(rowtag);
        rownum++;
        eval("if (!data.row"+rownum+") stop=true;");
    }
    
    //set size
    this.length=rownum;

    if (data.hasprevious || data.hasnext) {
    
        //writes footer
        footerrow=$(document.createElement("tr"));
        footerrow.className="pager_footer";
        footercell=$(document.createElement("td"));
        footercell.colSpan=data.fields.length;
        footerrow.appendChild(footercell);
        tbody.appendChild(footerrow);

        //adds footer controls
        firstPage=$(document.createElement("a"));
        if (data.hasprevious==true) {
            firstPage.className="first";
            firstPage.href="javascript:"+this.globalVarName+".goPage("+(parseInt(data.start))+");";
        }
        else
            firstPage.className="first_disabled";

        footercell.appendChild(firstPage);

        prevPage=$(document.createElement("a"));
        if (data.hasprevious==true) {
            prevPage.className="previous";
            prevPage.href="javascript:"+this.globalVarName+".goPage("+(data.currentpage-1)+");";
        }
        else
            prevPage.className="previous_disabled";

        //prevPage.appendChild(document.createTextNode(this.localizationMap.pager_previous));
        footercell.appendChild(prevPage);

        for (p=0;p<data.pages.length;p++) {
            plink=$(document.createElement("a"));
            if (data.pages[p]==data.currentpage)
                plink.className="pagelink_current";
            else {
                plink.className="pagelink";
                plink.href="javascript:"+this.globalVarName+".goPage("+data.pages[p]+");";
            }
            plink.appendChild(document.createTextNode(data.pages[p]));
            footercell.appendChild(plink);
        }

        nextPage=$(document.createElement("a"));
        if (data.hasnext==true) {
            nextPage.className="next";
            nextPage.href="javascript:"+this.globalVarName+".goPage("+(parseInt(data.currentpage)+1)+");";
        }
        else
            nextPage.className="next_disabled";

        //nextPage.appendChild(document.createTextNode(this.localizationMap.pager_next));
        footercell.appendChild(nextPage);

        lastPage=$(document.createElement("a"));
        if (data.hasnext==true) {
            lastPage.className="last";
            lastPage.href="javascript:"+this.globalVarName+".goPage("+data.pages[data.pages.length-1]+");";
        }
        else
            lastPage.className="last_disabled";
        footercell.appendChild(lastPage);
    }
    if (this.containerElement.childNodes.length>0) {
       this.containerElement.replaceChild(this.table,this.containerElement.childNodes[0]);
    } else
        this.containerElement.appendChild(this.table);
    
    
    if (selectionChange)
        this.triggerSelectionChange();
}


/*
 private function
*/
PE_Pager.prototype.switchSelection= function(id) {
    if (!this.table || this.table.childNodes.length==0)
        return;
    
    var tbody=this.table.childNodes[0];
    for (idx=0;idx<tbody.childNodes.length;idx++) {
        
        if (tbody.childNodes[idx].getAttribute)
            if (tbody.childNodes[idx].getAttribute("prv_id")==id){
                tbody.childNodes[idx].className="datarow_selected"; 

            } else {
                if (tbody.childNodes[idx].getAttribute("prv_id")){
                    if (((idx+1) % 2)==0)
                        tbody.childNodes[idx].className="datarow_even"; 
                    else
                        tbody.childNodes[idx].className="datarow_odd";   
                }

            }

    }

}

/*
 private function
*/
PE_Pager.prototype.renderCell= function(rowid,row,field) {
    

    if (field.type=='it.netedge.portaledge.uicomponents.ajax.pager.celltypes.RemoveField') {


        if (row.noremove) {
            return $(document.createElement("span"));
        }
        
        atag=$(document.createElement("a"));
        atag.className="removefield";



        if (row.toolTip)
            atag.title=row.toolTip;

        if (this.removeScript) {
            atag.href="javascript:"+this.removeScript+"('"+rowid+"')";
            atag.update()
        } else {
            if (row.message)
                atag.href="javascript:"+this.globalVarName+'.remove("'+rowid+'","'+row.message+'")';
            else
                atag.href="javascript:"+this.globalVarName+".remove('"+rowid+"')";

            if (row.removeText)
                atag.update(row.removeText);
            else
                atag.update();
        }
        
        
        return atag;
    }
    else if (field.type=='it.netedge.portaledge.uicomponents.ajax.pager.celltypes.ScriptField' || field.type=='it.netedge.portaledge.uicomponents.ajax.pager.celltypes.TopProductField' ) {
        
        atag=$(document.createElement("a"));
        atag.className=row["class"];
        
        if (row.scriptparam) {
            atag.href="javascript:"+row.script+"('"+row.scriptparam+"')";
            if (row.showvalue) atag.appendChild(document.createTextNode(row.textdata));
        }
        else {
            atag.href="javascript:"+row.script+"('"+rowid+"')";
            atag.update();
        }

        if (row.textdata) {
            atag.appendChild(document.createTextNode(row.textdata));
        }
        else {
            atag.update();
        }
        return atag;
    }
    else if (field.type=='it.netedge.portaledge.uicomponents.ajax.pager.celltypes.ImageField') {
        
        if (row.imgsrc) {
            imgtag=$(document.createElement("img"));
            imgtag.src=row.imgsrc;

            if (row.imgwidth) imgtag.width=row.imgwidth;
            if (row.imgheight) imgtag.height=row.imgheight;
            if (row.title) imgtag.title=row.title;

            return imgtag;
        }
        else {
            newdiv=$(document.createElement("div"));
            newdiv.innerHTML="&nbsp;";
            return newdiv;
            }
    }
    else if (field.type=='it.netedge.portaledge.uicomponents.ajax.pager.celltypes.HTMLField') {
        newdiv=$(document.createElement("div"));
        if (row.length>0)
            newdiv.innerHTML=row;
        else
            newdiv.innerHTML="&nbsp;";
        return newdiv;
    }
    else if (row.length>0)
        return document.createTextNode(row);
    else {
        newdiv=$(document.createElement("div"));
        newdiv.innerHTML="&nbsp;";
        return newdiv;
    }
        
        
}
/*
 private function
*/
PE_Pager.prototype.triggerSelectionChange= function() {
    
    PEEventManager.fireEvent(this.portletid,this.tablename,'selectionChanged');
}




