var coknown = {    
    // Don't mess with these values!
    PERMISSIONS: {
        no_access: 0,
        // NO_ACCESS
        can_read: 1,
        // READ
        can_add: 3,
        // READ | ADD
        can_modify: 7,
        // READ | ADD | MODIFY
        can_delete: 23,
        // READ | ADD | MODIFY | DELETE
        has_full: 32,
        // FULL
        is_blocked: 64,
        // BLOCKED
    },

    PERMISSION_UPDATE_EVENT: "coknown.permission.update",
    PERMISSION_UPDATE_NOTIFICATION: "notify.coknown.permission.update",

    PRIVACY_UPDATE_EVENT: "coknown.privacy.update",
    PRIVACY_UPDATE_NOTIFICATION: "notify.coknown.privacy.update",

    ARCHIVE_UPDATE_EVENT: "coknown.archive.update",
    ARCHIVE_UPDATE_NOTIFICATION: "notify.coknown.archive.update",

    //PROJECT_CATEGORY_EVENT = "coknown.project.category",

    addCropLayers: function(element, capId, coordinates) {
        setTimeout(function() {
            jQuery("#waitSpinner").css("display", "none");

            var $view = jQuery("#view" + capId);
            $view.css("display", "block");
            var $viewOffset = $view.offset();
            var scrollBarWidth = 2 * coknown.scrollBarWidth();
            var width = jQuery(element).attr("offsetWidth");
            var height = jQuery(element).attr("offsetHeight");
            var _w = jQuery(element).attr("width");
            var _h = jQuery(element).attr("height");
            var agent = navigator.userAgent.toLowerCase();
            var is_iphone = (agent.indexOf('iphone') != - 1);
            if (is_iphone) {
                $view.css("width", width + "px");
                $view.css("height", height + "px");
            } else {
                $view.css("width", jQuery(window).width() - scrollBarWidth - $viewOffset.left);
                $view.css("height", jQuery(window).height() - scrollBarWidth - $viewOffset.top);
                $view.css("overflow", "scroll");
            }

            $view.css("position", "absolute");
            $view.css("left", scrollBarWidth);

            if (coordinates != null && coordinates.length > 0) {
                var cropBox = coordinates.split(";");
                var left = parseInt(cropBox[0]);
                var top = parseInt(cropBox[1]);
                var width = parseInt(cropBox[2]);
                var height = parseInt(cropBox[3]);

                $view.append(coknown.createCropLayer({
                    "position": "absolute",
                    "left": left,
                    "top": top,
                    "width": width,
                    "height": height,
                    "z-index": "1000000000",
                    "border": "2px dotted black"
                }).attr("id", "ckCropLayer0"));
                $view.append(coknown.createCropLayer({
                    "position": "absolute",
                    "left": 0,
                    "top": 0,
                    "width": $view.width(),
                    "height": top,
                    "z-index": "1000000000",
                    "background-color": "black",
                    "opacity": "0.55"
                }).attr("id", "ckCropLayer1"));
                $view.append(coknown.createCropLayer({
                    "position": "absolute",
                    "left": 0,
                    "top": top,
                    "width": left,
                    "height": height,
                    "z-index": "1000000000",
                    "background-color": "black",
                    "opacity": "0.55"
                }).attr("id", "ckCropLayer2"));
                $view.append(coknown.createCropLayer({
                    "position": "absolute",
                    "left": left + width,
                    "top": top,
                    "width": $view.width() - left - width,
                    "height": height,
                    "z-index": "1000000000",
                    "background-color": "black",
                    "opacity": "0.55"
                }).attr("id", "ckCropLayer3"));
                $view.append(coknown.createCropLayer({
                    "position": "absolute",
                    "left": 0,
                    "top": top + height,
                    "width": $view.width(),
                    "height": $view.height(),
                    "z-index": "1000000000",
                    "background-color": "black",
                    "opacity": "0.55"
                }).attr("id", "ckCropLayer4"));
                $view.append(coknown.createCropLayer({
                    "position": "absolute",
                    "left": left,
                    "top": top,
                    "width": 16,
                    "height": 16,
                    "z-index": "1000000000",
                    "cursor": "pointer",
                    "background-image": "url('/toolbar/icons/close.png')",
                    "background-repeat": "no-repeat"
                }).attr("id", "ckCropLayer5").click(coknown.removeCropLayers));
                $view.scrollTo({
                    left: left - ($view.width() / 2) + (width / 2),
                    top: top - ($view.height() / 2) + (height / 2)
                });
            }
        },
        1000);
    },

    removeCropLayers: function() {
        for (var i = 0; i < 6; ++i) {
            var $layer = jQuery("#ckCropLayer" + i);
            if ($layer) {
                $layer.remove();
            }
        }
    },

    createCropLayer: function(o) {
        var $layer = jQuery(document.createElement("div"));
        for (p in o) {
            $layer.css(p, o[p]);
        }
        return $layer;
    },


    toggleNote: function(sortedListId, capId, event)
    {
        var $note = jQuery("#text" +sortedListId+"_"+ capId);
        $note.toggleClass("capNotefull", 500);
        var $va = jQuery("#nb_read_arrow" +sortedListId+"_"+ capId);
        $va.toggleClass("nb_read_arrow_active",500);
    },

    editNote: function(sortedListId, capId) {
//alert("TRYING TO EDIT "+sortedListId+" "+capId);
        var $nview = jQuery("#nview" +sortedListId+"_"+ capId);
        var $hideMe = jQuery("#hideMe" +sortedListId+"_"+ capId);
        $hideMe.slideUp("fast");
        $nview.slideDown("fast");
        return false;
    },

    doneEditing: function(trigger, sortedListId, captureId, event) {
        $.jStorage.set("CoKnownLastTab", sortedListId);
        var id = jQuery(trigger).attr("id");
        var needsUpdate = false;
        if (id == ("submitEditNote"+sortedListId+"_"+captureId)) {
            needsUpdate = true;
        } 
        else if (id == ("cancelEditNote"+sortedListId+"_"+captureId)) {
            var isEmpty = jQuery("#isEmptyNote"+sortedListId+"_" +captureId).attr("title");
            if (isEmpty == "true"){
                jQuery.ajax({
                    type: "PUT",
                    url: "/ckservice/notes/" + captureId+"/delete", 
                    contentType: "application/json",
                    data: json,
                    async: false,
                    cache: false,
                    dataType: "text",
                    success: function(data, status) {
                        jQuery(".sort-box"+captureId).remove();
                    },
                    error: function(xhr, status, error) {
                        alert("Unable to delete empty note! " + xhr.status);
                    }
                });
            }
        } 
        var $nview = jQuery("#nview" +sortedListId+"_"+ captureId);
        var $hideMe = jQuery("#hideMe" +sortedListId+"_"+ captureId);
        if (needsUpdate)
        {
            var title = jQuery("#capTitle"+sortedListId+"_"+captureId).val();
            var note = tinyMCE.get('capNote'+sortedListId+'_'+captureId).getContent();
            var json = JSON.stringify({
                title: title,
                note: note
            });
            jQuery.ajax({
                type: "PUT",
                url: "/ckservice/notes/" + captureId+"/",
                contentType: "application/json",
                data: json,
                async: false,
                cache: false,
                dataType: "text",
                success: function(data, status) {
                    jQuery(".edit-title"+captureId).text(title);
                    jQuery(".edit-note"+captureId).html(note);
                },
                error: function(xhr, status, error) {
                    alert("Unable to save changes! " + xhr.status);
                }
            });
        }
        $nview.slideUp("fast");
        $hideMe.slideDown("fast");
        event.returnValue = false;
        return false;
    },

    viewCrop: function(sortedListId, capId, url, event) {
        var $view = jQuery("#view" +sortedListId+"_"+ capId);
        var $img = jQuery("#img" +sortedListId+"_"+ capId);
        var $va = jQuery("#va" +sortedListId+"_"+ capId);
        var display = $view.css("display");
        if ($img.attr("src") == null) {
            $img.attr("src", url);
        }
        if (display != "none") {
            //      $view.css("display", "none");
            $view.slideUp("fast");
            $va.css("background-position", "0 -36px");

            $va.bind("mouseover", function() {
               jQuery(this).css("background-position", "0 -18px");
            });
            $va.bind("mouseout", function() {
                jQuery(this).css("background-position", "0 -36px");
            });
        } else {
            //      $view.css("display", "block");
            $view.slideDown("fast");
            $va.css("background-position", "0 0");
            $va.unbind("mouseout");
            $va.unbind("mouseover");
        }
        event.returnValue = false;
        return false;
    },

    setProjectTemplateness: function(projId) {
        var cbox = jQuery("#templateness");
        var value = cbox.is(':checked');
        var onOrOff = (value) ? 1 : 0 ;
        var str = onOrOff ? "make template": "undo template";
        jQuery.ajax({
            type: "PUT",
            url: "/ckservice/template/"+projId+"/"+onOrOff+"/",
            async: true,
            cache: false,
            dataType: "json",
            success: function() {
                jQuery("#templateness").attr('checked', value);
            },
            error: function(xhr, status, error) {
                alert("Unable to " + str + " for project: " + status + ", " + error);
            }
        });
        return false;
    },

    setProjectCategory: function(projId, categoryId) {
        var cbox = jQuery("#category_"+categoryId);
        var value = cbox.is(':checked');
        var onOrOff = (value) ? 1 : 0 ;
        var str = onOrOff ? "add category": "remove category";
        jQuery.ajax({
            type: "PUT",
            url: "/ckservice/project/category/"+projId+"/"+categoryId+"/"+onOrOff+"/",
            async: true,
            cache: false,
            dataType: "json",
            success: function() {
                jQuery("#category_"+categoryId).attr('checked', value);
            },
            error: function(xhr, status, error) {
                alert("Unable to " + str + " from project: " + status + ", " + error);
            }
        });
        return false;
    },

    findProjects: function(userId, searchString1) {
        var array = new Array();
        array[0] = searchString;
        var criteria = new Object();
        criteria.searchStrings = array;
        var json = JSON.stringify(criteria);
        jQuery.ajax({
            type: "PUT",
            url: "/ckservice/projects/find",
            async: true,
            cache: false,
            dataType: "json",
            success: function(data, status) {
            },
            error: function(xhr, status, error) {
                alert("Unable to search for projects.");
            }
        });
        return false;
    },


    archiveProject: function(trigger, projId, archive) {
        var value = archive ? "archive": "unarchive";
        var action = archive ? "add": "remove";
        jQuery.ajax({
            type: "PUT",
            url: "/ckservice/projects/archives/" + projId + "?action=" + action,
            async: true,
            cache: false,
            dataType: "json",
            success: function() {
                var data = {};
                data["trigger"] = trigger;
                data["action"] = action;
                jQuery(document).trigger(
                coknown.ARCHIVE_UPDATE_EVENT, data);
            },
            error: function(xhr, status, error) {
                alert("Unable to " + value + " project!: " + status + ", " + error);
            }
        });
        return false;
    },


    deleteProject: function(projId, userId, event) {
        if (confirm("Are you sure you want to delete this project?")) {
            jQuery.ajax({
                type: "DELETE",
                url: "/ckservice/projects/" + projId,
                async: true,
                cache: false,
                dataType: "json",
                success: function(data, status) {
                    jQuery.ajax({
                        type: "GET",
                        url: "/ckservice/projects?view=ProjectListView&userid=" + userId,
                        async: true,
                        cache: false,
                        dataType: "html",
                        success: function(data, status) {
                            jQuery("#projects").html(data);
                        },
                        error: function(xhr, status, error) {
                            alert("Unable to get project listing!");
                        }
                    });
                },
                error: function(xhr, status, error) {
                    alert("Unable to delete project!");
                }
            });
        }
        event.returnValue = false;
        return false;
    },


    backToDefault: function(defaultListId, projId, event) {
        $.jStorage.set("CoKnownLastTab", defaultListId);
        window.location = "/project/"+projId;
        event.returnValue = false;
        return false;
    },

    deleteList: function(sortedListId, event) {
        if (confirm("Are you sure you want to delete this list? This cannot be undone.")) {
            jQuery.ajax({
                type: "DELETE",
                url: "/ckservice/deletesortedlist/" + sortedListId,
                async: true,
                cache: false,
                dataType: "json",
                success: function(data, status) {
                    jQuery("#tt"+sortedListId).remove();
                    var $dialog = jQuery("#orderListsDialog");
                    $dialog.css("display", "none");
                },
                error: function(xhr, status, error) {
                    alert("Unable to delete list!");
                }
            });
        }
        event.returnValue = false;
        return false;
    },

    deleteCapture: function(sortedListId, capId, projId, isInline, event) {
         var text = "note";
         if (isInline == 1) text = "inline history";
        $.jStorage.set("CoKnownLastTab", sortedListId);
        var before_count = jQuery(".inline_wrapper").length ;
        if (confirm("Are you sure you want to delete this "+text+"? This cannot be undone.")) {
            jQuery.ajax({
                type: "DELETE",
                url: "/ckservice/captures/" + capId,
                async: true,
                cache: false,
                dataType: "json",
                success: function(data, status) {
                    if (isInline == 0 || before_count == 1)
                    {
                         window.location = "/project/"+projId;
                    }
                    else
                    {
                        jQuery(".sort-box"+capId).remove();
                        jQuery("#"+capId).remove();
                    }
                },
                error: function(xhr, status, error) {
                    alert("Unable to delete inline history or note!");
                }
            });
        }
        event.returnValue = false;
        return false;
    },

    deleteCapturesOnPage: function(projId, event) {
    if (confirm("Are you sure you want to delete ALL items on this page?  This cannot be undone.")) {
        var toDelete = jQuery(".inline_wrapper");
        var ids = "";
        for (i = 0; i < toDelete.length; i++)
        {
            var elem = toDelete[i];
            ids += ",";
            ids += $(elem).attr('id');
        }
        var json = JSON.stringify({
            ids: ids
            });
        jQuery.ajax({
            type: "DELETE",
            url: "/ckservice/captures/delete/" + projId+"/",
            contentType: "application/json",
            async: false,
            cache: false,
            data: json,
            dataType: "json",
            success: function(data, status) {
                window.location = "/project/"+projId;
            },
            error: function(xhr, status, error) {
                alert("Unable to delete inline histories and demoted smart marks.");
            }
        });
    }
    event.returnValue = false;
    return false;
    },


    demoteCapture: function(sortedListId, capId, event) {
        $.jStorage.set("CoKnownLastTab", sortedListId);
        jQuery.ajax({
            type: "PUT",
            url: "/ckservice/captures/" + capId + "/demote",
            async: true,
            cache: false,
            dataType: "json",
            success: function(data, status) {
                //jQuery(".sort-box"+capId).remove();
                window.location.reload();
            },
            error: function(xhr, status, error) {
            }
        });
        event.returnValue = false;
        return false;
    },

    promoteCapture: function(defaultListId, capId, backUrl, event) {
        $.jStorage.set("CoKnownLastTab", defaultListId);
        var before_count = jQuery(".inline_wrapper").length ;
        jQuery.ajax({
            type: "GET",
            url: "/ckservice/captures/" + capId + "?view=EditIboxView",
            async: false,
            cache: false,
            dataType: "html",
            success: function(data, status) {
                var $dialog = jQuery("#editDialog");
                $dialog.css("position", "absolute");
                $dialog.css("left", (jQuery(window).width() / 2) - 230);
                $dialog.css("top", event.clientY + document.documentElement.scrollTop - 100);
                $dialog.css("z-index", "1000000000");
                $dialog.css("display", "block");
                $dialog.html(data);
                jQuery("#captureInformation").attr("checked", "checked");
                jQuery("#submit").click(function() {
                    var title = jQuery("#captureTitle").val();
                    var note = jQuery("#captureNote").val();
                    var quote = jQuery("#captureQuote").val();
                    var type = 0;
                    if (jQuery("#captureInformation").is(":checked")) {
                        type = 1;
                    }
                    else if (jQuery("#captureDeadEnd").is(":checked")) {
                        type = 2;
                    }
                    else {
                        type = 3;
                    }
                    var json = JSON.stringify({
                        title: title,
                        note: note,
                        iNote: quote,
                        type: type
                    });
                    jQuery.ajax({
                        type: "PUT",
                        url: "/ckservice/captures/" + capId,
                        contentType: "application/json",
                        data: json,
                        async: false,
                        cache: false,
                        dataType: "text",
                        success: function(data, status) {
                            if (before_count == 1)
                            {
                                window.location.replace(backUrl);
                            }
                            else
                            {
                                jQuery("#"+capId).remove();
                            }
                        },
                        error: function(xhr, status, error) {
                            alert("Unable to save changes! " + xhr.status);
                        }
                    });
                });
                jQuery("#cancel").click(function() {
                    $dialog.css("display", "none");
                });
                jQuery("#captureTitle").focus();
            },
            error: function(xhr, status, error) {
                alert("Unable to edit capture!");
            }
        });
        event.returnValue = false;
        return false;
    },
    
    reorderList: function(ids, sortedListId, event) {
        var json = JSON.stringify({
            ids: ids
            });
        jQuery.ajax({
            type: "POST",
            url: "/ckservice/reorder/" + sortedListId+"/",
            contentType: "application/json",
            async: false,
            cache: false,
            data: json,
            dataType: "json",
            success: function(data, status) {
            },
            error: function(xhr, status, error) {
                alert("Unable to reorder list");
            }
        });
    },

    reorderGroup: function(ids, ownerId, name, event) {
        var json = JSON.stringify({
            ids: ids
            });
        jQuery.ajax({
            type: "POST",
            url: "/ckservice/reordergroup/" + ownerId +"/",
            contentType: "application/json",
            async: false,
            cache: false,
            data: json,
            dataType: "json",
            success: function(data, status) {
            },
            error: function(xhr, status, error) {
                alert("Unable to reorder group");
            }
        });
    },

    showMessagePopup: function(messageString) {
// start div is in messageString.  closing div is here!!!
        var $dialog = jQuery("#messagePopupDialog");
        $dialog.css("position", "absolute");
        $dialog.css("left", (jQuery(window).width() / 2) - 230);
        $dialog.css("top", document.documentElement.scrollTop - 150);
        $dialog.css("z-index", "1000000000");
        $dialog.css("display", "block"); 
        var div = jQuery(messageString +' <p/> <div textAlign="center"> <input id="okay" type="button" value="Close"/> </div> </div> ');
        $dialog.append(div);
        jQuery("#okay").click(function() {
            $dialog.css("display", "none");
        });
    },

    processCosearcherRequests: function(targetUserId, acceptRequest, requesterId) {
        var action = acceptRequest ? "accept": "decline";
        jQuery.ajax({
            type: "POST",
            url: "/ckservice/processcosearcherrequests/"+targetUserId+"/"+action+"/"+requesterId+"/",
            contentType: "application/json",
            async: false,
            cache: false,
            dataType: "json",
            success: function(data, status) {
                jQuery("#cr_row"+requesterId).remove();
            },
            error: function(xhr, status, error) {
                alert("cannot process cosearcher requests "+xhr.status + " : " + xhr.statusText);
            }
        });
    },

    newList: function(projId) {
        var all = jQuery("input:checked");
        var ids = "";
        for (i = 0; i < all.length; i++)
        {
            var elem = all[i];
            ids += ",";
            ids += $(elem).attr('id');
        }
        var json = JSON.stringify({
            ids: ids 
            });
        var newName = jQuery("#newListName").val();
        if (newName == "" || newName.indexOf("\/") != -1)
            return false;
        jQuery.ajax({
            type: "POST",
            url: "/ckservice/projects/"+projId+"/newsortedlist/"+newName+"/",
            contentType: "application/json",
            data: json,
            async: false,
            cache: false,
            dataType: "json",
            success: function(data, status, xhr) {
                window.location.reload();
            },
            error: function(xhr, status, error) {
                alert(xhr.status + " : " + xhr.statusText);
            }
        });
        return false;
    },

    makeMain: function(projId, sortedListId) {
        jQuery.ajax({
            type: "POST",
            url: "/ckservice/projects/"+projId+"/makemain/"+sortedListId+"/",
            contentType: "application/json",
            data: null,
            cache: false,
            dataType: "text",
            success: function(data, status, xhr) {
                window.location.reload();
            },
            error: function(xhr, status, error) {
                alert(xhr.status + " : " + xhr.statusText);
            }
        });
        return false;
    },


    hideFromList: function(projId, sortedListId, captureId, title) {
        $.jStorage.set("CoKnownLastTab", sortedListId);
        jQuery.ajax({
            type: "POST",
            url: "/ckservice/projects/"+projId+"/hidefromlist/"+sortedListId+"/"+captureId+"/",
            contentType: "application/json",
            data: null,
            cache: false,
            dataType: "text",
            success: function(data, status, xhr) {
                jQuery(".unique_"+sortedListId+"_"+captureId).remove();
                var parent = jQuery("#all-tbox-content"+sortedListId);
                var str = '<div id="tbox-content"> <span id="tbox-add" onclick="coknown.addToList('+projId+', ';
                str += sortedListId+', '+captureId+'); return false;">  <div id="t-check'+captureId;
                str += '"></div> <div id="t-title"> <span id="title'+captureId+'"> '+title+' </span>  </div>  </span>  </div> ';
                var newdiv = jQuery(str);
                parent.append(newdiv);
            },
            error: function(xhr, status, error) {
                alert(xhr.status + " : " + xhr.statusText);
            }
        });
        return false;
    },


    addToList: function(projId, sortedListId, captureId) {
        $.jStorage.set("CoKnownLastTab", sortedListId);
        jQuery.ajax({
            type: "POST",
            url: "/ckservice/projects/"+projId+"/addtolist/"+sortedListId+"/"+captureId+"/",
            contentType: "application/json",
            data: null,
            cache: false,
            dataType: "text",
            success: function(data, status, xhr) {
                window.location.reload();
            },
            error: function(xhr, status, error) {
                alert(xhr.status + " : " + xhr.statusText);
            }
        });
        return false;
    },



    addConclusion: function(projId, sortedListId) {
        $.jStorage.set("CoKnownLastTab", sortedListId);
        jQuery.ajax({
            type: "POST",
            url: "/ckservice/projects/"+projId+"/conclusion/"+sortedListId+"/",
            contentType: "application/json",
            data: null,
            cache: false,
            dataType: "text",
            success: function(data, status, xhr) {
                window.location.reload();
            },
            error: function(xhr, status, error) {
                alert(xhr.status + " : " + xhr.statusText);
            }
        });
        return false;
    },


    addNote: function(projId, sortedListId, afterThisId) {
        $.jStorage.set("CoKnownLastTab", sortedListId);
        jQuery.ajax({
            type: "GET",
            url: "/ckservice/projects/"+projId+"/newnote/"+sortedListId+"/"+afterThisId+"/",
            contentType: "application/json",
            async: false,
            cache: false,
            dataType: "html",
            data: null,
            success: function(data, status, xhr) {
                window.location.reload();
            },
            error: function(xhr, status, error) {
                alert(xhr.status + " : " + xhr.statusText);
            }
        });
        return false;
    },

    displayListOrderingForm: function(projId, sortedListId, event){
       jQuery.ajax({
            type: "GET",
            url: "/ckservice/orderlists/"+projId+"/"+sortedListId+"/",
            async: false,
            cache: false,
            dataType: "html",
            success: function(data, status) {
                var $dialog = jQuery("#orderListsDialog");
                $dialog.css("position", "absolute");
                $dialog.css("left", (jQuery(window).width() / 2) - 230);
                $dialog.css("top", event.clientY + document.documentElement.scrollTop - 100);
                $dialog.css("z-index", "1000000000");
                $dialog.css("display", "block");
                $dialog.html(data);
                jQuery("#submit").click(function() {
                    var newName = jQuery("#newListName").val();
                    if (typeof newName == "undefined")
                        newName = "HISTORICAL";
                    if (newName == "" || newName.indexOf("/") != -1)
                      return false;
                    var ids = jQuery("#hiddenIds").html();
                    var json = JSON.stringify({
                        ids: ids
                        });
                    jQuery.ajax({
                        type: "POST",
                        url: "/ckservice/editLists/"+projId+"/"+sortedListId+"/"+newName+"/",
                        contentType: "application/json",
                        data: json,
                        async: false,
                        cache: false,
                        dataType: "json",
                        success: function(data, status, xhr) {
                            window.location.reload();
                        },
                        error: function(xhr, status, error) {
                            alert(xhr.status + " : " + xhr.statusText);
                        }
                    });
                });
               jQuery("#cancel").click(function() {
                    $dialog.css("display", "none");
                });
            },
            error: function(xhr, status, error) {
                alert("Unable to order the lists!");
            }
        });
        event.returnValue = false;
        return false;
    },



    displayListNameForm: function(projId, sortedListId, currentName, event){
       $.jStorage.set("CoKnownLastTab", sortedListId);
       var newOrEdit = "editsortedlist/"+sortedListId;
       var ids = "";
       if (sortedListId == -1)
       {
           $.jStorage.flush();
           currentName = " " ;
           newOrEdit = "newsortedlist";
           var all = jQuery("input:checked");
           for (i = 0; i < all.length; i++)
           {
               var elem = all[i];
               ids += ",";
               ids += $(elem).attr('id');
           }
       }
       var json = JSON.stringify({
           ids: ids
           });
       jQuery.ajax({
            type: "GET",
            url: "/ckservice/listname/"+currentName,
            async: false,
            cache: false,
            dataType: "html",
            success: function(data, status) {
                var $dialog = jQuery("#listNameDialog");
                $dialog.css("position", "absolute");
                $dialog.css("left", (jQuery(window).width() / 2) - 230);
                $dialog.css("top", event.clientY + document.documentElement.scrollTop - 100);
                $dialog.css("z-index", "1000000000");
                $dialog.css("display", "block");
                $dialog.html(data);
                jQuery("#submit").click(function() {
                    var newName = jQuery("#newListName").val();
                    if (newName == "" || newName.indexOf("/") != -1)
                      return false;
                    jQuery.ajax({
                        type: "POST",
                        url: "/ckservice/projects/"+projId+"/"+newOrEdit+"/"+newName+"/",
                        contentType: "application/json",
                        data: json,
                        async: false,
                        cache: false,
                        dataType: "json",
                        success: function(data, status, xhr) {
                            window.location.reload();
                        },
                        error: function(xhr, status, error) {
                            alert(xhr.status + " : " + xhr.statusText);
                        }
                    });
                });
               jQuery("#cancel").click(function() {
                    $dialog.css("display", "none");
                });
                jQuery("#newListName").focus();
            },
            error: function(xhr, status, error) {
                alert("Unable to edit list name or create new list!");
            }
        });
        event.returnValue = false;
        return false;
    },

    emailForm: function(userId, projId, cosearcherId) {
       jQuery.ajax({
            type: "GET",
            url: "/ckservice/emailform/"+userId+"/"+projId+"/"+cosearcherId+"/",
            async: false,
            cache: false,
            dataType: "html",
            success: function(data, status) {
                var $dialog = jQuery("#emailDialog");
                $dialog.css("position", "fixed");
                $dialog.css("left", (jQuery(window).width() / 2) - 250);
                $dialog.css("top", 200);
                $dialog.css("z-index", "1000000000");
                $dialog.css("display", "block");
                $dialog.html(data);
                jQuery("#project_href").click(function() {return false; });
                jQuery("#submit").click(function() {
                var toEmail = jQuery("#toEmail").val()+" ";
                if ((toEmail.split(',').length - 1)  > 5) {
                    alert("Please enter 6 or fewer email addresses.");
                    return false;
                }
                jQuery("#cancel").click();
                //var fromEmail = jQuery("#fromEmail").val();
                var subject = jQuery("#subject").val();
                var message = jQuery("#message").val();
                var mail1 = jQuery("#mail1").html();
                var mail2 = jQuery("#mail2").html();
                message = mail1 +"<p>"+message+"<p>"+mail2;
                var json = JSON.stringify({
                    toEmail: toEmail,
                    //fromEmail: fromEmail,
                    subject: subject,
                    message: message
                    });
                jQuery.ajax({
                    type: "POST",
                    url: "/ckservice/sendemail/"+userId+"/",
                    contentType: "application/json",
                    async: false,
                    cache: false,
                    data: json,
                    dataType: "json",
                    success: function(data, status) {
                    },
                    error: function(xhr, status, error) {
                        alert("Unable to send email2");
                    }
                });
                });
               jQuery("#cancel").click(function() {
                    $dialog.css("display", "none");
               });
               jQuery("#toEmail").focus();
            },
            error: function(xhr, status, error) {
                alert("Unable to send email1");
            }
        });
    },



    editCapture: function(sortedListId, capId, event) {
        $.jStorage.set("CoKnownLastTab", sortedListId);
        jQuery.ajax({
            type: "GET",
            url: "/ckservice/captures/" + capId + "?view=EditIboxView",
            async: false,
            cache: false,
            dataType: "html",
            success: function(data, status) {
                var $dialog = jQuery("#editDialog");
                $dialog.css("position", "absolute");
                $dialog.css("left", (jQuery(window).width() / 2) - 230);
                $dialog.css("top", event.clientY + document.documentElement.scrollTop - 100);
                $dialog.css("z-index", "1000000000");
                $dialog.css("display", "block");
                $dialog.html(data);
                jQuery("#submit").click(function() {
                    var title = jQuery("#captureTitle").val();
                    var note = jQuery("#captureNote").val();
                    var quote = jQuery("#captureQuote").val();
                    var type = 0;
                    if (jQuery("#captureInformation").is(":checked")) {
                        type = 1;
                    }
                    else if (jQuery("#captureDeadEnd").is(":checked")) {
                        type = 2;
                    }
                    else {
                        type = 3;
                    }
                    var json = JSON.stringify({
                        title: title,
                        note: note,
                        iNote: quote,
                        type: type
                    });
                    jQuery.ajax({
                        type: "PUT",
                        url: "/ckservice/captures/" + capId,
                        contentType: "application/json",
                        data: json,
                        async: false,
                        cache: false,
                        dataType: "text",
                        success: function(data, status) {
                            var all = jQuery("[id=sortid_"+capId+"]");
                            for (i = 0; i < all.length; i++)
                            {
                                var elem = all[i];
                                $(elem).find("[id=title"+capId+"]").text(title);
                                $(elem).find("[id=note"+capId+"]").text(note);
                                $(elem).find("[id=quote"+capId+"]").text(quote);
                            }
                            all = jQuery("[id=tbox-content]");
                            for (i = 0; i < all.length; i++)
                            {
                                var elem = all[i];
                                $(elem).find("[id=title"+capId+"]").text(title);
                            }
                            var $type = jQuery("#type" + capId);
                            if (type == 1) {
                                $type.attr("src", "/images/icons-listview/info-lv.png");
                                $type.bind("mouseover", function() {
                                    jQuery(this).attr("src", "/images/icons-listview/info-lv-over.png");
                                });
                                $type.bind("mouseout", function() {
                                    jQuery(this).attr("src", "/images/icons-listview/info-lv.png");
                                });
                            } else if (type == 2) {
                                $type.attr("src", "/images/icons-listview/deadend-lv.png");
                                $type.bind("mouseover", function() {
                                    jQuery(this).attr("src", "/images/icons-listview/deadend-lv-over.png");
                                });
                                $type.bind("mouseout", function() {
                                    jQuery(this).attr("src", "/images/icons-listview/deadend-lv.png");
                                });
                            } else {
                                $type.attr("src", "/images/icons-listview/tangent-lv.png");
                                $type.bind("mouseover", function() {
                                    jQuery(this).attr("src", "/images/icons-listview/tangent-lv-over.png");
                                });
                                $type.bind("mouseout", function() {
                                    jQuery(this).attr("src", "/images/icons-listview/tangent-lv.png");
                                });
                            }
                            jQuery("#cancel").click();
                        },
                        error: function(xhr, status, error) {
                            alert("Unable to save changes! " + xhr.status);
                        }
                    });
                });
                jQuery("#cancel").click(function() {
                    $dialog.css("display", "none");
                });
                jQuery("#captureTitle").focus();
            },
            error: function(xhr, status, error) {
                alert("Unable to edit capture!");
            }
        });
        event.returnValue = false;
        return false;
    },

    scrollBarWidth: function() {
        var div = jQuery('<div style="width:50px;height:50px;overflow:hidden;position:absolute;top:-200px;left:-200px;"><div style="height:100px;"></div>');
        jQuery("body").append(div);
        var w1 = jQuery("div", div).innerWidth();
        div.css("overflow-y", "scroll");
        var w2 = jQuery("div", div).innerWidth();
        jQuery(div).remove();
        return (w1 - w2);
    },

    validateNewProject: function() {
        var $projName = jQuery("#proj_name");
        var name = $projName.val();
        if (name == null || name.length == 0) {
            alert("Please provide a name for your project.");
            $projName.focus();
            return false;
        }

        return true;
    },

    createProject: function() {
        if (!coknown.validateNewProject()) {
            return false;
        }

        var proj_name = jQuery("#proj_name").val();
        var proj_goal = jQuery("#proj_goal").val();
        var proj_keywords = jQuery("#proj_keywords").val();
        var proj_privacy = 1;
        // STUPID STUPID STUPID JQUERY BUTTONSET HANDLER!!!
        // What's wrong with jQuery(":radio:checked").val() ?
        jQuery(".ck_privacy_type").next().each(function() {
            if (jQuery(this).attr("aria-pressed") == "true") {
                proj_privacy = jQuery(this).prev().val();
            }
        });
        var json = JSON.stringify({
            name: proj_name,
            goal: proj_goal,
            keywords: proj_keywords,
            privacy: proj_privacy
        });

        jQuery.ajax({
            type: "POST",
            contentType: "application/json",
            url: "/ckservice/projects",
            data: json,
            cache: false,
            dataType: "text",
            success: function(data, status, xhr) {
                window.location.href = xhr.getResponseHeader("Location").replace("/ckservice", "");
            },
            error: function(xhr, status, error) {
                alert(xhr.status + " : " + xhr.statusText);
            }
        });

        return true;
    },


    createProjectFromTemplate: function(templateId) {
        if (!coknown.validateNewProject()) {
            return false;
        }

        var proj_name = jQuery("#proj_name").val();
        var proj_goal = jQuery("#proj_goal").val();
        var proj_keywords = jQuery("#proj_keywords").val();
        var proj_privacy = 1;
        // STUPID STUPID STUPID JQUERY BUTTONSET HANDLER!!!
        // What's wrong with jQuery(":radio:checked").val() ?
        jQuery(".ck_privacy_type").next().each(function() {
            if (jQuery(this).attr("aria-pressed") == "true") {
                proj_privacy = jQuery(this).prev().val();
            }
        });
        var json = JSON.stringify({
            name: proj_name,
            goal: proj_goal,
            keywords: proj_keywords,
            privacy: proj_privacy
        });

        jQuery.ajax({
            type: "POST",
            contentType: "application/json",
            url: "/ckservice/copytemplate/"+templateId+"/",
            data: json,
            cache: false,
            dataType: "text",
            success: function(data, status, xhr) {
                window.location.href = xhr.getResponseHeader("Location").replace("/ckservice", "");
            },
            error: function(xhr, status, error) {
                alert(xhr.status + " : " + xhr.statusText);
            }
        });

        return true;
    },


    retrieveNewProjectAcl: function(url) {
        jQuery.ajax({
            type: "GET",
            contentType: "application/json",
            url: url + "/cosearchers?view=AddCoSearchers",
            data: null,
            cache: false,
            dataType: "text",
            success: function(data, status, xhr) {
                jQuery("#ck_new_project_acl").html(data);
                jQuery("#ck_new_project_container input").attr("disabled", "true");
                jQuery("#ck_create_button").button({disabled: true});
                jQuery(".ck_privacy_type").button({disabled: true});
                jQuery("#ck_new_project_acl").slide();
            },
            error: function(xhr, status, error) {
                alert(xhr.status + " : " + xhr.statusText);
            }
        });
    },

    updateProject: function(trigger, projId, value, title, goal, keywords, oldValue) {
        var id = jQuery(trigger).attr("id");
        if (id == "project_title") {
            title = value;
        } else if (id == "project_goal") {
            goal = value;
        } else if (id == "project_keywords") {
            keywords = value;
        }

        var json = JSON.stringify({
            name: title,
            goal: goal,
            keywords: keywords
        });

        jQuery.ajax({
            type: "PUT",
            contentType: "application/json",
            url: "/ckservice/projects/" + projId + "/",
            data: json,
            cache: false,
            dataType: "text",
            success: function() {},
            error: function(xhr, status, error) {
                jQuery(trigger).html(oldValue);
                alert(xhr.status + " : " + xhr.statusText);
            }
        });
    },

    addCoSearcher: function(trigger, to_userid, projid) {
        var $dialog;
        if (projid == 0)
        {
            var root = jQuery(".cbUserListHeadTitle");
            $dialog = jQuery('<div  style="display: none;"></div>');
            jQuery($dialog).attr("id", "emailDialog");
            jQuery(root).append($dialog);
        }
        else 
        {
            $dialog = jQuery("#emailDialog");
        }
       jQuery.ajax({
            type: "GET",
            url: "/ckservice/emailform/"+to_userid+"/"+projid+"/"+to_userid+"/",
            async: false,
            cache: false,
            dataType: "html",
            success: function(data, status) {
                $dialog.css("position", "fixed");
                $dialog.css("left", (jQuery(window).width() / 2) - 250);
                $dialog.css("top", 200);
                $dialog.css("z-index", "1000000000");
                $dialog.css("display", "block");
                $dialog.html(data);
                jQuery("#project_href").click(function() {return false; });
                jQuery("#submit").click(function() {
                    jQuery("#cancel").click();
                    var message = jQuery("#message").val();
                    var json = JSON.stringify({
                        message: message
                        });
                    jQuery.ajax({
                        type: "POST",
                        url: "/ckservice/cosearcher/add/"+to_userid+"/"+projid+"/",
                        contentType: "application/json",
                        async: false,
                        cache: false,
                        data: json,
                        dataType: "json",
                        success: function(data, status) {
                            if (projid == 0) {
                                var span = jQuery(trigger).parent();
                                jQuery(span).html('<img src="/images/Cosearcher-pending.gif">');
                            }
                        },
                        error: function(xhr, status, error) {
                            alert("Unable to add cosearcher");
                        }
                    });
                });
               jQuery("#cancel").click(function() {
                    if (projid == 0)  $dialog.remove(); 
                    else $dialog.css("display", "none");
               });
            },
            error: function(xhr, status, error) {
                alert("Unable to add cosearcher2");
            }
        });
    },

    setGroupPermission: function(projId, trigger) {
        var permission = trigger.attr("value");
        var group = jQuery(trigger).attr("group");
        var options = jQuery("#cosearchers-" + group + " .cosearcher_option[value='" + permission + "']");
        options.attr("checked", "checked");
        jQuery(".cosearcher_option").button("refresh");
        var users = [];
        options.each(function() {
            users.push("username=" + jQuery(this).attr("username"));
        });
        if (users.length == 0) {
            // XXX(simon): display an alert, or just..
            return;
        }
        var user_string = users.join("&");
        var url = "/ckservice/cosearchers/" + projId + "/" + permission + "/?action=modify&" + user_string;
        jQuery.ajax({
            type: "POST",
            contentType: "application/json",
            url: url,
            data: null,
            cache: false,
            dataType: "text",
            success: function() {
                var data = {};
                jQuery(options).each(function() {
                    var username = jQuery(this).attr("username");
                    var fullname = jQuery(this).attr("fullname");
                    data["id"] = username + "-" + projId;
                    data["username"] = username;
                    data["fullname"] = fullname;
                    data["permissions"] = permission;
                    data["trigger"] = jQuery(trigger);
                    data["group"] = group;
                    jQuery(document).trigger(coknown.PERMISSION_UPDATE_EVENT, data);
                });
            },
            error: function(xhr, status, error) {
                alert(xhr.status + " : " + xhr.statusText);
            }
        });
    },

    savePermissions: function(projId, fullname, username, trigger) {
        var permissions = jQuery(trigger).attr("value");
        var group = jQuery(trigger).attr("group");
        jQuery.ajax({
            type: "POST",
            contentType: "application/json",
            url: "/ckservice/cosearchers/" + projId + "/" + username + "/" + permissions + "/?action=modify",
            data: null,
            cache: false,
            dataType: "text",
            success: function() {
                var data = {};
                data["id"] = username + "-" + projId;
                data["fullname"] = fullname;
                data["username"] = username;
                data["permissions"] = permissions;
                data["trigger"] = jQuery(trigger);
                data["group"] = group;
                jQuery(document).trigger(coknown.PERMISSION_UPDATE_EVENT, data);
            },
            error: function(xhr, status, error) {
                alert(xhr.status + " : " + xhr.statusText);
            }
        });
    },

    getCanonicalPermissionName: function(permission) {
        var result;
        if (permission == coknown.PERMISSIONS["is_blocked"] || permission == coknown.PERMISSIONS["no_access"]) {
            // TODO(simon): red-circle-with-line-through-it image
            result = "none";
        } else if (permission == coknown.PERMISSIONS["has_full"]) {
            result = "full";
        } else if ((permission & coknown.PERMISSIONS["can_delete"]) == coknown.PERMISSIONS["can_delete"]) {
            result = "adddelete";
        } else if ((permission & coknown.PERMISSIONS["can_modify"]) == coknown.PERMISSIONS["can_modify"]) {
            result = "modify";
        } else if ((permission & coknown.PERMISSIONS["can_add"]) == coknown.PERMISSIONS["can_add"]) {
            result = "add";
        } else if ((permission & coknown.PERMISSIONS["can_read"]) == coknown.PERMISSIONS["can_read"]) {
            result = "read";
        }
        return result;
    },

    displayProjectPermission: function(elem, permission) {
        var result;
        var cls = coknown.getCanonicalPermissionName(permission);
        if (permission == coknown.PERMISSIONS["is_blocked"] || permission == coknown.PERMISSIONS["no_access"]) {
            // TODO(simon): red-circle-with-line-through-it image
            result = "None";
        } else if (permission == coknown.PERMISSIONS["has_full"]) {
            result = "F";
        } else if ((permission & coknown.PERMISSIONS["can_delete"]) == coknown.PERMISSIONS["can_delete"]) {
            result = "&plusmn;";
        } else if ((permission & coknown.PERMISSIONS["can_modify"]) == coknown.PERMISSIONS["can_modify"]) {
            result = "M";
        } else if ((permission & coknown.PERMISSIONS["can_add"]) == coknown.PERMISSIONS["can_add"]) {
            result = "+";
        } else if ((permission & coknown.PERMISSIONS["can_read"]) == coknown.PERMISSIONS["can_read"]) {
            result = "R";
        }
        elem.html('<span class="permission_' + cls + '">' + result + "</span>");
        // TODO(simon): if not element, add one in the right place.
    },

    addPermissionToHeader: function(data) {
        var root = jQuery("#cosearchers_header");

        var link = jQuery("<a></a>");
        link.attr("href", "/my-profile/userprofile/" + data["username"]);
        link.html(data["fullname"]);

        var name_span = jQuery("<span></span>");
        name_span.addClass("cosearchers_name");
        name_span.append(link);

        var perm_span = jQuery("<span></span>");
        perm_span.addClass("cosearchers_permission_list");

        var div = jQuery("<div></div>");
        jQuery(div).attr("id", "cosearcher-" + data["id"]);
        jQuery(div).addClass("cosearcher_info");
        jQuery(div).append(name_span);
        jQuery(div).append(perm_span);

        jQuery(root).append(div);
        coknown.updatePermissionInHeader(data);

        //                var elem = jQuery("#cosearcher-" + data["id"] +
        //                             " .cosearchers_permission_list");
    },

    updatePermissionInHeader: function(data) {
        var elem = jQuery("#cosearcher-" + data["id"] + " .cosearchers_permission_list");
        var perm = data["permissions"];
        if (perm == coknown.PERMISSIONS["is_blocked"] || perm == coknown.PERMISSIONS["no_access"]) {
            elem.parent().hide("highlight", {},
            1000, null);
            return;
        }
        coknown.displayProjectPermission(elem, perm);
        elem.parent().effect("highlight", {},
        1000, null);
    },

    addPermissionToPane: function(index, data, perms) {
        var group = data["group"];
        var username = data["username"];
        var user_id = data["user_id"];
        var fullname = data["fullname"];
        var name = data["name"];
        var email = data["email"];
        var proj_id = data["proj_id"];
        var perm_id = data["id"];
        var perm_value = data["permissions"];
        var avatar_link = data["avatar"];

        var pane = jQuery("#sortable-group-" + group);

        var new_el = jQuery("<div></div>");
        jQuery(new_el).attr("id", "sortid_"+index);
        jQuery(new_el).addClass("cosearchers-row");
        jQuery(new_el).attr("group", group);

        var avatar_el = jQuery("<div></div>");
        jQuery(avatar_el).addClass("ck_avatar");

        var avatar_thumb = jQuery("<img/>");
        jQuery(avatar_thumb).attr("src",
        "/images/comprofiler/" + avatar_link);
        jQuery(avatar_thumb).addClass("thumbnail");
        var avatar_full = jQuery("<img/>");
        jQuery(avatar_full).addClass("fullsize");
        jQuery(avatar_full).attr("src",
        "/images/comprofiler/" + avatar_link);

        var alink = jQuery("<a></a>");
        alink.attr("href", "/my-profile/userprofile/" + data["username"]);
        var avatar_span = jQuery("<span></span>");
        avatar_span.addClass("cosearcher_avatar");
        jQuery(alink).append(avatar_thumb);
        jQuery(alink).append(avatar_full);
        avatar_span.append(alink);
        jQuery(avatar_el).append(avatar_span);

        var link = jQuery("<a></a>");
        link.attr("href", "/my-profile/userprofile/" + data["username"]);
        link.html(data["fullname"]);

        var name_el = jQuery("<div></div>");
        var name_span = jQuery("<span></span>");
        name_span.addClass("cosearcher_name");
        name_span.append(link);
        jQuery(name_el).append(name_span);

        var email_el = jQuery("<div></div>");
        jQuery(email_el).addClass("cosearcher_email");
        var img = jQuery("<img/>");
        img.attr("src", "/research_pages/project_acl/email.png");
        coknown.rollover(img, "/research_pages/project_acl/email.png", "/research_pages/project_acl/email-over.png");
        jQuery(email_el).append(img);
        jQuery(email_el).click(function() {
                coknown.emailForm(user_id, 0, 0);
        });

        if (proj_id != "0"){
        var perms_el = jQuery("<div></div>");
        jQuery(perms_el).attr("id", "cosearcher-options-" + group + "-" + username);

        var permissions = ["no_access", "can_read", "can_add", "can_modify", "can_delete", "has_full"];
        var labels = ["None", "Read", "Add", "Modify", "Delete", "Full"];

        for (var i = 0; i < permissions.length; ++i) {
            var span = jQuery("<span></span>");
            jQuery(span).addClass("cosearcher_permission");

            var value = coknown.PERMISSIONS[permissions[i]];

            var button = jQuery("<input/>");
            jQuery(button).attr("type", "radio");
            jQuery(button).attr("id", group + "-" + perm_id + "-" + value);
            jQuery(button).attr("name", perm_id);
            jQuery(button).attr("value", value);
            jQuery(button).attr("group", group);
            jQuery(button).attr("username", username);
            jQuery(button).attr("fullname", fullname);
            jQuery(button).addClass("cosearcher_option");
            // Will be useful to display how 'dangerous' a permission is.
            //                  jQuery(button).addClass(permissions[i]);
            jQuery(button).click(function() {
                coknown.savePermissions(proj_id, fullname, username, jQuery(this));
            });
            if (value == perm_value) {
                jQuery(button).attr("checked", "checked");
            }

            var label = jQuery("<label></label");
            jQuery(label).attr("for", jQuery(button).attr("id"));
            jQuery(label).html(labels[i]);

            jQuery(span).append(button);
            jQuery(span).append(label);
            jQuery(perms_el).append(span);
        }
        jQuery(perms_el).buttonset();

        var span = jQuery("<span></span>");
        jQuery(span).addClass("cosearcher_permission");
        jQuery(span).addClass("cosearcher_permission_block");
        coknown.addHover(jQuery(span), jQuery("#cosearcher_block_warning"));

        img = jQuery("<img/>");
        img.attr("src", "/images/block.png");
        coknown.rollover(img, "/images/block.png", "/images/block-over.png");
        jQuery(img).attr("id", group + "-" + perm_id + "-" + coknown.PERMISSIONS["is_blocked"]);
        jQuery(img).attr("name", perm_id);
        jQuery(img).attr("value", coknown.PERMISSIONS["is_blocked"]);
        jQuery(img).attr("group", group);
        jQuery(img).click(function() {
            jQuery("#cosearcher_block_warning").dialog("close");
            coknown.savePermissions(proj_id, fullname, username, jQuery(this));
        });

        jQuery(span).append(img);
        jQuery(perms_el).append(span);
        if (group == "blocked") {
            jQuery(span).css("display", "none");
            //                  jQuery(span).html('We need an "unblock" image');
        }
        }

        jQuery(new_el).append(avatar_el);
        jQuery(new_el).append(name_el);
        jQuery(new_el).append(email_el);
        if (proj_id != "0") jQuery(new_el).append(perms_el);
        jQuery(pane).append(new_el);
    },

    updatePermissionInPane: function(data) {
        var perm_value = data["permissions"];
        var trigger = data["trigger"];
        var row = jQuery(trigger).parent().parent().parent();
        var dest;
        if ((perm_value & coknown.PERMISSIONS["is_blocked"]) != 0) {
            // User is blocked; move them to the blocked group/ pane.
            dest = jQuery("#cosearchers-list-blocked");
            jQuery(row).find(".cosearcher_permission_block").css("display", "none");
            jQuery(row).attr("original_group", jQuery(row).attr("group"));
            jQuery(row).attr("group", "blocked");
            jQuery(row).find(".cosearcher_option").attr("group", "blocked");

        } else if (data["group"] == "blocked") {
            // We need to move the user back to their original pane,
            // but we don't yet support groups, so back to ALL they go.
            dest = jQuery("#cosearchers-list-all");
            jQuery(row).attr("group", "all");
            jQuery(row).find(".cosearcher_permission_block").find("img").attr("src", "/images/block.png");
            jQuery(row).find(".cosearcher_permission_block").css("display", "inline");
            jQuery(row).find(".cosearcher_option").attr("group", "all");

        } else {
            // Nothing special to do!
            return;
        }

        jQuery(row).hide("slide", {
            direction: "up"
        },
        1000, function() {
            jQuery(row).appendTo(jQuery(dest));
            jQuery(row).show("slide", {
                direction: "up"
            },
            1000, null);
            jQuery(dest).parent().prev().effect("highlight", {},
            1000, null);
        });
    },

    setProjectPrivacy: function(trigger, projId, newPrivacy) {
        jQuery.ajax({
            type: "POST",
            contentType: "application/json",
            url: "/ckservice/project/privacy/" + projId + "/" + newPrivacy + "/?action=modify",
            data: {},
            cache: false,
            dataType: "json",
            success: function(response, status) {
                var data = {
                    "trigger": trigger,
                    "projId": projId,
                    "privacy": response
                };
                jQuery(trigger).attr("privacy", newPrivacy);
                jQuery(document).trigger(coknown.PRIVACY_UPDATE_EVENT, data);
                window.location.reload();
            },
            error: function(xhr, status, error) {
                alert(xhr.status + " " + xhr.statusText);
            }
        });
    },

    showHelpPopup: function(projId, projPrivacy, turningOnOrOff) {
        if (turningOnOrOff == 'on') 
        {
            if (projPrivacy != 1) // 1 is for PUBLIC
            {
                var response = confirm('Project Privacy is set to Restricted/Hidden. Asking for Help will grant ALL of your CoSearchers ADD Permissions to this Project.');
                if (response != true)
                {
                    return false;
                }
            }
            var $dialog = jQuery("#helpDialog");
            $dialog.css("display", "block");
            var str = '<div id="help_dialog" class = "page_tutorial_box"><span class="help_title">Ask for Help on Your Project<br/></span><br/> ';
                str += '<div id="help_choices" class="help_choices"> <input id="cosearcher" type="radio" name = "radio" value="1" checked="checked"/><label for="cosearcher"> <img src="/research_pages/lifesaver-16.png"/>&nbsp;Ask Your CoSearchers for Help</label>';
                str += '<input id="everyone" type="radio" name = "radio" value="2"/><label for="everyone"> <img src="/research_pages/lifesaver-16.png"/>&nbsp;Ask Everyone for Help</label></div>';
                str += '<div class="help_text">This will email ALL your CoSearchers asking for their help. <br/><b> All Your CoSearchers will be given ADD Permissions. </b><br/> ';
                str += 'Asking Everyone for Help will also add a Help Badge to your Project. </div>';
                str += '<label class="message_label" style="font-weight:bold;">Personal Message:</label><br/><textarea id = "message" class="email_message" cols="60" rows="5"/>';
                str += '<div id="email_row">';
                str += '<div id="email_send"> <input id="submit" type="button" value="Send Emails & Get Help"/></div> ';
                str += '<div id="email_cancel"> <input id="cancel" type="button" value="Cancel"/></div> ';
                str += '</div> ';
                str += '</div> ';
            var div = jQuery(str);
            var helpType = 1;
            $dialog.append(div);
            jQuery('#help_choices').buttonset();
            jQuery("#cosearcher").click(function() {
                helpType = 1;
            });
            jQuery("#everyone").click(function() {
                helpType = 2;
            });
            jQuery("#cancel").click(function() {
                jQuery("#help_dialog").remove();
                $dialog.css("display", "none");
            });
            jQuery("#submit").click(function() {
                var message = jQuery("#message").val();
                coknown.setProjectHelpType(projId, helpType, message); // 1 is for COSEARCHER and 2 is for EVERYONE HELP
                jQuery("#help_dialog").remove();
                $dialog.css("display", "none");
                window.location.reload();
            });
        }
        else {
            var response = confirm('Do you wish to turn off Request Help?');
            if (response != true)
            {
                return false;
            }
            coknown.setProjectHelpType(projId, 0, 'no message'); // 0 is to turn the HELP OFF
            window.location.reload();
        }
        return false;
    },


    setProjectHelpType: function(projId, newHelpType, message) {
        var json = JSON.stringify(message);
        jQuery.ajax({
            type: "POST",
            contentType: "application/json",
            url: "/ckservice/project/help/" + projId + "/" + newHelpType,
            data: json,
            async: false,
            cache: false,
            dataType: "text",
            success: function(response, status) {
            },
            error: function(xhr, status, error) {
                alert(xhr.status + " " + xhr.statusText+" "+error);
            }
        });
        return false;
    },


    rollover: function(elements, normal_img, over_img) {
        jQuery(elements).mouseover(function() {
            jQuery(this).attr("src", over_img);
        });
        jQuery(elements).mouseout(function() {
            jQuery(this).attr("src", normal_img);
        });
        // Pre-load the rollover image for performance.
        var img = new Image();
        img.src = over_img;
    },

    addHover: function(elements, dialog) {
        jQuery(elements).mouseover(function() {
            jQuery(dialog).dialog();
        });
        jQuery(elements).mouseout(function() {
            jQuery(dialog).dialog("close");
        });
    },

    checkInputLimit: function(trigger, max, evt) {
        // method gets triggered BEFORE the new keypress is added to the
        // text box.
        var e = evt;
        var label = jQuery(trigger).parent().find(".ck_char_limit");
        var pattern = new RegExp("[\\s\\S]{0," + (max - 1) + "}", "g");
        var result = jQuery(trigger).attr("value").match(pattern);
        jQuery(trigger).attr("value", result[0]);
        jQuery(label).html("(" + ((max) - (jQuery(trigger).attr("value").length + 1)) + " left)");
    },

    makeMenu: function(container) {
        jQuery(container).find(".menu").find("a").each(function() {
            var href = jQuery(this).attr("href");
            jQuery(this).attr("href", "#");
        });
    }

};


