HJ.Attachments = Class.create();

HJ.Attachments.prototype = {

    initialize: function(display, header, maxRows, listUUID, addAttachmentBlock) {
        // here to avoid doing something like app.SIHP.homePageCalendar.months
        this.DOWNLOAD_ACTION = "C_";
        this.DELETE_ACTION = "D_";
        this.DOWNLOAD_NAME = "Download";
        this.DELETE_NAME = "";

        // a 0-length array to use to avoid extra null checking
        this.EMPTY_ARRAY = new Array(0);

        this.display = display;
        // cache the headers so we can relist without reloading 
        this.header = header;
        this.maxRows = maxRows;
        this.listUUID = listUUID;
        this.length = 0; // Veeru: number of attachments fetched
        this.addDelete = true;
        this.addAttachmentBlock = addAttachmentBlock;
        this.MAX_ATTACHMENT = 2;
    
    },

    init: function() {
    },

    cleanup: function() {
    },


    setListId: function(uuid) {
        this.listUUID = uuid;
    },
    
    fetchAttachments: function(addDelete) {
        this.addDelete = addDelete;
        if (this.listUUID == null) {
            this.attachments = this.EMPTY_ARRAY;
            return;
        }
        var req 
        = new Af.DataRequest(svcURL,
                             this.fetchAttachmentsCompleted.bind(this), 
                             requestFailedCommon.bind(this), 
                             null, 
                             requestTimedoutCommon.bind(this));
        req.addService("WorkspaceService", "getListAttachments");
        req.addParameter("UUID", this.listUUID);
        // we might use this, too.
        // req.addService("WorkspaceService", "getAttachmentsForList");
        // req.addParameter("listId", this.listUUID);
        ajaxEngine.processRequest(req);
    },

    fetchAttachmentsCompleted: function(response) {
        var xds = new Af.XMLToDataSet(response.responseXML);
        this.attachments = xds.data.Attachment;

        if (this.attachments == null || this.attachments == "undefined" ) {

            this.attachments = this.EMPTY_ARRAY;
            this.length = 0; 
        }
        else
        {
            this.length = this.attachments.length;

        }

        if (this.length > 0 && this.addAttachmentBlock != null)
            this.addAttachmentBlock.style.display = 'none';

        p = document.getElementById("addAttachText");
        if ( p ) {
            if(this.length > 0) {
                p.innerHTML = "Add another attachment";
            } else {
                p.innerHTML = "Add attachment";

            }
        }

        var addAttachmentButton = document.getElementById("addAttachLink");
        if(addAttachmentButton) {
            if(this.length >= this.MAX_ATTACHMENT) {
                
                addAttachmentButton.style.display = "none";
            } else {

                addAttachmentButton.style.display = "block";
            }
        }


        this.render();
    },

    render: function() {
        
        // delete and re-add cached headers if we render without a 
        // template reload.
        if (this.header != null) {
            this.display.removeChild(this.header);
        }
        this.display.innerHTML = "";
        if (this.header != null) {
            this.display.appendChild(this.header);
        }

        var factory = new HJ.Data_ObjectFactory();
        var attachmentHeader = document.getElementById("attachment_header");
        if (this.attachments.length > 0) {
            this.attachmentWrapper = factory.get(this.attachments[0]);
            headerDisplay = "block";
        } else {
            headerDisplay = "none";
            
        }

        if(attachmentHeader) {
            attachmentHeader.style.display = headerDisplay;
        }

        // loop while we have items to render from both arrays
        for (var i = 0; i < this.attachments.length && i < this.maxRows; i++) {
            this.attachmentWrapper.setData(this.attachments[i]);
            this.renderObject(this.attachmentWrapper);
            // Veeru: only allow 1 right now
            // 2011-12-21 kee: more than 1 now
            if (i == 1) break;
        }
        
		hideModalMessageDialog();
    },

    // render as 2 divs inside one div with the following class
    // attachmentListCont: savedName, savedAction
    renderObject: function(wrapper) {
        var line = document.createElement("li");
        line.className = "attachmentListCont2";

        // Display name, currently path
        //var d = document.createElement("div");
        //d.className = "savedName";
        //d.innerHTML = wrapper.getDisplayName();
        //line.appendChild(d);

        // actions
        // XXX: add icons for download and delete
        d=document.createElement("span");
        d.className = "attachDelete";
        
        if (this.addDelete == true) {
            //d.appendChild(document.createTextNode(" | "));
            a = this.createItemAnchor(this.DELETE_NAME, 
                                  this.DELETE_ACTION 
                                  + wrapper.getId());
            a.className = 'closeBtn';
            a.onclick = this.handleDisplayClick.bindAsEventListener(this);  
            
            d.appendChild(a);
        }
        line.appendChild(d);

        var d = document.createElement("span");
        d.className="savedAction";
        var a = this.createItemAnchor(wrapper.getDisplayName(), 
                                      this.DOWNLOAD_ACTION 
                                      + wrapper.getId());
        //a.href = "/rose/download?attachmentId=" + wrapper.getId();
        a.href = "#";
        a.onclick = this.handleDownloadClick.bindAsEventListener(this);
        d.appendChild(a);
        line.appendChild(d);
        

        this.display.appendChild(line);
    },

    createItemAnchor: function(text, id) {
        var a = document.createElement("A");
        a.innerHTML = text;
        a.id = id;
        // XXX: set class? 
        return a;
    },

    // click in the archive list display
    handleDisplayClick: function(event) {
        var target = event.target ? event.target : event.srcElement;
        if (target.tagName != 'A' || target.id == null) {
            // nothing to do
            return true;
        }
        var index = target.id.indexOf("_");
        if (index == -1) {
            return true;
        }
        index++;
        var action = target.id.substring(0, index);
        var uuid = target.id.substring(index);
        var attachment;
        var index;
        for (index = 0; index < this.attachments.length; index++) {
            if (this.attachments[index].UUID == uuid) {
                break;
            }
        }

        if (index >= this.attachments.length) {
            // uuid not found
            return true;
        }

        if (action == this.DOWNLOAD_ACTION) {
            this.downloadAttachment(index);
        } else if (action == this.DELETE_ACTION) {
            this.deleteAttachment(index);
            //this.render();
        } else {
            // XXX: warning? 
        }

        return false;
    },

    downloadAttachment: function(index) {
        
    },

    deleteAttachment: function(index) {
        var req 
        = new Af.DataRequest(svcURL,
                             this.deleteAttachmentsCompleted.bind(this), 
                             requestFailedCommon.bind(this), 
                             null, 
                             requestTimedoutCommon.bind(this));
        req.addService("PublicService", "deleteAttachment");
        req.addParameter("attachmentId", this.attachments[index].UUID);
        // we might use this, too.
        // req.addService("WorkspaceService", "getAttachmentsForList");
        // req.addParameter("listId", this.listUUID);
        ajaxEngine.processRequest(req);
    },

    /** 
     * Some event changed.
     * Called from Schedule.js
     * XXX: for now, we don't bother to check the event. 
     * If we are displayed, then we just update.
     */
	deleteAttachmentsCompleted:function(event) {
        this.fetchAttachments(true);
        //this.addAttachmentBlock.style.display = 'block';
	},

    eventChanged: function(event, wasDeleted) {
        if (document.getElementById("archiveDisplay") == null) {
            return;
        }
        this.fetchAttachments();
    },

    /**
     * Set the maximum number of rows to display, not counting the 
     * header. 
     * Caller should call render to change the display
     */
     setMaxRows: function(count) {
         this.maxRows = count;
     }, 

    /**
     * Get the maximum number of rows to display
     */
     getMaxRows: function() {
         return this.maxRows;
     },
     
     handleDownloadClick: function(e) {

        var target = e.target;
        if(!target) {
            // IE? 
            target = e.srcElement;
        }

        var aid = target.id.split("_")[1];
        
        var iframe = document.createElement("iframe");
        iframe.style.display = "none";

        iframe.src = "/rose/download?attachmentId=" + aid;
        document.body.appendChild(iframe);
        /*
		window.open("/rose/download?attachmentId=" + aid,
				 '_blank', 
				 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=1, height=1');
                 */
		return false;
     }
}

