All Downloads are FREE. Search and download functionalities are using the official Maven repository.

portal.default.mint.workflows.redbox.inputForms.js Maven / Gradle / Ivy

There is a newer version: 1.10
Show newest version

(function($){
    var wfUrl = "../workflows/redbox/name-authority.ajax"
    function getDataList(){
        dataList = {};      // name:{get:func(), set:func(d)], name.0:[get:func(i), set:func(i, d)}
        dataList.get = function(name){
            var m, i;
            if(m=name.match(/\.(\d+)/)){
                i=parseInt(m[1]);
                name = name.replace(/\.\d+/, ".0");
                return dataList[name].get(i);
            }else{
                return dataList[name].get();
            }
        };
        dataList.set = function(name, value){
            var m, i;
            try{
                if(m=name.match(/\.(\d+)/)){
                    i=parseInt(m[1]);
                    name = name.replace(/\.\d+/, ".0");
                    return dataList[name].set(i, value);
                }else{
                    return dataList[name].set(value);
                }
            }catch(e){
                
            }
        };
        function add(name, eName, eId){
            if(!eId) eId=name;
            var e=$(eName+"[id='"+eId+"']");
            dataList[name] = {
                get:function(){return e.val()},
                set:function(d){e.val(d);}
            };
        }
        function addi(name, eName, createNewElemFunc){
            // index placeholder = '.0'
            var eId=name;
            dataList[name] = {
                get:function(i){
                    return $(eName.replace(".0", "."+i) +
                        "[id='"+eId.replace(".0", "."+i)+"']").val();
                },
                set:function(i, d){
                    var e=$(eName.replace(".0", "."+i) +
                        "[id='"+eId.replace(".0", "."+i)+"']");
                    if(e.size()==0){
                        if(d=="") return;   // do not add a new empty element
                        createNewElemFunc();
                        e=$(eName.replace(".0", "."+i) +
                            "[id='"+eId.replace(".0", "."+i)+"']");
                    }
                    e.val(d);
                },
                isIndex:true
            };
        }
        add("title", "input", "dc:title");
        add("description", "textarea", "dc:abstract");

        //add("dc:title", "input");
        //add("dc:date", "input");
        //add("dc:abstract", "textarea");
        var metaList = $("[name=metaList]").val();
        if(metaList){
            metaList=metaList.split(/[,\s]+/);
            $.each(metaList, function(k, v){
                add(v, "");
            });
        }
        // Creators
        addi("dc:creator.0.foaf:Person.foaf:givenName", "input",
                function(){$("*[id='dc:creator.'] .add-tr-item").click();} );
        addi("dc:creator.0.foaf:Person.foaf:familyName", "input",
                function(){$("*[id='dc:creator.'] .add-tr-item").click();} );
        // -- More Details --
        // -- Reporting --
        // Field of research codes
        // 
        // 
        addi("dc:subject.anzsrc:for.0.rdf:resouce", "input")
        addi("dc:subject.anzsrc:for.0.skos:prefLabel", "input")
        function addAnzsrcForX(i, id, label){
            // wait until we have all the info.
            if(!addAnzsrcForX.ids)addAnzsrcForX.ids=[];
            if(!addAnzsrcForX.labels)addAnzsrcForX.labels=[];
            var ids=addAnzsrcForX.ids, labels=addAnzsrcForX.labels;
            if(id)ids[i]=id;
            if(label)labels[i]=label;
            if(ids[i] && labels[i]) addAnzsrcFor(ids[i], labels[i]);
        }
        dataList["dc:subject.anzsrc:for.0.rdf:resouce"].set = function(i, d){
            addAnzsrcForX(i, d);
        };
        dataList["dc:subject.anzsrc:for.0.skos:prefLabel"].set = function(i, d){
            addAnzsrcForX(i, null, d);
        };
        // Keywords
        addi("dc:subject.usq:folksonomy.0", "input",
                function(){$("*[id='dc:subject.usq:folksonomy.'] .add-tr-item").click();});
        dataList.getNameValues = function(){
            var d= {}, name, value;
            for(var k in dataList){
                if(typeof(dataList[k])!="function"){
                    if(dataList[k].isIndex){
                        for(var i=1; i<1000; i++){
                           name = k.replace(".0", "."+i);
                           value = dataList[k].get(i);
                           if(!value && value!="") break;
                           d[name]=$.trim(value);
                        }
                    }else{
                        d[k]=$.trim(dataList.get(k));
                    }
                }
            }
            return d;
        };
        return dataList;
    }
    _GetDataList = getDataList;

    function savePackage(){
        //messageBox("saved OK");
        var url = packageData.portalPath + "/actions/manifest.ajax";
        var func = "update-package-meta";
        var oid = packageData.oid;
        var metaList = [];
        var data = getDataList().getNameValues();
        for(var k in data){
            metaList.push(k);
        }
        data.func=func; data.oid=oid; data.metaList=metaList;
        $.ajax({ type:"POST", url:url, data:data,
            success:function(data){
                if(data.error || !data.ok){
                    messageBox("Failed to save! (error='"+data.error+"')");
                }else{
                    $("#saved-result").text("Saved OK").
                        css("color", "green").show().fadeOut(4000);
                }
            },
            error:function(xhr, status, e){
                messageBox("Failed to save! (status='"+status+"')");
            },
            dataType:"json"
        });
    }

    function updateForm(data){
        var key, value, setData;
        setData = getDataList();
        for(key in data){
            value = data[key];
            setData.set(key, value);
        }
    }

    function addFile(){
        var addAFile = $("#add-a-file");
        var file = addAFile.find("input[type=file]");  // "z:Attachment.0.dc:title"
        var metaData = {};
        var i, form = addAFile.find("form"), input, numOfFiles=0;
        var mdList, metaDataList = [
                        "z:Attachment.0.dc:title",
                        "z:Attachment.0.z:type",
                        "z:Attachment.0.dc:date",
                        "z:Attachment.0.dc:description",
                        ];
        if(!file.val()){
            messageBox("Please select a file to upload first!");
            return;
        }
        for(i=1; i<1000; i++){
            var givenName = "z:Attachment.0.dc:creator."+i+".foaf:Person.foaf:givenName";
            var familyName = "z:Attachment.0.dc:creator."+i+".foaf:Person.foaf:familyName";
            if(addAFile.find("*[id='"+givenName+"']").size()){
                metaDataList.push(givenName);
                metaDataList.push(familyName);
            }else{
                break;
            }
        }
        $.each(metaDataList, function(i, key){
            metaData[key] = addAFile.find("#[id='"+key+"']").val() || "";
        });
        metaData["title"] = file.val();
        metaData["description"] = metaData["z:Attachment.0.dc:description"];

        form.find("input[type=hidden]").remove();
        mdList = [];
        for(var key in metaData){
            //var nkey = key.replace(/\.0/, "." + (numOfFiles+1));
            var nkey = key;
            if(key.match(/\.0\./)){
                nkey = key.split(/\.0\./)[1];
            }
            mdList.push(nkey);
            input = $("");
            input.attr("name", nkey);
            input.attr("value", metaData[key]);
            form.append(input);
        }
        form.append("");
        form.attr("action", "../workflow.ajax");
        form.append("");
        input = $("");
        input.attr("value", mdList.join(","));
        form.append(input);
        form.attr("target", "uploadframe");

        function disableAllFields(tf){
            addAFile.find("input, select, textarea").attr("disabled", tf);
        }
        function resetAllFields(){
            disableAllFields(false);
            file.val("");
            $("#add-a-file .upload-info").html("");
            $.each(metaDataList, function(i, key){
                addAFile.find("#[id='"+key+"']").val("").attr("disabled", false);
            });
        }
        var iframe=$("#uploadframe");
        function getIBody(){
            var ibody;
            if(iframe[0].contentDocument) ibody=iframe[0].contentDocument.body;
            else ibody = iframe[0].contentWindow.document.body;
            return $(ibody);
        }
        form.submit();
        try{
            disableAllFields(true);
            $("#upload-file-loading").show();
            $("#uploading-file-msg").text("Uploading please wait.").
                css("color", "green").show();
            getIBody().text("Uploading please wait...");
        }catch(e){

        }
        try{
           iframe.unbind().load(function() {
                $("#upload-file-loading").hide();
                // add to list of already added files
                var json;
                try{
                    try{
                        eval("json=" + getIBody().text());
                    }catch(e){
                        throw "Invalid JSON '"+getIBody().text()+"'!";
                    }
                    if(json.ok){
                        resetAllFields();
                        // wfUrl?func=addItem&oid=X&id=X&title=X
                        var id=json.oid, oid=packageData.oid, title=metaData.title;
                        $.getJSON(wfUrl,
                            {func:"addItem", oid:oid, id:id, title:title},
                            function(data){
                                //alert(data.toSource());
                                if(data.ok){
                                    // wfUrl?func=getItem&id=
                                    $.getJSON(wfUrl, {func:"getItem", id:id},
                                        function(data){
                                            //alert(data.toSource());
                                            if(data.doc){
                                                addPackagedItem(0, data.doc);
                                                addItemToSet(id, title);
                                            }
                                        }
                                    );
                                }
                            }
                        );
                        $("#uploading-file-msg").text("Uploaded OK");
                    }else{
                        throw json.error;
                    }
                }catch(e){
                    $("#uploading-file-msg").css("color", "red").
                        text("Failed to uploading file. ERROR: "+e);
                    disableAllFields(false);
                }
                setTimeout(function(){ $("#uploading-file-msg").fadeOut(3000); }, 4000);
           });
        }catch(e){
            alert("Error: "+e);
        }
    }

    function itemSearch(pageNum){
        var portalPath = packageData.portalPath;
        var packagedItems = packageData.packagedItems;
        var searchResults, searchResultsDiv;
        var packagedIds = {};
        var paging = $("#add-items-search-query").parent().find(".paging");
        var pages, query;
        if(!pageNum) pageNum=1;
        $.each(packagedItems, function(i, doc){
            packagedIds[doc.id] = doc.id;
        });
        query=$("#add-items-search-query").val();
        searchResults = $("#search-results");
        searchResultsDiv = searchResults.find("> div").html("");
        searchResults.find("span.result-info").text("searching...");
        paging.html("");

        $.getJSON(wfUrl, {func:"search", query:query, pageNum:pageNum},
            function(data){
                gdata = data;   // for testing only
                var response=data.response;
                var start=1*response.start;
                var rows=1*data.responseHeader.params.rows; // page size
                var docs = response.docs;
                var found = 1*response.numFound;
                var sTo = found;
                if(found)start+=1;
                if(sTo>(start+rows)) sTo=start+rows;
                pages = Math.ceil(found/rows);
                if(pages>1){
                    var ul=$("
    "), li, a, nums=[]; nums[pages-1]=0; $.each(nums, function(i){ i+=1; if(i==pageNum){ li = $("
  • "+i+"
  • "); }else{ a = $(""+i+""); li = $("
  • "); li.append(a); a.click(function(){ $("#add-items-search-query").val(query); itemSearch(i); return false; }); } ul.append(li); }); paging.append(ul); } searchResults.find("span.result-info").text( found?("showing "+start+" to "+(sTo)+" of "+found+" items"):"No results found" ); if(found==0){ searchResultsDiv.append("No results found"); } searchResultsDiv.show(); searchResults.find(".showhide").text("(hide)").show().unbind().click(function(){ var i=searchResults.find(".showhide"); if(i.text()=="(show)"){ searchResultsDiv.show(); i.text("(hide)"); }else{ searchResultsDiv.hide(); i.text("(show)"); } }); $.each(docs, function(i, doc){ var div, h3, checkbox, id, title, description, thumbnail; try{ id = doc.id; title = doc.dc_title[0]; if(doc.dc_description){ description = doc.dc_description[0] }else{description=doc.dc_title[1]||"";} thumbnail = doc.thumbnail; //doc.dc_format; div = $("
    "); div.attr("id", "s-"+id); checkbox = $(""); if(packagedIds[id]){ checkbox.attr("checked", true); } h3 = $("

    "); h3.append(checkbox); h3.append(title); //h3.append("