Index: /main/trunk/greenstone3/web/interfaces/default/js/format_browse.js
===================================================================
--- /main/trunk/greenstone3/web/interfaces/default/js/format_browse.js	(revision 27714)
+++ /main/trunk/greenstone3/web/interfaces/default/js/format_browse.js	(revision 27714)
@@ -0,0 +1,128 @@
+
+console.log("Loading format_browse.js\n");
+
+/* FUNCTIONS FOR FORMAT EDITING */                                                                    
+
+function getFormatStatement()
+{
+    var formatDiv = document.getElementById('formatStatement');
+    var formatStatement = innerXHTML(formatDiv);
+    return formatStatement;
+}
+
+function checkClassifierRadio()
+{
+    var selection = $('input[name="classifiers"]'); //document.quiz.colour;
+
+    for (i=0; i<selection.length; i++)
+
+          if (selection[i].checked == true)
+              return selection[i].value;
+
+    return "this";
+
+}
+
+function updateFormatStatement()
+{
+    var formatStatement = getFormatStatement();
+
+    var thisOrAll = checkClassifierRadio();
+    console.log(thisOrAll);
+    var myurl = document.URL;
+
+    //var collection_name = getSubstring(myurl, "&c", "&");
+    var service_name = getSubstring(myurl, "&s", "&");  
+
+    if(thisOrAll == "all")
+        service_name = "AllClassifierBrowse";
+
+    var classifier_name = null;
+
+    if(service_name == "ClassifierBrowse")
+        classifier_name = getSubstring(myurl, "&cl", "&");
+
+    //var post_url = "http://localhost:8383/greenstone3/dev?a=f&sa=update&c=" + collection_name +"&s=" + service_name;
+    var post_url = host_info.pre_URL + "?a=f&sa=update&c=" + host_info.collection_name +"&s=" + service_name;
+
+    if(classifier_name != null)
+        post_url = post_url + "&cl=" + classifier_name;
+
+    $.post(post_url, {data: formatStatement}, function(data) {
+        //$('.result').innerHTML = data; //html(data);
+    
+        // An error is returned because there is no valid XSLT for a format update action, there probably shouldn't be one so we ignore what the post returns.    
+        console.log("Successfully updated");
+        //console.log(data);
+        }, 'html');
+}
+
+function saveFormatStatement()
+{
+    var formatStatement = getFormatStatement();
+    var thisOrAll = checkClassifierRadio();
+
+    var myurl = document.URL;
+
+    //var collection_name = getSubstring(myurl, "&c", "&");
+    var service_name = getSubstring(myurl, "&s", "&");
+    var classifier_name = null;
+
+    if(thisOrAll == "all")
+        service_name = "AllClassifierBrowse";
+
+    if(service_name == "ClassifierBrowse")
+        classifier_name = getSubstring(myurl, "&cl", "&");
+
+    //var post_url = "http://localhost:8383/greenstone3/dev?a=f&sa=save&c=" + collection_name +"&s=" + service_name;
+    var post_url = host_info.pre_URL + "?a=f&sa=save&c=" + host_info.collection_name +"&s=" + service_name;
+
+    if(classifier_name != null)
+        post_url = post_url + "&cl=" + classifier_name;
+
+    $.post(post_url, {data: formatStatement}, function(data) {
+        // An error is returned because there is no valid XSLT for a format update action, there probably shouldn't be one so we ignore what the post returns.    
+        console.log("Successfully saved");
+        }, 'html');
+}
+
+function find_class(current)
+{
+    var classes = current.className.split(' ');
+    var none = "";
+    for(var i = 0; i < classes.length; i++)
+    {
+        switch(classes[i])
+        {
+            case 'gsf_template':
+              return create_gsf_template(current);
+            default:
+            {
+              console.log("Class not found");
+              return none;
+            }
+        }
+    }
+}
+
+function create_gsf_template(current)
+{
+    // find match text which is an input with class match
+    var match = $(current).find('.match')[0].value;
+    console.log(match);
+    
+    // find mode text which is an input with class mode
+    var mode = $(current).find('.mode')[0].value;
+    console.log(mode);
+
+    // "<gsf:template match=\"classifierNode\" mode=\"horizontal\">"
+    var gsf = "<gsf:template match=\"" + match + "\"";
+    if(mode != "vertical")
+        gsf = gsf + " mode=\"" + mode + "\"";
+    gsf = gsf + ">";
+    
+    return gsf;
+
+}
+
+
Index: /main/trunk/greenstone3/web/interfaces/default/js/format_document.js
===================================================================
--- /main/trunk/greenstone3/web/interfaces/default/js/format_document.js	(revision 27714)
+++ /main/trunk/greenstone3/web/interfaces/default/js/format_document.js	(revision 27714)
@@ -0,0 +1,111 @@
+
+console.log("Loading format_document.js\n");
+
+$(document).ready(function(){
+
+        $('.sectionHeader').click(function () {
+            console.log('section Header click *');
+            getXSLT("sectionHeader");
+            return false; //don't event bubble
+            });
+
+        $('.sectionContainer').click(function () {
+            console.log('section Container click *');
+            getXSLT("sectionContainer");
+            return false; // don't event bubble
+            });
+        });
+
+/* DOCUMENT SPECIFIC FUNCTIONS */
+
+function displayTOC(checkbox)
+{
+    if (checkbox.checked == true)
+    {
+        console.log("Show the TOC!");
+        displaySideBar(true);
+        $("#tableOfContents").css("display", "block");
+    }
+    else
+    {
+        console.log("Hide the TOC!");
+        $("#tableOfContents").css("display", "none");
+        if ($("#coverImage").css("display") == "none")
+            displaySideBar(false);
+    }
+
+    return;
+}
+
+function displayBookCover(checkbox)
+{
+    if (checkbox.checked == true)
+    {
+        console.log("Show the book cover!");
+        displaySideBar(true);
+        $("#coverImage").css("display", "block");
+    }
+    else
+    {
+        console.log("Hide the book cover!");
+        $("#coverImage").css("display", "none");
+        if ($("#tableOfContents").css("display") == "none")
+            displaySideBar(false);
+    }
+
+    return;
+}
+
+function displaySideBar(toggle)
+{
+    if (toggle == true)
+    {
+        console.log("Show the sidebar!");
+        $("#rightSidebar").css("display", "block");
+    }
+    else
+    {
+        console.log("Hide the sidebar!");
+        $("#rightSidebar").css("display", "none");
+    }
+
+    return;
+}
+
+function checkDocumentRadio()
+{
+    var selection = $('input[name="documentChanges"]'); //document.quiz.colour;
+
+    for (i=0; i<selection.length; i++)
+
+        if (selection[i].checked == true)
+            return selection[i].value;
+
+    return "this";
+}
+
+function saveDocumentChanges()
+{
+    console.log("Saving changes to "+checkDocumentRadio());
+    console.log("TOC="+$('input[name="TOC"]').attr('checked'));
+    console.log("Cover Image="+$('input[name="bookCover"]').attr('checked'));
+
+    var myurl = document.URL;
+
+    //var collection_name = getSubstring(myurl, "&c", "&");
+    var document_id = getSubstring(myurl, "&d", "&");
+    var document_type = getSubstring(myurl, "&dt", "&");
+    var prev_action = getSubstring(myurl, "&p.a", "&");
+    var prev_service = getSubstring(myurl, "&p.s", "&");
+
+    //var post_url = "http://localhost:8383/greenstone3/dev?a=f&sa=saveDocument&c=" + collection_name + "&d=" + document_id + "&dt=" + document_type + "&p.a=" + prev_action + "&p.s=" + prev_service;
+    var post_url = host_info.pre_URL + "?a=f&sa=saveDocument&c=" + host_info.collection_name + "&d=" + document_id + "&dt=" + document_type + "&p.a=" + prev_action + "&p.s=" + prev_service;
+
+    // XML will be automatically wrapped in <display><format> tags when saved to collection config
+    var xml = '<format><gsf:option name="TOC" value="'+$('input[name="TOC"]').attr('checked')+'"/><gsf:option name="coverImage" value="'+$('input[name="bookCover"]').attr('checked')+'"/></format>';
+
+    $.post(post_url, {data: xml}, function(data) {
+            console.log("Success, we have received data");
+    }, 'xml');
+}
+
Index: /main/trunk/greenstone3/web/interfaces/default/js/format_jquery_prototypes.js
===================================================================
--- /main/trunk/greenstone3/web/interfaces/default/js/format_jquery_prototypes.js	(revision 27714)
+++ /main/trunk/greenstone3/web/interfaces/default/js/format_jquery_prototypes.js	(revision 27714)
@@ -0,0 +1,337 @@
+
+console.log("Loading format_jquery_prototypes.js\n");
+
+$(document).ready(function()
+{
+    /*
+    var collection = "";
+    
+    var regex = new RegExp("[?&]c=");
+    var matches = regex.exec(document.URL);
+    if(matches != null)
+    {
+        var startIndex = matches.index;
+        var endIndex = document.URL.indexOf("&", startIndex + 1);
+        
+        if(endIndex == -1)
+        {
+            endIndex = document.URL.length;
+        }
+        
+        collection = document.URL.substring(startIndex, endIndex);
+    }
+    */
+
+    //Retrieve the collection metadataset using ajax
+    $.ajax
+    ({
+        type: "GET",
+        url: "?a=g&s=CoverageMetadataRetrieve&o=xml&rt=r&c=" + host_info.collection_name,
+        success: function(data) 
+        {
+            var str = "<select name=\"meta_select\" onChange=\"onSelectChange(this)\">";
+            
+            var selectorArea = document.getElementById("metadataSelector");     
+            var metadataSets = data.getElementsByTagName("metadataSet");
+            for(var i = 0; i < metadataSets.length; i++)
+            {
+                var metadata = metadataSets[i].getElementsByTagName("metadata");
+                for(var j = 0; j < metadata.length; j++)
+                {
+                    var metaValue = metadataSets[i].getAttribute("name") + "." + metadata[j].getAttribute("name");
+                    str += "<option value=\"" + metaValue + "\">" + metaValue + "</option>";
+                }
+            }
+            
+            str += "</select>";
+
+            selectorArea.innerHTML = str;
+            gsf_metadata_element =  "<div class=\"gsf_metadata css_gsf_metadata block leaf\" title=\"gsf:metadata\"><table class=\"header\"><tbody><tr><td class=\"header\">" + str + "</td><td class=\"header\"><a href=\"#\" class=\"remove ui-icon ui-icon-closethick\" title=\"Click me to remove\"/></td></tr></tbody></table></div>";
+            //console.log("Metadata element from ajax: " + gsf_metadata_element);
+        }
+    });
+
+    $.ui.draggable.prototype._createHelper = function(event) {
+        var o = this.options;
+        var helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event])) : (o.helper == 'clone' ? this.element.clone().removeAttr('id') : this.element);
+
+        var select = $(this.element).find('select');
+        var value = select.attr('value');
+        console.log("Found "+value+" in helper");
+        CURRENT_SELECT_VALUE = value;
+        helper.find('select').attr('value', value);
+
+        if(!helper.parents('body').length)
+            helper.appendTo((o.appendTo == 'parent' ? this.element[0].parentNode : o.appendTo));
+
+        if(helper[0] != this.element[0] && !(/(fixed|absolute)/).test(helper.css("position")))
+            helper.css("position", "absolute");
+
+        return helper;
+
+    };
+    
+    $.ui.sortable.prototype._removeCurrentsFromItems = function() {
+        //console.log("IN _removeCurrentsFromItems FUNCTION");
+        //console.log("this = " + this.currentItem[0].getAttribute('class'));
+        var list = this.currentItem.find(":data(sortable-item)");
+
+        var i = 0;
+        while (i<this.items.length) {
+            var found_match = false;
+            for (var j=0; j<list.length; j++) {
+                if(this.items[i])
+                {
+                    if(list[j] == this.items[i].item[0]) {
+                        //console.log("Item to splice = " + this.items[i].item[0].getAttribute('class'));
+                        this.items.splice(i,1);
+                        found_match = true;
+                        break;
+                    }
+                }
+            };
+            if (!found_match)
+                i++;
+            else
+                break;
+        }
+    };
+    
+    $.ui.plugin.add("draggable", "connectToSortable", {
+        start: function(event, ui) {
+            //console.log("FUNCTION start draggable connectToSortable");
+            var inst = $(this).data("draggable"), o = inst.options, uiSortable = $.extend({}, ui, { item: inst.element });
+            inst.sortables = [];
+            $(o.connectToSortable).each(function() {
+                var sortable = $.data(this, 'sortable');
+                if (sortable && !sortable.options.disabled) {
+                    inst.sortables.push({instance: sortable, shouldRevert: sortable.options.revert});
+                    sortable._refreshItems();   //Do a one-time refresh at start to refresh the containerCache
+                    sortable._trigger("activate", event, uiSortable);
+                }   
+            });
+
+        },
+        stop: function(event, ui) {
+
+            //console.log("FUNCTION stop draggable connectToSortable");
+            //If we are still over the sortable, we fake the stop event of the sortable, but also remove helper
+            var inst = $(this).data("draggable"),
+            uiSortable = $.extend({}, ui, { item: inst.element });
+
+            $.each(inst.sortables, function() {
+                if(this.instance.isOver) {
+
+                    this.instance.isOver = 0;
+
+                    inst.cancelHelperRemoval = true; //Don't remove the helper in the draggable instance
+                    this.instance.cancelHelperRemoval = false; //Remove it in the sortable instance (so sortable plugins like revert still work)
+
+                    //The sortable revert is supported, and we have to set a temporary dropped variable on the draggable to support revert: 'valid/invalid'
+                    if(this.shouldRevert) this.instance.options.revert = true;
+
+                    //Trigger the stop of the sortable
+                    //console.log("Draggable tells sortable to stop");
+                    this.instance._mouseStop(event);
+
+                    this.instance.options.helper = this.instance.options._helper;
+
+                    //If the helper has been the original item, restore properties in the sortable
+                    if(inst.options.helper == 'original')
+                        this.instance.currentItem.css({ top: 'auto', left: 'auto' });
+
+                } else {
+                    this.instance.cancelHelperRemoval = false; //Remove the helper in the sortable instance
+                    this.instance._trigger("deactivate", event, uiSortable);
+                }
+            });
+
+        },
+        drag: function(event, ui) {
+            //console.log("FUNCTION drag draggable connectToSortable");
+
+            var inst = $(this).data("draggable"), self = this;
+
+            var checkPos = function(o) {
+                var dyClick = this.offset.click.top, dxClick = this.offset.click.left;
+                var helperTop = this.positionAbs.top, helperLeft = this.positionAbs.left;
+                var itemHeight = o.height, itemWidth = o.width;
+                var itemTop = o.top, itemLeft = o.left;
+
+                return $.ui.isOver(helperTop + dyClick, helperLeft + dxClick, itemTop, itemLeft, itemHeight, itemWidth);
+            };
+
+            var intersecting_items = new Array();
+
+            $.each(inst.sortables, function(i) {
+            
+                //Copy over some variables to allow calling the sortable's native _intersectsWith
+                this.instance.positionAbs = inst.positionAbs;
+                this.instance.helperProportions = inst.helperProportions;
+                this.instance.offset.click = inst.offset.click;
+            
+                if(this.instance._intersectsWith(this.instance.containerCache)) {
+
+                    //If it intersects, we use a little isOver variable and set it once, so our move-in stuff gets fired only once
+                    //if(!this.instance.isOver) {
+
+                    //console.log('Line 1113');
+
+                    //  this.instance.isOver = 1;
+
+                    intersecting_items.push(this.instance); // sam
+                    //} //sam
+
+                    //Now we fake the start of dragging for the sortable instance,
+                    //by cloning the list group item, appending it to the sortable and using it as inst.currentItem
+                    //We can then fire the start event of the sortable with our passed browser event, and our own helper (so it doesn't create a new one)
+                    //sam this.instance.currentItem = $(self).clone().appendTo(this.instance.element).data("sortable-item", true);
+                    //sam this.instance.options._helper = this.instance.options.helper; //Store helper option to later restore it
+                    //sam this.instance.options.helper = function() { return ui.helper[0]; };
+
+                    //sam event.target = this.instance.currentItem[0];
+                    //sam this.instance._mouseCapture(event, true);
+                    //sam this.instance._mouseStart(event, true, true);
+
+                    //Because the browser event is way off the new appended portlet, we modify a couple of variables to reflect the changes
+                    //sam this.instance.offset.click.top = inst.offset.click.top;
+                    //sam this.instance.offset.click.left = inst.offset.click.left;
+                    //sam this.instance.offset.parent.left -= inst.offset.parent.left - this.instance.offset.parent.left;
+                    //sam this.instance.offset.parent.top -= inst.offset.parent.top - this.instance.offset.parent.top;
+
+                    //sam inst._trigger("toSortable", event);
+                    //sam inst.dropped = this.instance.element; //draggable revert needs that
+                    //hack so receive/update callbacks work (mostly)
+                    //sam inst.currentItem = inst.element;
+                    //sam this.instance.fromOutside = inst;
+
+                //sam brace
+
+                //Provided we did all the previous steps, we can fire the drag event of the sortable on every draggable drag, when it intersects with the sortable
+                //sam if(this.instance.currentItem) this.instance._mouseDrag(event);
+
+                } else {
+
+                    //If it doesn't intersect with the sortable, and it intersected before,
+                    //we fake the drag stop of the sortable, but make sure it doesn't remove the helper by using cancelHelperRemoval
+                    if(this.instance.isOver) {
+
+                        console.log("UNSETTING ISOVER");
+                        console.log("ON ITEM="+this.instance.currentItem[0].getAttribute('class'))
+                        this.instance.isOver = 0;
+                        this.instance.cancelHelperRemoval = true;
+                    
+                        //Prevent reverting on this forced stop
+                        this.instance.options.revert = false;
+                    
+                        // The out event needs to be triggered independently
+                        this.instance._trigger('out', event, this.instance._uiHash(this.instance));
+                    
+                        this.instance._mouseStop(event, true);
+                        this.instance.options.helper = this.instance.options._helper;
+
+                        //Now we remove our currentItem, the list group clone again, and the placeholder, and animate the helper back to it's original size
+                        //console.log("DO WE GET HERE?");
+                        this.instance.currentItem.remove();
+                        if(this.instance.placeholder) this.instance.placeholder.remove();
+
+                        inst._trigger("fromSortable", event);
+                        inst.dropped = false; //draggable revert needs that
+                
+                    }
+                } 
+            });
+
+            //sam
+            //console.log("Contents of intersecting_items");
+            var innermostContainer = null, innermostIndex = null;       
+            for (i=0;i<intersecting_items.length;i++)
+            {
+                //console.log('ITEM: '+intersecting_items[i].element[0].getAttribute('class'));
+    
+                if(innermostContainer && $.ui.contains(intersecting_items[i].element[0], innermostContainer.element[0]))
+                    continue;
+                        
+                innermostContainer = intersecting_items[i];
+                innermostIndex = i; 
+            }
+
+            for (i=0;i<intersecting_items.length;i++)
+            {
+                if(intersecting_items[i] != innermostContainer)
+                    if(intersecting_items[i].isOver) {
+
+                        console.log("UNSETTING ISOVER");
+                        console.log("ON ITEM="+intersecting_items[i].currentItem[0].getAttribute('class'))
+                        intersecting_items[i].isOver = 0;
+                        intersecting_items[i].cancelHelperRemoval = true;
+
+                        //Prevent reverting on this forced stop
+                        intersecting_items[i].options.revert = false;
+
+                        // The out event needs to be triggered independently
+                        intersecting_items[i]._trigger('out', event, intersecting_items[i]._uiHash(intersecting_items[i]));
+
+                        intersecting_items[i]._mouseStop(event, true);
+                        intersecting_items[i].options.helper = intersecting_items[i].options._helper;
+
+                        //Now we remove our currentItem, the list group clone again, and the placeholder, and animate the helper back to it's original size
+                        //console.log("DO WE GET HERE?");
+                        if(intersecting_items[i].currentItem) intersecting_items[i].currentItem.remove();
+                        if(intersecting_items[i].placeholder) intersecting_items[i].placeholder.remove();
+
+                        inst._trigger("fromSortable", event);
+                        inst.dropped = false; //draggable revert needs that
+                    }
+
+                    intersecting_items[i].isOver = 0;
+            }
+
+            if(innermostContainer && !innermostContainer.isOver)
+            {
+                console.log("INNER="+innermostContainer.element[0].getAttribute('class'));
+                console.log("SETTING ISOVER");
+                innermostContainer.isOver = 1;
+
+                //Now we fake the start of dragging for the sortable instance,
+                //by cloning the list group item, appending it to the sortable and using it as inst.currentItem
+                //We can then fire the start event of the sortable with our passed browser event, and our own helper (so it doesn't create a new one)
+
+                if(innermostContainer.currentItem) innermostContainer.currentItem.remove();
+                if(innermostContainer.placeholder) innermostContainer.placeholder.remove();
+
+                innermostContainer.currentItem = $(self).clone().appendTo(innermostContainer.element).data("sortable-item", true);
+            
+                innermostContainer.options._helper = innermostContainer.options.helper; //Store helper option to later restore it
+                innermostContainer.options.helper = function() { return ui.helper[0]; };
+
+                console.log("EVENT TARGET="+innermostContainer.currentItem[0].getAttribute('class'));
+                event.target = innermostContainer.currentItem[0];
+                innermostContainer._mouseCapture(event, true);
+                innermostContainer._mouseStart(event, true, true);
+
+                //Because the browser event is way off the new appended portlet, we modify a couple of variables to reflect the changes
+                innermostContainer.offset.click.top = inst.offset.click.top;
+                innermostContainer.offset.click.left = inst.offset.click.left;
+                innermostContainer.offset.parent.left -= inst.offset.parent.left - innermostContainer.offset.parent.left;
+                innermostContainer.offset.parent.top -= inst.offset.parent.top - innermostContainer.offset.parent.top;
+
+                inst._trigger("toSortable", event);
+                inst.dropped = innermostContainer.element; //draggable revert needs that
+                //hack so receive/update callbacks work (mostly)
+                inst.currentItem = inst.element;
+                innermostContainer.fromOutside = inst;
+
+                //sam brace
+            }
+
+            if(innermostContainer)
+            {
+                //Provided we did all the previous steps, we can fire the drag event of the sortable on every draggable drag, when it intersects with the sortable
+                if(innermostContainer.currentItem) innermostContainer._mouseDrag(event);
+            }
+
+              }
+    });
+
+});
Index: /main/trunk/greenstone3/web/interfaces/default/js/format_util.js
===================================================================
--- /main/trunk/greenstone3/web/interfaces/default/js/format_util.js	(revision 27714)
+++ /main/trunk/greenstone3/web/interfaces/default/js/format_util.js	(revision 27714)
@@ -0,0 +1,761 @@
+
+console.log("Loading format_util.js\n");
+
+/* Ensures that a change to a text field is remembered */
+function onTextChange(item, text)
+{
+    console.log("I have set "+item+".value to "+text);
+    item.setAttribute("value",text);
+}
+
+/* Ensures that a change to a select field is remembered */
+function onSelectChange(item)
+{
+    console.log("I have set "+item.value+".selected to selected");
+    for (var i=0; i<item.options.length; i++)
+    {
+        if(item.selectedIndex == i)
+            item.options[i].setAttribute("selected", "selected");
+        else
+            item.options[i].removeAttribute("selected");
+    }
+    //item.options[item.selectedIndex].selected = "selected";
+    //item.setAttribute("selected","selected");
+}
+
+
+/* Get substring */
+function getSubstring(str, first, last)
+{
+    var first_index = str.indexOf(first)+first.length+1;
+    var last_index = str.indexOf(last, first_index);
+
+    if(last_index == -1)
+        last_index = str.length;
+
+    var substring = str.substring(first_index, last_index);
+
+    return substring;
+}
+    
+function getXSLT(classname)
+{
+    console.log("*** Function getXSLT ***");
+    var myurl = document.URL;
+
+    var document_id = getSubstring(myurl, "&d", "&");
+    var document_type = getSubstring(myurl, "&dt", "&");
+
+    var post_url = host_info.pre_URL +"?a=d&c=" + host_info.collection_name + "&d=" + document_id + "&dt=" + document_type + "&o=skinandlib";
+
+    $.post(post_url, function(data) {
+            console.log("Success, we have received the XSLT for the relevant page part");
+            classname = "." + classname;
+            /* There seemed to be a problem with MIME types for the data received from the post. */ 
+            /* The best fix for now is to set the data type to text and then reparse as xml */
+            xml = $.parseXML(data);
+            var content = $( xml ).find(classname);
+            /* The xml() function is provided by jquery.xml.js (included by formatmanager.xsl) */
+            $("#XSLTcode").val(content.xml());
+            }, 'text');
+}
+
+function traverse(node, formatstring)
+{
+
+    if(node.nodeName=='DIV')
+    {
+        console.log("Found a div" +node.nodeName+","+node.nodeType);
+        formatstring = formatstring + find_class(node);
+        console.log(formatstring);
+    }
+
+    var children = $(node).children();
+    for(var i=0; i < children.length; i++)
+        formatstring = formatstring + traverse(children[i], formatstring);
+
+    return formatstring;
+}
+        
+
+/*
+$("#iframe").ready(function(){
+        console.log("iframe is ready ...");
+        var iframe = document.getElementById('iframe');
+        var iframe_document = iframe.document;
+
+        if(iframe.contentDocument)
+        {
+            iframe_document = iframe.contentDocument; // For NS6
+            console.log("Chose content document");
+        }
+        else if(iframe.contentWindow)
+        {
+            iframe_document = iframe.contentWindow.document; // For IE5.5 and IE6
+            console.log("Chose content window");
+        }
+
+        console.log(iframe_document.documentElement.innerHTML); //document.documentElement.outerHTML
+
+        $(iframe_document.documentElement.innerHTML).find('a').each(function() {
+            console.log("data "+$(this).data('href'));
+            console.log("getAttribute "+$(this).getAttribute('href'));
+            console.log("attr "+$(this).attr('href'));
+            console.log("this.href "+this.href);
+            var original = this.href; //$(this).attr('href');
+            // check if greenstone link ie. starts with format
+            //var original = $(this).data('href');
+            var modified = original.toString().concat("&excerptid=gs_content");
+            console.log(modified);
+            this.href = modified;
+            //$(this).attr('href',modified);
+            //$(this).data('href', modified);
+            //console.log($(this).attr('href'));
+            console.log("data "+$(this).data('href'));
+            console.log("getAttribute "+$(this).getAttribute('href'));
+            console.log("attr "+$(this).attr('href'));
+            console.log("this.href "+this.href);
+            console.log("**********");
+
+        });
+}); */
+/*
+function loadXMLDoc()
+{
+    if (window.XMLHttpRequest)
+    {// code for IE7+, Firefox, Chrome, Opera, Safari
+        xmlhttp=new XMLHttpRequest();
+    }
+    else
+    {// code for IE6, IE5
+        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
+    }
+    
+    xmlhttp.onreadystatechange=function()
+    {  
+        console.log("state changed to " + xmlhttp.readyState);
+        console.log("status is " + xmlhttp.status);
+        if (xmlhttp.readyState==4 && xmlhttp.status==200)
+        {
+            console.log("get code");
+            console.log(xmlhttp.responseText);
+            document.getElementById("gs_content").innerHTML=xmlhttp.responseText;
+        }
+    }
+    
+    xmlhttp.open("GET","http://localhost:8080/greenstone3/format?a=b&rt=s&s=ClassifierBrowse&c=simpleht&cl=CL1&excerptid=gs_content",true);
+    //xmlhttp.open("GET","http://www.cs.waikato.ac.nz",true);
+    //xmlhttp.open("GET","http://wand.net.nz/~sjb48/index.html",true);
+    xmlhttp.send();
+}
+*/
+$(document).ready(function(){
+
+    console.log("Document ready function\n");
+	
+    CURRENT_SELECT_VALUE = ""; //global - gets set by ui.draggable
+
+    var r = /(https?:\/\/)?([\da-z\.-]+):(\d+)\/([\da-z]+)\/([\da-z]+)\?.*&c=([\da-z\.-]+).*/;
+    var s = document.URL;
+    s.match(r);
+    //var matches = regex.exec(document.URL);
+    /* Host info needs to be globally available */
+    host_info = new Object();
+    console.log("Hostname: " + RegExp.$2);
+    host_info.host_name = RegExp.$2;
+    console.log("Port: " + RegExp.$3);
+    host_info.port = RegExp.$3;
+    console.log("Library: " + RegExp.$4);
+    host_info.library = RegExp.$4;
+    console.log("Servlet: " + RegExp.$5);
+    host_info.servlet = RegExp.$5;
+    console.log("Collection: " + RegExp.$6);
+    host_info.collection_name = RegExp.$6;
+
+    host_info.pre_URL = "http://" + host_info.host_name + ":" + host_info.port + "/" + host_info.library + "/" + host_info.servlet;
+    console.log("Pre URL: " + host_info.pre_URL);
+
+    /*
+    var iframe = document.getElementById('iframe');
+    var iframe_document = iframe.document;
+   
+    if(iframe.contentDocument)
+    {
+        iframe_document = iframe.contentDocument; // For NS6
+        console.log("Chose content document");
+    }
+    else if(iframe.contentWindow)
+    {
+        iframe_document = iframe.contentWindow.document; // For IE5.5 and IE6
+        console.log("Chose content window");
+    }
+
+    // Edit the hrefs in preview_html - search for <a href="format?a=b&rt=r&s=ClassifierBrowse&c=simpleht&cl=CL1.2">
+    var start_index = 0;
+    var end_index = 0;
+    while(start_index != -1)
+    {
+        start_index = preview_html.indexOf("href=\"format", start_index);
+        console.log("start index = " + start_index);
+        if(start_index != -1)
+        {
+            end_index = preview_html.indexOf("\">", start_index);
+            console.log("end_index = " + end_index);
+            a = preview_html.substring(0,end_index);
+            b = preview_html.substring(end_index);
+            preview_html = a.concat("&excerptid=results", b);
+            console.log(preview_html);
+            start_index = end_index + "&excerptid=results\">".length;
+        }
+    }
+
+    // Split the html code in to three parts
+    var first_index = preview_html.indexOf("<ul id=\"results\"");
+    console.log("First index is "+first_index);
+    var second_index = preview_html.indexOf("</ul>", first_index) + "</ul>".length;
+    console.log("Second index is "+second_index);
+
+    var first_half = preview_html.substring(0, first_index);
+    var iframe_code = preview_html.substring(first_index, second_index);
+    var second_half = preview_html.substring(second_index);
+
+    //$('#my_categories').innerHTML = first_half.concat(second_half);
+    document.getElementById("my_categories").innerHTML = first_half.concat(second_half);
+
+    // Put the content in the iframe
+    if(initialised_iframe == "false")
+    {
+        console.log("Initialised iframe with preview html");
+        console.log(preview_html);
+        iframe_document.open();
+        iframe_document.writeln(iframe_code); //.concat("&excerptid=gs_content"));
+        iframe_document.close(); 
+        initialised_iframe = "true";
+    }
+    */
+
+    /*    
+    $(iframe_document.documentElement.innerHTML).find('a').each(function() {
+            console.log("data "+$(this).data('href'));
+            console.log("getAttribute "+this.getAttribute('href'));
+            console.log("attr "+$(this).attr('href'));
+            console.log("this.href "+this.href);
+            var original = this.href; //$(this).attr('href');
+            // check if greenstone link ie. starts with format
+            //var original = $(this).data('href');
+            var modified = original.toString().concat("&excerptid=gs_content");
+            console.log("*                      *");
+            console.log(modified);
+            console.log("*                      *");
+            //this.href = modified;
+            //$(this).attr('href',modified);
+            //$(this).data('href', modified);
+            $(this).attr({ 'href': modified });
+            //console.log($(this).attr('href'));
+            console.log("data "+$(this).data('href'));
+            console.log("getAttribute "+this.getAttribute('href'));
+            console.log("attr "+$(this).attr('href'));
+            console.log("this.href "+this.href);
+            console.log("***********************");
+    });
+    */
+
+    /******************************************/
+    /*              DRAGGABLES                */
+    /******************************************/
+
+    $(".draggable_gsf_template").draggable({
+            cursor: 'crosshair',
+            connectToSortable: '#formatStatement',
+            helper: 'clone',
+            revert: 'invalid'
+    });
+
+    $(".draggable_table").draggable({
+            cursor: 'crosshair',
+            connectToSortable: '.gsf_template',
+            helper: 'clone',
+            revert: 'invalid'
+    });
+
+    $(".draggable_tr").draggable({
+            cursor: 'crosshair',
+            connectToSortable: '.gsf_table',
+            helper: 'clone',
+            revert: 'invalid'
+    })
+
+    $(".draggable_td").draggable({
+            cursor: 'crosshair',
+            //connectToSortable: '.td',
+            helper: 'clone',
+            revert: 'invalid'
+    })
+
+    $(".draggable_gsf_text").draggable({
+            cursor: 'crosshair',
+            connectToSortable: '.td-div, .gsf_when, .gsf_otherwise, .gsf_link, .gsf_choose_metadata, .gsf_default',
+            helper: 'clone',
+            revert: 'invalid'
+    });
+    
+    $(".draggable_gsf_choose_metadata").draggable({
+            cursor: 'crosshair',
+            connectToSortable: '.td-div, .gsf_link, .gsf_when, .gsf_otherwise',
+            helper: 'clone',
+            revert: 'invalid'
+    });
+
+    //$(".element_type_gsf_metadata").draggable({
+    $(".draggable_gsf_metadata").draggable({
+            cursor: 'crosshair',
+            connectToSortable: '.gsf_choose_metadata, .gsf_when, .gsf_otherwise, .gsf_link, .td-div',
+            helper: 'clone',
+            revert: 'invalid'
+            
+    });
+
+    $(".draggable_gsf_link").draggable({
+            cursor: 'crosshair',
+            connectToSortable: '.td-div, .gsf_when, .gsf_otherwise, .gsf_link',
+            helper: 'clone',
+            revert: 'invalid'
+    });
+
+    // switch, when, otherwise, icon
+    $(".draggable_gsf_switch").draggable({
+            cursor: 'crosshair',
+            connectToSortable: '.td-div, .gsf_link',
+            helper: 'clone',
+            revert: 'invalid'
+    });
+
+    $(".draggable_gsf_when").draggable({
+            cursor: 'crosshair',
+            connectToSortable: '.gsf_switch',
+            helper: 'clone',
+            revert: 'invalid'
+    });
+
+    $(".draggable_gsf_otherwise").draggable({
+            cursor: 'crosshair',
+            connectToSortable: '.gsf_switch',
+            helper: 'clone',
+            revert: 'invalid'
+    });
+
+    $(".draggable_gsf_icon").draggable({
+            cursor: 'crosshair',
+            connectToSortable: '.td-div, .gsf_link, .gsf_choose, .gsf_when, .gsf_otherwise',
+            helper: 'clone',
+            revert: 'invalid'
+    });
+
+ 
+    /******************************************/
+    /*               SORTABLES                */
+    /******************************************/
+
+    bind_td_sortable();
+    bind_all_sortables();
+
+    $('#formatStatement').sortable({
+            cursor: 'pointer',
+            tolerance: 'pointer',
+            items: '.gsf_template',
+            placeholder:'placeholder',
+            //'nested':'div'
+            stop: function(event, ui) {
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('css_gsf_template')) { replace_with(ui.item,gsf_template_element); }
+            }
+    });
+
+    $(".draggable_gsf_metadata").each(function(){
+        this.onselectstart = function() { return false; };
+    });
+ 
+    $('div.gsf_template').children(".block,.table").slideUp(300); 
+}); 
+
+/*******************************************************************************/
+
+function bind_all_sortables()
+{
+    console.log('function bind_all_sortables()');
+    bind_template_sortable();
+    bind_choose_metadata_sortable();
+    bind_link_sortable();
+    bind_switch_sortable();
+    bind_when_sortable();
+    bind_otherwise_sortable();
+
+    bind_tables();
+
+    bind_block_mouseover();
+    bind_minmax_remove();    
+}
+
+function bind_tables()
+{
+    console.log('function bind_tables()');
+
+    $('#sectionHeader').click(function () {
+         console.log('section Header click *');
+         return true;
+    });
+    
+    $('#sectionContainer').click(function () {
+         console.log('section Container click *');
+         return true;
+    });
+
+    $(".td-div").resizable({
+                alsoResize: 'parent',
+                handles: 'w,e',
+                stop: function(event, ui) {
+                        console.log('Resize table on stop');
+                        resize_tables($(this));
+                }, });
+
+    $(".droppable").droppable({
+            accept: '.element_type_td',
+            tolerance: 'pointer', 
+            activate: function(event, ui) { $(this).addClass("droppable_hl");}, 
+            deactivate: function(event, ui) { $(this).removeClass("droppable_hl"); },
+            drop: function(event, ui) {
+                 var neverempty = document.createElement("div");
+                 neverempty.setAttribute("class","neverempty block");
+                 neverempty.setAttribute("style","height:50px");
+                 neverempty.setAttribute("style","display:block");
+                 var text = document.createTextNode('NEVER EMPTY');
+                 neverempty.appendChild(text);
+                 var td = document.createElement("td");
+                 var div = document.createElement("div"); 
+                 div.setAttribute("title","td-div");
+                 div.setAttribute("class","td-div block");
+                 div.setAttribute("style","margin-left:0px");
+                 div.setAttribute("width","25px");
+                 td.appendChild(div);
+                 div.appendChild(neverempty);
+                 var sep = document.createElement("td");
+                 sep.setAttribute("class","droppable");
+                 sep.setAttribute("width","10px"); 
+                 $(this).after(sep);                
+                 $(this).after(td);                
+                 bind_tables();
+                 resize_tables($(this));
+                 bind_td_sortable();
+                 bind_block_mouseover();
+            }
+        });
+
+}
+
+function replace_with(item, me)
+{
+    // Search me for select
+    console.log("ME is "+me);
+    if(me.search("select") != -1)
+    {
+        console.log("ME is "+me);
+        // If select exists, then find CURRENT_SELECT_VALUE
+        if(me.search(CURRENT_SELECT_VALUE) != -1)
+        {
+            var index = me.search("\""+CURRENT_SELECT_VALUE+"\"");
+            if(index == -1)
+                console.log("Did not find " + CURRENT_SELECT_VALUE);
+            else
+            {
+                console.log("Found " + CURRENT_SELECT_VALUE + " at index " + index);    
+                index = index + CURRENT_SELECT_VALUE.length + 2;
+                console.log("Attempt inserting select at new index "+index);
+                a = me.substring(0,index);
+                b = me.substring(index);
+                me = a.concat(" selected",b);
+            }
+        }
+    }
+    
+    console.log("Replacing "+item+" with "+me);
+
+    item.replaceWith(me); //'<div class="element element-txt">This text box has been added!</div>');
+
+    resize_tables(item);
+
+    bind_all_sortables();
+}
+
+function resize_tables(item)
+{
+    var max_height = 0;
+    (item.parents('.table')).each(function(index) {
+        $(this).children().children().children().each(function() {
+            var sum_one = 0;
+            var sum_two = 0;
+            $(this).children('.block').each(function() { sum_one = sum_one + $(this).height();  
+                $(this).children('.block').each(function() { sum_two = sum_two + $(this).height(); } );
+                console.log("My height is " + $(this).height() + ", sum height 2 is " + sum_two);
+            });
+            console.log("My height is " + $(this).height() + ", sum height 1 is " + sum_one);
+            if (sum_two > max_height)
+                max_height = sum_two;
+        });
+    });
+    equalHeights(item,max_height);
+}
+
+function bind_template_sortable()
+{
+    //console.log('function bind_template_sortable()');
+    $('.gsf_template').sortable({
+            'cursor':'pointer',
+            'tolerance': 'pointer',
+            'items':'.table', //.gsf_choose_metadata, .gsf_metadata',
+            'placeholder':'placeholder',
+            //'nested':'.gsf:metadata'
+            receive: function(event, ui) { alert("template attempted to receive"); },
+            stop: function(event, ui) {
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_table')) { replace_with(ui.item, "<table class=\"table\" border=\"2\"></table>"); }
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_choose_metadata')) { replace_with(ui.item, gsf_choose_metadata_element); }
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_metadata')) { replace_with(ui.item, gsf_metadata_element); }
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_link')) { replace_with(ui.item, gsf_link_element); }
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_switch')) { replace_with(ui.item, gsf_switch_element); }
+            }
+    });
+
+    $('.gsf_template').click(function () {
+         console.log('gsf_template class click');
+         return false;
+    });
+
+}
+
+function bind_td_sortable()
+{
+
+    $('tr').sortable({
+            'cursor':'pointer',
+            'tolerance': 'intersect',
+            'items':'.column',
+            'placeholder':'placeholder_td',
+            'connectWith':'column',
+            receive: function(event, ui) { alert("template attempted to receive");} 
+    });
+
+    $('.td-div').sortable({
+            'cursor':'pointer',
+            'tolerance': 'pointer',
+            'items':'.gsf_metadata, .gsf_choose_metadata, .gsf_link, .gsf_switch',
+            'placeholder':'placeholder',
+            receive: function(event, ui) { alert("td-div attempted to receive"); },
+            stop: function(event, ui) {
+                // gsf metadata
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_metadata')) { replace_with(ui.item, gsf_metadata_element); }
+                // gsf choose metadata
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_choose_metadata')) { replace_with(ui.item, gsf_choose_metadata_element); }
+                // gsf link
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_link')) { replace_with(ui.item, gsf_link_element); }
+                // gsf switch
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_switch')) { replace_with(ui.item, gsf_switch_element); }
+                
+            }
+
+    });
+
+    $('.td-div').click(function () {    
+         //console.log('td class click');
+         return true;
+    });
+
+
+
+}
+
+
+function bind_choose_metadata_sortable()
+{
+    //console.log('function bind_choose_metadata_sortable()');
+    $('.gsf_choose_metadata').sortable({
+            'cursor':'pointer',
+            'tolerance': 'pointer',
+            'items':'.gsf_metadata, .gsf_text, .gsf_default',
+            'placeholder':'placeholder',
+            'connectWith':'.gsf_choose_metadata',
+            //'nested':'.gsf:metadata'
+            receive: function(event, ui) { alert("choose-metadata attempted to receive"); },
+            stop: function(event, ui) {
+                // gsf metadata
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_metadata')) { 
+                    console.log(gsf_metadata_element);
+                    replace_with(ui.item, gsf_metadata_element); 
+                } 
+                // gsf text
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_text')) { replace_with(ui.item, gsf_text_element); } 
+                // gsf default
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_default')) { replace_with(ui.item, gsf_default_element); } 
+
+                bind_all_sortables();
+            }
+    });
+}
+
+function bind_link_sortable()
+{
+    //console.log('function bind_link_sortable()');
+    $('.gsf_link').sortable({
+            'cursor':'pointer',
+            'tolerance': 'pointer',
+            'items':'.leaf, .gsf_link, .gsf_switch, .gsf_choose',
+            'placeholder':'placeholder',
+            'connectWith':'.gsf_link',
+            //'nested':'.gsf:metadata'
+            stop: function(event, ui) {
+                // gsf icon
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_icon')) { replace_with(ui.item, gsf_icon_element); }
+                // gsf text
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_text')) { replace_with(ui.item, "<input type=\"text\" name=\"rawtextinput\" size=\"10\"/>"); }
+                // gsf metadata
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_metadata')) { replace_with(ui.item, gsf_metadata_element); } 
+                // gsf link
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_link')) { replace_with(ui.item, gsf_link_element); }
+                // gsf switch
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_switch')) { replace_with(ui.item, gsf_switch_element); }
+                // gsf choose
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_choose_metadata')) { replace_with(ui.item, gsf_choose_metadata_element); }
+            }
+    });
+}
+
+function bind_switch_sortable()
+{
+    //console.log('function bind_switch_sortable()');
+    $('.gsf_switch').sortable({
+            'cursor':'pointer',
+            'tolerance': 'pointer',
+            'items':'.gsf_metadata, .gsf_when, .gsf_otherwise, .gsf_text',
+            'placeholder':'placeholder',
+            'connectWith':'.gsf_switch',
+            //'nested':'.gsf:metadata'
+            stop: function(event, ui) {
+                // gsf when
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_when')) { replace_with(ui.item, gsf_when_element); }
+                // gsf otherwise
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_otherwise')) { replace_with(ui.item, gsf_otherwise_element); }
+                // gsf metadata
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_metadata')) { replace_with(ui.item, gsf_metadata_element); } 
+                // gsf text
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_text')) { replace_with(ui.item, gsf_text_element); } 
+            }
+    });
+}
+
+function bind_when_sortable()
+{
+    //console.log('function bind_when_sortable()');
+    $('.gsf_when').sortable({
+            'cursor':'pointer',
+            'tolerance': 'pointer',
+            'items':'.leaf, .gsf_link, .gsf_choose',
+            'placeholder':'placeholder',
+            //'nested':'.gsf:metadata'
+            stop: function(event, ui) {
+                // gsf metadata
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_metadata')) { replace_with(ui.item, gsf_metadata_element); }
+                // gsf icon
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_icon')) { replace_with(ui.item, gsf_icon_element); } 
+                // gsf text
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_text')) { replace_with(ui.item, gsf_text_element); } 
+                // gsf link
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_link')) { replace_with(ui.item, gsf_link_element); } 
+                // gsf choose
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_choose')) { replace_with(ui.item, gsf_choose_element); } 
+            }
+    });
+}
+
+function bind_otherwise_sortable()
+{
+    //console.log('function bind_otherwise_sortable()');
+    $('.gsf_otherwise').sortable({
+            'cursor':'pointer',
+            'tolerance': 'pointer',
+            'items':'.leaf, .gsf_link, .gsf_choose',
+            'placeholder':'placeholder',
+            //'nested':'.gsf:metadata'
+            stop: function(event, ui) {
+                // gsf metadata
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_metadata')) { replace_with(ui.item, gsf_metadata_element); }
+                // gsf text
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_text')) { replace_with(ui.item, "<input type=\"text\" name=\"rawtextinput\" size=\"10\"/>"); }
+                // gsf icon
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_icon')) { replace_with(ui.item, gsf_icon_element); } 
+                // gsf link
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_link')) { replace_with(ui.item, gsf_link_element); } 
+                // gsf choose
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_choose')) { replace_with(ui.item, gsf_choose_element); } 
+            }
+    });
+}
+
+function bind_block_mouseover()
+{
+    //console.log('function bind_block_mouseover()');
+    $(".block").mouseover(function()
+    {
+        $(this).parents().css("border", "");
+        $(this).css("border", "2px solid blue");
+        return false;
+    }).mouseout(function(){
+        $(this).css("border", "");
+        return false;
+    });
+}
+
+function bind_minmax_remove()
+{
+    console.log('function bind_minmax_remove()');
+    $('a.minmax').bind('click', toggleContent);
+    $('a.remove').bind('click', removeContent);
+};
+
+var removeContent = (function () {
+    //console.log('var removeContent = (function ()');
+        // this -> a -> td -> tr -> tbody -> table -> div
+        //$(this).parent().parent().parent().parent().parent().remove();
+        $(this).closest(".block").remove();
+    });
+
+
+var toggleContent = function(e)
+{
+    console.log('parent: ' + $(this).html());
+    if ($(this).html() == '[+]'){ //targetContent.css('display') == 'none') {
+        $(this).closest(".block").children(".table, .block").slideDown(300);
+        $(this).html('[-]');
+        $(this).removeClass("ui-icon-plusthick");
+        $(this).addClass("ui-icon-minusthick");
+    } else {
+        $(this).closest(".block").children(".table, .block").slideUp(300);
+        $(this).html('[+]');
+        $(this).removeClass("ui-icon-minusthick");
+        $(this).addClass("ui-icon-plusthick");
+    }
+    return false;
+};
+
+function serialize(s)
+{
+    serial = $.SortSerialize(s);
+    alert(serial.hash);
+};
+
+function equalHeights(item, height) {
+    //console.log('function equalHeights(item, height)');
+    (item.parents('.table')).each(function(index) {
+        $(this).children().children().children().each(function() {
+            $(this).height(height);
+            $(this).children().height(height);
+        });
+    });
+};
+
Index: in/trunk/greenstone3/web/interfaces/default/js/formateditor/format_browse.js
===================================================================
--- /main/trunk/greenstone3/web/interfaces/default/js/formateditor/format_browse.js	(revision 27713)
+++ 	(revision )
@@ -1,128 +1,0 @@
-
-console.log("Loading format_browse.js\n");
-
-/* FUNCTIONS FOR FORMAT EDITING */                                                                    
-
-function getFormatStatement()
-{
-    var formatDiv = document.getElementById('formatStatement');
-    var formatStatement = innerXHTML(formatDiv);
-    return formatStatement;
-}
-
-function checkClassifierRadio()
-{
-    var selection = $('input[name="classifiers"]'); //document.quiz.colour;
-
-    for (i=0; i<selection.length; i++)
-
-          if (selection[i].checked == true)
-              return selection[i].value;
-
-    return "this";
-
-}
-
-function updateFormatStatement()
-{
-    var formatStatement = getFormatStatement();
-
-    var thisOrAll = checkClassifierRadio();
-    console.log(thisOrAll);
-    var myurl = document.URL;
-
-    //var collection_name = getSubstring(myurl, "&c", "&");
-    var service_name = getSubstring(myurl, "&s", "&");  
-
-    if(thisOrAll == "all")
-        service_name = "AllClassifierBrowse";
-
-    var classifier_name = null;
-
-    if(service_name == "ClassifierBrowse")
-        classifier_name = getSubstring(myurl, "&cl", "&");
-
-    //var post_url = "http://localhost:8383/greenstone3/dev?a=f&sa=update&c=" + collection_name +"&s=" + service_name;
-    var post_url = host_info.pre_URL + "?a=f&sa=update&c=" + host_info.collection_name +"&s=" + service_name;
-
-    if(classifier_name != null)
-        post_url = post_url + "&cl=" + classifier_name;
-
-    $.post(post_url, {data: formatStatement}, function(data) {
-        //$('.result').innerHTML = data; //html(data);
-    
-        // An error is returned because there is no valid XSLT for a format update action, there probably shouldn't be one so we ignore what the post returns.    
-        console.log("Successfully updated");
-        //console.log(data);
-        }, 'html');
-}
-
-function saveFormatStatement()
-{
-    var formatStatement = getFormatStatement();
-    var thisOrAll = checkClassifierRadio();
-
-    var myurl = document.URL;
-
-    //var collection_name = getSubstring(myurl, "&c", "&");
-    var service_name = getSubstring(myurl, "&s", "&");
-    var classifier_name = null;
-
-    if(thisOrAll == "all")
-        service_name = "AllClassifierBrowse";
-
-    if(service_name == "ClassifierBrowse")
-        classifier_name = getSubstring(myurl, "&cl", "&");
-
-    //var post_url = "http://localhost:8383/greenstone3/dev?a=f&sa=save&c=" + collection_name +"&s=" + service_name;
-    var post_url = host_info.pre_URL + "?a=f&sa=save&c=" + host_info.collection_name +"&s=" + service_name;
-
-    if(classifier_name != null)
-        post_url = post_url + "&cl=" + classifier_name;
-
-    $.post(post_url, {data: formatStatement}, function(data) {
-        // An error is returned because there is no valid XSLT for a format update action, there probably shouldn't be one so we ignore what the post returns.    
-        console.log("Successfully saved");
-        }, 'html');
-}
-
-function find_class(current)
-{
-    var classes = current.className.split(' ');
-    var none = "";
-    for(var i = 0; i < classes.length; i++)
-    {
-        switch(classes[i])
-        {
-            case 'gsf_template':
-              return create_gsf_template(current);
-            default:
-            {
-              console.log("Class not found");
-              return none;
-            }
-        }
-    }
-}
-
-function create_gsf_template(current)
-{
-    // find match text which is an input with class match
-    var match = $(current).find('.match')[0].value;
-    console.log(match);
-    
-    // find mode text which is an input with class mode
-    var mode = $(current).find('.mode')[0].value;
-    console.log(mode);
-
-    // "<gsf:template match=\"classifierNode\" mode=\"horizontal\">"
-    var gsf = "<gsf:template match=\"" + match + "\"";
-    if(mode != "vertical")
-        gsf = gsf + " mode=\"" + mode + "\"";
-    gsf = gsf + ">";
-    
-    return gsf;
-
-}
-
-
Index: in/trunk/greenstone3/web/interfaces/default/js/formateditor/format_document.js
===================================================================
--- /main/trunk/greenstone3/web/interfaces/default/js/formateditor/format_document.js	(revision 27713)
+++ 	(revision )
@@ -1,111 +1,0 @@
-
-console.log("Loading format_document.js\n");
-
-$(document).ready(function(){
-
-        $('.sectionHeader').click(function () {
-            console.log('section Header click *');
-            getXSLT("sectionHeader");
-            return false; //don't event bubble
-            });
-
-        $('.sectionContainer').click(function () {
-            console.log('section Container click *');
-            getXSLT("sectionContainer");
-            return false; // don't event bubble
-            });
-        });
-
-/* DOCUMENT SPECIFIC FUNCTIONS */
-
-function displayTOC(checkbox)
-{
-    if (checkbox.checked == true)
-    {
-        console.log("Show the TOC!");
-        displaySideBar(true);
-        $("#tableOfContents").css("display", "block");
-    }
-    else
-    {
-        console.log("Hide the TOC!");
-        $("#tableOfContents").css("display", "none");
-        if ($("#coverImage").css("display") == "none")
-            displaySideBar(false);
-    }
-
-    return;
-}
-
-function displayBookCover(checkbox)
-{
-    if (checkbox.checked == true)
-    {
-        console.log("Show the book cover!");
-        displaySideBar(true);
-        $("#coverImage").css("display", "block");
-    }
-    else
-    {
-        console.log("Hide the book cover!");
-        $("#coverImage").css("display", "none");
-        if ($("#tableOfContents").css("display") == "none")
-            displaySideBar(false);
-    }
-
-    return;
-}
-
-function displaySideBar(toggle)
-{
-    if (toggle == true)
-    {
-        console.log("Show the sidebar!");
-        $("#rightSidebar").css("display", "block");
-    }
-    else
-    {
-        console.log("Hide the sidebar!");
-        $("#rightSidebar").css("display", "none");
-    }
-
-    return;
-}
-
-function checkDocumentRadio()
-{
-    var selection = $('input[name="documentChanges"]'); //document.quiz.colour;
-
-    for (i=0; i<selection.length; i++)
-
-        if (selection[i].checked == true)
-            return selection[i].value;
-
-    return "this";
-}
-
-function saveDocumentChanges()
-{
-    console.log("Saving changes to "+checkDocumentRadio());
-    console.log("TOC="+$('input[name="TOC"]').attr('checked'));
-    console.log("Cover Image="+$('input[name="bookCover"]').attr('checked'));
-
-    var myurl = document.URL;
-
-    //var collection_name = getSubstring(myurl, "&c", "&");
-    var document_id = getSubstring(myurl, "&d", "&");
-    var document_type = getSubstring(myurl, "&dt", "&");
-    var prev_action = getSubstring(myurl, "&p.a", "&");
-    var prev_service = getSubstring(myurl, "&p.s", "&");
-
-    //var post_url = "http://localhost:8383/greenstone3/dev?a=f&sa=saveDocument&c=" + collection_name + "&d=" + document_id + "&dt=" + document_type + "&p.a=" + prev_action + "&p.s=" + prev_service;
-    var post_url = host_info.pre_URL + "?a=f&sa=saveDocument&c=" + host_info.collection_name + "&d=" + document_id + "&dt=" + document_type + "&p.a=" + prev_action + "&p.s=" + prev_service;
-
-    // XML will be automatically wrapped in <display><format> tags when saved to collection config
-    var xml = '<format><gsf:option name="TOC" value="'+$('input[name="TOC"]').attr('checked')+'"/><gsf:option name="coverImage" value="'+$('input[name="bookCover"]').attr('checked')+'"/></format>';
-
-    $.post(post_url, {data: xml}, function(data) {
-            console.log("Success, we have received data");
-    }, 'xml');
-}
-
Index: in/trunk/greenstone3/web/interfaces/default/js/formateditor/format_jquery_prototypes.js
===================================================================
--- /main/trunk/greenstone3/web/interfaces/default/js/formateditor/format_jquery_prototypes.js	(revision 27713)
+++ 	(revision )
@@ -1,337 +1,0 @@
-
-console.log("Loading format_jquery_prototypes.js\n");
-
-$(document).ready(function()
-{
-    /*
-    var collection = "";
-    
-    var regex = new RegExp("[?&]c=");
-    var matches = regex.exec(document.URL);
-    if(matches != null)
-    {
-        var startIndex = matches.index;
-        var endIndex = document.URL.indexOf("&", startIndex + 1);
-        
-        if(endIndex == -1)
-        {
-            endIndex = document.URL.length;
-        }
-        
-        collection = document.URL.substring(startIndex, endIndex);
-    }
-    */
-
-    //Retrieve the collection metadataset using ajax
-    $.ajax
-    ({
-        type: "GET",
-        url: "?a=g&s=CoverageMetadataRetrieve&o=xml&rt=r&c=" + host_info.collection_name,
-        success: function(data) 
-        {
-            var str = "<select name=\"meta_select\" onChange=\"onSelectChange(this)\">";
-            
-            var selectorArea = document.getElementById("metadataSelector");     
-            var metadataSets = data.getElementsByTagName("metadataSet");
-            for(var i = 0; i < metadataSets.length; i++)
-            {
-                var metadata = metadataSets[i].getElementsByTagName("metadata");
-                for(var j = 0; j < metadata.length; j++)
-                {
-                    var metaValue = metadataSets[i].getAttribute("name") + "." + metadata[j].getAttribute("name");
-                    str += "<option value=\"" + metaValue + "\">" + metaValue + "</option>";
-                }
-            }
-            
-            str += "</select>";
-
-            selectorArea.innerHTML = str;
-            gsf_metadata_element =  "<div class=\"gsf_metadata css_gsf_metadata block leaf\" title=\"gsf:metadata\"><table class=\"header\"><tbody><tr><td class=\"header\">" + str + "</td><td class=\"header\"><a href=\"#\" class=\"remove ui-icon ui-icon-closethick\" title=\"Click me to remove\"/></td></tr></tbody></table></div>";
-            //console.log("Metadata element from ajax: " + gsf_metadata_element);
-        }
-    });
-
-    $.ui.draggable.prototype._createHelper = function(event) {
-        var o = this.options;
-        var helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event])) : (o.helper == 'clone' ? this.element.clone().removeAttr('id') : this.element);
-
-        var select = $(this.element).find('select');
-        var value = select.attr('value');
-        console.log("Found "+value+" in helper");
-        CURRENT_SELECT_VALUE = value;
-        helper.find('select').attr('value', value);
-
-        if(!helper.parents('body').length)
-            helper.appendTo((o.appendTo == 'parent' ? this.element[0].parentNode : o.appendTo));
-
-        if(helper[0] != this.element[0] && !(/(fixed|absolute)/).test(helper.css("position")))
-            helper.css("position", "absolute");
-
-        return helper;
-
-    };
-    
-    $.ui.sortable.prototype._removeCurrentsFromItems = function() {
-        //console.log("IN _removeCurrentsFromItems FUNCTION");
-        //console.log("this = " + this.currentItem[0].getAttribute('class'));
-        var list = this.currentItem.find(":data(sortable-item)");
-
-        var i = 0;
-        while (i<this.items.length) {
-            var found_match = false;
-            for (var j=0; j<list.length; j++) {
-                if(this.items[i])
-                {
-                    if(list[j] == this.items[i].item[0]) {
-                        //console.log("Item to splice = " + this.items[i].item[0].getAttribute('class'));
-                        this.items.splice(i,1);
-                        found_match = true;
-                        break;
-                    }
-                }
-            };
-            if (!found_match)
-                i++;
-            else
-                break;
-        }
-    };
-    
-    $.ui.plugin.add("draggable", "connectToSortable", {
-        start: function(event, ui) {
-            //console.log("FUNCTION start draggable connectToSortable");
-            var inst = $(this).data("draggable"), o = inst.options, uiSortable = $.extend({}, ui, { item: inst.element });
-            inst.sortables = [];
-            $(o.connectToSortable).each(function() {
-                var sortable = $.data(this, 'sortable');
-                if (sortable && !sortable.options.disabled) {
-                    inst.sortables.push({instance: sortable, shouldRevert: sortable.options.revert});
-                    sortable._refreshItems();   //Do a one-time refresh at start to refresh the containerCache
-                    sortable._trigger("activate", event, uiSortable);
-                }   
-            });
-
-        },
-        stop: function(event, ui) {
-
-            //console.log("FUNCTION stop draggable connectToSortable");
-            //If we are still over the sortable, we fake the stop event of the sortable, but also remove helper
-            var inst = $(this).data("draggable"),
-            uiSortable = $.extend({}, ui, { item: inst.element });
-
-            $.each(inst.sortables, function() {
-                if(this.instance.isOver) {
-
-                    this.instance.isOver = 0;
-
-                    inst.cancelHelperRemoval = true; //Don't remove the helper in the draggable instance
-                    this.instance.cancelHelperRemoval = false; //Remove it in the sortable instance (so sortable plugins like revert still work)
-
-                    //The sortable revert is supported, and we have to set a temporary dropped variable on the draggable to support revert: 'valid/invalid'
-                    if(this.shouldRevert) this.instance.options.revert = true;
-
-                    //Trigger the stop of the sortable
-                    //console.log("Draggable tells sortable to stop");
-                    this.instance._mouseStop(event);
-
-                    this.instance.options.helper = this.instance.options._helper;
-
-                    //If the helper has been the original item, restore properties in the sortable
-                    if(inst.options.helper == 'original')
-                        this.instance.currentItem.css({ top: 'auto', left: 'auto' });
-
-                } else {
-                    this.instance.cancelHelperRemoval = false; //Remove the helper in the sortable instance
-                    this.instance._trigger("deactivate", event, uiSortable);
-                }
-            });
-
-        },
-        drag: function(event, ui) {
-            //console.log("FUNCTION drag draggable connectToSortable");
-
-            var inst = $(this).data("draggable"), self = this;
-
-            var checkPos = function(o) {
-                var dyClick = this.offset.click.top, dxClick = this.offset.click.left;
-                var helperTop = this.positionAbs.top, helperLeft = this.positionAbs.left;
-                var itemHeight = o.height, itemWidth = o.width;
-                var itemTop = o.top, itemLeft = o.left;
-
-                return $.ui.isOver(helperTop + dyClick, helperLeft + dxClick, itemTop, itemLeft, itemHeight, itemWidth);
-            };
-
-            var intersecting_items = new Array();
-
-            $.each(inst.sortables, function(i) {
-            
-                //Copy over some variables to allow calling the sortable's native _intersectsWith
-                this.instance.positionAbs = inst.positionAbs;
-                this.instance.helperProportions = inst.helperProportions;
-                this.instance.offset.click = inst.offset.click;
-            
-                if(this.instance._intersectsWith(this.instance.containerCache)) {
-
-                    //If it intersects, we use a little isOver variable and set it once, so our move-in stuff gets fired only once
-                    //if(!this.instance.isOver) {
-
-                    //console.log('Line 1113');
-
-                    //  this.instance.isOver = 1;
-
-                    intersecting_items.push(this.instance); // sam
-                    //} //sam
-
-                    //Now we fake the start of dragging for the sortable instance,
-                    //by cloning the list group item, appending it to the sortable and using it as inst.currentItem
-                    //We can then fire the start event of the sortable with our passed browser event, and our own helper (so it doesn't create a new one)
-                    //sam this.instance.currentItem = $(self).clone().appendTo(this.instance.element).data("sortable-item", true);
-                    //sam this.instance.options._helper = this.instance.options.helper; //Store helper option to later restore it
-                    //sam this.instance.options.helper = function() { return ui.helper[0]; };
-
-                    //sam event.target = this.instance.currentItem[0];
-                    //sam this.instance._mouseCapture(event, true);
-                    //sam this.instance._mouseStart(event, true, true);
-
-                    //Because the browser event is way off the new appended portlet, we modify a couple of variables to reflect the changes
-                    //sam this.instance.offset.click.top = inst.offset.click.top;
-                    //sam this.instance.offset.click.left = inst.offset.click.left;
-                    //sam this.instance.offset.parent.left -= inst.offset.parent.left - this.instance.offset.parent.left;
-                    //sam this.instance.offset.parent.top -= inst.offset.parent.top - this.instance.offset.parent.top;
-
-                    //sam inst._trigger("toSortable", event);
-                    //sam inst.dropped = this.instance.element; //draggable revert needs that
-                    //hack so receive/update callbacks work (mostly)
-                    //sam inst.currentItem = inst.element;
-                    //sam this.instance.fromOutside = inst;
-
-                //sam brace
-
-                //Provided we did all the previous steps, we can fire the drag event of the sortable on every draggable drag, when it intersects with the sortable
-                //sam if(this.instance.currentItem) this.instance._mouseDrag(event);
-
-                } else {
-
-                    //If it doesn't intersect with the sortable, and it intersected before,
-                    //we fake the drag stop of the sortable, but make sure it doesn't remove the helper by using cancelHelperRemoval
-                    if(this.instance.isOver) {
-
-                        console.log("UNSETTING ISOVER");
-                        console.log("ON ITEM="+this.instance.currentItem[0].getAttribute('class'))
-                        this.instance.isOver = 0;
-                        this.instance.cancelHelperRemoval = true;
-                    
-                        //Prevent reverting on this forced stop
-                        this.instance.options.revert = false;
-                    
-                        // The out event needs to be triggered independently
-                        this.instance._trigger('out', event, this.instance._uiHash(this.instance));
-                    
-                        this.instance._mouseStop(event, true);
-                        this.instance.options.helper = this.instance.options._helper;
-
-                        //Now we remove our currentItem, the list group clone again, and the placeholder, and animate the helper back to it's original size
-                        //console.log("DO WE GET HERE?");
-                        this.instance.currentItem.remove();
-                        if(this.instance.placeholder) this.instance.placeholder.remove();
-
-                        inst._trigger("fromSortable", event);
-                        inst.dropped = false; //draggable revert needs that
-                
-                    }
-                } 
-            });
-
-            //sam
-            //console.log("Contents of intersecting_items");
-            var innermostContainer = null, innermostIndex = null;       
-            for (i=0;i<intersecting_items.length;i++)
-            {
-                //console.log('ITEM: '+intersecting_items[i].element[0].getAttribute('class'));
-    
-                if(innermostContainer && $.ui.contains(intersecting_items[i].element[0], innermostContainer.element[0]))
-                    continue;
-                        
-                innermostContainer = intersecting_items[i];
-                innermostIndex = i; 
-            }
-
-            for (i=0;i<intersecting_items.length;i++)
-            {
-                if(intersecting_items[i] != innermostContainer)
-                    if(intersecting_items[i].isOver) {
-
-                        console.log("UNSETTING ISOVER");
-                        console.log("ON ITEM="+intersecting_items[i].currentItem[0].getAttribute('class'))
-                        intersecting_items[i].isOver = 0;
-                        intersecting_items[i].cancelHelperRemoval = true;
-
-                        //Prevent reverting on this forced stop
-                        intersecting_items[i].options.revert = false;
-
-                        // The out event needs to be triggered independently
-                        intersecting_items[i]._trigger('out', event, intersecting_items[i]._uiHash(intersecting_items[i]));
-
-                        intersecting_items[i]._mouseStop(event, true);
-                        intersecting_items[i].options.helper = intersecting_items[i].options._helper;
-
-                        //Now we remove our currentItem, the list group clone again, and the placeholder, and animate the helper back to it's original size
-                        //console.log("DO WE GET HERE?");
-                        if(intersecting_items[i].currentItem) intersecting_items[i].currentItem.remove();
-                        if(intersecting_items[i].placeholder) intersecting_items[i].placeholder.remove();
-
-                        inst._trigger("fromSortable", event);
-                        inst.dropped = false; //draggable revert needs that
-                    }
-
-                    intersecting_items[i].isOver = 0;
-            }
-
-            if(innermostContainer && !innermostContainer.isOver)
-            {
-                console.log("INNER="+innermostContainer.element[0].getAttribute('class'));
-                console.log("SETTING ISOVER");
-                innermostContainer.isOver = 1;
-
-                //Now we fake the start of dragging for the sortable instance,
-                //by cloning the list group item, appending it to the sortable and using it as inst.currentItem
-                //We can then fire the start event of the sortable with our passed browser event, and our own helper (so it doesn't create a new one)
-
-                if(innermostContainer.currentItem) innermostContainer.currentItem.remove();
-                if(innermostContainer.placeholder) innermostContainer.placeholder.remove();
-
-                innermostContainer.currentItem = $(self).clone().appendTo(innermostContainer.element).data("sortable-item", true);
-            
-                innermostContainer.options._helper = innermostContainer.options.helper; //Store helper option to later restore it
-                innermostContainer.options.helper = function() { return ui.helper[0]; };
-
-                console.log("EVENT TARGET="+innermostContainer.currentItem[0].getAttribute('class'));
-                event.target = innermostContainer.currentItem[0];
-                innermostContainer._mouseCapture(event, true);
-                innermostContainer._mouseStart(event, true, true);
-
-                //Because the browser event is way off the new appended portlet, we modify a couple of variables to reflect the changes
-                innermostContainer.offset.click.top = inst.offset.click.top;
-                innermostContainer.offset.click.left = inst.offset.click.left;
-                innermostContainer.offset.parent.left -= inst.offset.parent.left - innermostContainer.offset.parent.left;
-                innermostContainer.offset.parent.top -= inst.offset.parent.top - innermostContainer.offset.parent.top;
-
-                inst._trigger("toSortable", event);
-                inst.dropped = innermostContainer.element; //draggable revert needs that
-                //hack so receive/update callbacks work (mostly)
-                inst.currentItem = inst.element;
-                innermostContainer.fromOutside = inst;
-
-                //sam brace
-            }
-
-            if(innermostContainer)
-            {
-                //Provided we did all the previous steps, we can fire the drag event of the sortable on every draggable drag, when it intersects with the sortable
-                if(innermostContainer.currentItem) innermostContainer._mouseDrag(event);
-            }
-
-              }
-    });
-
-});
Index: in/trunk/greenstone3/web/interfaces/default/js/formateditor/format_util.js
===================================================================
--- /main/trunk/greenstone3/web/interfaces/default/js/formateditor/format_util.js	(revision 27713)
+++ 	(revision )
@@ -1,761 +1,0 @@
-
-console.log("Loading format_util.js\n");
-
-/* Ensures that a change to a text field is remembered */
-function onTextChange(item, text)
-{
-    console.log("I have set "+item+".value to "+text);
-    item.setAttribute("value",text);
-}
-
-/* Ensures that a change to a select field is remembered */
-function onSelectChange(item)
-{
-    console.log("I have set "+item.value+".selected to selected");
-    for (var i=0; i<item.options.length; i++)
-    {
-        if(item.selectedIndex == i)
-            item.options[i].setAttribute("selected", "selected");
-        else
-            item.options[i].removeAttribute("selected");
-    }
-    //item.options[item.selectedIndex].selected = "selected";
-    //item.setAttribute("selected","selected");
-}
-
-
-/* Get substring */
-function getSubstring(str, first, last)
-{
-    var first_index = str.indexOf(first)+first.length+1;
-    var last_index = str.indexOf(last, first_index);
-
-    if(last_index == -1)
-        last_index = str.length;
-
-    var substring = str.substring(first_index, last_index);
-
-    return substring;
-}
-    
-function getXSLT(classname)
-{
-    console.log("*** Function getXSLT ***");
-    var myurl = document.URL;
-
-    var document_id = getSubstring(myurl, "&d", "&");
-    var document_type = getSubstring(myurl, "&dt", "&");
-
-    var post_url = host_info.pre_URL +"?a=d&c=" + host_info.collection_name + "&d=" + document_id + "&dt=" + document_type + "&o=skinandlib";
-
-    $.post(post_url, function(data) {
-            console.log("Success, we have received the XSLT for the relevant page part");
-            classname = "." + classname;
-            /* There seemed to be a problem with MIME types for the data received from the post. */ 
-            /* The best fix for now is to set the data type to text and then reparse as xml */
-            xml = $.parseXML(data);
-            var content = $( xml ).find(classname);
-            /* The xml() function is provided by jquery.xml.js (included by formatmanager.xsl) */
-            $("#XSLTcode").val(content.xml());
-            }, 'text');
-}
-
-function traverse(node, formatstring)
-{
-
-    if(node.nodeName=='DIV')
-    {
-        console.log("Found a div" +node.nodeName+","+node.nodeType);
-        formatstring = formatstring + find_class(node);
-        console.log(formatstring);
-    }
-
-    var children = $(node).children();
-    for(var i=0; i < children.length; i++)
-        formatstring = formatstring + traverse(children[i], formatstring);
-
-    return formatstring;
-}
-        
-
-/*
-$("#iframe").ready(function(){
-        console.log("iframe is ready ...");
-        var iframe = document.getElementById('iframe');
-        var iframe_document = iframe.document;
-
-        if(iframe.contentDocument)
-        {
-            iframe_document = iframe.contentDocument; // For NS6
-            console.log("Chose content document");
-        }
-        else if(iframe.contentWindow)
-        {
-            iframe_document = iframe.contentWindow.document; // For IE5.5 and IE6
-            console.log("Chose content window");
-        }
-
-        console.log(iframe_document.documentElement.innerHTML); //document.documentElement.outerHTML
-
-        $(iframe_document.documentElement.innerHTML).find('a').each(function() {
-            console.log("data "+$(this).data('href'));
-            console.log("getAttribute "+$(this).getAttribute('href'));
-            console.log("attr "+$(this).attr('href'));
-            console.log("this.href "+this.href);
-            var original = this.href; //$(this).attr('href');
-            // check if greenstone link ie. starts with format
-            //var original = $(this).data('href');
-            var modified = original.toString().concat("&excerptid=gs_content");
-            console.log(modified);
-            this.href = modified;
-            //$(this).attr('href',modified);
-            //$(this).data('href', modified);
-            //console.log($(this).attr('href'));
-            console.log("data "+$(this).data('href'));
-            console.log("getAttribute "+$(this).getAttribute('href'));
-            console.log("attr "+$(this).attr('href'));
-            console.log("this.href "+this.href);
-            console.log("**********");
-
-        });
-}); */
-/*
-function loadXMLDoc()
-{
-    if (window.XMLHttpRequest)
-    {// code for IE7+, Firefox, Chrome, Opera, Safari
-        xmlhttp=new XMLHttpRequest();
-    }
-    else
-    {// code for IE6, IE5
-        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
-    }
-    
-    xmlhttp.onreadystatechange=function()
-    {  
-        console.log("state changed to " + xmlhttp.readyState);
-        console.log("status is " + xmlhttp.status);
-        if (xmlhttp.readyState==4 && xmlhttp.status==200)
-        {
-            console.log("get code");
-            console.log(xmlhttp.responseText);
-            document.getElementById("gs_content").innerHTML=xmlhttp.responseText;
-        }
-    }
-    
-    xmlhttp.open("GET","http://localhost:8080/greenstone3/format?a=b&rt=s&s=ClassifierBrowse&c=simpleht&cl=CL1&excerptid=gs_content",true);
-    //xmlhttp.open("GET","http://www.cs.waikato.ac.nz",true);
-    //xmlhttp.open("GET","http://wand.net.nz/~sjb48/index.html",true);
-    xmlhttp.send();
-}
-*/
-$(document).ready(function(){
-
-    console.log("Document ready function\n");
-	
-    CURRENT_SELECT_VALUE = ""; //global - gets set by ui.draggable
-
-    var r = /(https?:\/\/)?([\da-z\.-]+):(\d+)\/([\da-z]+)\/([\da-z]+)\?.*&c=([\da-z\.-]+).*/;
-    var s = document.URL;
-    s.match(r);
-    //var matches = regex.exec(document.URL);
-    /* Host info needs to be globally available */
-    host_info = new Object();
-    console.log("Hostname: " + RegExp.$2);
-    host_info.host_name = RegExp.$2;
-    console.log("Port: " + RegExp.$3);
-    host_info.port = RegExp.$3;
-    console.log("Library: " + RegExp.$4);
-    host_info.library = RegExp.$4;
-    console.log("Servlet: " + RegExp.$5);
-    host_info.servlet = RegExp.$5;
-    console.log("Collection: " + RegExp.$6);
-    host_info.collection_name = RegExp.$6;
-
-    host_info.pre_URL = "http://" + host_info.host_name + ":" + host_info.port + "/" + host_info.library + "/" + host_info.servlet;
-    console.log("Pre URL: " + host_info.pre_URL);
-
-    /*
-    var iframe = document.getElementById('iframe');
-    var iframe_document = iframe.document;
-   
-    if(iframe.contentDocument)
-    {
-        iframe_document = iframe.contentDocument; // For NS6
-        console.log("Chose content document");
-    }
-    else if(iframe.contentWindow)
-    {
-        iframe_document = iframe.contentWindow.document; // For IE5.5 and IE6
-        console.log("Chose content window");
-    }
-
-    // Edit the hrefs in preview_html - search for <a href="format?a=b&rt=r&s=ClassifierBrowse&c=simpleht&cl=CL1.2">
-    var start_index = 0;
-    var end_index = 0;
-    while(start_index != -1)
-    {
-        start_index = preview_html.indexOf("href=\"format", start_index);
-        console.log("start index = " + start_index);
-        if(start_index != -1)
-        {
-            end_index = preview_html.indexOf("\">", start_index);
-            console.log("end_index = " + end_index);
-            a = preview_html.substring(0,end_index);
-            b = preview_html.substring(end_index);
-            preview_html = a.concat("&excerptid=results", b);
-            console.log(preview_html);
-            start_index = end_index + "&excerptid=results\">".length;
-        }
-    }
-
-    // Split the html code in to three parts
-    var first_index = preview_html.indexOf("<ul id=\"results\"");
-    console.log("First index is "+first_index);
-    var second_index = preview_html.indexOf("</ul>", first_index) + "</ul>".length;
-    console.log("Second index is "+second_index);
-
-    var first_half = preview_html.substring(0, first_index);
-    var iframe_code = preview_html.substring(first_index, second_index);
-    var second_half = preview_html.substring(second_index);
-
-    //$('#my_categories').innerHTML = first_half.concat(second_half);
-    document.getElementById("my_categories").innerHTML = first_half.concat(second_half);
-
-    // Put the content in the iframe
-    if(initialised_iframe == "false")
-    {
-        console.log("Initialised iframe with preview html");
-        console.log(preview_html);
-        iframe_document.open();
-        iframe_document.writeln(iframe_code); //.concat("&excerptid=gs_content"));
-        iframe_document.close(); 
-        initialised_iframe = "true";
-    }
-    */
-
-    /*    
-    $(iframe_document.documentElement.innerHTML).find('a').each(function() {
-            console.log("data "+$(this).data('href'));
-            console.log("getAttribute "+this.getAttribute('href'));
-            console.log("attr "+$(this).attr('href'));
-            console.log("this.href "+this.href);
-            var original = this.href; //$(this).attr('href');
-            // check if greenstone link ie. starts with format
-            //var original = $(this).data('href');
-            var modified = original.toString().concat("&excerptid=gs_content");
-            console.log("*                      *");
-            console.log(modified);
-            console.log("*                      *");
-            //this.href = modified;
-            //$(this).attr('href',modified);
-            //$(this).data('href', modified);
-            $(this).attr({ 'href': modified });
-            //console.log($(this).attr('href'));
-            console.log("data "+$(this).data('href'));
-            console.log("getAttribute "+this.getAttribute('href'));
-            console.log("attr "+$(this).attr('href'));
-            console.log("this.href "+this.href);
-            console.log("***********************");
-    });
-    */
-
-    /******************************************/
-    /*              DRAGGABLES                */
-    /******************************************/
-
-    $(".draggable_gsf_template").draggable({
-            cursor: 'crosshair',
-            connectToSortable: '#formatStatement',
-            helper: 'clone',
-            revert: 'invalid'
-    });
-
-    $(".draggable_table").draggable({
-            cursor: 'crosshair',
-            connectToSortable: '.gsf_template',
-            helper: 'clone',
-            revert: 'invalid'
-    });
-
-    $(".draggable_tr").draggable({
-            cursor: 'crosshair',
-            connectToSortable: '.gsf_table',
-            helper: 'clone',
-            revert: 'invalid'
-    })
-
-    $(".draggable_td").draggable({
-            cursor: 'crosshair',
-            //connectToSortable: '.td',
-            helper: 'clone',
-            revert: 'invalid'
-    })
-
-    $(".draggable_gsf_text").draggable({
-            cursor: 'crosshair',
-            connectToSortable: '.td-div, .gsf_when, .gsf_otherwise, .gsf_link, .gsf_choose_metadata, .gsf_default',
-            helper: 'clone',
-            revert: 'invalid'
-    });
-    
-    $(".draggable_gsf_choose_metadata").draggable({
-            cursor: 'crosshair',
-            connectToSortable: '.td-div, .gsf_link, .gsf_when, .gsf_otherwise',
-            helper: 'clone',
-            revert: 'invalid'
-    });
-
-    //$(".element_type_gsf_metadata").draggable({
-    $(".draggable_gsf_metadata").draggable({
-            cursor: 'crosshair',
-            connectToSortable: '.gsf_choose_metadata, .gsf_when, .gsf_otherwise, .gsf_link, .td-div',
-            helper: 'clone',
-            revert: 'invalid'
-            
-    });
-
-    $(".draggable_gsf_link").draggable({
-            cursor: 'crosshair',
-            connectToSortable: '.td-div, .gsf_when, .gsf_otherwise, .gsf_link',
-            helper: 'clone',
-            revert: 'invalid'
-    });
-
-    // switch, when, otherwise, icon
-    $(".draggable_gsf_switch").draggable({
-            cursor: 'crosshair',
-            connectToSortable: '.td-div, .gsf_link',
-            helper: 'clone',
-            revert: 'invalid'
-    });
-
-    $(".draggable_gsf_when").draggable({
-            cursor: 'crosshair',
-            connectToSortable: '.gsf_switch',
-            helper: 'clone',
-            revert: 'invalid'
-    });
-
-    $(".draggable_gsf_otherwise").draggable({
-            cursor: 'crosshair',
-            connectToSortable: '.gsf_switch',
-            helper: 'clone',
-            revert: 'invalid'
-    });
-
-    $(".draggable_gsf_icon").draggable({
-            cursor: 'crosshair',
-            connectToSortable: '.td-div, .gsf_link, .gsf_choose, .gsf_when, .gsf_otherwise',
-            helper: 'clone',
-            revert: 'invalid'
-    });
-
- 
-    /******************************************/
-    /*               SORTABLES                */
-    /******************************************/
-
-    bind_td_sortable();
-    bind_all_sortables();
-
-    $('#formatStatement').sortable({
-            cursor: 'pointer',
-            tolerance: 'pointer',
-            items: '.gsf_template',
-            placeholder:'placeholder',
-            //'nested':'div'
-            stop: function(event, ui) {
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('css_gsf_template')) { replace_with(ui.item,gsf_template_element); }
-            }
-    });
-
-    $(".draggable_gsf_metadata").each(function(){
-        this.onselectstart = function() { return false; };
-    });
- 
-    $('div.gsf_template').children(".block,.table").slideUp(300); 
-}); 
-
-/*******************************************************************************/
-
-function bind_all_sortables()
-{
-    console.log('function bind_all_sortables()');
-    bind_template_sortable();
-    bind_choose_metadata_sortable();
-    bind_link_sortable();
-    bind_switch_sortable();
-    bind_when_sortable();
-    bind_otherwise_sortable();
-
-    bind_tables();
-
-    bind_block_mouseover();
-    bind_minmax_remove();    
-}
-
-function bind_tables()
-{
-    console.log('function bind_tables()');
-
-    $('#sectionHeader').click(function () {
-         console.log('section Header click *');
-         return true;
-    });
-    
-    $('#sectionContainer').click(function () {
-         console.log('section Container click *');
-         return true;
-    });
-
-    $(".td-div").resizable({
-                alsoResize: 'parent',
-                handles: 'w,e',
-                stop: function(event, ui) {
-                        console.log('Resize table on stop');
-                        resize_tables($(this));
-                }, });
-
-    $(".droppable").droppable({
-            accept: '.element_type_td',
-            tolerance: 'pointer', 
-            activate: function(event, ui) { $(this).addClass("droppable_hl");}, 
-            deactivate: function(event, ui) { $(this).removeClass("droppable_hl"); },
-            drop: function(event, ui) {
-                 var neverempty = document.createElement("div");
-                 neverempty.setAttribute("class","neverempty block");
-                 neverempty.setAttribute("style","height:50px");
-                 neverempty.setAttribute("style","display:block");
-                 var text = document.createTextNode('NEVER EMPTY');
-                 neverempty.appendChild(text);
-                 var td = document.createElement("td");
-                 var div = document.createElement("div"); 
-                 div.setAttribute("title","td-div");
-                 div.setAttribute("class","td-div block");
-                 div.setAttribute("style","margin-left:0px");
-                 div.setAttribute("width","25px");
-                 td.appendChild(div);
-                 div.appendChild(neverempty);
-                 var sep = document.createElement("td");
-                 sep.setAttribute("class","droppable");
-                 sep.setAttribute("width","10px"); 
-                 $(this).after(sep);                
-                 $(this).after(td);                
-                 bind_tables();
-                 resize_tables($(this));
-                 bind_td_sortable();
-                 bind_block_mouseover();
-            }
-        });
-
-}
-
-function replace_with(item, me)
-{
-    // Search me for select
-    console.log("ME is "+me);
-    if(me.search("select") != -1)
-    {
-        console.log("ME is "+me);
-        // If select exists, then find CURRENT_SELECT_VALUE
-        if(me.search(CURRENT_SELECT_VALUE) != -1)
-        {
-            var index = me.search("\""+CURRENT_SELECT_VALUE+"\"");
-            if(index == -1)
-                console.log("Did not find " + CURRENT_SELECT_VALUE);
-            else
-            {
-                console.log("Found " + CURRENT_SELECT_VALUE + " at index " + index);    
-                index = index + CURRENT_SELECT_VALUE.length + 2;
-                console.log("Attempt inserting select at new index "+index);
-                a = me.substring(0,index);
-                b = me.substring(index);
-                me = a.concat(" selected",b);
-            }
-        }
-    }
-    
-    console.log("Replacing "+item+" with "+me);
-
-    item.replaceWith(me); //'<div class="element element-txt">This text box has been added!</div>');
-
-    resize_tables(item);
-
-    bind_all_sortables();
-}
-
-function resize_tables(item)
-{
-    var max_height = 0;
-    (item.parents('.table')).each(function(index) {
-        $(this).children().children().children().each(function() {
-            var sum_one = 0;
-            var sum_two = 0;
-            $(this).children('.block').each(function() { sum_one = sum_one + $(this).height();  
-                $(this).children('.block').each(function() { sum_two = sum_two + $(this).height(); } );
-                console.log("My height is " + $(this).height() + ", sum height 2 is " + sum_two);
-            });
-            console.log("My height is " + $(this).height() + ", sum height 1 is " + sum_one);
-            if (sum_two > max_height)
-                max_height = sum_two;
-        });
-    });
-    equalHeights(item,max_height);
-}
-
-function bind_template_sortable()
-{
-    //console.log('function bind_template_sortable()');
-    $('.gsf_template').sortable({
-            'cursor':'pointer',
-            'tolerance': 'pointer',
-            'items':'.table', //.gsf_choose_metadata, .gsf_metadata',
-            'placeholder':'placeholder',
-            //'nested':'.gsf:metadata'
-            receive: function(event, ui) { alert("template attempted to receive"); },
-            stop: function(event, ui) {
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_table')) { replace_with(ui.item, "<table class=\"table\" border=\"2\"></table>"); }
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_choose_metadata')) { replace_with(ui.item, gsf_choose_metadata_element); }
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_metadata')) { replace_with(ui.item, gsf_metadata_element); }
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_link')) { replace_with(ui.item, gsf_link_element); }
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_switch')) { replace_with(ui.item, gsf_switch_element); }
-            }
-    });
-
-    $('.gsf_template').click(function () {
-         console.log('gsf_template class click');
-         return false;
-    });
-
-}
-
-function bind_td_sortable()
-{
-
-    $('tr').sortable({
-            'cursor':'pointer',
-            'tolerance': 'intersect',
-            'items':'.column',
-            'placeholder':'placeholder_td',
-            'connectWith':'column',
-            receive: function(event, ui) { alert("template attempted to receive");} 
-    });
-
-    $('.td-div').sortable({
-            'cursor':'pointer',
-            'tolerance': 'pointer',
-            'items':'.gsf_metadata, .gsf_choose_metadata, .gsf_link, .gsf_switch',
-            'placeholder':'placeholder',
-            receive: function(event, ui) { alert("td-div attempted to receive"); },
-            stop: function(event, ui) {
-                // gsf metadata
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_metadata')) { replace_with(ui.item, gsf_metadata_element); }
-                // gsf choose metadata
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_choose_metadata')) { replace_with(ui.item, gsf_choose_metadata_element); }
-                // gsf link
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_link')) { replace_with(ui.item, gsf_link_element); }
-                // gsf switch
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_switch')) { replace_with(ui.item, gsf_switch_element); }
-                
-            }
-
-    });
-
-    $('.td-div').click(function () {    
-         //console.log('td class click');
-         return true;
-    });
-
-
-
-}
-
-
-function bind_choose_metadata_sortable()
-{
-    //console.log('function bind_choose_metadata_sortable()');
-    $('.gsf_choose_metadata').sortable({
-            'cursor':'pointer',
-            'tolerance': 'pointer',
-            'items':'.gsf_metadata, .gsf_text, .gsf_default',
-            'placeholder':'placeholder',
-            'connectWith':'.gsf_choose_metadata',
-            //'nested':'.gsf:metadata'
-            receive: function(event, ui) { alert("choose-metadata attempted to receive"); },
-            stop: function(event, ui) {
-                // gsf metadata
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_metadata')) { 
-                    console.log(gsf_metadata_element);
-                    replace_with(ui.item, gsf_metadata_element); 
-                } 
-                // gsf text
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_text')) { replace_with(ui.item, gsf_text_element); } 
-                // gsf default
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_default')) { replace_with(ui.item, gsf_default_element); } 
-
-                bind_all_sortables();
-            }
-    });
-}
-
-function bind_link_sortable()
-{
-    //console.log('function bind_link_sortable()');
-    $('.gsf_link').sortable({
-            'cursor':'pointer',
-            'tolerance': 'pointer',
-            'items':'.leaf, .gsf_link, .gsf_switch, .gsf_choose',
-            'placeholder':'placeholder',
-            'connectWith':'.gsf_link',
-            //'nested':'.gsf:metadata'
-            stop: function(event, ui) {
-                // gsf icon
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_icon')) { replace_with(ui.item, gsf_icon_element); }
-                // gsf text
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_text')) { replace_with(ui.item, "<input type=\"text\" name=\"rawtextinput\" size=\"10\"/>"); }
-                // gsf metadata
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_metadata')) { replace_with(ui.item, gsf_metadata_element); } 
-                // gsf link
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_link')) { replace_with(ui.item, gsf_link_element); }
-                // gsf switch
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_switch')) { replace_with(ui.item, gsf_switch_element); }
-                // gsf choose
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_choose_metadata')) { replace_with(ui.item, gsf_choose_metadata_element); }
-            }
-    });
-}
-
-function bind_switch_sortable()
-{
-    //console.log('function bind_switch_sortable()');
-    $('.gsf_switch').sortable({
-            'cursor':'pointer',
-            'tolerance': 'pointer',
-            'items':'.gsf_metadata, .gsf_when, .gsf_otherwise, .gsf_text',
-            'placeholder':'placeholder',
-            'connectWith':'.gsf_switch',
-            //'nested':'.gsf:metadata'
-            stop: function(event, ui) {
-                // gsf when
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_when')) { replace_with(ui.item, gsf_when_element); }
-                // gsf otherwise
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_otherwise')) { replace_with(ui.item, gsf_otherwise_element); }
-                // gsf metadata
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_metadata')) { replace_with(ui.item, gsf_metadata_element); } 
-                // gsf text
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_text')) { replace_with(ui.item, gsf_text_element); } 
-            }
-    });
-}
-
-function bind_when_sortable()
-{
-    //console.log('function bind_when_sortable()');
-    $('.gsf_when').sortable({
-            'cursor':'pointer',
-            'tolerance': 'pointer',
-            'items':'.leaf, .gsf_link, .gsf_choose',
-            'placeholder':'placeholder',
-            //'nested':'.gsf:metadata'
-            stop: function(event, ui) {
-                // gsf metadata
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_metadata')) { replace_with(ui.item, gsf_metadata_element); }
-                // gsf icon
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_icon')) { replace_with(ui.item, gsf_icon_element); } 
-                // gsf text
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_text')) { replace_with(ui.item, gsf_text_element); } 
-                // gsf link
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_link')) { replace_with(ui.item, gsf_link_element); } 
-                // gsf choose
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_choose')) { replace_with(ui.item, gsf_choose_element); } 
-            }
-    });
-}
-
-function bind_otherwise_sortable()
-{
-    //console.log('function bind_otherwise_sortable()');
-    $('.gsf_otherwise').sortable({
-            'cursor':'pointer',
-            'tolerance': 'pointer',
-            'items':'.leaf, .gsf_link, .gsf_choose',
-            'placeholder':'placeholder',
-            //'nested':'.gsf:metadata'
-            stop: function(event, ui) {
-                // gsf metadata
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_metadata')) { replace_with(ui.item, gsf_metadata_element); }
-                // gsf text
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_text')) { replace_with(ui.item, "<input type=\"text\" name=\"rawtextinput\" size=\"10\"/>"); }
-                // gsf icon
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_icon')) { replace_with(ui.item, gsf_icon_element); } 
-                // gsf link
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_link')) { replace_with(ui.item, gsf_link_element); } 
-                // gsf choose
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_choose')) { replace_with(ui.item, gsf_choose_element); } 
-            }
-    });
-}
-
-function bind_block_mouseover()
-{
-    //console.log('function bind_block_mouseover()');
-    $(".block").mouseover(function()
-    {
-        $(this).parents().css("border", "");
-        $(this).css("border", "2px solid blue");
-        return false;
-    }).mouseout(function(){
-        $(this).css("border", "");
-        return false;
-    });
-}
-
-function bind_minmax_remove()
-{
-    console.log('function bind_minmax_remove()');
-    $('a.minmax').bind('click', toggleContent);
-    $('a.remove').bind('click', removeContent);
-};
-
-var removeContent = (function () {
-    //console.log('var removeContent = (function ()');
-        // this -> a -> td -> tr -> tbody -> table -> div
-        //$(this).parent().parent().parent().parent().parent().remove();
-        $(this).closest(".block").remove();
-    });
-
-
-var toggleContent = function(e)
-{
-    console.log('parent: ' + $(this).html());
-    if ($(this).html() == '[+]'){ //targetContent.css('display') == 'none') {
-        $(this).closest(".block").children(".table, .block").slideDown(300);
-        $(this).html('[-]');
-        $(this).removeClass("ui-icon-plusthick");
-        $(this).addClass("ui-icon-minusthick");
-    } else {
-        $(this).closest(".block").children(".table, .block").slideUp(300);
-        $(this).html('[+]');
-        $(this).removeClass("ui-icon-minusthick");
-        $(this).addClass("ui-icon-plusthick");
-    }
-    return false;
-};
-
-function serialize(s)
-{
-    serial = $.SortSerialize(s);
-    alert(serial.hash);
-};
-
-function equalHeights(item, height) {
-    //console.log('function equalHeights(item, height)');
-    (item.parents('.table')).each(function(index) {
-        $(this).children().children().children().each(function() {
-            $(this).height(height);
-            $(this).children().height(height);
-        });
-    });
-};
-
Index: in/trunk/greenstone3/web/interfaces/default/js/formateditor/gui_div.js
===================================================================
--- /main/trunk/greenstone3/web/interfaces/default/js/formateditor/gui_div.js	(revision 27713)
+++ 	(revision )
@@ -1,1301 +1,0 @@
-
-console.log("Loading gui_div.js\n");
-
-/* DOCUMENT SPECIFIC FUNCTIONS */
-
-function displayTOC(checkbox)
-{
-    if (checkbox.checked == true)
-    {
-        console.log("Show the TOC!");
-        displaySideBar(true);
-        $("#tableOfContents").css("display", "block");
-    }
-    else
-    {
-        console.log("Hide the TOC!");
-        $("#tableOfContents").css("display", "none");
-        if ($("#coverImage").css("display") == "none")
-            displaySideBar(false);
-    }
-
-    return;
-}
-
-function displayBookCover(checkbox)
-{
-    if (checkbox.checked == true)
-    {
-        console.log("Show the book cover!");
-        displaySideBar(true);
-        $("#coverImage").css("display", "block");
-    }
-    else
-    {
-        console.log("Hide the book cover!");
-        $("#coverImage").css("display", "none");
-        if ($("#tableOfContents").css("display") == "none")
-            displaySideBar(false);
-    }
-
-    return;
-}
-
-function displaySideBar(toggle)
-{
-    if (toggle == true)
-    {
-        console.log("Show the sidebar!");
-        $("#rightSidebar").css("display", "block");
-    }
-    else
-    {
-        console.log("Hide the sidebar!");
-        $("#rightSidebar").css("display", "none");
-    }
-
-    return;
-}
-
-function checkDocumentRadio()
-{
-    var selection = $('input[name="documentChanges"]'); //document.quiz.colour;
-
-    for (i=0; i<selection.length; i++)
-
-        if (selection[i].checked == true)
-            return selection[i].value;
-
-    return "this";
-}
-
-function saveDocumentChanges()
-{
-    console.log("Saving changes to "+checkDocumentRadio());
-    console.log("TOC="+$('input[name="TOC"]').attr('checked'));
-    console.log("Cover Image="+$('input[name="bookCover"]').attr('checked'));
-
-    var myurl = document.URL;
-
-    var collection_name = getSubstring(myurl, "&c", "&");
-    var document_id = getSubstring(myurl, "&d", "&");
-    var document_type = getSubstring(myurl, "&dt", "&");
-    var prev_action = getSubstring(myurl, "&p.a", "&");
-    var prev_service = getSubstring(myurl, "&p.s", "&");
-
-    var post_url = "http://localhost:8383/greenstone3/dev?a=f&sa=saveDocument&c=" + collection_name + "&d=" + document_id + "&dt=" + document_type + "&p.a=" + prev_action + "&p.s=" + prev_service;
-
-    // XML will be automatically wrapped in <display><format> tags when saved to collection config
-    var xml = '<format><gsf:option name="TOC" value="'+$('input[name="TOC"]').attr('checked')+'"/><gsf:option name="coverImage" value="'+$('input[name="bookCover"]').attr('checked')+'"/></format>';
-
-    $.post(post_url, {data: xml}, function(data) {
-            console.log("Success, we have received data");
-    }, 'xml');
-}
-
-/* FUNCTIONS FOR FORMAT EDITING */                                                                    
-
-// Ensures that a change to a text field is remembered
-function onTextChange(item, text)
-{
-    console.log("I have set "+item+".value to "+text);
-    item.setAttribute("value",text);
-}
-
-// Ensures that a change to a select field is remembered
-function onSelectChange(item)
-{
-    console.log("I have set "+item.value+".selected to selected");
-    for (var i=0; i<item.options.length; i++)
-    {
-        if(item.selectedIndex == i)
-            item.options[i].setAttribute("selected", "selected");
-        else
-            item.options[i].removeAttribute("selected");
-    }
-    //item.options[item.selectedIndex].selected = "selected";
-    //item.setAttribute("selected","selected");
-}
-
-function getSubstring(str, first, last)
-{
-    var first_index = str.indexOf(first)+first.length+1;
-    var last_index = str.indexOf(last, first_index);
-
-    if(last_index == -1)
-        last_index = str.length;
-
-    var substring = str.substring(first_index, last_index);
-
-    console.log(substring);
-
-    return substring;
-}
-    
-function getFormatStatement()
-{
-    var formatDiv = document.getElementById('formatStatement');
-    var formatStatement = innerXHTML(formatDiv);
-    return formatStatement;
-}
-
-function checkClassifierRadio()
-{
-    var selection = $('input[name="classifiers"]'); //document.quiz.colour;
-
-    for (i=0; i<selection.length; i++)
-
-          if (selection[i].checked == true)
-              return selection[i].value;
-
-    return "this";
-
-}
-
-function updateFormatStatement()
-{
-    var formatStatement = getFormatStatement();
-
-    var thisOrAll = checkClassifierRadio();
-    console.log(thisOrAll);
-    var myurl = document.URL;
-
-    var collection_name = getSubstring(myurl, "&c", "&");
-    var service_name = getSubstring(myurl, "&s", "&");  
-
-    if(thisOrAll == "all")
-        service_name = "AllClassifierBrowse";
-
-    var classifier_name = null;
-
-    if(service_name == "ClassifierBrowse")
-        classifier_name = getSubstring(myurl, "&cl", "&");
-
-    var post_url = "http://localhost:8383/greenstone3/dev?a=f&sa=update&c=" + collection_name +"&s=" + service_name;
-
-    if(classifier_name != null)
-        post_url = post_url + "&cl=" + classifier_name;
-
-    $.post(post_url, {data: formatStatement}, function(data) {
-        //$('.result').innerHTML = data; //html(data);
-    
-        // An error is returned because there is no valid XSLT for a format update action, there probably shouldn't be one so we ignore what the post returns.    
-        console.log("Successfully updated");
-        //console.log(data);
-        }, 'html');
-}
-
-function saveFormatStatement()
-{
-    var formatStatement = getFormatStatement();
-    var thisOrAll = checkClassifierRadio();
-
-    var myurl = document.URL;
-
-    var collection_name = getSubstring(myurl, "&c", "&");
-    var service_name = getSubstring(myurl, "&s", "&");
-    var classifier_name = null;
-
-    if(thisOrAll == "all")
-        service_name = "AllClassifierBrowse";
-
-    if(service_name == "ClassifierBrowse")
-        classifier_name = getSubstring(myurl, "&cl", "&");
-
-    var post_url = "http://localhost:8383/greenstone3/dev?a=f&sa=save&c=" + collection_name +"&s=" + service_name;
-
-    if(classifier_name != null)
-        post_url = post_url + "&cl=" + classifier_name;
-
-    $.post(post_url, {data: formatStatement}, function(data) {
-        // An error is returned because there is no valid XSLT for a format update action, there probably shouldn't be one so we ignore what the post returns.    
-        console.log("Successfully saved");
-        }, 'html');
-}
-
-function getXSLT(classname)
-{
-    var myurl = document.URL;
-
-    var collection_name = getSubstring(myurl, "&c", "&");
-    var document_id = getSubstring(myurl, "&d", "&");
-    var document_type = getSubstring(myurl, "&dt", "&");
-    var prev_action = getSubstring(myurl, "&p.a", "&");
-    var prev_service = getSubstring(myurl, "&p.s", "&");
-
-    var post_url = "http://localhost:8383/greenstone3/dev?a=d&c=" + collection_name + "&d=" + document_id + "&dt=" + document_type + "&p.a=" + prev_action + "&p.s=" + prev_service + "&o=skinandlib";
-
-    $.post(post_url, {data: classname}, function(data) {
-            console.log("Success, we have received data");
-            classname = "." + classname;
-            console.log(classname); 
-            var content = $( data ).find(classname);
-            console.log(content.xml());
-            $("#XSLTcode").val(content.xml());
-            }, 'xml');
-}
-
-function traverse(node, formatstring)
-  {
-
-    if(node.nodeName=='DIV')
-    {
-        console.log("Found a div" +node.nodeName+","+node.nodeType);
-        formatstring = formatstring + find_class(node);
-        console.log(formatstring);
-    }
-
-    var children = $(node).children();
-    for(var i=0; i < children.length; i++)
-        formatstring = formatstring + traverse(children[i], formatstring);
-
-    return formatstring;
-  }
-        
-function find_class(current)
-{
-    var classes = current.className.split(' ');
-    var none = "";
-    for(var i = 0; i < classes.length; i++)
-    {
-        switch(classes[i])
-        {
-            case 'gsf_template':
-              return create_gsf_template(current);
-            default:
-            {
-              console.log("Class not found");
-              return none;
-            }
-        }
-    }
-}
-
-function create_gsf_template(current)
-{
-    // find match text which is an input with class match
-    var match = $(current).find('.match')[0].value;
-    console.log(match);
-    
-    // find mode text which is an input with class mode
-    var mode = $(current).find('.mode')[0].value;
-    console.log(mode);
-
-    // "<gsf:template match=\"classifierNode\" mode=\"horizontal\">"
-    var gsf = "<gsf:template match=\"" + match + "\"";
-    if(mode != "vertical")
-        gsf = gsf + " mode=\"" + mode + "\"";
-    gsf = gsf + ">";
-    
-    return gsf;
-
-}
-
-/*
-$("#iframe").ready(function(){
-        console.log("iframe is ready ...");
-        var iframe = document.getElementById('iframe');
-        var iframe_document = iframe.document;
-
-        if(iframe.contentDocument)
-        {
-            iframe_document = iframe.contentDocument; // For NS6
-            console.log("Chose content document");
-        }
-        else if(iframe.contentWindow)
-        {
-            iframe_document = iframe.contentWindow.document; // For IE5.5 and IE6
-            console.log("Chose content window");
-        }
-
-        console.log(iframe_document.documentElement.innerHTML); //document.documentElement.outerHTML
-
-        $(iframe_document.documentElement.innerHTML).find('a').each(function() {
-            console.log("data "+$(this).data('href'));
-            console.log("getAttribute "+$(this).getAttribute('href'));
-            console.log("attr "+$(this).attr('href'));
-            console.log("this.href "+this.href);
-            var original = this.href; //$(this).attr('href');
-            // check if greenstone link ie. starts with format
-            //var original = $(this).data('href');
-            var modified = original.toString().concat("&excerptid=gs_content");
-            console.log(modified);
-            this.href = modified;
-            //$(this).attr('href',modified);
-            //$(this).data('href', modified);
-            //console.log($(this).attr('href'));
-            console.log("data "+$(this).data('href'));
-            console.log("getAttribute "+$(this).getAttribute('href'));
-            console.log("attr "+$(this).attr('href'));
-            console.log("this.href "+this.href);
-            console.log("**********");
-
-        });
-}); */
-/*
-function loadXMLDoc()
-{
-    if (window.XMLHttpRequest)
-    {// code for IE7+, Firefox, Chrome, Opera, Safari
-        xmlhttp=new XMLHttpRequest();
-    }
-    else
-    {// code for IE6, IE5
-        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
-    }
-    
-    xmlhttp.onreadystatechange=function()
-    {  
-        console.log("state changed to " + xmlhttp.readyState);
-        console.log("status is " + xmlhttp.status);
-        if (xmlhttp.readyState==4 && xmlhttp.status==200)
-        {
-            console.log("get code");
-            console.log(xmlhttp.responseText);
-            document.getElementById("gs_content").innerHTML=xmlhttp.responseText;
-        }
-    }
-    
-    xmlhttp.open("GET","http://localhost:8080/greenstone3/format?a=b&rt=s&s=ClassifierBrowse&c=simpleht&cl=CL1&excerptid=gs_content",true);
-    //xmlhttp.open("GET","http://www.cs.waikato.ac.nz",true);
-    //xmlhttp.open("GET","http://wand.net.nz/~sjb48/index.html",true);
-    xmlhttp.send();
-}
-*/
-$(document).ready(function(){
-
-    console.log("Document ready function\n");
-	
-    CURRENT_SELECT_VALUE = ""; //global - gets set by ui.draggable
-
-    /* DOCUMENT SPECIFIC FUNCTIONS */
-
-    $('.sectionHeader').click(function () {
-        console.log('section Header click *');
-        getXSLT("sectionHeader");
-        return false; //don't event bubble
-    });
-
-    $('.sectionContainer').click(function () {
-        console.log('section Container click *');
-        getXSLT("sectionContainer");
-        return false; // don't event bubble
-    });
-	
-	var collection = "";
-	
-	var regex = new RegExp("[?&]c=");
-	var matches = regex.exec(document.URL);
-	if(matches != null)
-	{
-		var startIndex = matches.index;
-		var endIndex = document.URL.indexOf("&", startIndex + 1);
-		
-		if(endIndex == -1)
-		{
-			endIndex = document.URL.length;
-		}
-		
-		collection = document.URL.substring(startIndex, endIndex);
-	}
-
-	//Retrieve the collection metadataset using ajax
-	$.ajax
-	({
-		type: "GET",
-		url: "?a=g&s=CoverageMetadataRetrieve&o=xml&rt=r&c=" + collection,
-		success: function(data) 
-		{
-			var str = "<select name=\"meta_select\" onChange=\"onSelectChange(this)\">";
-			
-			var selectorArea = document.getElementById("metadataSelector");		
-			var metadataSets = data.getElementsByTagName("metadataSet");
-			for(var i = 0; i < metadataSets.length; i++)
-			{
-				var metadata = metadataSets[i].getElementsByTagName("metadata");
-				for(var j = 0; j < metadata.length; j++)
-				{
-					var metaValue = metadataSets[i].getAttribute("name") + "." + metadata[j].getAttribute("name");
-					str += "<option value=\"" + metaValue + "\">" + metaValue + "</option>";
-				}
-			}
-			
-			str += "</select>";
-
-			selectorArea.innerHTML = str;
-			gsf_metadata_element = str;
-		}
-	});
-
-$.ui.plugin.add("draggable", "cursor", {
-	start: function(event, ui) {
-		var t = $('body'), o = $(this).data('draggable').options;
-		if (t.css("cursor")) o._cursor = t.css("cursor");
-		t.css("cursor", o.cursor);
-	},
-	stop: function(event, ui) {
-		var o = $(this).data('draggable').options;
-		if (o._cursor) $('body').css("cursor", o._cursor);
-	}
-});
-
-	$.ui.draggable.prototype._createHelper = function(event) {
-
-                var o = this.options;
-                var helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event])) : (o.helper == 'clone' ? this.element.clone().removeAttr('id') : this.element);
-
-		var select = $(this.element).find('select');
-		var value = select.attr('value');
-		console.log("Found "+value+" in helper");
-		CURRENT_SELECT_VALUE = value;
-		helper.find('select').attr('value', value);
-
-                if(!helper.parents('body').length)
-                        helper.appendTo((o.appendTo == 'parent' ? this.element[0].parentNode : o.appendTo));
-
-                if(helper[0] != this.element[0] && !(/(fixed|absolute)/).test(helper.css("position")))
-                        helper.css("position", "absolute");
-
-                return helper;
-
-        };
-	
-	$.ui.sortable.prototype._removeCurrentsFromItems = function() {
-		//console.log("IN _removeCurrentsFromItems FUNCTION");
-		//console.log("this = " + this.currentItem[0].getAttribute('class'));
-		var list = this.currentItem.find(":data(sortable-item)");
-
-		var i = 0;
-		while (i<this.items.length) {
-			var found_match = false;
-			for (var j=0; j<list.length; j++) {
-				if(this.items[i])
-				{
-					if(list[j] == this.items[i].item[0]) {
-						//console.log("Item to splice = " + this.items[i].item[0].getAttribute('class'));
-						this.items.splice(i,1);
-						found_match = true;
-						break;
-					}
-				}
-			};
-			if (!found_match)
-				i++;
-			else
-				break;
-		}
-	};
-	
-	$.ui.plugin.add("draggable", "connectToSortable", {
-	start: function(event, ui) {
-        //console.log("FUNCTION start draggable connectToSortable");
-		var inst = $(this).data("draggable"), o = inst.options,
-			uiSortable = $.extend({}, ui, { item: inst.element });
-		inst.sortables = [];
-		$(o.connectToSortable).each(function() {
-			var sortable = $.data(this, 'sortable');
-			if (sortable && !sortable.options.disabled) {
-				inst.sortables.push({
-					instance: sortable,
-					shouldRevert: sortable.options.revert
-				});
-				sortable._refreshItems();	//Do a one-time refresh at start to refresh the containerCache
-				sortable._trigger("activate", event, uiSortable);
-			}
-		});
-
-	},
-	stop: function(event, ui) {
-
-        //console.log("FUNCTION stop draggable connectToSortable");
-		//If we are still over the sortable, we fake the stop event of the sortable, but also remove helper
-		var inst = $(this).data("draggable"),
-			uiSortable = $.extend({}, ui, { item: inst.element });
-
-		$.each(inst.sortables, function() {
-			if(this.instance.isOver) {
-
-				this.instance.isOver = 0;
-
-				inst.cancelHelperRemoval = true; //Don't remove the helper in the draggable instance
-				this.instance.cancelHelperRemoval = false; //Remove it in the sortable instance (so sortable plugins like revert still work)
-
-				//The sortable revert is supported, and we have to set a temporary dropped variable on the draggable to support revert: 'valid/invalid'
-				if(this.shouldRevert) this.instance.options.revert = true;
-
-				//Trigger the stop of the sortable
-                //console.log("Draggable tells sortable to stop");
-				this.instance._mouseStop(event);
-
-				this.instance.options.helper = this.instance.options._helper;
-
-				//If the helper has been the original item, restore properties in the sortable
-				if(inst.options.helper == 'original')
-					this.instance.currentItem.css({ top: 'auto', left: 'auto' });
-
-			} else {
-				this.instance.cancelHelperRemoval = false; //Remove the helper in the sortable instance
-				this.instance._trigger("deactivate", event, uiSortable);
-			}
-
-		});
-
-	},
-	drag: function(event, ui) {
-        //console.log("FUNCTION drag draggable connectToSortable");
-
-		var inst = $(this).data("draggable"), self = this;
-
-		var checkPos = function(o) {
-			var dyClick = this.offset.click.top, dxClick = this.offset.click.left;
-			var helperTop = this.positionAbs.top, helperLeft = this.positionAbs.left;
-			var itemHeight = o.height, itemWidth = o.width;
-			var itemTop = o.top, itemLeft = o.left;
-
-			return $.ui.isOver(helperTop + dyClick, helperLeft + dxClick, itemTop, itemLeft, itemHeight, itemWidth);
-		};
-
-        var intersecting_items = new Array();
-
-		$.each(inst.sortables, function(i) {
-			
-			//Copy over some variables to allow calling the sortable's native _intersectsWith
-			this.instance.positionAbs = inst.positionAbs;
-			this.instance.helperProportions = inst.helperProportions;
-			this.instance.offset.click = inst.offset.click;
-			
-			if(this.instance._intersectsWith(this.instance.containerCache)) {
-
-				//If it intersects, we use a little isOver variable and set it once, so our move-in stuff gets fired only once
-				//if(!this.instance.isOver) {
-
-                    //console.log('Line 1113');
-
-				//	this.instance.isOver = 1;
-
-                    intersecting_items.push(this.instance); // sam
-                //} //sam
-
-					//Now we fake the start of dragging for the sortable instance,
-					//by cloning the list group item, appending it to the sortable and using it as inst.currentItem
-					//We can then fire the start event of the sortable with our passed browser event, and our own helper (so it doesn't create a new one)
-					//sam this.instance.currentItem = $(self).clone().appendTo(this.instance.element).data("sortable-item", true);
-					//sam this.instance.options._helper = this.instance.options.helper; //Store helper option to later restore it
-					//sam this.instance.options.helper = function() { return ui.helper[0]; };
-
-					//sam event.target = this.instance.currentItem[0];
-					//sam this.instance._mouseCapture(event, true);
-					//sam this.instance._mouseStart(event, true, true);
-
-					//Because the browser event is way off the new appended portlet, we modify a couple of variables to reflect the changes
-					//sam this.instance.offset.click.top = inst.offset.click.top;
-					//sam this.instance.offset.click.left = inst.offset.click.left;
-					//sam this.instance.offset.parent.left -= inst.offset.parent.left - this.instance.offset.parent.left;
-					//sam this.instance.offset.parent.top -= inst.offset.parent.top - this.instance.offset.parent.top;
-
-					//sam inst._trigger("toSortable", event);
-					//sam inst.dropped = this.instance.element; //draggable revert needs that
-					//hack so receive/update callbacks work (mostly)
-					//sam inst.currentItem = inst.element;
-					//sam this.instance.fromOutside = inst;
-
-				//sam brace
-
-				//Provided we did all the previous steps, we can fire the drag event of the sortable on every draggable drag, when it intersects with the sortable
-				//sam if(this.instance.currentItem) this.instance._mouseDrag(event);
-
-			} else {
-
-				//If it doesn't intersect with the sortable, and it intersected before,
-				//we fake the drag stop of the sortable, but make sure it doesn't remove the helper by using cancelHelperRemoval
-				if(this.instance.isOver) {
-
-                    console.log("UNSETTING ISOVER");
-                    console.log("ON ITEM="+this.instance.currentItem[0].getAttribute('class'))
-					this.instance.isOver = 0;
-					this.instance.cancelHelperRemoval = true;
-					
-					//Prevent reverting on this forced stop
-					this.instance.options.revert = false;
-					
-					// The out event needs to be triggered independently
-					this.instance._trigger('out', event, this.instance._uiHash(this.instance));
-					
-					this.instance._mouseStop(event, true);
-					this.instance.options.helper = this.instance.options._helper;
-
-					//Now we remove our currentItem, the list group clone again, and the placeholder, and animate the helper back to it's original size
-                    //console.log("DO WE GET HERE?");
-					this.instance.currentItem.remove();
-					if(this.instance.placeholder) this.instance.placeholder.remove();
-
-					inst._trigger("fromSortable", event);
-					inst.dropped = false; //draggable revert needs that
-				
-	            }
-       
-            } 
-        });
-
-        //sam
-        //console.log("Contents of intersecting_items");
-        var innermostContainer = null, innermostIndex = null;       
-        for (i=0;i<intersecting_items.length;i++)
-        {
-            //console.log('ITEM: '+intersecting_items[i].element[0].getAttribute('class'));
-    
-            if(innermostContainer && $.ui.contains(intersecting_items[i].element[0], innermostContainer.element[0]))
-                continue;
-                        
-            innermostContainer = intersecting_items[i];
-            innermostIndex = i; 
-                    
-        }
-
-        for (i=0;i<intersecting_items.length;i++)
-        {
-            if(intersecting_items[i] != innermostContainer)
-                if(intersecting_items[i].isOver) {
-
-                    console.log("UNSETTING ISOVER");
-                    console.log("ON ITEM="+intersecting_items[i].currentItem[0].getAttribute('class'))
-                    intersecting_items[i].isOver = 0;
-                    intersecting_items[i].cancelHelperRemoval = true;
-
-                    //Prevent reverting on this forced stop
-                    intersecting_items[i].options.revert = false;
-
-                    // The out event needs to be triggered independently
-                    intersecting_items[i]._trigger('out', event, intersecting_items[i]._uiHash(intersecting_items[i]));
-
-                    intersecting_items[i]._mouseStop(event, true);
-                    intersecting_items[i].options.helper = intersecting_items[i].options._helper;
-
-                    //Now we remove our currentItem, the list group clone again, and the placeholder, and animate the helper back to it's original size
-                    //console.log("DO WE GET HERE?");
-                    if(intersecting_items[i].currentItem) intersecting_items[i].currentItem.remove();
-                    if(intersecting_items[i].placeholder) intersecting_items[i].placeholder.remove();
-
-                    inst._trigger("fromSortable", event);
-                    inst.dropped = false; //draggable revert needs that
-                }
-
-                intersecting_items[i].isOver = 0;
-            
-        }
-
-        if(innermostContainer && !innermostContainer.isOver)
-        {
-            console.log("INNER="+innermostContainer.element[0].getAttribute('class'));
-            console.log("SETTING ISOVER");
-    	    innermostContainer.isOver = 1;
-
-            //Now we fake the start of dragging for the sortable instance,
-            //by cloning the list group item, appending it to the sortable and using it as inst.currentItem
-            //We can then fire the start event of the sortable with our passed browser event, and our own helper (so it doesn't create a new one)
-
-            if(innermostContainer.currentItem) innermostContainer.currentItem.remove();
-            if(innermostContainer.placeholder) innermostContainer.placeholder.remove();
-
-            innermostContainer.currentItem = $(self).clone().appendTo(innermostContainer.element).data("sortable-item", true);
-            
-            innermostContainer.options._helper = innermostContainer.options.helper; //Store helper option to later restore it
-            innermostContainer.options.helper = function() { return ui.helper[0]; };
-
-            console.log("EVENT TARGET="+innermostContainer.currentItem[0].getAttribute('class'));
-            event.target = innermostContainer.currentItem[0];
-            innermostContainer._mouseCapture(event, true);
-            innermostContainer._mouseStart(event, true, true);
-
-            //Because the browser event is way off the new appended portlet, we modify a couple of variables to reflect the changes
-            innermostContainer.offset.click.top = inst.offset.click.top;
-            innermostContainer.offset.click.left = inst.offset.click.left;
-            innermostContainer.offset.parent.left -= inst.offset.parent.left - innermostContainer.offset.parent.left;
-            innermostContainer.offset.parent.top -= inst.offset.parent.top - innermostContainer.offset.parent.top;
-
-            inst._trigger("toSortable", event);
-            inst.dropped = innermostContainer.element; //draggable revert needs that
-            //hack so receive/update callbacks work (mostly)
-            inst.currentItem = inst.element;
-            innermostContainer.fromOutside = inst;
-
-            //sam brace
-        }
-
-        if(innermostContainer)
-        {
-            //Provided we did all the previous steps, we can fire the drag event of the sortable on every draggable drag, when it intersects with the sortable
-            if(innermostContainer.currentItem) innermostContainer._mouseDrag(event);
-        }
-
-	}
-});
-
-    /*
-    var iframe = document.getElementById('iframe');
-    var iframe_document = iframe.document;
-   
-    if(iframe.contentDocument)
-    {
-        iframe_document = iframe.contentDocument; // For NS6
-        console.log("Chose content document");
-    }
-    else if(iframe.contentWindow)
-    {
-        iframe_document = iframe.contentWindow.document; // For IE5.5 and IE6
-        console.log("Chose content window");
-    }
-
-    // Edit the hrefs in preview_html - search for <a href="format?a=b&rt=r&s=ClassifierBrowse&c=simpleht&cl=CL1.2">
-    var start_index = 0;
-    var end_index = 0;
-    while(start_index != -1)
-    {
-        start_index = preview_html.indexOf("href=\"format", start_index);
-        console.log("start index = " + start_index);
-        if(start_index != -1)
-        {
-            end_index = preview_html.indexOf("\">", start_index);
-            console.log("end_index = " + end_index);
-            a = preview_html.substring(0,end_index);
-            b = preview_html.substring(end_index);
-            preview_html = a.concat("&excerptid=results", b);
-            console.log(preview_html);
-            start_index = end_index + "&excerptid=results\">".length;
-        }
-    }
-
-    // Split the html code in to three parts
-    var first_index = preview_html.indexOf("<ul id=\"results\"");
-    console.log("First index is "+first_index);
-    var second_index = preview_html.indexOf("</ul>", first_index) + "</ul>".length;
-    console.log("Second index is "+second_index);
-
-    var first_half = preview_html.substring(0, first_index);
-    var iframe_code = preview_html.substring(first_index, second_index);
-    var second_half = preview_html.substring(second_index);
-
-    //$('#my_categories').innerHTML = first_half.concat(second_half);
-    document.getElementById("my_categories").innerHTML = first_half.concat(second_half);
-
-    // Put the content in the iframe
-    if(initialised_iframe == "false")
-    {
-        console.log("Initialised iframe with preview html");
-        console.log(preview_html);
-        iframe_document.open();
-        iframe_document.writeln(iframe_code); //.concat("&excerptid=gs_content"));
-        iframe_document.close(); 
-        initialised_iframe = "true";
-    }
-    */
-
-    /*    
-    $(iframe_document.documentElement.innerHTML).find('a').each(function() {
-            console.log("data "+$(this).data('href'));
-            console.log("getAttribute "+this.getAttribute('href'));
-            console.log("attr "+$(this).attr('href'));
-            console.log("this.href "+this.href);
-            var original = this.href; //$(this).attr('href');
-            // check if greenstone link ie. starts with format
-            //var original = $(this).data('href');
-            var modified = original.toString().concat("&excerptid=gs_content");
-            console.log("*                      *");
-            console.log(modified);
-            console.log("*                      *");
-            //this.href = modified;
-            //$(this).attr('href',modified);
-            //$(this).data('href', modified);
-            $(this).attr({ 'href': modified });
-            //console.log($(this).attr('href'));
-            console.log("data "+$(this).data('href'));
-            console.log("getAttribute "+this.getAttribute('href'));
-            console.log("attr "+$(this).attr('href'));
-            console.log("this.href "+this.href);
-            console.log("***********************");
-    });
-    */
-
-    /******************************************/
-    /*              DRAGGABLES                */
-    /******************************************/
-
-    $(".draggable_gsf_template").draggable({
-            cursor: 'crosshair',
-            connectToSortable: '#formatStatement',
-            helper: 'clone',
-            revert: 'invalid'
-    });
-
-    $(".draggable_table").draggable({
-            cursor: 'crosshair',
-            connectToSortable: '.gsf_template',
-            helper: 'clone',
-            revert: 'invalid'
-    });
-
-    $(".draggable_tr").draggable({
-            cursor: 'crosshair',
-            connectToSortable: '.gsf_table',
-            helper: 'clone',
-            revert: 'invalid'
-    })
-
-    $(".draggable_td").draggable({
-            cursor: 'crosshair',
-            //connectToSortable: '.td',
-            helper: 'clone',
-            revert: 'invalid'
-    })
-
-    $(".draggable_gsf_text").draggable({
-            cursor: 'crosshair',
-            connectToSortable: '.td-div, .gsf_when, .gsf_otherwise, .gsf_link, .gsf_choose_metadata, .gsf_default',
-            helper: 'clone',
-            revert: 'invalid'
-    });
-    
-    $(".draggable_gsf_choose_metadata").draggable({
-            cursor: 'crosshair',
-            connectToSortable: '.td-div, .gsf_link, .gsf_when, .gsf_otherwise',
-            helper: 'clone',
-            revert: 'invalid'
-    });
-
-    //$(".element_type_gsf_metadata").draggable({
-    $(".draggable_gsf_metadata").draggable({
-            cursor: 'crosshair',
-            connectToSortable: '.gsf_choose_metadata, .gsf_when, .gsf_otherwise, .gsf_link, .td-div',
-            helper: 'clone',
-            revert: 'invalid'
-    });
-
-    $(".draggable_gsf_link").draggable({
-            cursor: 'crosshair',
-            connectToSortable: '.td-div, .gsf_when, .gsf_otherwise, .gsf_link',
-            helper: 'clone',
-            revert: 'invalid'
-    });
-
-    // switch, when, otherwise, icon
-    $(".draggable_gsf_switch").draggable({
-            cursor: 'crosshair',
-            connectToSortable: '.td-div, .gsf_link',
-            helper: 'clone',
-            revert: 'invalid'
-    });
-
-    $(".draggable_gsf_when").draggable({
-            cursor: 'crosshair',
-            connectToSortable: '.gsf_switch',
-            helper: 'clone',
-            revert: 'invalid'
-    });
-
-    $(".draggable_gsf_otherwise").draggable({
-            cursor: 'crosshair',
-            connectToSortable: '.gsf_switch',
-            helper: 'clone',
-            revert: 'invalid'
-    });
-
-    $(".draggable_gsf_icon").draggable({
-            cursor: 'crosshair',
-            connectToSortable: '.td-div, .gsf_link, .gsf_choose, .gsf_when, .gsf_otherwise',
-            helper: 'clone',
-            revert: 'invalid'
-    });
-
- 
-    /******************************************/
-    /*               SORTABLES                */
-    /******************************************/
-
-    bind_td_sortable();
-    bind_all_sortables();
-
-    $('#formatStatement').sortable({
-            cursor: 'pointer',
-            tolerance: 'pointer',
-            items: '.gsf_template',
-            placeholder:'placeholder',
-            //'nested':'div'
-            stop: function(event, ui) {
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('css_gsf_template')) { replace_with(ui.item,gsf_template_element); }
-            }
-    });
- 
-    $('div.gsf_template').children(".block,.table").slideUp(300); 
-}); 
-
-/*******************************************************************************/
-
-function bind_all_sortables()
-{
-    console.log('function bind_all_sortables()');
-    bind_template_sortable();
-    bind_choose_metadata_sortable();
-    bind_link_sortable();
-    bind_switch_sortable();
-    bind_when_sortable();
-    bind_otherwise_sortable();
-
-    bind_tables();
-
-    bind_block_mouseover();
-    bind_minmax_remove();    
-}
-
-function bind_tables()
-{
-    console.log('function bind_tables()');
-
-    $('#sectionHeader').click(function () {
-         console.log('section Header click *');
-         return true;
-    });
-    
-    $('#sectionContainer').click(function () {
-         console.log('section Container click *');
-         return true;
-    });
-
-    $(".td-div").resizable({
-                alsoResize: 'parent',
-                handles: 'w,e',
-                stop: function(event, ui) {
-                        console.log('Resize table on stop');
-                        resize_tables($(this));
-                }, });
-
-    $(".droppable").droppable({
-            accept: '.element_type_td',
-            tolerance: 'pointer', 
-            activate: function(event, ui) { $(this).addClass("droppable_hl");}, 
-            deactivate: function(event, ui) { $(this).removeClass("droppable_hl"); },
-            drop: function(event, ui) {
-                 var neverempty = document.createElement("div");
-                 neverempty.setAttribute("class","neverempty block");
-                 neverempty.setAttribute("style","height:50px");
-                 neverempty.setAttribute("style","display:block");
-                 var text = document.createTextNode('NEVER EMPTY');
-                 neverempty.appendChild(text);
-                 var td = document.createElement("td");
-                 var div = document.createElement("div"); 
-                 div.setAttribute("title","td-div");
-                 div.setAttribute("class","td-div block");
-                 div.setAttribute("style","margin-left:0px");
-                 div.setAttribute("width","25px");
-                 td.appendChild(div);
-                 div.appendChild(neverempty);
-                 var sep = document.createElement("td");
-                 sep.setAttribute("class","droppable");
-                 sep.setAttribute("width","10px"); 
-                 $(this).after(sep);                
-                 $(this).after(td);                
-                 bind_tables();
-                 resize_tables($(this));
-                 bind_td_sortable();
-                 bind_block_mouseover();
-            }
-        });
-
-}
-
-function replace_with(item, me)
-{
-    // Search me for select
-    if(me.search("select") != -1)
-    {
-    // If select exists, then find CURRENT_SELECT_VALUE
-	if(me.search(CURRENT_SELECT_VALUE) != -1)
-	{
-	    var index = me.search(CURRENT_SELECT_VALUE);
-            if(index == -1)
-                console.log("Did not find " + CURRENT_SELECT_VALUE);
-            else
-	    {
-                console.log("Found " + CURRENT_SELECT_VALUE + " at index " + index);    
-                index = index + CURRENT_SELECT_VALUE.length + 1;
-                console.log("Attempt inserting select at new index "+index);
-                a = me.substring(0,index);
-                b = me.substring(index);
-                me = a.concat("selected",b);
-            }
-	}
-    }
-
-    item.replaceWith(me); //'<div class="element element-txt">This text box has been added!</div>');
-
-    resize_tables(item);
-
-    bind_all_sortables();
-}
-
-function resize_tables(item)
-{
-    var max_height = 0;
-    (item.parents('.table')).each(function(index) {
-        $(this).children().children().children().each(function() {
-            var sum_one = 0;
-            var sum_two = 0;
-            $(this).children('.block').each(function() { sum_one = sum_one + $(this).height();  
-                $(this).children('.block').each(function() { sum_two = sum_two + $(this).height(); } );
-                console.log("My height is " + $(this).height() + ", sum height 2 is " + sum_two);
-            });
-            console.log("My height is " + $(this).height() + ", sum height 1 is " + sum_one);
-            if (sum_two > max_height)
-                max_height = sum_two;
-        });
-    });
-    equalHeights(item,max_height);
-}
-
-function bind_template_sortable()
-{
-    //console.log('function bind_template_sortable()');
-    $('.gsf_template').sortable({
-            'cursor':'pointer',
-            'tolerance': 'pointer',
-            'items':'.table', //.gsf_choose_metadata, .gsf_metadata',
-            'placeholder':'placeholder',
-            //'nested':'.gsf:metadata'
-            stop: function(event, ui) {
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_table')) { replace_with(ui.item, "<table class=\"table\" border=\"2\"></table>"); }
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_choose_metadata')) { replace_with(ui.item, gsf_choose_metadata_element); }
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_metadata')) { replace_with(ui.item, gsf_metadata_element); }
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_link')) { replace_with(ui.item, gsf_link_element); }
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_switch')) { replace_with(ui.item, gsf_switch_element); }
-            }
-    });
-
-    $('.gsf_template').click(function () {
-         console.log('gsf_template class click');
-         return false;
-    });
-
-}
-
-function bind_td_sortable()
-{
-
-    $('tr').sortable({
-            'cursor':'pointer',
-            'tolerance': 'intersect',
-            'items':'.column',
-            'placeholder':'placeholder_td',
-            'connectWith':'column'});
-
-    $('.td-div').sortable({
-            'cursor':'pointer',
-            'tolerance': 'pointer',
-            'items':'.gsf_metadata, .gsf_choose_metadata, .gsf_link, .gsf_switch',
-            'placeholder':'placeholder',
-            receive: function(event, ui) { alert("Attempted to receive"); },
-            stop: function(event, ui) {
-                // gsf metadata
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_metadata')) { replace_with(ui.item, gsf_metadata_element); }
-                // gsf choose metadata
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_choose_metadata')) { replace_with(ui.item, gsf_choose_metadata_element); }
-                // gsf link
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_link')) { replace_with(ui.item, gsf_link_element); }
-                // gsf switch
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_switch')) { replace_with(ui.item, gsf_switch_element); }
-                
-            }
-
-    });
-
-    $('.td-div').click(function () {    
-         //console.log('td class click');
-         return true;
-    });
-
-
-
-}
-
-
-function bind_choose_metadata_sortable()
-{
-    //console.log('function bind_choose_metadata_sortable()');
-    $('.gsf_choose_metadata').sortable({
-            'cursor':'pointer',
-            'tolerance': 'pointer',
-            'items':'.gsf_metadata, .gsf_text, .gsf_default',
-            'placeholder':'placeholder',
-            'connectWith':'.gsf_choose_metadata',
-            //'nested':'.gsf:metadata'
-            stop: function(event, ui) {
-                // gsf metadata
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_metadata')) { replace_with(ui.item, gsf_metadata_element); } 
-                // gsf text
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_text')) { replace_with(ui.item, gsf_text_element); } 
-                // gsf default
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_default')) { replace_with(ui.item, gsf_default_element); } 
-
-                bind_all_sortables();
-            }
-    });
-}
-
-function bind_link_sortable()
-{
-    //console.log('function bind_link_sortable()');
-    $('.gsf_link').sortable({
-            'cursor':'pointer',
-            'tolerance': 'pointer',
-            'items':'.leaf, .gsf_link, .gsf_switch, .gsf_choose',
-            'placeholder':'placeholder',
-            'connectWith':'.gsf_link',
-            //'nested':'.gsf:metadata'
-            stop: function(event, ui) {
-                // gsf icon
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_icon')) { replace_with(ui.item, gsf_icon_element); }
-                // gsf text
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_text')) { replace_with(ui.item, "<input type=\"text\" name=\"rawtextinput\" size=\"10\"/>"); }
-                // gsf metadata
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_metadata')) { replace_with(ui.item, gsf_metadata_element); } 
-                // gsf link
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_link')) { replace_with(ui.item, gsf_link_element); }
-                // gsf switch
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_switch')) { replace_with(ui.item, gsf_switch_element); }
-                // gsf choose
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_choose_metadata')) { replace_with(ui.item, gsf_choose_metadata_element); }
-            }
-    });
-}
-
-function bind_switch_sortable()
-{
-    //console.log('function bind_switch_sortable()');
-    $('.gsf_switch').sortable({
-            'cursor':'pointer',
-            'tolerance': 'pointer',
-            'items':'.gsf_metadata, .gsf_when, .gsf_otherwise, .gsf_text',
-            'placeholder':'placeholder',
-            'connectWith':'.gsf_switch',
-            //'nested':'.gsf:metadata'
-            stop: function(event, ui) {
-                // gsf when
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_when')) { replace_with(ui.item, gsf_when_element); }
-                // gsf otherwise
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_otherwise')) { replace_with(ui.item, gsf_otherwise_element); }
-                // gsf metadata
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_metadata')) { replace_with(ui.item, gsf_metadata_element); } 
-                // gsf text
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_text')) { replace_with(ui.item, gsf_text_element); } 
-            }
-    });
-}
-
-function bind_when_sortable()
-{
-    //console.log('function bind_when_sortable()');
-    $('.gsf_when').sortable({
-            'cursor':'pointer',
-            'tolerance': 'pointer',
-            'items':'.leaf, .gsf_link, .gsf_choose',
-            'placeholder':'placeholder',
-            //'nested':'.gsf:metadata'
-            stop: function(event, ui) {
-                // gsf metadata
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_metadata')) { replace_with(ui.item, gsf_metadata_element); }
-                // gsf icon
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_icon')) { replace_with(ui.item, gsf_icon_element); } 
-                // gsf text
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_text')) { replace_with(ui.item, gsf_text_element); } 
-                // gsf link
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_link')) { replace_with(ui.item, gsf_link_element); } 
-                // gsf choose
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_choose')) { replace_with(ui.item, gsf_choose_element); } 
-            }
-    });
-}
-
-function bind_otherwise_sortable()
-{
-    //console.log('function bind_otherwise_sortable()');
-    $('.gsf_otherwise').sortable({
-            'cursor':'pointer',
-            'tolerance': 'pointer',
-            'items':'.leaf, .gsf_link, .gsf_choose',
-            'placeholder':'placeholder',
-            //'nested':'.gsf:metadata'
-            stop: function(event, ui) {
-                // gsf metadata
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_metadata')) { replace_with(ui.item, gsf_metadata_element); }
-                // gsf text
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_text')) { replace_with(ui.item, "<input type=\"text\" name=\"rawtextinput\" size=\"10\"/>"); }
-                // gsf icon
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_icon')) { replace_with(ui.item, gsf_icon_element); } 
-                // gsf link
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_link')) { replace_with(ui.item, gsf_link_element); } 
-                // gsf choose
-                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_choose')) { replace_with(ui.item, gsf_choose_element); } 
-            }
-    });
-}
-
-function bind_block_mouseover()
-{
-    //console.log('function bind_block_mouseover()');
-    $(".block").mouseover(function()
-    {
-        $(this).parents().css("border", "");
-        $(this).css("border", "2px solid blue");
-        return false;
-    }).mouseout(function(){
-        $(this).css("border", "");
-        return false;
-    });
-}
-
-function bind_minmax_remove()
-{
-    console.log('function bind_minmax_remove()');
-    $('a.minmax').bind('click', toggleContent);
-    $('a.remove').bind('click', removeContent);
-};
-
-var removeContent = (function () {
-    //console.log('var removeContent = (function ()');
-        // this -> a -> td -> tr -> tbody -> table -> div
-        //$(this).parent().parent().parent().parent().parent().remove();
-        $(this).closest(".block").remove();
-    });
-
-
-var toggleContent = function(e)
-{
-    console.log('parent: ' + $(this).html());
-    if ($(this).html() == '[+]'){ //targetContent.css('display') == 'none') {
-        $(this).closest(".block").children(".table, .block").slideDown(300);
-        $(this).html('[-]');
-        $(this).removeClass("ui-icon-plusthick");
-        $(this).addClass("ui-icon-minusthick");
-    } else {
-        $(this).closest(".block").children(".table, .block").slideUp(300);
-        $(this).html('[+]');
-        $(this).removeClass("ui-icon-minusthick");
-        $(this).addClass("ui-icon-plusthick");
-    }
-    return false;
-};
-
-function serialize(s)
-{
-    serial = $.SortSerialize(s);
-    alert(serial.hash);
-};
-
-function equalHeights(item, height) {
-    //console.log('function equalHeights(item, height)');
-    (item.parents('.table')).each(function(index) {
-        $(this).children().children().children().each(function() {
-            $(this).height(height);
-            $(this).children().height(height);
-        });
-    });
-};
-
Index: in/trunk/greenstone3/web/interfaces/default/js/formateditor/innerxhtml.js
===================================================================
--- /main/trunk/greenstone3/web/interfaces/default/js/formateditor/innerxhtml.js	(revision 27713)
+++ 	(revision )
@@ -1,162 +1,0 @@
-/*
-Written by Steve Tucker, 2006, http://www.stevetucker.co.uk
-Full documentation can be found at http://www.stevetucker.co.uk/page-innerxhtml.php
-Released under the Creative Commons Attribution-Share Alike 3.0  License, http://creativecommons.org/licenses/by-sa/3.0/
-
-Change Log
-----------
-15/10/2006  v0.3    innerXHTML official release.
-21/03/2007  v0.4    1. Third argument $appendage added (Steve Tucker & Stef Dawson, www.stefdawson.com)
-            2. $source argument accepts string ID (Stef Dawson)
-            3. IE6 'on' functions work (Stef Dawson & Steve Tucker)
-*/
-innerXHTML = function($source,$string,$appendage) {
-    // (v0.4) Written 2006 by Steve Tucker, http://www.stevetucker.co.uk
-    if (typeof($source) == 'string') $source = document.getElementById($source);
-    if (!($source.nodeType == 1)) return false;
-    var $children = $source.childNodes;
-    var $xhtml = '';
-    if (!$string) {
-        for (var $i=0; $i<$children.length; $i++) {
-            if ($children[$i].nodeType == 3) {
-                var $text_content = $children[$i].nodeValue;
-                $text_content = $text_content.replace(/</g,'&lt;');
-                $text_content = $text_content.replace(/>/g,'&gt;');
-                $xhtml += $text_content;
-            }
-            else if ($children[$i].nodeType == 8) {
-                $xhtml += '<!--'+$children[$i].nodeValue+'-->';
-            }
-            else {
-                $xhtml += '<'+$children[$i].nodeName.toLowerCase();
-                var $attributes = $children[$i].attributes;
-                for (var $j=0; $j<$attributes.length; $j++) {
-                    var $attName = $attributes[$j].nodeName.toLowerCase();
-                    var $attValue = $attributes[$j].nodeValue;
-                    if ($attName == 'style' && $children[$i].style.cssText) {
-                        $xhtml += ' style="'+$children[$i].style.cssText.toLowerCase()+'"';
-                    }
-                    else if ($attValue && $attName != 'contenteditable') {
-                        $xhtml += ' '+$attName+'="'+$attValue+'"';
-                    }
-                }
-                $xhtml += '>'+innerXHTML($children[$i]);
-                $xhtml += '</'+$children[$i].nodeName.toLowerCase()+'>';
-            }
-        }
-    }
-    else {
-        if (!$appendage) {
-            while ($children.length>0) {
-                $source.removeChild($children[0]);
-            }
-            $appendage = false;
-        }
-        $xhtml = $string;
-        while ($string) {
-            var $returned = translateXHTML($string);
-            var $elements = $returned[0];
-            $string = $returned[1];
-            if ($elements) {
-                if (typeof($appendage) == 'string') $appendage = document.getElementById($appendage);
-                if (!($appendage.nodeType == 1)) $source.appendChild($elements);
-                else $source.insertBefore($elements,$appendage);
-            }
-        }
-    }
-    return $xhtml;
-}
-function translateXHTML($string) {
-    var $match = /^<\/[a-z0-9]{1,}>/i.test($string);
-    if ($match) {
-        var $return = Array;
-        $return[0] = false;
-        $return[1] = $string.replace(/^<\/[a-z0-9]{1,}>/i,'');
-        return $return;
-    }
-    $match = /^<[a-z]{1,}/i.test($string);
-    if ($match) {
-        $string = $string.replace(/^</,'');
-        var $element = $string.match(/[a-z0-9]{1,}/i);
-        if ($element) {
-            var $new_element = document.createElement($element[0]);
-            $string = $string.replace(/[a-z0-9]{1,}/i,'');
-            var $attribute = true;
-            while ($attribute) {
-                $string = $string.replace(/^\s{1,}/,'');
-                $attribute = $string.match(/^[a-z1-9_-]{1,}="[^"]{0,}"/i);
-                if ($attribute) {
-                    $attribute = $attribute[0];
-                    $string = $string.replace(/^[a-z1-9_-]{1,}="[^"]{0,}"/i,'');
-                    var $attName = $attribute.match(/^[a-z1-9_-]{1,}/i);
-                    $attribute = $attribute.replace(/^[a-z1-9_-]{1,}="/i,'');
-                    $attribute = $attribute.replace(/;{0,1}"$/,'');
-                    if ($attribute) {
-                        var $attValue = $attribute;
-                        if ($attName == 'value') $new_element.value = $attValue;
-                        else if ($attName == 'class') $new_element.className = $attValue;
-                        else if ($attName == 'style') {
-                            var $style = $attValue.split(';');
-                            for (var $i=0; $i<$style.length; $i++) {
-                                var $this_style = $style[$i].split(':');
-                                $this_style[0] = $this_style[0].toLowerCase().replace(/(^\s{0,})|(\s{0,1}$)/,'');
-                                $this_style[1] = $this_style[1].toLowerCase().replace(/(^\s{0,})|(\s{0,1}$)/,'');
-                                if (/-{1,}/g.test($this_style[0])) {
-                                    var $this_style_words = $this_style[0].split(/-/g);
-                                    $this_style[0] = '';
-                                    for (var $j=0; $j<$this_style_words.length; $j++) {
-                                        if ($j==0) {
-                                            $this_style[0] = $this_style_words[0];
-                                            continue;
-                                        }
-                                        var $first_letter = $this_style_words[$j].toUpperCase().match(/^[a-z]{1,1}/i);
-                                        $this_style[0] += $first_letter+$this_style_words[$j].replace(/^[a-z]{1,1}/,'');
-                                    }
-                                }
-                                $new_element.style[$this_style[0]] = $this_style[1];
-                            }
-                        }
-                        else if (/^on/.test($attName)) $new_element[$attName] = function() { eval($attValue) };
-                        else $new_element.setAttribute($attName,$attValue);
-                    }
-                    else $attribute = true;
-                }
-            }
-            $match = /^>/.test($string);
-            if ($match) {
-                $string = $string.replace(/^>/,'');
-                var $child = true;
-                while ($child) {
-                    var $returned = translateXHTML($string,false);
-                    $child = $returned[0];
-                    if ($child) $new_element.appendChild($child);
-                    $string = $returned[1];
-                }
-            }
-            $string = $string.replace(/^\/>/,'');
-        }
-    }
-    $match = /^[^<>]{1,}/i.test($string);
-    if ($match && !$new_element) {
-        var $text_content = $string.match(/^[^<>]{1,}/i)[0];
-        $text_content = $text_content.replace(/&lt;/g,'<');
-        $text_content = $text_content.replace(/&gt;/g,'>');
-        var $new_element = document.createTextNode($text_content);
-        $string = $string.replace(/^[^<>]{1,}/i,'');
-    }
-    $match = /^<!--[^<>]{1,}-->/i.test($string);
-    if ($match && !$new_element) {
-        if (document.createComment) {
-            $string = $string.replace(/^<!--/i,'');
-            var $text_content = $string.match(/^[^<>]{0,}-->{1,}/i);
-            $text_content = $text_content[0].replace(/-->{1,1}$/,'');           
-            var $new_element = document.createComment($text_content);
-            $string = $string.replace(/^[^<>]{1,}-->/i,'');
-        }
-        else $string = $string.replace(/^<!--[^<>]{1,}-->/i,'');
-    }
-    var $return = Array;
-    $return[0] = $new_element;
-    $return[1] = $string;
-    return $return;
-}
Index: in/trunk/greenstone3/web/interfaces/default/js/formateditor/jquery.selectboxes.js
===================================================================
--- /main/trunk/greenstone3/web/interfaces/default/js/formateditor/jquery.selectboxes.js	(revision 27713)
+++ 	(revision )
@@ -1,526 +1,0 @@
-/*
- *
- * Copyright (c) 2006-2009 Sam Collett (http://www.texotela.co.uk)
- * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
- * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
- *
- * Version 2.2.4
- * Demo: http://www.texotela.co.uk/code/jquery/select/
- *
- * $LastChangedDate: 2009-02-08 00:28:12 +0000 (Sun, 08 Feb 2009) $
- * $Rev: 6185 $
- *
- */
- 
-;(function($) {
- 
-/**
- * Adds (single/multiple) options to a select box (or series of select boxes)
- *
- * @name     addOption
- * @author   Sam Collett (http://www.texotela.co.uk)
- * @type     jQuery
- * @example  $("#myselect").addOption("Value", "Text"); // add single value (will be selected)
- * @example  $("#myselect").addOption("Value 2", "Text 2", false); // add single value (won't be selected)
- * @example  $("#myselect").addOption({"foo":"bar","bar":"baz"}, false); // add multiple values, but don't select
- *
- */
-$.fn.addOption = function()
-{
-	var add = function(el, v, t, sO)
-	{
-		var option = document.createElement("option");
-		option.value = v, option.text = t;
-		// get options
-		var o = el.options;
-		// get number of options
-		var oL = o.length;
-		if(!el.cache)
-		{
-			el.cache = {};
-			// loop through existing options, adding to cache
-			for(var i = 0; i < oL; i++)
-			{
-				el.cache[o[i].value] = i;
-			}
-		}
-		// add to cache if it isn't already
-		if(typeof el.cache[v] == "undefined") el.cache[v] = oL;
-		el.options[el.cache[v]] = option;
-		if(sO)
-		{
-			option.selected = true;
-		}
-	};
-	
-	var a = arguments;
-	if(a.length == 0) return this;
-	// select option when added? default is true
-	var sO = true;
-	// multiple items
-	var m = false;
-	// other variables
-	var items, v, t;
-	if(typeof(a[0]) == "object")
-	{
-		m = true;
-		items = a[0];
-	}
-	if(a.length >= 2)
-	{
-		if(typeof(a[1]) == "boolean") sO = a[1];
-		else if(typeof(a[2]) == "boolean") sO = a[2];
-		if(!m)
-		{
-			v = a[0];
-			t = a[1];
-		}
-	}
-	this.each(
-		function()
-		{
-			if(this.nodeName.toLowerCase() != "select") return;
-			if(m)
-			{
-				for(var item in items)
-				{
-					add(this, item, items[item], sO);
-				}
-			}
-			else
-			{
-				add(this, v, t, sO);
-			}
-		}
-	);
-	return this;
-};
-
-/**
- * Add options via ajax
- *
- * @name     ajaxAddOption
- * @author   Sam Collett (http://www.texotela.co.uk)
- * @type     jQuery
- * @param    String url      Page to get options from (must be valid JSON)
- * @param    Object params   (optional) Any parameters to send with the request
- * @param    Boolean select  (optional) Select the added options, default true
- * @param    Function fn     (optional) Call this function with the select object as param after completion
- * @param    Array args      (optional) Array with params to pass to the function afterwards
- * @example  $("#myselect").ajaxAddOption("myoptions.php");
- * @example  $("#myselect").ajaxAddOption("myoptions.php", {"code" : "007"});
- * @example  $("#myselect").ajaxAddOption("myoptions.php", {"code" : "007"}, false, sortoptions, [{"dir": "desc"}]);
- *
- */
-$.fn.ajaxAddOption = function(url, params, select, fn, args)
-{
-	if(typeof(url) != "string") return this;
-	if(typeof(params) != "object") params = {};
-	if(typeof(select) != "boolean") select = true;
-	this.each(
-		function()
-		{
-			var el = this;
-			$.getJSON(url,
-				params,
-				function(r)
-				{
-					$(el).addOption(r, select);
-					if(typeof fn == "function")
-					{
-						if(typeof args == "object")
-						{
-							fn.apply(el, args);
-						} 
-						else
-						{
-							fn.call(el);
-						}
-					}
-				}
-			);
-		}
-	);
-	return this;
-};
-
-/**
- * Removes an option (by value or index) from a select box (or series of select boxes)
- *
- * @name     removeOption
- * @author   Sam Collett (http://www.texotela.co.uk)
- * @type     jQuery
- * @param    String|RegExp|Number what  Option to remove
- * @param    Boolean selectedOnly       (optional) Remove only if it has been selected (default false)   
- * @example  $("#myselect").removeOption("Value"); // remove by value
- * @example  $("#myselect").removeOption(/^val/i); // remove options with a value starting with 'val'
- * @example  $("#myselect").removeOption(/./); // remove all options
- * @example  $("#myselect").removeOption(/./, true); // remove all options that have been selected
- * @example  $("#myselect").removeOption(0); // remove by index
- * @example  $("#myselect").removeOption(["myselect_1","myselect_2"]); // values contained in passed array
- *
- */
-$.fn.removeOption = function()
-{
-	var a = arguments;
-	if(a.length == 0) return this;
-	var ta = typeof(a[0]);
-	var v, index;
-	// has to be a string or regular expression (object in IE, function in Firefox)
-	if(ta == "string" || ta == "object" || ta == "function" )
-	{
-		v = a[0];
-		// if an array, remove items
-		if(v.constructor == Array)
-		{
-			var l = v.length;
-			for(var i = 0; i<l; i++)
-			{
-				this.removeOption(v[i], a[1]); 
-			}
-			return this;
-		}
-	}
-	else if(ta == "number") index = a[0];
-	else return this;
-	this.each(
-		function()
-		{
-			if(this.nodeName.toLowerCase() != "select") return;
-			// clear cache
-			if(this.cache) this.cache = null;
-			// does the option need to be removed?
-			var remove = false;
-			// get options
-			var o = this.options;
-			if(!!v)
-			{
-				// get number of options
-				var oL = o.length;
-				for(var i=oL-1; i>=0; i--)
-				{
-					if(v.constructor == RegExp)
-					{
-						if(o[i].value.match(v))
-						{
-							remove = true;
-						}
-					}
-					else if(o[i].value == v)
-					{
-						remove = true;
-					}
-					// if the option is only to be removed if selected
-					if(remove && a[1] === true) remove = o[i].selected;
-					if(remove)
-					{
-						o[i] = null;
-					}
-					remove = false;
-				}
-			}
-			else
-			{
-				// only remove if selected?
-				if(a[1] === true)
-				{
-					remove = o[index].selected;
-				}
-				else
-				{
-					remove = true;
-				}
-				if(remove)
-				{
-					this.remove(index);
-				}
-			}
-		}
-	);
-	return this;
-};
-
-/**
- * Sort options (ascending or descending) in a select box (or series of select boxes)
- *
- * @name     sortOptions
- * @author   Sam Collett (http://www.texotela.co.uk)
- * @type     jQuery
- * @param    Boolean ascending   (optional) Sort ascending (true/undefined), or descending (false)
- * @example  // ascending
- * $("#myselect").sortOptions(); // or $("#myselect").sortOptions(true);
- * @example  // descending
- * $("#myselect").sortOptions(false);
- *
- */
-$.fn.sortOptions = function(ascending)
-{
-	// get selected values first
-	var sel = $(this).selectedValues();
-	var a = typeof(ascending) == "undefined" ? true : !!ascending;
-	this.each(
-		function()
-		{
-			if(this.nodeName.toLowerCase() != "select") return;
-			// get options
-			var o = this.options;
-			// get number of options
-			var oL = o.length;
-			// create an array for sorting
-			var sA = [];
-			// loop through options, adding to sort array
-			for(var i = 0; i<oL; i++)
-			{
-				sA[i] = {
-					v: o[i].value,
-					t: o[i].text
-				}
-			}
-			// sort items in array
-			sA.sort(
-				function(o1, o2)
-				{
-					// option text is made lowercase for case insensitive sorting
-					o1t = o1.t.toLowerCase(), o2t = o2.t.toLowerCase();
-					// if options are the same, no sorting is needed
-					if(o1t == o2t) return 0;
-					if(a)
-					{
-						return o1t < o2t ? -1 : 1;
-					}
-					else
-					{
-						return o1t > o2t ? -1 : 1;
-					}
-				}
-			);
-			// change the options to match the sort array
-			for(var i = 0; i<oL; i++)
-			{
-				o[i].text = sA[i].t;
-				o[i].value = sA[i].v;
-			}
-		}
-	).selectOptions(sel, true); // select values, clearing existing ones
-	return this;
-};
-/**
- * Selects an option by value
- *
- * @name     selectOptions
- * @author   Mathias Bank (http://www.mathias-bank.de), original function
- * @author   Sam Collett (http://www.texotela.co.uk), addition of regular expression matching
- * @type     jQuery
- * @param    String|RegExp|Array value  Which options should be selected
- * can be a string or regular expression, or an array of strings / regular expressions
- * @param    Boolean clear  Clear existing selected options, default false
- * @example  $("#myselect").selectOptions("val1"); // with the value 'val1'
- * @example  $("#myselect").selectOptions(["val1","val2","val3"]); // with the values 'val1' 'val2' 'val3'
- * @example  $("#myselect").selectOptions(/^val/i); // with the value starting with 'val', case insensitive
- *
- */
-$.fn.selectOptions = function(value, clear)
-{
-	var v = value;
-	var vT = typeof(value);
-	// handle arrays
-	if(vT == "object" && v.constructor == Array)
-	{
-		var $this = this;
-		$.each(v, function()
-			{
-      				$this.selectOptions(this, clear);
-    			}
-		);
-	};
-	var c = clear || false;
-	// has to be a string or regular expression (object in IE, function in Firefox)
-	if(vT != "string" && vT != "function" && vT != "object") return this;
-	this.each(
-		function()
-		{
-			if(this.nodeName.toLowerCase() != "select") return this;
-			// get options
-			var o = this.options;
-			// get number of options
-			var oL = o.length;
-			for(var i = 0; i<oL; i++)
-			{
-				if(v.constructor == RegExp)
-				{
-					if(o[i].value.match(v))
-					{
-						o[i].selected = true;
-					}
-					else if(c)
-					{
-						o[i].selected = false;
-					}
-				}
-				else
-				{
-					if(o[i].value == v)
-					{
-						o[i].selected = true;
-					}
-					else if(c)
-					{
-						o[i].selected = false;
-					}
-				}
-			}
-		}
-	);
-	return this;
-};
-
-/**
- * Copy options to another select
- *
- * @name     copyOptions
- * @author   Sam Collett (http://www.texotela.co.uk)
- * @type     jQuery
- * @param    String to  Element to copy to
- * @param    String which  (optional) Specifies which options should be copied - 'all' or 'selected'. Default is 'selected'
- * @example  $("#myselect").copyOptions("#myselect2"); // copy selected options from 'myselect' to 'myselect2'
- * @example  $("#myselect").copyOptions("#myselect2","selected"); // same as above
- * @example  $("#myselect").copyOptions("#myselect2","all"); // copy all options from 'myselect' to 'myselect2'
- *
- */
-$.fn.copyOptions = function(to, which)
-{
-	var w = which || "selected";
-	if($(to).size() == 0) return this;
-	this.each(
-		function()
-		{
-			if(this.nodeName.toLowerCase() != "select") return this;
-			// get options
-			var o = this.options;
-			// get number of options
-			var oL = o.length;
-			for(var i = 0; i<oL; i++)
-			{
-				if(w == "all" || (w == "selected" && o[i].selected))
-				{
-					$(to).addOption(o[i].value, o[i].text);
-				}
-			}
-		}
-	);
-	return this;
-};
-
-/**
- * Checks if a select box has an option with the supplied value
- *
- * @name     containsOption
- * @author   Sam Collett (http://www.texotela.co.uk)
- * @type     Boolean|jQuery
- * @param    String|RegExp value  Which value to check for. Can be a string or regular expression
- * @param    Function fn          (optional) Function to apply if an option with the given value is found.
- * Use this if you don't want to break the chaining
- * @example  if($("#myselect").containsOption("val1")) alert("Has an option with the value 'val1'");
- * @example  if($("#myselect").containsOption(/^val/i)) alert("Has an option with the value starting with 'val'");
- * @example  $("#myselect").containsOption("val1", copyoption).doSomethingElseWithSelect(); // calls copyoption (user defined function) for any options found, chain is continued
- *
- */
-$.fn.containsOption = function(value, fn)
-{
-	var found = false;
-	var v = value;
-	var vT = typeof(v);
-	var fT = typeof(fn);
-	// has to be a string or regular expression (object in IE, function in Firefox)
-	if(vT != "string" && vT != "function" && vT != "object") return fT == "function" ? this: found;
-	this.each(
-		function()
-		{
-			if(this.nodeName.toLowerCase() != "select") return this;
-			// option already found
-			if(found && fT != "function") return false;
-			// get options
-			var o = this.options;
-			// get number of options
-			var oL = o.length;
-			for(var i = 0; i<oL; i++)
-			{
-				if(v.constructor == RegExp)
-				{
-					if (o[i].value.match(v))
-					{
-						found = true;
-						if(fT == "function") fn.call(o[i], i);
-					}
-				}
-				else
-				{
-					if (o[i].value == v)
-					{
-						found = true;
-						if(fT == "function") fn.call(o[i], i);
-					}
-				}
-			}
-		}
-	);
-	return fT == "function" ? this : found;
-};
-
-/**
- * Returns values which have been selected
- *
- * @name     selectedValues
- * @author   Sam Collett (http://www.texotela.co.uk)
- * @type     Array
- * @example  $("#myselect").selectedValues();
- *
- */
-$.fn.selectedValues = function()
-{
-	var v = [];
-	this.selectedOptions().each(
-		function()
-		{
-			v[v.length] = this.value;
-		}
-	);
-	return v;
-};
-
-/**
- * Returns text which has been selected
- *
- * @name     selectedTexts
- * @author   Sam Collett (http://www.texotela.co.uk)
- * @type     Array
- * @example  $("#myselect").selectedTexts();
- *
- */
-$.fn.selectedTexts = function()
-{
-	var t = [];
-	this.selectedOptions().each(
-		function()
-		{
-			t[t.length] = this.text;
-		}
-	);
-	return t;
-};
-
-/**
- * Returns options which have been selected
- *
- * @name     selectedOptions
- * @author   Sam Collett (http://www.texotela.co.uk)
- * @type     jQuery
- * @example  $("#myselect").selectedOptions();
- *
- */
-$.fn.selectedOptions = function()
-{
-	return this.find("option:selected");
-};
-
-})(jQuery);
Index: in/trunk/greenstone3/web/interfaces/default/js/formateditor/jquery.xml.js
===================================================================
--- /main/trunk/greenstone3/web/interfaces/default/js/formateditor/jquery.xml.js	(revision 27713)
+++ 	(revision )
@@ -1,56 +1,0 @@
-/**
- * jQuery xml plugin
- * Converts XML node(s) to string 
- *
- * Copyright (c) 2009 Radim Svoboda
- * Dual licensed under the MIT (MIT-LICENSE.txt)
- * and GPL (GPL-LICENSE.txt) licenses.
- *
- * @author 	Radim Svoboda, user Zzzzzz
- * @version 1.0.0
- */
- 
-   
-/**
- * Converts XML node(s) to string using web-browser features.
- * Similar to .html() with HTML nodes 
- * This method is READ-ONLY.
- *  
- * @param all set to TRUE (1,"all",etc.) process all elements,
- * otherwise process content of the first matched element 
- *  
- * @return string obtained from XML node(s)  
- */         
-jQuery.fn.xml = function(all) {
-      
-  //result to return
-  var s = "";
-  
-   //Anything to process ?
-   if( this.length )
-  
-    //"object" with nodes to convert to string  
-   (
-      ( ( typeof all != 'undefined' ) && all ) ?
-      //all the nodes 
-      this 
-      :
-      //content of the first matched element 
-      jQuery(this[0]).contents()
-    )
-   //convert node(s) to string  
-   .each(function(){
-    s += window.ActiveXObject ?//==  IE browser ?
-       //for IE
-	     this.xml
-	     :
-	     //for other browsers
-	     (new XMLSerializer()).serializeToString(this)
-	     ;
-  }); 
-    
-    
-  return	s;		
-  
-  };
-                     
Index: in/trunk/greenstone3/web/interfaces/default/js/formateditor/ui.nestedSortable.js
===================================================================
--- /main/trunk/greenstone3/web/interfaces/default/js/formateditor/ui.nestedSortable.js	(revision 27713)
+++ 	(revision )
@@ -1,1210 +1,0 @@
-/*
- * based on jQuery UI Sortable 1.7.2
- *
- * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about) and Steven Lots (Lotsofdots bvba) 
- * Dual licensed under the MIT (MIT-LICENSE.txt)
- * and GPL (GPL-LICENSE.txt) licenses.
- *
- * http://docs.jquery.com/UI/Sortables
- * http://www.b-hind.eu/jquery/
- * Depends:
- *	ui.core.js
- */
-(function($) {
-
-$.widget("ui.sortable", $.extend({}, $.ui.mouse, {
-	_init: function() {
-
-		var o = this.options;
-		this.containerCache = {};
-		this.element.addClass("ui-sortable");
-
-		//Get the items
-		this.refresh();
-
-		//Let's determine if the items are floating
-		this.floating = this.items.length ? (/left|right/).test(this.items[0].item.css('float')) : false;
-
-		//Let's determine the parent's offset
-		this.offset = this.element.offset();
-
-		//Initialize mouse events for interaction
-		this._mouseInit();
-
-	},
-
-	destroy: function() {
-		this.element
-			.removeClass("ui-sortable ui-sortable-disabled")
-			.removeData("sortable")
-			.unbind(".sortable");
-		this._mouseDestroy();
-
-		for ( var i = this.items.length - 1; i >= 0; i-- )
-			this.items[i].item.removeData("sortable-item");
-	},
-
-	_mouseCapture: function(event, overrideHandle) {
-
-		if (this.reverting) {
-			return false;
-		}
-
-		if(this.options.disabled || this.options.type == 'static') return false;
-
-		//We have to refresh the items data once first
-		this._refreshItems(event);
-
-		//Find out if the clicked node (or one of its parents) is a actual item in this.items
-		var currentItem = null, self = this, nodes = $(event.target).parents().each(function() {
-			if($.data(this, 'sortable-item') == self) {
-				currentItem = $(this);
-				return false;
-			}
-		});
-		if($.data(event.target, 'sortable-item') == self) currentItem = $(event.target);
-
-		if(!currentItem) return false;
-		if(this.options.handle && !overrideHandle) {
-			var validHandle = false;
-
-			$(this.options.handle, currentItem).find("*").andSelf().each(function() { if(this == event.target) validHandle = true; });
-			if(!validHandle) return false;
-		}
-
-		this.currentItem = currentItem;
-		this._removeCurrentsFromItems();
-		return true;
-
-	},
-
-	_mouseStart: function(event, overrideHandle, noActivation) {
-
-		var o = this.options, self = this;
-		this.currentContainer = this;
-
-		//We only need to call refreshPositions, because the refreshItems call has been moved to mouseCapture
-		this.refreshPositions();
-
-		//Create and append the visible helper
-		this.helper = this._createHelper(event);
-
-		//Cache the helper size
-		this._cacheHelperProportions();
-
-		/*
-		 * - Position generation -
-		 * This block generates everything position related - it's the core of draggables.
-		 */
-
-		//Cache the margins of the original element
-		this._cacheMargins();
-
-		//Get the next scrolling parent
-		this.scrollParent = this.helper.scrollParent();
-
-		//The element's absolute position on the page minus margins
-		this.offset = this.currentItem.offset();
-		this.offset = {
-			top: this.offset.top - this.margins.top,
-			left: this.offset.left - this.margins.left
-		};
-
-		// Only after we got the offset, we can change the helper's position to absolute
-		// TODO: Still need to figure out a way to make relative sorting possible
-		this.helper.css("position", "absolute");
-		this.cssPosition = this.helper.css("position");
-
-		$.extend(this.offset, {
-			click: { //Where the click happened, relative to the element
-				left: event.pageX - this.offset.left,
-				top: event.pageY - this.offset.top
-			},
-			parent: this._getParentOffset(),
-			relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper
-		});
-
-		//Generate the original position
-		this.originalPosition = this._generatePosition(event);
-		this.originalPageX = event.pageX;
-		this.originalPageY = event.pageY;
-
-		//Adjust the mouse offset relative to the helper if 'cursorAt' is supplied
-		if(o.cursorAt)
-			this._adjustOffsetFromHelper(o.cursorAt);
-
-		//Cache the former DOM position
-		this.domPosition = { prev: this.currentItem.prev()[0], parent: this.currentItem.parent()[0] };
-
-		//If the helper is not the original, hide the original so it's not playing any role during the drag, won't cause anything bad this way
-		if(this.helper[0] != this.currentItem[0]) {
-			this.currentItem.hide();
-		}
-
-		//Create the placeholder
-		this._createPlaceholder();
-
-		//Set a containment if given in the options
-		if(o.containment)
-			this._setContainment();
-
-		if(o.cursor) { // cursor option
-			if ($('body').css("cursor")) this._storedCursor = $('body').css("cursor");
-			$('body').css("cursor", o.cursor);
-		}
-
-		if(o.opacity) { // opacity option
-			if (this.helper.css("opacity")) this._storedOpacity = this.helper.css("opacity");
-			this.helper.css("opacity", o.opacity);
-		}
-
-		if(o.zIndex) { // zIndex option
-			if (this.helper.css("zIndex")) this._storedZIndex = this.helper.css("zIndex");
-			this.helper.css("zIndex", o.zIndex);
-		}
-
-		//Prepare scrolling
-		if(this.scrollParent[0] != document && this.scrollParent[0].tagName != 'HTML')
-			this.overflowOffset = this.scrollParent.offset();
-
-		//Call callbacks
-		this._trigger("start", event, this._uiHash());
-
-		//Recache the helper size
-		if(!this._preserveHelperProportions)
-			this._cacheHelperProportions();
-
-
-		//Post 'activate' events to possible containers
-		if(!noActivation) {
-			 for (var i = this.containers.length - 1; i >= 0; i--) { this.containers[i]._trigger("activate", event, self._uiHash(this)); }
-		}
-
-		//Prepare possible droppables
-		if($.ui.ddmanager)
-			$.ui.ddmanager.current = this;
-
-		if ($.ui.ddmanager && !o.dropBehaviour)
-			$.ui.ddmanager.prepareOffsets(this, event);
-
-		this.dragging = true;
-
-		this.helper.addClass("ui-sortable-helper");
-		this._mouseDrag(event); //Execute the drag once - this causes the helper not to be visible before getting its correct position
-		return true;
-
-	},
-
-	_mouseDrag: function(event) {
-
-		//Compute the helpers position
-		this.position = this._generatePosition(event);
-		//console.log(this.position); //b-hind
-		this.positionAbs = this._convertPositionTo("absolute");
-
-		if (!this.lastPositionAbs) {
-			this.lastPositionAbs = this.positionAbs;
-		}
-
-		//Do scrolling
-		if(this.options.scroll) {
-			var o = this.options, scrolled = false;
-			if(this.scrollParent[0] != document && this.scrollParent[0].tagName != 'HTML') {
-
-				if((this.overflowOffset.top + this.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity)
-					this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop + o.scrollSpeed;
-				else if(event.pageY - this.overflowOffset.top < o.scrollSensitivity)
-					this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop - o.scrollSpeed;
-
-				if((this.overflowOffset.left + this.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity)
-					this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft + o.scrollSpeed;
-				else if(event.pageX - this.overflowOffset.left < o.scrollSensitivity)
-					this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft - o.scrollSpeed;
-
-			} else {
-
-				if(event.pageY - $(document).scrollTop() < o.scrollSensitivity)
-					scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed);
-				else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity)
-					scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed);
-
-				if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity)
-					scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed);
-				else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity)
-					scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed);
-
-			}
-			
-			if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour)
-				$.ui.ddmanager.prepareOffsets(this, event);
-		}
-
-		//Regenerate the absolute position used for position checks
-		this.positionAbs = this._convertPositionTo("absolute");
-		
-		//Set the helper position
-		if(!this.options.axis || this.options.axis != "y") this.helper[0].style.left = this.position.left+'px';
-		if(!this.options.axis || this.options.axis != "x") this.helper[0].style.top = this.position.top+'px';
-
-		//Rearrange
-		
-		for (var i = this.items.length - 1; i >= 0; i--) {
-			
-			//Cache variables and intersection, continue if no intersection
-			var item = this.items[i], itemElement = item.item[0], intersection = this._intersectsWithPointer(item);
-			if (!intersection) continue;
-			if(itemElement != this.currentItem[0] //cannot intersect with itself
-				&&	this.placeholder[intersection == 1 ? "next" : "prev"]()[0] != itemElement //no useless actions that have been done before
-				&&	!$.ui.contains(this.placeholder[0], itemElement) //no action if the item moved is the parent of the item checked
-				&& (this.options.type == 'semi-dynamic' ? !$.ui.contains(this.element[0], itemElement) : true)
-			) {
-				
-				this.direction = intersection == 1 ? "down" : "up";
-				//b-hind : here we must also check 
-				
-				//var level = this._getLevel(item.item);
-				//console.log($.ui.isOverAxis(this.positionAbs.left, item.left, item.width));
-				//var haschildNode = this._hasChildNodes(item.item);
-				//console.log("haschildNode : "+haschildNode);
-				//moved to _rearrange
-				
-				
-				if (this.options.tolerance == "pointer" || this._intersectsWithSides(item)) {
-					this._rearrange(event, item);
-				} else {
-					break;
-				}
-
-				this._trigger("change", event, this._uiHash());
-				break;
-			}
-		}
-
-		//Post events to containers
-		this._contactContainers(event);
-
-		//Interconnect with droppables
-		if($.ui.ddmanager) $.ui.ddmanager.drag(this, event);
-
-		//Call callbacks
-		this._trigger('sort', event, this._uiHash());
-
-		this.lastPositionAbs = this.positionAbs;
-		return false;
-
-	},
-
-	_mouseStop: function(event, noPropagation) {
-
-		if(!event) return;
-
-		//If we are using droppables, inform the manager about the drop
-		if ($.ui.ddmanager && !this.options.dropBehaviour)
-			$.ui.ddmanager.drop(this, event);
-
-		if(this.options.revert) {
-			var self = this;
-			var cur = self.placeholder.offset();
-
-			self.reverting = true;
-
-			$(this.helper).animate({
-				left: cur.left - this.offset.parent.left - self.margins.left + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollLeft),
-				top: cur.top - this.offset.parent.top - self.margins.top + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollTop)
-			}, parseInt(this.options.revert, 10) || 500, function() {
-				self._clear(event);
-			});
-		} else {
-			this._clear(event, noPropagation);
-		}
-
-		return false;
-
-	},
-
-	cancel: function() {
-
-		var self = this;
-
-		if(this.dragging) {
-
-			this._mouseUp();
-
-			if(this.options.helper == "original")
-				this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper");
-			else
-				this.currentItem.show();
-
-			//Post deactivating events to containers
-			for (var i = this.containers.length - 1; i >= 0; i--){
-				this.containers[i]._trigger("deactivate", null, self._uiHash(this));
-				if(this.containers[i].containerCache.over) {
-					this.containers[i]._trigger("out", null, self._uiHash(this));
-					this.containers[i].containerCache.over = 0;
-				}
-			}
-
-		}
-
-		//$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node!
-		if(this.placeholder[0].parentNode) this.placeholder[0].parentNode.removeChild(this.placeholder[0]);
-		if(this.options.helper != "original" && this.helper && this.helper[0].parentNode) this.helper.remove();
-
-		$.extend(this, {
-			helper: null,
-			dragging: false,
-			reverting: false,
-			_noFinalSort: null
-		});
-
-		if(this.domPosition.prev) {
-			$(this.domPosition.prev).after(this.currentItem);
-		} else {
-			$(this.domPosition.parent).prepend(this.currentItem);
-		}
-
-		return true;
-
-	},
-
-	serialize: function(o) {
-
-		var items = this._getItemsAsjQuery(o && o.connected);
-		var str = []; o = o || {};
-		if(this.options.nested){
-			var level = 0;
-			var levels = [];
-			var key = 0;
-			for(var i=0;i<items.length;i++){
-				var itemlevel = this._getLevel($(items[i]));
-				if(level== itemlevel){
-					var res = ($(o.item || items[i]).attr(o.attribute || 'id') || '').match(o.expression || (/(.+)[-=_](.+)/));
-					if(res) str.push((o.key || res[1]+(itemlevel==1?"":"_"+levels[levels.length-1])+'[]')+'='+(o.key && o.expression ? res[1] : res[2]));
-					if(res) key = res[2];
-				}else if(itemlevel > level){
-					level = itemlevel;
-					var res = ($(o.item || items[i]).attr(o.attribute || 'id') || '').match(o.expression || (/(.+)[-=_](.+)/));
-					if(res) levels[levels.length] =  key;
-					if(res) str.push((o.key || res[1]+(itemlevel==1?"":"_"+levels[levels.length-1])+'[]')+'='+(o.key && o.expression ? res[1] : res[2]));
-					if(res) key = res[2];
-				}else{
-					
-					do{
-						levels.pop();
-						key = levels[levels.length-1];
-						level--;
-					
-					}while(level > itemlevel);
-					var res = ($(o.item || items[i]).attr(o.attribute || 'id') || '').match(o.expression || (/(.+)[-=_](.+)/));
-					if(res) str.push((o.key || res[1]+(itemlevel==1?"":"_"+key)+'[]')+'='+(o.key && o.expression ? res[1] : res[2]));
-					if(res) key = res[2];
-				}
-				
-			}
-		}else{
-			$(items).each(function() {
-				var res = ($(o.item || this).attr(o.attribute || 'id') || '').match(o.expression || (/(.+)[-=_](.+)/));
-				if(res) str.push((o.key || res[1]+'[]')+'='+(o.key && o.expression ? res[1] : res[2]));
-			});
-		}
-		
-		return str.join('&');
-
-	},
-
-	toArray: function(o) {
-
-		var items = this._getItemsAsjQuery(o && o.connected);
-		var ret = []; o = o || {};
-		var self = this;
-		//add first item is always level 1
-		
-		
-		if(this.options.nested){
-	
-			var level = 1;
-			var currentAr = ret;
-			var levels = [];
-			
-			for(var i=0;i<items.length;i++){
-				var item = items[i];
-				var itemlevel = this._getLevel($(item));
-				
-				if(itemlevel == level){
-					currentAr.push([$(o.item || item).attr(o.attribute || 'id') || '',[]]);
-					
-				}else if(itemlevel > level){
-					
-					level = itemlevel;
-					levels[levels.length] = currentAr;
-					// get last element
-					currentAr = currentAr[currentAr.length-1][1];
-					currentAr.push([$(o.item || item).attr(o.attribute || 'id') || '',[]]);
-				}else{
-					
-					do{
-						currentAr = levels[levels.length-1];
-						levels.pop();
-						level--;
-					}while(level > itemlevel);
-					
-					currentAr.push([$(o.item || item).attr(o.attribute || 'id') || '',[]]);
-				}
-			}
-		
-
-		}else{
-				items.each(function() { ret.push($(o.item || this).attr(o.attribute || 'id') || ''); });
-		}
-
-	
-		return ret;
-
-	},
-
-	/* Be careful with the following core functions */
-	_intersectsWith: function(item) {
-
-		var x1 = this.positionAbs.left,
-			x2 = x1 + this.helperProportions.width,
-			y1 = this.positionAbs.top,
-			y2 = y1 + this.helperProportions.height;
-
-		var l = item.left,
-			r = l + item.width,
-			t = item.top,
-			b = t + item.height;
-
-		var dyClick = this.offset.click.top,
-			dxClick = this.offset.click.left;
-
-		var isOverElement = (y1 + dyClick) > t && (y1 + dyClick) < b && (x1 + dxClick) > l && (x1 + dxClick) < r;
-
-		if(	   this.options.tolerance == "pointer"
-			|| this.options.forcePointerForContainers
-			|| (this.options.tolerance != "pointer" && this.helperProportions[this.floating ? 'width' : 'height'] > item[this.floating ? 'width' : 'height'])
-		) {
-			return isOverElement;
-		} else {
-
-			return (l < x1 + (this.helperProportions.width / 2) // Right Half
-				&& x2 - (this.helperProportions.width / 2) < r // Left Half
-				&& t < y1 + (this.helperProportions.height / 2) // Bottom Half
-				&& y2 - (this.helperProportions.height / 2) < b ); // Top Half
-
-		}
-	},
-	/* check of the pointer  is over an other element  (while dragging) */
-	_intersectsWithPointer: function(item) {
-
-		var isOverElementHeight = $.ui.isOverAxis(this.positionAbs.top + this.offset.click.top, item.top, item.height),
-			isOverElementWidth = $.ui.isOverAxis(this.positionAbs.left + this.offset.click.left, item.left, item.width),
-			isOverElement = isOverElementHeight && isOverElementWidth,
-			verticalDirection = this._getDragVerticalDirection(),
-			horizontalDirection = this._getDragHorizontalDirection();
-
-		if (!isOverElement)
-			return false;
-
-		return this.floating ?
-			( ((horizontalDirection && horizontalDirection == "right") || verticalDirection == "down") ? 2 : 1 )
-			: ( verticalDirection && (verticalDirection == "down" ? 2 : 1) );
-
-	},
-	/* check of the dragged element is over an other element */
-	_intersectsWithSides: function(item) {
-
-		var isOverBottomHalf = $.ui.isOverAxis(this.positionAbs.top + this.offset.click.top, item.top + (item.height/2), item.height),
-			isOverRightHalf = $.ui.isOverAxis(this.positionAbs.left + this.offset.click.left, item.left + (item.width/2), item.width),
-			verticalDirection = this._getDragVerticalDirection(),
-			horizontalDirection = this._getDragHorizontalDirection();
-
-		if (this.floating && horizontalDirection) {
-			return ((horizontalDirection == "right" && isOverRightHalf) || (horizontalDirection == "left" && !isOverRightHalf));
-		} else {
-			return verticalDirection && ((verticalDirection == "down" && isOverBottomHalf) || (verticalDirection == "up" && !isOverBottomHalf));
-		}
-
-	},
-
-	_getDragVerticalDirection: function() {
-		var delta = this.positionAbs.top - this.lastPositionAbs.top;
-		return delta != 0 && (delta > 0 ? "down" : "up");
-	},
-
-	_getDragHorizontalDirection: function() {
-		var delta = this.positionAbs.left - this.lastPositionAbs.left;
-		return delta != 0 && (delta > 0 ? "right" : "left");
-	},
-
-	refresh: function(event) {
-		this._refreshItems(event);
-		this.refreshPositions();
-	},
-
-	_connectWith: function() {
-		var options = this.options;
-		return options.connectWith.constructor == String
-			? [options.connectWith]
-			: options.connectWith;
-	},
-	
-	_getItemsAsjQuery: function(connected) {
-
-		var self = this;
-		var items = [];
-		var queries = [];
-		var connectWith = this._connectWith();
-
-		if(connectWith && connected) {
-			for (var i = connectWith.length - 1; i >= 0; i--){
-				var cur = $(connectWith[i]);
-				for (var j = cur.length - 1; j >= 0; j--){
-					var inst = $.data(cur[j], 'sortable');
-					if(inst && inst != this && !inst.options.disabled) {
-						queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element) : $(inst.options.items, inst.element).not(".ui-sortable-helper"), inst]);
-					}
-				};
-			};
-		}
-
-		queries.push([$.isFunction(this.options.items) ? this.options.items.call(this.element, null, { options: this.options, item: this.currentItem }) : $(this.options.items, this.element).not(".ui-sortable-helper"), this]);
-
-		for (var i = queries.length - 1; i >= 0; i--){
-			queries[i][0].each(function() {
-				items.push(this);
-			});
-		};
-		
-
-		return $(items);
-
-	},
-
-	_removeCurrentsFromItems: function() {
-
-		var list = this.currentItem.find(":data(sortable-item)");
-
-		for (var i=0; i < this.items.length; i++) {
-
-			for (var j=0; j < list.length; j++) {
-				if(list[j] == this.items[i].item[0])
-					this.items.splice(i,1);
-			};
-
-		};
-
-	},
-
-	_refreshItems: function(event) {
-
-		this.items = [];
-		this.containers = [this];
-		var items = this.items;
-		var self = this;
-		var queries = [[$.isFunction(this.options.items) ? this.options.items.call(this.element[0], event, { item: this.currentItem }) : $(this.options.items, this.element), this]];
-		var connectWith = this._connectWith();
-
-		if(connectWith) {
-			for (var i = connectWith.length - 1; i >= 0; i--){
-				var cur = $(connectWith[i]);
-				for (var j = cur.length - 1; j >= 0; j--){
-					var inst = $.data(cur[j], 'sortable');
-					if(inst && inst != this && !inst.options.disabled) {
-						queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element[0], event, { item: this.currentItem }) : $(inst.options.items, inst.element), inst]);
-						this.containers.push(inst);
-					}
-				};
-			};
-		}
-
-		for (var i = queries.length - 1; i >= 0; i--) {
-			var targetData = queries[i][1];
-			var _queries = queries[i][0];
-
-			for (var j=0, queriesLength = _queries.length; j < queriesLength; j++) {
-				var item = $(_queries[j]);
-
-				item.data('sortable-item', targetData); // Data for target checking (mouse manager)
-
-				items.push({
-					item: item,
-					instance: targetData,
-					width: 0, height: 0,
-					left: 0, top: 0
-				});
-			};
-		};
-
-	},
-
-	refreshPositions: function(fast) {
-
-		//This has to be redone because due to the item being moved out/into the offsetParent, the offsetParent's position will change
-		if(this.offsetParent && this.helper) {
-			this.offset.parent = this._getParentOffset();
-		}
-
-		for (var i = this.items.length - 1; i >= 0; i--){
-			var item = this.items[i];
-
-			//We ignore calculating positions of all connected containers when we're not over them
-			if(item.instance != this.currentContainer && this.currentContainer && item.item[0] != this.currentItem[0])
-				continue;
-
-			var t = this.options.toleranceElement ? $(this.options.toleranceElement, item.item) : item.item;
-
-			if (!fast) {
-				item.width = t.outerWidth();
-				item.height = t.outerHeight();
-			}
-
-			var p = t.offset();
-			item.left = p.left;
-			item.top = p.top;
-		};
-
-		if(this.options.custom && this.options.custom.refreshContainers) {
-			this.options.custom.refreshContainers.call(this);
-		} else {
-			for (var i = this.containers.length - 1; i >= 0; i--){
-				var p = this.containers[i].element.offset();
-				this.containers[i].containerCache.left = p.left;
-				this.containers[i].containerCache.top = p.top;
-				this.containers[i].containerCache.width	= this.containers[i].element.outerWidth();
-				this.containers[i].containerCache.height = this.containers[i].element.outerHeight();
-			};
-		}
-
-	},
-
-	_createPlaceholder: function(that) {
-
-		var self = that || this, o = self.options;
-
-		if(!o.placeholder || o.placeholder.constructor == String) {
-			var className = o.placeholder;
-			o.placeholder = {
-				element: function() {
-
-					var el = $(document.createElement(self.currentItem[0].nodeName))
-						.addClass(className || self.currentItem[0].className+" ui-sortable-placeholder")
-						.removeClass("ui-sortable-helper")[0];
-
-					if(!className)
-						el.style.visibility = "hidden";
-
-					return el;
-				},
-				update: function(container, p) {
-
-					// 1. If a className is set as 'placeholder option, we don't force sizes - the class is responsible for that
-					// 2. The option 'forcePlaceholderSize can be enabled to force it even if a class name is specified
-					if(className && !o.forcePlaceholderSize) return;
-
-					//If the element doesn't have a actual height by itself (without styles coming from a stylesheet), it receives the inline height from the dragged item
-					if(!p.height()) { p.height(self.currentItem.innerHeight() - parseInt(self.currentItem.css('paddingTop')||0, 10) - parseInt(self.currentItem.css('paddingBottom')||0, 10)); };
-					if(!p.width()) { p.width(self.currentItem.innerWidth() - parseInt(self.currentItem.css('paddingLeft')||0, 10) - parseInt(self.currentItem.css('paddingRight')||0, 10)); };
-				}
-			};
-		}
-
-		//Create the placeholder
-		self.placeholder = $(o.placeholder.element.call(self.element, self.currentItem));
-
-		//Append it after the actual current item
-		/**********************************************
-		b-hind patch : append it after or as a child if nested is true
-		check position of element
-		
-		problem : on deep nested items what is te depth of the required item to place
-		first solution: create a visible location after each depth -> requires a fyical height and chacges the layout of the nested tree:(
-		second solution : check the indent from the helper, but what if the nesteditems dont have an indent
-		
-		We go for the second solution  !!!
-		
-		so what tot do: check the indent of each read left -padding or left -margin
-		if the helper (left side is between th left side of the parent en itself put it as an extra element of the parent if it is larger than itself put it as a child/
-		
-		**********************************************/
-		
-		self.currentItem.after(self.placeholder);
-
-		//Update the size of the placeholder (TODO: Logic to fuzzy, see line 316/317)
-		o.placeholder.update(self, self.placeholder);
-
-	},
-
-	_contactContainers: function(event) {
-		for (var i = this.containers.length - 1; i >= 0; i--){
-
-			if(this._intersectsWith(this.containers[i].containerCache)) {
-				if(!this.containers[i].containerCache.over) {
-
-					if(this.currentContainer != this.containers[i]) {
-
-						//When entering a new container, we will find the item with the least distance and append our item near it
-						var dist = 10000; var itemWithLeastDistance = null; var base = this.positionAbs[this.containers[i].floating ? 'left' : 'top'];
-						for (var j = this.items.length - 1; j >= 0; j--) {
-							if(!$.ui.contains(this.containers[i].element[0], this.items[j].item[0])) continue;
-							var cur = this.items[j][this.containers[i].floating ? 'left' : 'top'];
-							if(Math.abs(cur - base) < dist) {
-								dist = Math.abs(cur - base); itemWithLeastDistance = this.items[j];
-							}
-						}
-
-						if(!itemWithLeastDistance && !this.options.dropOnEmpty) //Check if dropOnEmpty is enabled
-							continue;
-
-						this.currentContainer = this.containers[i];
-						itemWithLeastDistance ? this._rearrange(event, itemWithLeastDistance, null, true) : this._rearrange(event, null, this.containers[i].element, true);
-						this._trigger("change", event, this._uiHash());
-						this.containers[i]._trigger("change", event, this._uiHash(this));
-
-						//Update the placeholder
-						this.options.placeholder.update(this.currentContainer, this.placeholder);
-
-					}
-
-					this.containers[i]._trigger("over", event, this._uiHash(this));
-					this.containers[i].containerCache.over = 1;
-				}
-			} else {
-				if(this.containers[i].containerCache.over) {
-					this.containers[i]._trigger("out", event, this._uiHash(this));
-					this.containers[i].containerCache.over = 0;
-				}
-			}
-
-		};
-	},
-
-	_createHelper: function(event) {
-
-		var o = this.options;
-		var helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event, this.currentItem])) : (o.helper == 'clone' ? this.currentItem.clone() : this.currentItem);
-
-		if(!helper.parents('body').length) //Add the helper to the DOM if that didn't happen already
-			$(o.appendTo != 'parent' ? o.appendTo : this.currentItem[0].parentNode)[0].appendChild(helper[0]);
-
-		if(helper[0] == this.currentItem[0])
-			this._storedCSS = { width: this.currentItem[0].style.width, height: this.currentItem[0].style.height, position: this.currentItem.css("position"), top: this.currentItem.css("top"), left: this.currentItem.css("left") };
-
-		if(helper[0].style.width == '' || o.forceHelperSize) helper.width(this.currentItem.width());
-		if(helper[0].style.height == '' || o.forceHelperSize) helper.height(this.currentItem.height());
-
-		return helper;
-
-	},
-
-	_adjustOffsetFromHelper: function(obj) {
-		if(obj.left != undefined) this.offset.click.left = obj.left + this.margins.left;
-		if(obj.right != undefined) this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
-		if(obj.top != undefined) this.offset.click.top = obj.top + this.margins.top;
-		if(obj.bottom != undefined) this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
-	},
-
-	_getParentOffset: function() {
-
-
-		//Get the offsetParent and cache its position
-		this.offsetParent = this.helper.offsetParent();
-		var po = this.offsetParent.offset();
-
-		// This is a special case where we need to modify a offset calculated on start, since the following happened:
-		// 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent
-		// 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that
-		//    the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag
-		if(this.cssPosition == 'absolute' && this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) {
-			po.left += this.scrollParent.scrollLeft();
-			po.top += this.scrollParent.scrollTop();
-		}
-
-		if((this.offsetParent[0] == document.body) //This needs to be actually done for all browsers, since pageX/pageY includes this information
-		|| (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() == 'html' && $.browser.msie)) //Ugly IE fix
-			po = { top: 0, left: 0 };
-
-		return {
-			top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0),
-			left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0)
-		};
-
-	},
-
-	_getRelativeOffset: function() {
-
-		if(this.cssPosition == "relative") {
-			var p = this.currentItem.position();
-			return {
-				top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(),
-				left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft()
-			};
-		} else {
-			return { top: 0, left: 0 };
-		}
-
-	},
-
-	_cacheMargins: function() {
-		this.margins = {
-			left: (parseInt(this.currentItem.css("marginLeft"),10) || 0),
-			top: (parseInt(this.currentItem.css("marginTop"),10) || 0)
-		};
-	},
-
-	_cacheHelperProportions: function() {
-		this.helperProportions = {
-			width: this.helper.outerWidth(),
-			height: this.helper.outerHeight()
-		};
-	},
-
-	_setContainment: function() {
-
-		var o = this.options;
-		if(o.containment == 'parent') o.containment = this.helper[0].parentNode;
-		if(o.containment == 'document' || o.containment == 'window') this.containment = [
-			0 - this.offset.relative.left - this.offset.parent.left,
-			0 - this.offset.relative.top - this.offset.parent.top,
-			$(o.containment == 'document' ? document : window).width() - this.helperProportions.width - this.margins.left,
-			($(o.containment == 'document' ? document : window).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top
-		];
-
-		if(!(/^(document|window|parent)$/).test(o.containment)) {
-			var ce = $(o.containment)[0];
-			var co = $(o.containment).offset();
-			var over = ($(ce).css("overflow") != 'hidden');
-
-			this.containment = [
-				co.left + (parseInt($(ce).css("borderLeftWidth"),10) || 0) + (parseInt($(ce).css("paddingLeft"),10) || 0) - this.margins.left,
-				co.top + (parseInt($(ce).css("borderTopWidth"),10) || 0) + (parseInt($(ce).css("paddingTop"),10) || 0) - this.margins.top,
-				co.left+(over ? Math.max(ce.scrollWidth,ce.offsetWidth) : ce.offsetWidth) - (parseInt($(ce).css("borderLeftWidth"),10) || 0) - (parseInt($(ce).css("paddingRight"),10) || 0) - this.helperProportions.width - this.margins.left,
-				co.top+(over ? Math.max(ce.scrollHeight,ce.offsetHeight) : ce.offsetHeight) - (parseInt($(ce).css("borderTopWidth"),10) || 0) - (parseInt($(ce).css("paddingBottom"),10) || 0) - this.helperProportions.height - this.margins.top
-			];
-		}
-
-	},
-
-	_convertPositionTo: function(d, pos) {
-
-		if(!pos) pos = this.position;
-		var mod = d == "absolute" ? 1 : -1;
-		var o = this.options, scroll = this.cssPosition == 'absolute' && !(this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);
-
-		return {
-			top: (
-				pos.top																	// The absolute mouse position
-				+ this.offset.relative.top * mod										// Only for relative positioned nodes: Relative offset from element to offset parent
-				+ this.offset.parent.top * mod											// The offsetParent's offset without borders (offset + border)
-				- ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod)
-			),
-			left: (
-				pos.left																// The absolute mouse position
-				+ this.offset.relative.left * mod										// Only for relative positioned nodes: Relative offset from element to offset parent
-				+ this.offset.parent.left * mod											// The offsetParent's offset without borders (offset + border)
-				- ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ) * mod)
-			)
-		};
-
-	},
-
-	_generatePosition: function(event) {
-
-		var o = this.options, scroll = this.cssPosition == 'absolute' && !(this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);
-
-		// This is another very weird special case that only happens for relative elements:
-		// 1. If the css position is relative
-		// 2. and the scroll parent is the document or similar to the offset parent
-		// we have to refresh the relative offset during the scroll so there are no jumps
-		if(this.cssPosition == 'relative' && !(this.scrollParent[0] != document && this.scrollParent[0] != this.offsetParent[0])) {
-			this.offset.relative = this._getRelativeOffset();
-		}
-
-		var pageX = event.pageX;
-		var pageY = event.pageY;
-
-		/*
-		 * - Position constraining -
-		 * Constrain the position to a mix of grid, containment.
-		 */
-
-		if(this.originalPosition) { //If we are not dragging yet, we won't check for options
-
-			if(this.containment) {
-				if(event.pageX - this.offset.click.left < this.containment[0]) pageX = this.containment[0] + this.offset.click.left;
-				if(event.pageY - this.offset.click.top < this.containment[1]) pageY = this.containment[1] + this.offset.click.top;
-				if(event.pageX - this.offset.click.left > this.containment[2]) pageX = this.containment[2] + this.offset.click.left;
-				if(event.pageY - this.offset.click.top > this.containment[3]) pageY = this.containment[3] + this.offset.click.top;
-			}
-
-			if(o.grid) {
-				var top = this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1];
-				pageY = this.containment ? (!(top - this.offset.click.top < this.containment[1] || top - this.offset.click.top > this.containment[3]) ? top : (!(top - this.offset.click.top < this.containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top;
-
-				var left = this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0];
-				pageX = this.containment ? (!(left - this.offset.click.left < this.containment[0] || left - this.offset.click.left > this.containment[2]) ? left : (!(left - this.offset.click.left < this.containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left;
-			}
-
-		}
-
-		return {
-			top: (
-				pageY																// The absolute mouse position
-				- this.offset.click.top													// Click offset (relative to the element)
-				- this.offset.relative.top												// Only for relative positioned nodes: Relative offset from element to offset parent
-				- this.offset.parent.top												// The offsetParent's offset without borders (offset + border)
-				+ ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ))
-			),
-			left: (
-				pageX																// The absolute mouse position
-				- this.offset.click.left												// Click offset (relative to the element)
-				- this.offset.relative.left												// Only for relative positioned nodes: Relative offset from element to offset parent
-				- this.offset.parent.left												// The offsetParent's offset without borders (offset + border)
-				+ ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ))
-			)
-		};
-
-	},
-
-	_rearrange: function(event, i, a, hardRefresh) {
-		
-		var haschildNode = this._hasChildNodes(i.item);
-		// do this if is
-		if(this.options.nested && this.error){
-			if(this._storedCursor) $('body').css("cursor", this._storedCursor);
-			this.error = false;
-		}
-		if(!this.options.nested){
-			a ? a[0].appendChild(this.placeholder[0]) : i.item[0].parentNode.insertBefore(this.placeholder[0], (this.direction == 'down' ? i.item[0] : i.item[0].nextSibling));
-		}else{
-			var level = this._getLevel(i.item);
-			var childlevels = this._getChildLevels(this.helper);
-			// aantal items op deze level
-			
-			
-			if(this.options.maxLevels <= level+childlevels){
-				if(this.error != true){
-					this._storedCursor = $('body').css("cursor");
-					$('body').css("cursor", "not-allowed"); //Reset cursor
-					this.error = true;
-				}
-			}else{
-				if(!$.ui.isOverAxis(this.positionAbs.left, i.left, i.width)){
-					
-					if(this.options.maxItems.length <= level-1 || (i.item.closest(this.options.nested).children(this.options.items).not(".ui-sortable-helper,.ui-sortable-placeholder").length < this.options.maxItems[level-1])){ // als maxitems niet berijkt voor level 
-						a ? a[0].appendChild(this.placeholder[0]) : i.item[0].parentNode.insertBefore(this.placeholder[0], (this.direction == 'down' ? i.item[0] : i.item[0].nextSibling));
-					}else{
-						this._storedCursor = $('body').css("cursor");
-						$('body').css("cursor", "not-allowed"); //Reset cursor
-						this.error = true;
-					}
-				}else{
-					
-					if(i.item.find(this.options.nested).siblings().length<=0){
-						var element = document.createElement(this.options.nested);
-						
-						i.item.append($(element));
-						
-					}
-					
-					
-					if(this.options.maxItems.length <= level || (i.item.children(this.options.nested).children(this.options.items).not(".ui-sortable-helper,.ui-sortable-placeholder").length < this.options.maxItems[level])){
-						//i.item.find(this.options.nested)[0].appendChild(this.placeholder[0],i.item.find(this.options.nested)[0].firstChild);
-						i.item.find(this.options.nested)[0].insertBefore(this.placeholder[0],i.item.find(this.options.nested)[0].firstChild);
-					}else{
-						this._storedCursor = $('body').css("cursor");
-						$('body').css("cursor", "not-allowed"); //Reset cursor
-						this.error = true;
-					}
-					
-				}
-			}
-			
-			
-			//a ?  a[0].appendChild(this.placeholder[0])
-		}
-		//Various things done here to improve the performance:
-		// 1. we create a setTimeout, that calls refreshPositions
-		// 2. on the instance, we have a counter variable, that get's higher after every append
-		// 3. on the local scope, we copy the counter variable, and check in the timeout, if it's still the same
-		// 4. this lets only the last addition to the timeout stack through
-		this.counter = this.counter ? ++this.counter : 1;
-		var self = this, counter = this.counter;
-
-		window.setTimeout(function() {
-			if(counter == self.counter) self.refreshPositions(!hardRefresh); //Precompute after each DOM insertion, NOT on mousemove
-		},0);
-
-	},
-	/*b-hind function : get level from element */
-	_getLevel:function(item){
-		
-		var level =1;
-		if(this.options.nested){
-			var list = item.closest(this.options.nested);
-			//.ui-sortable
-			while(!list.is(".ui-sortable") && level < this.options.maxLevels){
-					level++;
-					list = list.parent().closest(this.options.nested);
-			}
-		}
-		return level;
-	},
-	_getChildLevels:function(item){
-		
-			levels = item.find(this.options.items).filter(this.options.items+":first-child").length;
-
-			return levels;
-	},
-	_getItemsOnLevel:function(item){
-		//console.log(item.closest(this.options.nested).html())
-		return item.closest(this.options.nested).children(this.options.items).not('.ui-sortable-placeholder').length;
-	},
-	_hasChildNodes:function(item){
-		if(this.options.nested){
-			if(item.find(this.options.nested) && item.find(this.options.nested).children(this.options.items).length>0){
-				return true;	
-			}else{
-				return false;	
-			}
-		}
-	},
-
-	_clear: function(event, noPropagation) {
-
-		this.reverting = false;
-		// We delay all events that have to be triggered to after the point where the placeholder has been removed and
-		// everything else normalized again
-		var delayedTriggers = [], self = this;
-
-		// We first have to update the dom position of the actual currentItem
-		// Note: don't do it if the current item is already removed (by a user), or it gets reappended (see #4088)
-		if(!this._noFinalSort && this.currentItem[0].parentNode) this.placeholder.before(this.currentItem);
-		this._noFinalSort = null;
-
-		if(this.helper[0] == this.currentItem[0]) {
-			for(var i in this._storedCSS) {
-				if(this._storedCSS[i] == 'auto' || this._storedCSS[i] == 'static') this._storedCSS[i] = '';
-			}
-			this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper");
-		} else {
-			this.currentItem.show();
-		}
-
-		if(this.fromOutside && !noPropagation) delayedTriggers.push(function(event) { this._trigger("receive", event, this._uiHash(this.fromOutside)); });
-		if((this.fromOutside || this.domPosition.prev != this.currentItem.prev().not(".ui-sortable-helper")[0] || this.domPosition.parent != this.currentItem.parent()[0]) && !noPropagation) delayedTriggers.push(function(event) { this._trigger("update", event, this._uiHash()); }); //Trigger update callback if the DOM position has changed
-		if(!$.ui.contains(this.element[0], this.currentItem[0])) { //Node was moved out of the current element
-			if(!noPropagation) delayedTriggers.push(function(event) { this._trigger("remove", event, this._uiHash()); });
-			for (var i = this.containers.length - 1; i >= 0; i--){
-				if($.ui.contains(this.containers[i].element[0], this.currentItem[0]) && !noPropagation) {
-					delayedTriggers.push((function(c) { return function(event) { c._trigger("receive", event, this._uiHash(this)); };  }).call(this, this.containers[i]));
-					delayedTriggers.push((function(c) { return function(event) { c._trigger("update", event, this._uiHash(this));  }; }).call(this, this.containers[i]));
-				}
-			};
-		};
-
-		//Post events to containers
-		for (var i = this.containers.length - 1; i >= 0; i--){
-			if(!noPropagation) delayedTriggers.push((function(c) { return function(event) { c._trigger("deactivate", event, this._uiHash(this)); };  }).call(this, this.containers[i]));
-			if(this.containers[i].containerCache.over) {
-				delayedTriggers.push((function(c) { return function(event) { c._trigger("out", event, this._uiHash(this)); };  }).call(this, this.containers[i]));
-				this.containers[i].containerCache.over = 0;
-			}
-		}
-
-		//Do what was originally in plugins
-		if(this._storedCursor) $('body').css("cursor", this._storedCursor); //Reset cursor
-		if(this._storedOpacity) this.helper.css("opacity", this._storedOpacity); //Reset cursor
-		if(this._storedZIndex) this.helper.css("zIndex", this._storedZIndex == 'auto' ? '' : this._storedZIndex); //Reset z-index
-
-		this.dragging = false;
-		if(this.cancelHelperRemoval) {
-			if(!noPropagation) {
-				this._trigger("beforeStop", event, this._uiHash());
-				for (var i=0; i < delayedTriggers.length; i++) { delayedTriggers[i].call(this, event); }; //Trigger all delayed events
-				this._trigger("stop", event, this._uiHash());
-			}
-			return false;
-		}
-
-		if(!noPropagation) this._trigger("beforeStop", event, this._uiHash());
-
-		//$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node!
-		this.placeholder[0].parentNode.removeChild(this.placeholder[0]);
-
-		if(this.helper[0] != this.currentItem[0]) this.helper.remove(); this.helper = null;
-
-		if(!noPropagation) {
-			for (var i=0; i < delayedTriggers.length; i++) { delayedTriggers[i].call(this, event); }; //Trigger all delayed events
-			this._trigger("stop", event, this._uiHash());
-		}
-		//b-hind clear empty nested elements
-		if(this.options.nested){
-			
-			this.element.find(this.options.nested+":empty").remove();
-			
-		}
-		this.fromOutside = false;
-		return true;
-
-	},
-
-	_trigger: function() {
-		if ($.widget.prototype._trigger.apply(this, arguments) === false) {
-			this.cancel();
-		}
-	},
-
-	_uiHash: function(inst) {
-		var self = inst || this;
-		return {
-			helper: self.helper,
-			placeholder: self.placeholder || $([]),
-			position: self.position,
-			absolutePosition: self.positionAbs, //deprecated
-			offset: self.positionAbs,
-			item: self.currentItem,
-			sender: inst ? inst.element : null
-		};
-	}
-
-}));
-
-$.extend($.ui.sortable, {
-	getter: "serialize toArray",
-	version: "1.7.2",
-	eventPrefix: "sort",
-	defaults: {
-		appendTo: "parent",
-		axis: false,
-		cancel: ":input,option",
-		connectWith: false,
-		containment: false,
-		cursor: 'auto',
-		cursorAt: false,
-		delay: 0,
-		distance: 1,
-		
-		dropOnEmpty: true,
-		forcePlaceholderSize: false,
-		forceHelperSize: false,
-		grid: false,
-		handle: false,
-		helper: "original",
-		items: '> *',
-		opacity: false,
-		placeholder: false,
-		revert: false,
-		scroll: true,
-		scrollSensitivity: 20,
-		scrollSpeed: 20,
-		scope: "default",
-		tolerance: "intersect",
-		zIndex: 1000,
-		nested:false,
-		maxLevels: 100,
-		maxItems : []
-		}
-});
-
-})(jQuery);
Index: /main/trunk/greenstone3/web/interfaces/default/js/gui_div.js
===================================================================
--- /main/trunk/greenstone3/web/interfaces/default/js/gui_div.js	(revision 27714)
+++ /main/trunk/greenstone3/web/interfaces/default/js/gui_div.js	(revision 27714)
@@ -0,0 +1,1301 @@
+
+console.log("Loading gui_div.js\n");
+
+/* DOCUMENT SPECIFIC FUNCTIONS */
+
+function displayTOC(checkbox)
+{
+    if (checkbox.checked == true)
+    {
+        console.log("Show the TOC!");
+        displaySideBar(true);
+        $("#tableOfContents").css("display", "block");
+    }
+    else
+    {
+        console.log("Hide the TOC!");
+        $("#tableOfContents").css("display", "none");
+        if ($("#coverImage").css("display") == "none")
+            displaySideBar(false);
+    }
+
+    return;
+}
+
+function displayBookCover(checkbox)
+{
+    if (checkbox.checked == true)
+    {
+        console.log("Show the book cover!");
+        displaySideBar(true);
+        $("#coverImage").css("display", "block");
+    }
+    else
+    {
+        console.log("Hide the book cover!");
+        $("#coverImage").css("display", "none");
+        if ($("#tableOfContents").css("display") == "none")
+            displaySideBar(false);
+    }
+
+    return;
+}
+
+function displaySideBar(toggle)
+{
+    if (toggle == true)
+    {
+        console.log("Show the sidebar!");
+        $("#rightSidebar").css("display", "block");
+    }
+    else
+    {
+        console.log("Hide the sidebar!");
+        $("#rightSidebar").css("display", "none");
+    }
+
+    return;
+}
+
+function checkDocumentRadio()
+{
+    var selection = $('input[name="documentChanges"]'); //document.quiz.colour;
+
+    for (i=0; i<selection.length; i++)
+
+        if (selection[i].checked == true)
+            return selection[i].value;
+
+    return "this";
+}
+
+function saveDocumentChanges()
+{
+    console.log("Saving changes to "+checkDocumentRadio());
+    console.log("TOC="+$('input[name="TOC"]').attr('checked'));
+    console.log("Cover Image="+$('input[name="bookCover"]').attr('checked'));
+
+    var myurl = document.URL;
+
+    var collection_name = getSubstring(myurl, "&c", "&");
+    var document_id = getSubstring(myurl, "&d", "&");
+    var document_type = getSubstring(myurl, "&dt", "&");
+    var prev_action = getSubstring(myurl, "&p.a", "&");
+    var prev_service = getSubstring(myurl, "&p.s", "&");
+
+    var post_url = "http://localhost:8383/greenstone3/dev?a=f&sa=saveDocument&c=" + collection_name + "&d=" + document_id + "&dt=" + document_type + "&p.a=" + prev_action + "&p.s=" + prev_service;
+
+    // XML will be automatically wrapped in <display><format> tags when saved to collection config
+    var xml = '<format><gsf:option name="TOC" value="'+$('input[name="TOC"]').attr('checked')+'"/><gsf:option name="coverImage" value="'+$('input[name="bookCover"]').attr('checked')+'"/></format>';
+
+    $.post(post_url, {data: xml}, function(data) {
+            console.log("Success, we have received data");
+    }, 'xml');
+}
+
+/* FUNCTIONS FOR FORMAT EDITING */                                                                    
+
+// Ensures that a change to a text field is remembered
+function onTextChange(item, text)
+{
+    console.log("I have set "+item+".value to "+text);
+    item.setAttribute("value",text);
+}
+
+// Ensures that a change to a select field is remembered
+function onSelectChange(item)
+{
+    console.log("I have set "+item.value+".selected to selected");
+    for (var i=0; i<item.options.length; i++)
+    {
+        if(item.selectedIndex == i)
+            item.options[i].setAttribute("selected", "selected");
+        else
+            item.options[i].removeAttribute("selected");
+    }
+    //item.options[item.selectedIndex].selected = "selected";
+    //item.setAttribute("selected","selected");
+}
+
+function getSubstring(str, first, last)
+{
+    var first_index = str.indexOf(first)+first.length+1;
+    var last_index = str.indexOf(last, first_index);
+
+    if(last_index == -1)
+        last_index = str.length;
+
+    var substring = str.substring(first_index, last_index);
+
+    console.log(substring);
+
+    return substring;
+}
+    
+function getFormatStatement()
+{
+    var formatDiv = document.getElementById('formatStatement');
+    var formatStatement = innerXHTML(formatDiv);
+    return formatStatement;
+}
+
+function checkClassifierRadio()
+{
+    var selection = $('input[name="classifiers"]'); //document.quiz.colour;
+
+    for (i=0; i<selection.length; i++)
+
+          if (selection[i].checked == true)
+              return selection[i].value;
+
+    return "this";
+
+}
+
+function updateFormatStatement()
+{
+    var formatStatement = getFormatStatement();
+
+    var thisOrAll = checkClassifierRadio();
+    console.log(thisOrAll);
+    var myurl = document.URL;
+
+    var collection_name = getSubstring(myurl, "&c", "&");
+    var service_name = getSubstring(myurl, "&s", "&");  
+
+    if(thisOrAll == "all")
+        service_name = "AllClassifierBrowse";
+
+    var classifier_name = null;
+
+    if(service_name == "ClassifierBrowse")
+        classifier_name = getSubstring(myurl, "&cl", "&");
+
+    var post_url = "http://localhost:8383/greenstone3/dev?a=f&sa=update&c=" + collection_name +"&s=" + service_name;
+
+    if(classifier_name != null)
+        post_url = post_url + "&cl=" + classifier_name;
+
+    $.post(post_url, {data: formatStatement}, function(data) {
+        //$('.result').innerHTML = data; //html(data);
+    
+        // An error is returned because there is no valid XSLT for a format update action, there probably shouldn't be one so we ignore what the post returns.    
+        console.log("Successfully updated");
+        //console.log(data);
+        }, 'html');
+}
+
+function saveFormatStatement()
+{
+    var formatStatement = getFormatStatement();
+    var thisOrAll = checkClassifierRadio();
+
+    var myurl = document.URL;
+
+    var collection_name = getSubstring(myurl, "&c", "&");
+    var service_name = getSubstring(myurl, "&s", "&");
+    var classifier_name = null;
+
+    if(thisOrAll == "all")
+        service_name = "AllClassifierBrowse";
+
+    if(service_name == "ClassifierBrowse")
+        classifier_name = getSubstring(myurl, "&cl", "&");
+
+    var post_url = "http://localhost:8383/greenstone3/dev?a=f&sa=save&c=" + collection_name +"&s=" + service_name;
+
+    if(classifier_name != null)
+        post_url = post_url + "&cl=" + classifier_name;
+
+    $.post(post_url, {data: formatStatement}, function(data) {
+        // An error is returned because there is no valid XSLT for a format update action, there probably shouldn't be one so we ignore what the post returns.    
+        console.log("Successfully saved");
+        }, 'html');
+}
+
+function getXSLT(classname)
+{
+    var myurl = document.URL;
+
+    var collection_name = getSubstring(myurl, "&c", "&");
+    var document_id = getSubstring(myurl, "&d", "&");
+    var document_type = getSubstring(myurl, "&dt", "&");
+    var prev_action = getSubstring(myurl, "&p.a", "&");
+    var prev_service = getSubstring(myurl, "&p.s", "&");
+
+    var post_url = "http://localhost:8383/greenstone3/dev?a=d&c=" + collection_name + "&d=" + document_id + "&dt=" + document_type + "&p.a=" + prev_action + "&p.s=" + prev_service + "&o=skinandlib";
+
+    $.post(post_url, {data: classname}, function(data) {
+            console.log("Success, we have received data");
+            classname = "." + classname;
+            console.log(classname); 
+            var content = $( data ).find(classname);
+            console.log(content.xml());
+            $("#XSLTcode").val(content.xml());
+            }, 'xml');
+}
+
+function traverse(node, formatstring)
+  {
+
+    if(node.nodeName=='DIV')
+    {
+        console.log("Found a div" +node.nodeName+","+node.nodeType);
+        formatstring = formatstring + find_class(node);
+        console.log(formatstring);
+    }
+
+    var children = $(node).children();
+    for(var i=0; i < children.length; i++)
+        formatstring = formatstring + traverse(children[i], formatstring);
+
+    return formatstring;
+  }
+        
+function find_class(current)
+{
+    var classes = current.className.split(' ');
+    var none = "";
+    for(var i = 0; i < classes.length; i++)
+    {
+        switch(classes[i])
+        {
+            case 'gsf_template':
+              return create_gsf_template(current);
+            default:
+            {
+              console.log("Class not found");
+              return none;
+            }
+        }
+    }
+}
+
+function create_gsf_template(current)
+{
+    // find match text which is an input with class match
+    var match = $(current).find('.match')[0].value;
+    console.log(match);
+    
+    // find mode text which is an input with class mode
+    var mode = $(current).find('.mode')[0].value;
+    console.log(mode);
+
+    // "<gsf:template match=\"classifierNode\" mode=\"horizontal\">"
+    var gsf = "<gsf:template match=\"" + match + "\"";
+    if(mode != "vertical")
+        gsf = gsf + " mode=\"" + mode + "\"";
+    gsf = gsf + ">";
+    
+    return gsf;
+
+}
+
+/*
+$("#iframe").ready(function(){
+        console.log("iframe is ready ...");
+        var iframe = document.getElementById('iframe');
+        var iframe_document = iframe.document;
+
+        if(iframe.contentDocument)
+        {
+            iframe_document = iframe.contentDocument; // For NS6
+            console.log("Chose content document");
+        }
+        else if(iframe.contentWindow)
+        {
+            iframe_document = iframe.contentWindow.document; // For IE5.5 and IE6
+            console.log("Chose content window");
+        }
+
+        console.log(iframe_document.documentElement.innerHTML); //document.documentElement.outerHTML
+
+        $(iframe_document.documentElement.innerHTML).find('a').each(function() {
+            console.log("data "+$(this).data('href'));
+            console.log("getAttribute "+$(this).getAttribute('href'));
+            console.log("attr "+$(this).attr('href'));
+            console.log("this.href "+this.href);
+            var original = this.href; //$(this).attr('href');
+            // check if greenstone link ie. starts with format
+            //var original = $(this).data('href');
+            var modified = original.toString().concat("&excerptid=gs_content");
+            console.log(modified);
+            this.href = modified;
+            //$(this).attr('href',modified);
+            //$(this).data('href', modified);
+            //console.log($(this).attr('href'));
+            console.log("data "+$(this).data('href'));
+            console.log("getAttribute "+$(this).getAttribute('href'));
+            console.log("attr "+$(this).attr('href'));
+            console.log("this.href "+this.href);
+            console.log("**********");
+
+        });
+}); */
+/*
+function loadXMLDoc()
+{
+    if (window.XMLHttpRequest)
+    {// code for IE7+, Firefox, Chrome, Opera, Safari
+        xmlhttp=new XMLHttpRequest();
+    }
+    else
+    {// code for IE6, IE5
+        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
+    }
+    
+    xmlhttp.onreadystatechange=function()
+    {  
+        console.log("state changed to " + xmlhttp.readyState);
+        console.log("status is " + xmlhttp.status);
+        if (xmlhttp.readyState==4 && xmlhttp.status==200)
+        {
+            console.log("get code");
+            console.log(xmlhttp.responseText);
+            document.getElementById("gs_content").innerHTML=xmlhttp.responseText;
+        }
+    }
+    
+    xmlhttp.open("GET","http://localhost:8080/greenstone3/format?a=b&rt=s&s=ClassifierBrowse&c=simpleht&cl=CL1&excerptid=gs_content",true);
+    //xmlhttp.open("GET","http://www.cs.waikato.ac.nz",true);
+    //xmlhttp.open("GET","http://wand.net.nz/~sjb48/index.html",true);
+    xmlhttp.send();
+}
+*/
+$(document).ready(function(){
+
+    console.log("Document ready function\n");
+	
+    CURRENT_SELECT_VALUE = ""; //global - gets set by ui.draggable
+
+    /* DOCUMENT SPECIFIC FUNCTIONS */
+
+    $('.sectionHeader').click(function () {
+        console.log('section Header click *');
+        getXSLT("sectionHeader");
+        return false; //don't event bubble
+    });
+
+    $('.sectionContainer').click(function () {
+        console.log('section Container click *');
+        getXSLT("sectionContainer");
+        return false; // don't event bubble
+    });
+	
+	var collection = "";
+	
+	var regex = new RegExp("[?&]c=");
+	var matches = regex.exec(document.URL);
+	if(matches != null)
+	{
+		var startIndex = matches.index;
+		var endIndex = document.URL.indexOf("&", startIndex + 1);
+		
+		if(endIndex == -1)
+		{
+			endIndex = document.URL.length;
+		}
+		
+		collection = document.URL.substring(startIndex, endIndex);
+	}
+
+	//Retrieve the collection metadataset using ajax
+	$.ajax
+	({
+		type: "GET",
+		url: "?a=g&s=CoverageMetadataRetrieve&o=xml&rt=r&c=" + collection,
+		success: function(data) 
+		{
+			var str = "<select name=\"meta_select\" onChange=\"onSelectChange(this)\">";
+			
+			var selectorArea = document.getElementById("metadataSelector");		
+			var metadataSets = data.getElementsByTagName("metadataSet");
+			for(var i = 0; i < metadataSets.length; i++)
+			{
+				var metadata = metadataSets[i].getElementsByTagName("metadata");
+				for(var j = 0; j < metadata.length; j++)
+				{
+					var metaValue = metadataSets[i].getAttribute("name") + "." + metadata[j].getAttribute("name");
+					str += "<option value=\"" + metaValue + "\">" + metaValue + "</option>";
+				}
+			}
+			
+			str += "</select>";
+
+			selectorArea.innerHTML = str;
+			gsf_metadata_element = str;
+		}
+	});
+
+$.ui.plugin.add("draggable", "cursor", {
+	start: function(event, ui) {
+		var t = $('body'), o = $(this).data('draggable').options;
+		if (t.css("cursor")) o._cursor = t.css("cursor");
+		t.css("cursor", o.cursor);
+	},
+	stop: function(event, ui) {
+		var o = $(this).data('draggable').options;
+		if (o._cursor) $('body').css("cursor", o._cursor);
+	}
+});
+
+	$.ui.draggable.prototype._createHelper = function(event) {
+
+                var o = this.options;
+                var helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event])) : (o.helper == 'clone' ? this.element.clone().removeAttr('id') : this.element);
+
+		var select = $(this.element).find('select');
+		var value = select.attr('value');
+		console.log("Found "+value+" in helper");
+		CURRENT_SELECT_VALUE = value;
+		helper.find('select').attr('value', value);
+
+                if(!helper.parents('body').length)
+                        helper.appendTo((o.appendTo == 'parent' ? this.element[0].parentNode : o.appendTo));
+
+                if(helper[0] != this.element[0] && !(/(fixed|absolute)/).test(helper.css("position")))
+                        helper.css("position", "absolute");
+
+                return helper;
+
+        };
+	
+	$.ui.sortable.prototype._removeCurrentsFromItems = function() {
+		//console.log("IN _removeCurrentsFromItems FUNCTION");
+		//console.log("this = " + this.currentItem[0].getAttribute('class'));
+		var list = this.currentItem.find(":data(sortable-item)");
+
+		var i = 0;
+		while (i<this.items.length) {
+			var found_match = false;
+			for (var j=0; j<list.length; j++) {
+				if(this.items[i])
+				{
+					if(list[j] == this.items[i].item[0]) {
+						//console.log("Item to splice = " + this.items[i].item[0].getAttribute('class'));
+						this.items.splice(i,1);
+						found_match = true;
+						break;
+					}
+				}
+			};
+			if (!found_match)
+				i++;
+			else
+				break;
+		}
+	};
+	
+	$.ui.plugin.add("draggable", "connectToSortable", {
+	start: function(event, ui) {
+        //console.log("FUNCTION start draggable connectToSortable");
+		var inst = $(this).data("draggable"), o = inst.options,
+			uiSortable = $.extend({}, ui, { item: inst.element });
+		inst.sortables = [];
+		$(o.connectToSortable).each(function() {
+			var sortable = $.data(this, 'sortable');
+			if (sortable && !sortable.options.disabled) {
+				inst.sortables.push({
+					instance: sortable,
+					shouldRevert: sortable.options.revert
+				});
+				sortable._refreshItems();	//Do a one-time refresh at start to refresh the containerCache
+				sortable._trigger("activate", event, uiSortable);
+			}
+		});
+
+	},
+	stop: function(event, ui) {
+
+        //console.log("FUNCTION stop draggable connectToSortable");
+		//If we are still over the sortable, we fake the stop event of the sortable, but also remove helper
+		var inst = $(this).data("draggable"),
+			uiSortable = $.extend({}, ui, { item: inst.element });
+
+		$.each(inst.sortables, function() {
+			if(this.instance.isOver) {
+
+				this.instance.isOver = 0;
+
+				inst.cancelHelperRemoval = true; //Don't remove the helper in the draggable instance
+				this.instance.cancelHelperRemoval = false; //Remove it in the sortable instance (so sortable plugins like revert still work)
+
+				//The sortable revert is supported, and we have to set a temporary dropped variable on the draggable to support revert: 'valid/invalid'
+				if(this.shouldRevert) this.instance.options.revert = true;
+
+				//Trigger the stop of the sortable
+                //console.log("Draggable tells sortable to stop");
+				this.instance._mouseStop(event);
+
+				this.instance.options.helper = this.instance.options._helper;
+
+				//If the helper has been the original item, restore properties in the sortable
+				if(inst.options.helper == 'original')
+					this.instance.currentItem.css({ top: 'auto', left: 'auto' });
+
+			} else {
+				this.instance.cancelHelperRemoval = false; //Remove the helper in the sortable instance
+				this.instance._trigger("deactivate", event, uiSortable);
+			}
+
+		});
+
+	},
+	drag: function(event, ui) {
+        //console.log("FUNCTION drag draggable connectToSortable");
+
+		var inst = $(this).data("draggable"), self = this;
+
+		var checkPos = function(o) {
+			var dyClick = this.offset.click.top, dxClick = this.offset.click.left;
+			var helperTop = this.positionAbs.top, helperLeft = this.positionAbs.left;
+			var itemHeight = o.height, itemWidth = o.width;
+			var itemTop = o.top, itemLeft = o.left;
+
+			return $.ui.isOver(helperTop + dyClick, helperLeft + dxClick, itemTop, itemLeft, itemHeight, itemWidth);
+		};
+
+        var intersecting_items = new Array();
+
+		$.each(inst.sortables, function(i) {
+			
+			//Copy over some variables to allow calling the sortable's native _intersectsWith
+			this.instance.positionAbs = inst.positionAbs;
+			this.instance.helperProportions = inst.helperProportions;
+			this.instance.offset.click = inst.offset.click;
+			
+			if(this.instance._intersectsWith(this.instance.containerCache)) {
+
+				//If it intersects, we use a little isOver variable and set it once, so our move-in stuff gets fired only once
+				//if(!this.instance.isOver) {
+
+                    //console.log('Line 1113');
+
+				//	this.instance.isOver = 1;
+
+                    intersecting_items.push(this.instance); // sam
+                //} //sam
+
+					//Now we fake the start of dragging for the sortable instance,
+					//by cloning the list group item, appending it to the sortable and using it as inst.currentItem
+					//We can then fire the start event of the sortable with our passed browser event, and our own helper (so it doesn't create a new one)
+					//sam this.instance.currentItem = $(self).clone().appendTo(this.instance.element).data("sortable-item", true);
+					//sam this.instance.options._helper = this.instance.options.helper; //Store helper option to later restore it
+					//sam this.instance.options.helper = function() { return ui.helper[0]; };
+
+					//sam event.target = this.instance.currentItem[0];
+					//sam this.instance._mouseCapture(event, true);
+					//sam this.instance._mouseStart(event, true, true);
+
+					//Because the browser event is way off the new appended portlet, we modify a couple of variables to reflect the changes
+					//sam this.instance.offset.click.top = inst.offset.click.top;
+					//sam this.instance.offset.click.left = inst.offset.click.left;
+					//sam this.instance.offset.parent.left -= inst.offset.parent.left - this.instance.offset.parent.left;
+					//sam this.instance.offset.parent.top -= inst.offset.parent.top - this.instance.offset.parent.top;
+
+					//sam inst._trigger("toSortable", event);
+					//sam inst.dropped = this.instance.element; //draggable revert needs that
+					//hack so receive/update callbacks work (mostly)
+					//sam inst.currentItem = inst.element;
+					//sam this.instance.fromOutside = inst;
+
+				//sam brace
+
+				//Provided we did all the previous steps, we can fire the drag event of the sortable on every draggable drag, when it intersects with the sortable
+				//sam if(this.instance.currentItem) this.instance._mouseDrag(event);
+
+			} else {
+
+				//If it doesn't intersect with the sortable, and it intersected before,
+				//we fake the drag stop of the sortable, but make sure it doesn't remove the helper by using cancelHelperRemoval
+				if(this.instance.isOver) {
+
+                    console.log("UNSETTING ISOVER");
+                    console.log("ON ITEM="+this.instance.currentItem[0].getAttribute('class'))
+					this.instance.isOver = 0;
+					this.instance.cancelHelperRemoval = true;
+					
+					//Prevent reverting on this forced stop
+					this.instance.options.revert = false;
+					
+					// The out event needs to be triggered independently
+					this.instance._trigger('out', event, this.instance._uiHash(this.instance));
+					
+					this.instance._mouseStop(event, true);
+					this.instance.options.helper = this.instance.options._helper;
+
+					//Now we remove our currentItem, the list group clone again, and the placeholder, and animate the helper back to it's original size
+                    //console.log("DO WE GET HERE?");
+					this.instance.currentItem.remove();
+					if(this.instance.placeholder) this.instance.placeholder.remove();
+
+					inst._trigger("fromSortable", event);
+					inst.dropped = false; //draggable revert needs that
+				
+	            }
+       
+            } 
+        });
+
+        //sam
+        //console.log("Contents of intersecting_items");
+        var innermostContainer = null, innermostIndex = null;       
+        for (i=0;i<intersecting_items.length;i++)
+        {
+            //console.log('ITEM: '+intersecting_items[i].element[0].getAttribute('class'));
+    
+            if(innermostContainer && $.ui.contains(intersecting_items[i].element[0], innermostContainer.element[0]))
+                continue;
+                        
+            innermostContainer = intersecting_items[i];
+            innermostIndex = i; 
+                    
+        }
+
+        for (i=0;i<intersecting_items.length;i++)
+        {
+            if(intersecting_items[i] != innermostContainer)
+                if(intersecting_items[i].isOver) {
+
+                    console.log("UNSETTING ISOVER");
+                    console.log("ON ITEM="+intersecting_items[i].currentItem[0].getAttribute('class'))
+                    intersecting_items[i].isOver = 0;
+                    intersecting_items[i].cancelHelperRemoval = true;
+
+                    //Prevent reverting on this forced stop
+                    intersecting_items[i].options.revert = false;
+
+                    // The out event needs to be triggered independently
+                    intersecting_items[i]._trigger('out', event, intersecting_items[i]._uiHash(intersecting_items[i]));
+
+                    intersecting_items[i]._mouseStop(event, true);
+                    intersecting_items[i].options.helper = intersecting_items[i].options._helper;
+
+                    //Now we remove our currentItem, the list group clone again, and the placeholder, and animate the helper back to it's original size
+                    //console.log("DO WE GET HERE?");
+                    if(intersecting_items[i].currentItem) intersecting_items[i].currentItem.remove();
+                    if(intersecting_items[i].placeholder) intersecting_items[i].placeholder.remove();
+
+                    inst._trigger("fromSortable", event);
+                    inst.dropped = false; //draggable revert needs that
+                }
+
+                intersecting_items[i].isOver = 0;
+            
+        }
+
+        if(innermostContainer && !innermostContainer.isOver)
+        {
+            console.log("INNER="+innermostContainer.element[0].getAttribute('class'));
+            console.log("SETTING ISOVER");
+    	    innermostContainer.isOver = 1;
+
+            //Now we fake the start of dragging for the sortable instance,
+            //by cloning the list group item, appending it to the sortable and using it as inst.currentItem
+            //We can then fire the start event of the sortable with our passed browser event, and our own helper (so it doesn't create a new one)
+
+            if(innermostContainer.currentItem) innermostContainer.currentItem.remove();
+            if(innermostContainer.placeholder) innermostContainer.placeholder.remove();
+
+            innermostContainer.currentItem = $(self).clone().appendTo(innermostContainer.element).data("sortable-item", true);
+            
+            innermostContainer.options._helper = innermostContainer.options.helper; //Store helper option to later restore it
+            innermostContainer.options.helper = function() { return ui.helper[0]; };
+
+            console.log("EVENT TARGET="+innermostContainer.currentItem[0].getAttribute('class'));
+            event.target = innermostContainer.currentItem[0];
+            innermostContainer._mouseCapture(event, true);
+            innermostContainer._mouseStart(event, true, true);
+
+            //Because the browser event is way off the new appended portlet, we modify a couple of variables to reflect the changes
+            innermostContainer.offset.click.top = inst.offset.click.top;
+            innermostContainer.offset.click.left = inst.offset.click.left;
+            innermostContainer.offset.parent.left -= inst.offset.parent.left - innermostContainer.offset.parent.left;
+            innermostContainer.offset.parent.top -= inst.offset.parent.top - innermostContainer.offset.parent.top;
+
+            inst._trigger("toSortable", event);
+            inst.dropped = innermostContainer.element; //draggable revert needs that
+            //hack so receive/update callbacks work (mostly)
+            inst.currentItem = inst.element;
+            innermostContainer.fromOutside = inst;
+
+            //sam brace
+        }
+
+        if(innermostContainer)
+        {
+            //Provided we did all the previous steps, we can fire the drag event of the sortable on every draggable drag, when it intersects with the sortable
+            if(innermostContainer.currentItem) innermostContainer._mouseDrag(event);
+        }
+
+	}
+});
+
+    /*
+    var iframe = document.getElementById('iframe');
+    var iframe_document = iframe.document;
+   
+    if(iframe.contentDocument)
+    {
+        iframe_document = iframe.contentDocument; // For NS6
+        console.log("Chose content document");
+    }
+    else if(iframe.contentWindow)
+    {
+        iframe_document = iframe.contentWindow.document; // For IE5.5 and IE6
+        console.log("Chose content window");
+    }
+
+    // Edit the hrefs in preview_html - search for <a href="format?a=b&rt=r&s=ClassifierBrowse&c=simpleht&cl=CL1.2">
+    var start_index = 0;
+    var end_index = 0;
+    while(start_index != -1)
+    {
+        start_index = preview_html.indexOf("href=\"format", start_index);
+        console.log("start index = " + start_index);
+        if(start_index != -1)
+        {
+            end_index = preview_html.indexOf("\">", start_index);
+            console.log("end_index = " + end_index);
+            a = preview_html.substring(0,end_index);
+            b = preview_html.substring(end_index);
+            preview_html = a.concat("&excerptid=results", b);
+            console.log(preview_html);
+            start_index = end_index + "&excerptid=results\">".length;
+        }
+    }
+
+    // Split the html code in to three parts
+    var first_index = preview_html.indexOf("<ul id=\"results\"");
+    console.log("First index is "+first_index);
+    var second_index = preview_html.indexOf("</ul>", first_index) + "</ul>".length;
+    console.log("Second index is "+second_index);
+
+    var first_half = preview_html.substring(0, first_index);
+    var iframe_code = preview_html.substring(first_index, second_index);
+    var second_half = preview_html.substring(second_index);
+
+    //$('#my_categories').innerHTML = first_half.concat(second_half);
+    document.getElementById("my_categories").innerHTML = first_half.concat(second_half);
+
+    // Put the content in the iframe
+    if(initialised_iframe == "false")
+    {
+        console.log("Initialised iframe with preview html");
+        console.log(preview_html);
+        iframe_document.open();
+        iframe_document.writeln(iframe_code); //.concat("&excerptid=gs_content"));
+        iframe_document.close(); 
+        initialised_iframe = "true";
+    }
+    */
+
+    /*    
+    $(iframe_document.documentElement.innerHTML).find('a').each(function() {
+            console.log("data "+$(this).data('href'));
+            console.log("getAttribute "+this.getAttribute('href'));
+            console.log("attr "+$(this).attr('href'));
+            console.log("this.href "+this.href);
+            var original = this.href; //$(this).attr('href');
+            // check if greenstone link ie. starts with format
+            //var original = $(this).data('href');
+            var modified = original.toString().concat("&excerptid=gs_content");
+            console.log("*                      *");
+            console.log(modified);
+            console.log("*                      *");
+            //this.href = modified;
+            //$(this).attr('href',modified);
+            //$(this).data('href', modified);
+            $(this).attr({ 'href': modified });
+            //console.log($(this).attr('href'));
+            console.log("data "+$(this).data('href'));
+            console.log("getAttribute "+this.getAttribute('href'));
+            console.log("attr "+$(this).attr('href'));
+            console.log("this.href "+this.href);
+            console.log("***********************");
+    });
+    */
+
+    /******************************************/
+    /*              DRAGGABLES                */
+    /******************************************/
+
+    $(".draggable_gsf_template").draggable({
+            cursor: 'crosshair',
+            connectToSortable: '#formatStatement',
+            helper: 'clone',
+            revert: 'invalid'
+    });
+
+    $(".draggable_table").draggable({
+            cursor: 'crosshair',
+            connectToSortable: '.gsf_template',
+            helper: 'clone',
+            revert: 'invalid'
+    });
+
+    $(".draggable_tr").draggable({
+            cursor: 'crosshair',
+            connectToSortable: '.gsf_table',
+            helper: 'clone',
+            revert: 'invalid'
+    })
+
+    $(".draggable_td").draggable({
+            cursor: 'crosshair',
+            //connectToSortable: '.td',
+            helper: 'clone',
+            revert: 'invalid'
+    })
+
+    $(".draggable_gsf_text").draggable({
+            cursor: 'crosshair',
+            connectToSortable: '.td-div, .gsf_when, .gsf_otherwise, .gsf_link, .gsf_choose_metadata, .gsf_default',
+            helper: 'clone',
+            revert: 'invalid'
+    });
+    
+    $(".draggable_gsf_choose_metadata").draggable({
+            cursor: 'crosshair',
+            connectToSortable: '.td-div, .gsf_link, .gsf_when, .gsf_otherwise',
+            helper: 'clone',
+            revert: 'invalid'
+    });
+
+    //$(".element_type_gsf_metadata").draggable({
+    $(".draggable_gsf_metadata").draggable({
+            cursor: 'crosshair',
+            connectToSortable: '.gsf_choose_metadata, .gsf_when, .gsf_otherwise, .gsf_link, .td-div',
+            helper: 'clone',
+            revert: 'invalid'
+    });
+
+    $(".draggable_gsf_link").draggable({
+            cursor: 'crosshair',
+            connectToSortable: '.td-div, .gsf_when, .gsf_otherwise, .gsf_link',
+            helper: 'clone',
+            revert: 'invalid'
+    });
+
+    // switch, when, otherwise, icon
+    $(".draggable_gsf_switch").draggable({
+            cursor: 'crosshair',
+            connectToSortable: '.td-div, .gsf_link',
+            helper: 'clone',
+            revert: 'invalid'
+    });
+
+    $(".draggable_gsf_when").draggable({
+            cursor: 'crosshair',
+            connectToSortable: '.gsf_switch',
+            helper: 'clone',
+            revert: 'invalid'
+    });
+
+    $(".draggable_gsf_otherwise").draggable({
+            cursor: 'crosshair',
+            connectToSortable: '.gsf_switch',
+            helper: 'clone',
+            revert: 'invalid'
+    });
+
+    $(".draggable_gsf_icon").draggable({
+            cursor: 'crosshair',
+            connectToSortable: '.td-div, .gsf_link, .gsf_choose, .gsf_when, .gsf_otherwise',
+            helper: 'clone',
+            revert: 'invalid'
+    });
+
+ 
+    /******************************************/
+    /*               SORTABLES                */
+    /******************************************/
+
+    bind_td_sortable();
+    bind_all_sortables();
+
+    $('#formatStatement').sortable({
+            cursor: 'pointer',
+            tolerance: 'pointer',
+            items: '.gsf_template',
+            placeholder:'placeholder',
+            //'nested':'div'
+            stop: function(event, ui) {
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('css_gsf_template')) { replace_with(ui.item,gsf_template_element); }
+            }
+    });
+ 
+    $('div.gsf_template').children(".block,.table").slideUp(300); 
+}); 
+
+/*******************************************************************************/
+
+function bind_all_sortables()
+{
+    console.log('function bind_all_sortables()');
+    bind_template_sortable();
+    bind_choose_metadata_sortable();
+    bind_link_sortable();
+    bind_switch_sortable();
+    bind_when_sortable();
+    bind_otherwise_sortable();
+
+    bind_tables();
+
+    bind_block_mouseover();
+    bind_minmax_remove();    
+}
+
+function bind_tables()
+{
+    console.log('function bind_tables()');
+
+    $('#sectionHeader').click(function () {
+         console.log('section Header click *');
+         return true;
+    });
+    
+    $('#sectionContainer').click(function () {
+         console.log('section Container click *');
+         return true;
+    });
+
+    $(".td-div").resizable({
+                alsoResize: 'parent',
+                handles: 'w,e',
+                stop: function(event, ui) {
+                        console.log('Resize table on stop');
+                        resize_tables($(this));
+                }, });
+
+    $(".droppable").droppable({
+            accept: '.element_type_td',
+            tolerance: 'pointer', 
+            activate: function(event, ui) { $(this).addClass("droppable_hl");}, 
+            deactivate: function(event, ui) { $(this).removeClass("droppable_hl"); },
+            drop: function(event, ui) {
+                 var neverempty = document.createElement("div");
+                 neverempty.setAttribute("class","neverempty block");
+                 neverempty.setAttribute("style","height:50px");
+                 neverempty.setAttribute("style","display:block");
+                 var text = document.createTextNode('NEVER EMPTY');
+                 neverempty.appendChild(text);
+                 var td = document.createElement("td");
+                 var div = document.createElement("div"); 
+                 div.setAttribute("title","td-div");
+                 div.setAttribute("class","td-div block");
+                 div.setAttribute("style","margin-left:0px");
+                 div.setAttribute("width","25px");
+                 td.appendChild(div);
+                 div.appendChild(neverempty);
+                 var sep = document.createElement("td");
+                 sep.setAttribute("class","droppable");
+                 sep.setAttribute("width","10px"); 
+                 $(this).after(sep);                
+                 $(this).after(td);                
+                 bind_tables();
+                 resize_tables($(this));
+                 bind_td_sortable();
+                 bind_block_mouseover();
+            }
+        });
+
+}
+
+function replace_with(item, me)
+{
+    // Search me for select
+    if(me.search("select") != -1)
+    {
+    // If select exists, then find CURRENT_SELECT_VALUE
+	if(me.search(CURRENT_SELECT_VALUE) != -1)
+	{
+	    var index = me.search(CURRENT_SELECT_VALUE);
+            if(index == -1)
+                console.log("Did not find " + CURRENT_SELECT_VALUE);
+            else
+	    {
+                console.log("Found " + CURRENT_SELECT_VALUE + " at index " + index);    
+                index = index + CURRENT_SELECT_VALUE.length + 1;
+                console.log("Attempt inserting select at new index "+index);
+                a = me.substring(0,index);
+                b = me.substring(index);
+                me = a.concat("selected",b);
+            }
+	}
+    }
+
+    item.replaceWith(me); //'<div class="element element-txt">This text box has been added!</div>');
+
+    resize_tables(item);
+
+    bind_all_sortables();
+}
+
+function resize_tables(item)
+{
+    var max_height = 0;
+    (item.parents('.table')).each(function(index) {
+        $(this).children().children().children().each(function() {
+            var sum_one = 0;
+            var sum_two = 0;
+            $(this).children('.block').each(function() { sum_one = sum_one + $(this).height();  
+                $(this).children('.block').each(function() { sum_two = sum_two + $(this).height(); } );
+                console.log("My height is " + $(this).height() + ", sum height 2 is " + sum_two);
+            });
+            console.log("My height is " + $(this).height() + ", sum height 1 is " + sum_one);
+            if (sum_two > max_height)
+                max_height = sum_two;
+        });
+    });
+    equalHeights(item,max_height);
+}
+
+function bind_template_sortable()
+{
+    //console.log('function bind_template_sortable()');
+    $('.gsf_template').sortable({
+            'cursor':'pointer',
+            'tolerance': 'pointer',
+            'items':'.table', //.gsf_choose_metadata, .gsf_metadata',
+            'placeholder':'placeholder',
+            //'nested':'.gsf:metadata'
+            stop: function(event, ui) {
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_table')) { replace_with(ui.item, "<table class=\"table\" border=\"2\"></table>"); }
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_choose_metadata')) { replace_with(ui.item, gsf_choose_metadata_element); }
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_metadata')) { replace_with(ui.item, gsf_metadata_element); }
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_link')) { replace_with(ui.item, gsf_link_element); }
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_switch')) { replace_with(ui.item, gsf_switch_element); }
+            }
+    });
+
+    $('.gsf_template').click(function () {
+         console.log('gsf_template class click');
+         return false;
+    });
+
+}
+
+function bind_td_sortable()
+{
+
+    $('tr').sortable({
+            'cursor':'pointer',
+            'tolerance': 'intersect',
+            'items':'.column',
+            'placeholder':'placeholder_td',
+            'connectWith':'column'});
+
+    $('.td-div').sortable({
+            'cursor':'pointer',
+            'tolerance': 'pointer',
+            'items':'.gsf_metadata, .gsf_choose_metadata, .gsf_link, .gsf_switch',
+            'placeholder':'placeholder',
+            receive: function(event, ui) { alert("Attempted to receive"); },
+            stop: function(event, ui) {
+                // gsf metadata
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_metadata')) { replace_with(ui.item, gsf_metadata_element); }
+                // gsf choose metadata
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_choose_metadata')) { replace_with(ui.item, gsf_choose_metadata_element); }
+                // gsf link
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_link')) { replace_with(ui.item, gsf_link_element); }
+                // gsf switch
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_switch')) { replace_with(ui.item, gsf_switch_element); }
+                
+            }
+
+    });
+
+    $('.td-div').click(function () {    
+         //console.log('td class click');
+         return true;
+    });
+
+
+
+}
+
+
+function bind_choose_metadata_sortable()
+{
+    //console.log('function bind_choose_metadata_sortable()');
+    $('.gsf_choose_metadata').sortable({
+            'cursor':'pointer',
+            'tolerance': 'pointer',
+            'items':'.gsf_metadata, .gsf_text, .gsf_default',
+            'placeholder':'placeholder',
+            'connectWith':'.gsf_choose_metadata',
+            //'nested':'.gsf:metadata'
+            stop: function(event, ui) {
+                // gsf metadata
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_metadata')) { replace_with(ui.item, gsf_metadata_element); } 
+                // gsf text
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_text')) { replace_with(ui.item, gsf_text_element); } 
+                // gsf default
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_default')) { replace_with(ui.item, gsf_default_element); } 
+
+                bind_all_sortables();
+            }
+    });
+}
+
+function bind_link_sortable()
+{
+    //console.log('function bind_link_sortable()');
+    $('.gsf_link').sortable({
+            'cursor':'pointer',
+            'tolerance': 'pointer',
+            'items':'.leaf, .gsf_link, .gsf_switch, .gsf_choose',
+            'placeholder':'placeholder',
+            'connectWith':'.gsf_link',
+            //'nested':'.gsf:metadata'
+            stop: function(event, ui) {
+                // gsf icon
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_icon')) { replace_with(ui.item, gsf_icon_element); }
+                // gsf text
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_text')) { replace_with(ui.item, "<input type=\"text\" name=\"rawtextinput\" size=\"10\"/>"); }
+                // gsf metadata
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_metadata')) { replace_with(ui.item, gsf_metadata_element); } 
+                // gsf link
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_link')) { replace_with(ui.item, gsf_link_element); }
+                // gsf switch
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_switch')) { replace_with(ui.item, gsf_switch_element); }
+                // gsf choose
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_choose_metadata')) { replace_with(ui.item, gsf_choose_metadata_element); }
+            }
+    });
+}
+
+function bind_switch_sortable()
+{
+    //console.log('function bind_switch_sortable()');
+    $('.gsf_switch').sortable({
+            'cursor':'pointer',
+            'tolerance': 'pointer',
+            'items':'.gsf_metadata, .gsf_when, .gsf_otherwise, .gsf_text',
+            'placeholder':'placeholder',
+            'connectWith':'.gsf_switch',
+            //'nested':'.gsf:metadata'
+            stop: function(event, ui) {
+                // gsf when
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_when')) { replace_with(ui.item, gsf_when_element); }
+                // gsf otherwise
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_otherwise')) { replace_with(ui.item, gsf_otherwise_element); }
+                // gsf metadata
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_metadata')) { replace_with(ui.item, gsf_metadata_element); } 
+                // gsf text
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_text')) { replace_with(ui.item, gsf_text_element); } 
+            }
+    });
+}
+
+function bind_when_sortable()
+{
+    //console.log('function bind_when_sortable()');
+    $('.gsf_when').sortable({
+            'cursor':'pointer',
+            'tolerance': 'pointer',
+            'items':'.leaf, .gsf_link, .gsf_choose',
+            'placeholder':'placeholder',
+            //'nested':'.gsf:metadata'
+            stop: function(event, ui) {
+                // gsf metadata
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_metadata')) { replace_with(ui.item, gsf_metadata_element); }
+                // gsf icon
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_icon')) { replace_with(ui.item, gsf_icon_element); } 
+                // gsf text
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_text')) { replace_with(ui.item, gsf_text_element); } 
+                // gsf link
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_link')) { replace_with(ui.item, gsf_link_element); } 
+                // gsf choose
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_choose')) { replace_with(ui.item, gsf_choose_element); } 
+            }
+    });
+}
+
+function bind_otherwise_sortable()
+{
+    //console.log('function bind_otherwise_sortable()');
+    $('.gsf_otherwise').sortable({
+            'cursor':'pointer',
+            'tolerance': 'pointer',
+            'items':'.leaf, .gsf_link, .gsf_choose',
+            'placeholder':'placeholder',
+            //'nested':'.gsf:metadata'
+            stop: function(event, ui) {
+                // gsf metadata
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_metadata')) { replace_with(ui.item, gsf_metadata_element); }
+                // gsf text
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_text')) { replace_with(ui.item, "<input type=\"text\" name=\"rawtextinput\" size=\"10\"/>"); }
+                // gsf icon
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_icon')) { replace_with(ui.item, gsf_icon_element); } 
+                // gsf link
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_link')) { replace_with(ui.item, gsf_link_element); } 
+                // gsf choose
+                if (ui.item.hasClass("ui-draggable") && ui.item.hasClass('draggable_gsf_choose')) { replace_with(ui.item, gsf_choose_element); } 
+            }
+    });
+}
+
+function bind_block_mouseover()
+{
+    //console.log('function bind_block_mouseover()');
+    $(".block").mouseover(function()
+    {
+        $(this).parents().css("border", "");
+        $(this).css("border", "2px solid blue");
+        return false;
+    }).mouseout(function(){
+        $(this).css("border", "");
+        return false;
+    });
+}
+
+function bind_minmax_remove()
+{
+    console.log('function bind_minmax_remove()');
+    $('a.minmax').bind('click', toggleContent);
+    $('a.remove').bind('click', removeContent);
+};
+
+var removeContent = (function () {
+    //console.log('var removeContent = (function ()');
+        // this -> a -> td -> tr -> tbody -> table -> div
+        //$(this).parent().parent().parent().parent().parent().remove();
+        $(this).closest(".block").remove();
+    });
+
+
+var toggleContent = function(e)
+{
+    console.log('parent: ' + $(this).html());
+    if ($(this).html() == '[+]'){ //targetContent.css('display') == 'none') {
+        $(this).closest(".block").children(".table, .block").slideDown(300);
+        $(this).html('[-]');
+        $(this).removeClass("ui-icon-plusthick");
+        $(this).addClass("ui-icon-minusthick");
+    } else {
+        $(this).closest(".block").children(".table, .block").slideUp(300);
+        $(this).html('[+]');
+        $(this).removeClass("ui-icon-minusthick");
+        $(this).addClass("ui-icon-plusthick");
+    }
+    return false;
+};
+
+function serialize(s)
+{
+    serial = $.SortSerialize(s);
+    alert(serial.hash);
+};
+
+function equalHeights(item, height) {
+    //console.log('function equalHeights(item, height)');
+    (item.parents('.table')).each(function(index) {
+        $(this).children().children().children().each(function() {
+            $(this).height(height);
+            $(this).children().height(height);
+        });
+    });
+};
+
Index: /main/trunk/greenstone3/web/interfaces/default/js/innerxhtml.js
===================================================================
--- /main/trunk/greenstone3/web/interfaces/default/js/innerxhtml.js	(revision 27714)
+++ /main/trunk/greenstone3/web/interfaces/default/js/innerxhtml.js	(revision 27714)
@@ -0,0 +1,162 @@
+/*
+Written by Steve Tucker, 2006, http://www.stevetucker.co.uk
+Full documentation can be found at http://www.stevetucker.co.uk/page-innerxhtml.php
+Released under the Creative Commons Attribution-Share Alike 3.0  License, http://creativecommons.org/licenses/by-sa/3.0/
+
+Change Log
+----------
+15/10/2006  v0.3    innerXHTML official release.
+21/03/2007  v0.4    1. Third argument $appendage added (Steve Tucker & Stef Dawson, www.stefdawson.com)
+            2. $source argument accepts string ID (Stef Dawson)
+            3. IE6 'on' functions work (Stef Dawson & Steve Tucker)
+*/
+innerXHTML = function($source,$string,$appendage) {
+    // (v0.4) Written 2006 by Steve Tucker, http://www.stevetucker.co.uk
+    if (typeof($source) == 'string') $source = document.getElementById($source);
+    if (!($source.nodeType == 1)) return false;
+    var $children = $source.childNodes;
+    var $xhtml = '';
+    if (!$string) {
+        for (var $i=0; $i<$children.length; $i++) {
+            if ($children[$i].nodeType == 3) {
+                var $text_content = $children[$i].nodeValue;
+                $text_content = $text_content.replace(/</g,'&lt;');
+                $text_content = $text_content.replace(/>/g,'&gt;');
+                $xhtml += $text_content;
+            }
+            else if ($children[$i].nodeType == 8) {
+                $xhtml += '<!--'+$children[$i].nodeValue+'-->';
+            }
+            else {
+                $xhtml += '<'+$children[$i].nodeName.toLowerCase();
+                var $attributes = $children[$i].attributes;
+                for (var $j=0; $j<$attributes.length; $j++) {
+                    var $attName = $attributes[$j].nodeName.toLowerCase();
+                    var $attValue = $attributes[$j].nodeValue;
+                    if ($attName == 'style' && $children[$i].style.cssText) {
+                        $xhtml += ' style="'+$children[$i].style.cssText.toLowerCase()+'"';
+                    }
+                    else if ($attValue && $attName != 'contenteditable') {
+                        $xhtml += ' '+$attName+'="'+$attValue+'"';
+                    }
+                }
+                $xhtml += '>'+innerXHTML($children[$i]);
+                $xhtml += '</'+$children[$i].nodeName.toLowerCase()+'>';
+            }
+        }
+    }
+    else {
+        if (!$appendage) {
+            while ($children.length>0) {
+                $source.removeChild($children[0]);
+            }
+            $appendage = false;
+        }
+        $xhtml = $string;
+        while ($string) {
+            var $returned = translateXHTML($string);
+            var $elements = $returned[0];
+            $string = $returned[1];
+            if ($elements) {
+                if (typeof($appendage) == 'string') $appendage = document.getElementById($appendage);
+                if (!($appendage.nodeType == 1)) $source.appendChild($elements);
+                else $source.insertBefore($elements,$appendage);
+            }
+        }
+    }
+    return $xhtml;
+}
+function translateXHTML($string) {
+    var $match = /^<\/[a-z0-9]{1,}>/i.test($string);
+    if ($match) {
+        var $return = Array;
+        $return[0] = false;
+        $return[1] = $string.replace(/^<\/[a-z0-9]{1,}>/i,'');
+        return $return;
+    }
+    $match = /^<[a-z]{1,}/i.test($string);
+    if ($match) {
+        $string = $string.replace(/^</,'');
+        var $element = $string.match(/[a-z0-9]{1,}/i);
+        if ($element) {
+            var $new_element = document.createElement($element[0]);
+            $string = $string.replace(/[a-z0-9]{1,}/i,'');
+            var $attribute = true;
+            while ($attribute) {
+                $string = $string.replace(/^\s{1,}/,'');
+                $attribute = $string.match(/^[a-z1-9_-]{1,}="[^"]{0,}"/i);
+                if ($attribute) {
+                    $attribute = $attribute[0];
+                    $string = $string.replace(/^[a-z1-9_-]{1,}="[^"]{0,}"/i,'');
+                    var $attName = $attribute.match(/^[a-z1-9_-]{1,}/i);
+                    $attribute = $attribute.replace(/^[a-z1-9_-]{1,}="/i,'');
+                    $attribute = $attribute.replace(/;{0,1}"$/,'');
+                    if ($attribute) {
+                        var $attValue = $attribute;
+                        if ($attName == 'value') $new_element.value = $attValue;
+                        else if ($attName == 'class') $new_element.className = $attValue;
+                        else if ($attName == 'style') {
+                            var $style = $attValue.split(';');
+                            for (var $i=0; $i<$style.length; $i++) {
+                                var $this_style = $style[$i].split(':');
+                                $this_style[0] = $this_style[0].toLowerCase().replace(/(^\s{0,})|(\s{0,1}$)/,'');
+                                $this_style[1] = $this_style[1].toLowerCase().replace(/(^\s{0,})|(\s{0,1}$)/,'');
+                                if (/-{1,}/g.test($this_style[0])) {
+                                    var $this_style_words = $this_style[0].split(/-/g);
+                                    $this_style[0] = '';
+                                    for (var $j=0; $j<$this_style_words.length; $j++) {
+                                        if ($j==0) {
+                                            $this_style[0] = $this_style_words[0];
+                                            continue;
+                                        }
+                                        var $first_letter = $this_style_words[$j].toUpperCase().match(/^[a-z]{1,1}/i);
+                                        $this_style[0] += $first_letter+$this_style_words[$j].replace(/^[a-z]{1,1}/,'');
+                                    }
+                                }
+                                $new_element.style[$this_style[0]] = $this_style[1];
+                            }
+                        }
+                        else if (/^on/.test($attName)) $new_element[$attName] = function() { eval($attValue) };
+                        else $new_element.setAttribute($attName,$attValue);
+                    }
+                    else $attribute = true;
+                }
+            }
+            $match = /^>/.test($string);
+            if ($match) {
+                $string = $string.replace(/^>/,'');
+                var $child = true;
+                while ($child) {
+                    var $returned = translateXHTML($string,false);
+                    $child = $returned[0];
+                    if ($child) $new_element.appendChild($child);
+                    $string = $returned[1];
+                }
+            }
+            $string = $string.replace(/^\/>/,'');
+        }
+    }
+    $match = /^[^<>]{1,}/i.test($string);
+    if ($match && !$new_element) {
+        var $text_content = $string.match(/^[^<>]{1,}/i)[0];
+        $text_content = $text_content.replace(/&lt;/g,'<');
+        $text_content = $text_content.replace(/&gt;/g,'>');
+        var $new_element = document.createTextNode($text_content);
+        $string = $string.replace(/^[^<>]{1,}/i,'');
+    }
+    $match = /^<!--[^<>]{1,}-->/i.test($string);
+    if ($match && !$new_element) {
+        if (document.createComment) {
+            $string = $string.replace(/^<!--/i,'');
+            var $text_content = $string.match(/^[^<>]{0,}-->{1,}/i);
+            $text_content = $text_content[0].replace(/-->{1,1}$/,'');           
+            var $new_element = document.createComment($text_content);
+            $string = $string.replace(/^[^<>]{1,}-->/i,'');
+        }
+        else $string = $string.replace(/^<!--[^<>]{1,}-->/i,'');
+    }
+    var $return = Array;
+    $return[0] = $new_element;
+    $return[1] = $string;
+    return $return;
+}
Index: /main/trunk/greenstone3/web/interfaces/default/js/jquery.selectboxes.js
===================================================================
--- /main/trunk/greenstone3/web/interfaces/default/js/jquery.selectboxes.js	(revision 27714)
+++ /main/trunk/greenstone3/web/interfaces/default/js/jquery.selectboxes.js	(revision 27714)
@@ -0,0 +1,526 @@
+/*
+ *
+ * Copyright (c) 2006-2009 Sam Collett (http://www.texotela.co.uk)
+ * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
+ * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
+ *
+ * Version 2.2.4
+ * Demo: http://www.texotela.co.uk/code/jquery/select/
+ *
+ * $LastChangedDate: 2009-02-08 00:28:12 +0000 (Sun, 08 Feb 2009) $
+ * $Rev: 6185 $
+ *
+ */
+ 
+;(function($) {
+ 
+/**
+ * Adds (single/multiple) options to a select box (or series of select boxes)
+ *
+ * @name     addOption
+ * @author   Sam Collett (http://www.texotela.co.uk)
+ * @type     jQuery
+ * @example  $("#myselect").addOption("Value", "Text"); // add single value (will be selected)
+ * @example  $("#myselect").addOption("Value 2", "Text 2", false); // add single value (won't be selected)
+ * @example  $("#myselect").addOption({"foo":"bar","bar":"baz"}, false); // add multiple values, but don't select
+ *
+ */
+$.fn.addOption = function()
+{
+	var add = function(el, v, t, sO)
+	{
+		var option = document.createElement("option");
+		option.value = v, option.text = t;
+		// get options
+		var o = el.options;
+		// get number of options
+		var oL = o.length;
+		if(!el.cache)
+		{
+			el.cache = {};
+			// loop through existing options, adding to cache
+			for(var i = 0; i < oL; i++)
+			{
+				el.cache[o[i].value] = i;
+			}
+		}
+		// add to cache if it isn't already
+		if(typeof el.cache[v] == "undefined") el.cache[v] = oL;
+		el.options[el.cache[v]] = option;
+		if(sO)
+		{
+			option.selected = true;
+		}
+	};
+	
+	var a = arguments;
+	if(a.length == 0) return this;
+	// select option when added? default is true
+	var sO = true;
+	// multiple items
+	var m = false;
+	// other variables
+	var items, v, t;
+	if(typeof(a[0]) == "object")
+	{
+		m = true;
+		items = a[0];
+	}
+	if(a.length >= 2)
+	{
+		if(typeof(a[1]) == "boolean") sO = a[1];
+		else if(typeof(a[2]) == "boolean") sO = a[2];
+		if(!m)
+		{
+			v = a[0];
+			t = a[1];
+		}
+	}
+	this.each(
+		function()
+		{
+			if(this.nodeName.toLowerCase() != "select") return;
+			if(m)
+			{
+				for(var item in items)
+				{
+					add(this, item, items[item], sO);
+				}
+			}
+			else
+			{
+				add(this, v, t, sO);
+			}
+		}
+	);
+	return this;
+};
+
+/**
+ * Add options via ajax
+ *
+ * @name     ajaxAddOption
+ * @author   Sam Collett (http://www.texotela.co.uk)
+ * @type     jQuery
+ * @param    String url      Page to get options from (must be valid JSON)
+ * @param    Object params   (optional) Any parameters to send with the request
+ * @param    Boolean select  (optional) Select the added options, default true
+ * @param    Function fn     (optional) Call this function with the select object as param after completion
+ * @param    Array args      (optional) Array with params to pass to the function afterwards
+ * @example  $("#myselect").ajaxAddOption("myoptions.php");
+ * @example  $("#myselect").ajaxAddOption("myoptions.php", {"code" : "007"});
+ * @example  $("#myselect").ajaxAddOption("myoptions.php", {"code" : "007"}, false, sortoptions, [{"dir": "desc"}]);
+ *
+ */
+$.fn.ajaxAddOption = function(url, params, select, fn, args)
+{
+	if(typeof(url) != "string") return this;
+	if(typeof(params) != "object") params = {};
+	if(typeof(select) != "boolean") select = true;
+	this.each(
+		function()
+		{
+			var el = this;
+			$.getJSON(url,
+				params,
+				function(r)
+				{
+					$(el).addOption(r, select);
+					if(typeof fn == "function")
+					{
+						if(typeof args == "object")
+						{
+							fn.apply(el, args);
+						} 
+						else
+						{
+							fn.call(el);
+						}
+					}
+				}
+			);
+		}
+	);
+	return this;
+};
+
+/**
+ * Removes an option (by value or index) from a select box (or series of select boxes)
+ *
+ * @name     removeOption
+ * @author   Sam Collett (http://www.texotela.co.uk)
+ * @type     jQuery
+ * @param    String|RegExp|Number what  Option to remove
+ * @param    Boolean selectedOnly       (optional) Remove only if it has been selected (default false)   
+ * @example  $("#myselect").removeOption("Value"); // remove by value
+ * @example  $("#myselect").removeOption(/^val/i); // remove options with a value starting with 'val'
+ * @example  $("#myselect").removeOption(/./); // remove all options
+ * @example  $("#myselect").removeOption(/./, true); // remove all options that have been selected
+ * @example  $("#myselect").removeOption(0); // remove by index
+ * @example  $("#myselect").removeOption(["myselect_1","myselect_2"]); // values contained in passed array
+ *
+ */
+$.fn.removeOption = function()
+{
+	var a = arguments;
+	if(a.length == 0) return this;
+	var ta = typeof(a[0]);
+	var v, index;
+	// has to be a string or regular expression (object in IE, function in Firefox)
+	if(ta == "string" || ta == "object" || ta == "function" )
+	{
+		v = a[0];
+		// if an array, remove items
+		if(v.constructor == Array)
+		{
+			var l = v.length;
+			for(var i = 0; i<l; i++)
+			{
+				this.removeOption(v[i], a[1]); 
+			}
+			return this;
+		}
+	}
+	else if(ta == "number") index = a[0];
+	else return this;
+	this.each(
+		function()
+		{
+			if(this.nodeName.toLowerCase() != "select") return;
+			// clear cache
+			if(this.cache) this.cache = null;
+			// does the option need to be removed?
+			var remove = false;
+			// get options
+			var o = this.options;
+			if(!!v)
+			{
+				// get number of options
+				var oL = o.length;
+				for(var i=oL-1; i>=0; i--)
+				{
+					if(v.constructor == RegExp)
+					{
+						if(o[i].value.match(v))
+						{
+							remove = true;
+						}
+					}
+					else if(o[i].value == v)
+					{
+						remove = true;
+					}
+					// if the option is only to be removed if selected
+					if(remove && a[1] === true) remove = o[i].selected;
+					if(remove)
+					{
+						o[i] = null;
+					}
+					remove = false;
+				}
+			}
+			else
+			{
+				// only remove if selected?
+				if(a[1] === true)
+				{
+					remove = o[index].selected;
+				}
+				else
+				{
+					remove = true;
+				}
+				if(remove)
+				{
+					this.remove(index);
+				}
+			}
+		}
+	);
+	return this;
+};
+
+/**
+ * Sort options (ascending or descending) in a select box (or series of select boxes)
+ *
+ * @name     sortOptions
+ * @author   Sam Collett (http://www.texotela.co.uk)
+ * @type     jQuery
+ * @param    Boolean ascending   (optional) Sort ascending (true/undefined), or descending (false)
+ * @example  // ascending
+ * $("#myselect").sortOptions(); // or $("#myselect").sortOptions(true);
+ * @example  // descending
+ * $("#myselect").sortOptions(false);
+ *
+ */
+$.fn.sortOptions = function(ascending)
+{
+	// get selected values first
+	var sel = $(this).selectedValues();
+	var a = typeof(ascending) == "undefined" ? true : !!ascending;
+	this.each(
+		function()
+		{
+			if(this.nodeName.toLowerCase() != "select") return;
+			// get options
+			var o = this.options;
+			// get number of options
+			var oL = o.length;
+			// create an array for sorting
+			var sA = [];
+			// loop through options, adding to sort array
+			for(var i = 0; i<oL; i++)
+			{
+				sA[i] = {
+					v: o[i].value,
+					t: o[i].text
+				}
+			}
+			// sort items in array
+			sA.sort(
+				function(o1, o2)
+				{
+					// option text is made lowercase for case insensitive sorting
+					o1t = o1.t.toLowerCase(), o2t = o2.t.toLowerCase();
+					// if options are the same, no sorting is needed
+					if(o1t == o2t) return 0;
+					if(a)
+					{
+						return o1t < o2t ? -1 : 1;
+					}
+					else
+					{
+						return o1t > o2t ? -1 : 1;
+					}
+				}
+			);
+			// change the options to match the sort array
+			for(var i = 0; i<oL; i++)
+			{
+				o[i].text = sA[i].t;
+				o[i].value = sA[i].v;
+			}
+		}
+	).selectOptions(sel, true); // select values, clearing existing ones
+	return this;
+};
+/**
+ * Selects an option by value
+ *
+ * @name     selectOptions
+ * @author   Mathias Bank (http://www.mathias-bank.de), original function
+ * @author   Sam Collett (http://www.texotela.co.uk), addition of regular expression matching
+ * @type     jQuery
+ * @param    String|RegExp|Array value  Which options should be selected
+ * can be a string or regular expression, or an array of strings / regular expressions
+ * @param    Boolean clear  Clear existing selected options, default false
+ * @example  $("#myselect").selectOptions("val1"); // with the value 'val1'
+ * @example  $("#myselect").selectOptions(["val1","val2","val3"]); // with the values 'val1' 'val2' 'val3'
+ * @example  $("#myselect").selectOptions(/^val/i); // with the value starting with 'val', case insensitive
+ *
+ */
+$.fn.selectOptions = function(value, clear)
+{
+	var v = value;
+	var vT = typeof(value);
+	// handle arrays
+	if(vT == "object" && v.constructor == Array)
+	{
+		var $this = this;
+		$.each(v, function()
+			{
+      				$this.selectOptions(this, clear);
+    			}
+		);
+	};
+	var c = clear || false;
+	// has to be a string or regular expression (object in IE, function in Firefox)
+	if(vT != "string" && vT != "function" && vT != "object") return this;
+	this.each(
+		function()
+		{
+			if(this.nodeName.toLowerCase() != "select") return this;
+			// get options
+			var o = this.options;
+			// get number of options
+			var oL = o.length;
+			for(var i = 0; i<oL; i++)
+			{
+				if(v.constructor == RegExp)
+				{
+					if(o[i].value.match(v))
+					{
+						o[i].selected = true;
+					}
+					else if(c)
+					{
+						o[i].selected = false;
+					}
+				}
+				else
+				{
+					if(o[i].value == v)
+					{
+						o[i].selected = true;
+					}
+					else if(c)
+					{
+						o[i].selected = false;
+					}
+				}
+			}
+		}
+	);
+	return this;
+};
+
+/**
+ * Copy options to another select
+ *
+ * @name     copyOptions
+ * @author   Sam Collett (http://www.texotela.co.uk)
+ * @type     jQuery
+ * @param    String to  Element to copy to
+ * @param    String which  (optional) Specifies which options should be copied - 'all' or 'selected'. Default is 'selected'
+ * @example  $("#myselect").copyOptions("#myselect2"); // copy selected options from 'myselect' to 'myselect2'
+ * @example  $("#myselect").copyOptions("#myselect2","selected"); // same as above
+ * @example  $("#myselect").copyOptions("#myselect2","all"); // copy all options from 'myselect' to 'myselect2'
+ *
+ */
+$.fn.copyOptions = function(to, which)
+{
+	var w = which || "selected";
+	if($(to).size() == 0) return this;
+	this.each(
+		function()
+		{
+			if(this.nodeName.toLowerCase() != "select") return this;
+			// get options
+			var o = this.options;
+			// get number of options
+			var oL = o.length;
+			for(var i = 0; i<oL; i++)
+			{
+				if(w == "all" || (w == "selected" && o[i].selected))
+				{
+					$(to).addOption(o[i].value, o[i].text);
+				}
+			}
+		}
+	);
+	return this;
+};
+
+/**
+ * Checks if a select box has an option with the supplied value
+ *
+ * @name     containsOption
+ * @author   Sam Collett (http://www.texotela.co.uk)
+ * @type     Boolean|jQuery
+ * @param    String|RegExp value  Which value to check for. Can be a string or regular expression
+ * @param    Function fn          (optional) Function to apply if an option with the given value is found.
+ * Use this if you don't want to break the chaining
+ * @example  if($("#myselect").containsOption("val1")) alert("Has an option with the value 'val1'");
+ * @example  if($("#myselect").containsOption(/^val/i)) alert("Has an option with the value starting with 'val'");
+ * @example  $("#myselect").containsOption("val1", copyoption).doSomethingElseWithSelect(); // calls copyoption (user defined function) for any options found, chain is continued
+ *
+ */
+$.fn.containsOption = function(value, fn)
+{
+	var found = false;
+	var v = value;
+	var vT = typeof(v);
+	var fT = typeof(fn);
+	// has to be a string or regular expression (object in IE, function in Firefox)
+	if(vT != "string" && vT != "function" && vT != "object") return fT == "function" ? this: found;
+	this.each(
+		function()
+		{
+			if(this.nodeName.toLowerCase() != "select") return this;
+			// option already found
+			if(found && fT != "function") return false;
+			// get options
+			var o = this.options;
+			// get number of options
+			var oL = o.length;
+			for(var i = 0; i<oL; i++)
+			{
+				if(v.constructor == RegExp)
+				{
+					if (o[i].value.match(v))
+					{
+						found = true;
+						if(fT == "function") fn.call(o[i], i);
+					}
+				}
+				else
+				{
+					if (o[i].value == v)
+					{
+						found = true;
+						if(fT == "function") fn.call(o[i], i);
+					}
+				}
+			}
+		}
+	);
+	return fT == "function" ? this : found;
+};
+
+/**
+ * Returns values which have been selected
+ *
+ * @name     selectedValues
+ * @author   Sam Collett (http://www.texotela.co.uk)
+ * @type     Array
+ * @example  $("#myselect").selectedValues();
+ *
+ */
+$.fn.selectedValues = function()
+{
+	var v = [];
+	this.selectedOptions().each(
+		function()
+		{
+			v[v.length] = this.value;
+		}
+	);
+	return v;
+};
+
+/**
+ * Returns text which has been selected
+ *
+ * @name     selectedTexts
+ * @author   Sam Collett (http://www.texotela.co.uk)
+ * @type     Array
+ * @example  $("#myselect").selectedTexts();
+ *
+ */
+$.fn.selectedTexts = function()
+{
+	var t = [];
+	this.selectedOptions().each(
+		function()
+		{
+			t[t.length] = this.text;
+		}
+	);
+	return t;
+};
+
+/**
+ * Returns options which have been selected
+ *
+ * @name     selectedOptions
+ * @author   Sam Collett (http://www.texotela.co.uk)
+ * @type     jQuery
+ * @example  $("#myselect").selectedOptions();
+ *
+ */
+$.fn.selectedOptions = function()
+{
+	return this.find("option:selected");
+};
+
+})(jQuery);
Index: /main/trunk/greenstone3/web/interfaces/default/js/jquery.xml.js
===================================================================
--- /main/trunk/greenstone3/web/interfaces/default/js/jquery.xml.js	(revision 27714)
+++ /main/trunk/greenstone3/web/interfaces/default/js/jquery.xml.js	(revision 27714)
@@ -0,0 +1,56 @@
+/**
+ * jQuery xml plugin
+ * Converts XML node(s) to string 
+ *
+ * Copyright (c) 2009 Radim Svoboda
+ * Dual licensed under the MIT (MIT-LICENSE.txt)
+ * and GPL (GPL-LICENSE.txt) licenses.
+ *
+ * @author 	Radim Svoboda, user Zzzzzz
+ * @version 1.0.0
+ */
+ 
+   
+/**
+ * Converts XML node(s) to string using web-browser features.
+ * Similar to .html() with HTML nodes 
+ * This method is READ-ONLY.
+ *  
+ * @param all set to TRUE (1,"all",etc.) process all elements,
+ * otherwise process content of the first matched element 
+ *  
+ * @return string obtained from XML node(s)  
+ */         
+jQuery.fn.xml = function(all) {
+      
+  //result to return
+  var s = "";
+  
+   //Anything to process ?
+   if( this.length )
+  
+    //"object" with nodes to convert to string  
+   (
+      ( ( typeof all != 'undefined' ) && all ) ?
+      //all the nodes 
+      this 
+      :
+      //content of the first matched element 
+      jQuery(this[0]).contents()
+    )
+   //convert node(s) to string  
+   .each(function(){
+    s += window.ActiveXObject ?//==  IE browser ?
+       //for IE
+	     this.xml
+	     :
+	     //for other browsers
+	     (new XMLSerializer()).serializeToString(this)
+	     ;
+  }); 
+    
+    
+  return	s;		
+  
+  };
+                     
Index: /main/trunk/greenstone3/web/interfaces/default/js/ui.nestedSortable.js
===================================================================
--- /main/trunk/greenstone3/web/interfaces/default/js/ui.nestedSortable.js	(revision 27714)
+++ /main/trunk/greenstone3/web/interfaces/default/js/ui.nestedSortable.js	(revision 27714)
@@ -0,0 +1,1210 @@
+/*
+ * based on jQuery UI Sortable 1.7.2
+ *
+ * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about) and Steven Lots (Lotsofdots bvba) 
+ * Dual licensed under the MIT (MIT-LICENSE.txt)
+ * and GPL (GPL-LICENSE.txt) licenses.
+ *
+ * http://docs.jquery.com/UI/Sortables
+ * http://www.b-hind.eu/jquery/
+ * Depends:
+ *	ui.core.js
+ */
+(function($) {
+
+$.widget("ui.sortable", $.extend({}, $.ui.mouse, {
+	_init: function() {
+
+		var o = this.options;
+		this.containerCache = {};
+		this.element.addClass("ui-sortable");
+
+		//Get the items
+		this.refresh();
+
+		//Let's determine if the items are floating
+		this.floating = this.items.length ? (/left|right/).test(this.items[0].item.css('float')) : false;
+
+		//Let's determine the parent's offset
+		this.offset = this.element.offset();
+
+		//Initialize mouse events for interaction
+		this._mouseInit();
+
+	},
+
+	destroy: function() {
+		this.element
+			.removeClass("ui-sortable ui-sortable-disabled")
+			.removeData("sortable")
+			.unbind(".sortable");
+		this._mouseDestroy();
+
+		for ( var i = this.items.length - 1; i >= 0; i-- )
+			this.items[i].item.removeData("sortable-item");
+	},
+
+	_mouseCapture: function(event, overrideHandle) {
+
+		if (this.reverting) {
+			return false;
+		}
+
+		if(this.options.disabled || this.options.type == 'static') return false;
+
+		//We have to refresh the items data once first
+		this._refreshItems(event);
+
+		//Find out if the clicked node (or one of its parents) is a actual item in this.items
+		var currentItem = null, self = this, nodes = $(event.target).parents().each(function() {
+			if($.data(this, 'sortable-item') == self) {
+				currentItem = $(this);
+				return false;
+			}
+		});
+		if($.data(event.target, 'sortable-item') == self) currentItem = $(event.target);
+
+		if(!currentItem) return false;
+		if(this.options.handle && !overrideHandle) {
+			var validHandle = false;
+
+			$(this.options.handle, currentItem).find("*").andSelf().each(function() { if(this == event.target) validHandle = true; });
+			if(!validHandle) return false;
+		}
+
+		this.currentItem = currentItem;
+		this._removeCurrentsFromItems();
+		return true;
+
+	},
+
+	_mouseStart: function(event, overrideHandle, noActivation) {
+
+		var o = this.options, self = this;
+		this.currentContainer = this;
+
+		//We only need to call refreshPositions, because the refreshItems call has been moved to mouseCapture
+		this.refreshPositions();
+
+		//Create and append the visible helper
+		this.helper = this._createHelper(event);
+
+		//Cache the helper size
+		this._cacheHelperProportions();
+
+		/*
+		 * - Position generation -
+		 * This block generates everything position related - it's the core of draggables.
+		 */
+
+		//Cache the margins of the original element
+		this._cacheMargins();
+
+		//Get the next scrolling parent
+		this.scrollParent = this.helper.scrollParent();
+
+		//The element's absolute position on the page minus margins
+		this.offset = this.currentItem.offset();
+		this.offset = {
+			top: this.offset.top - this.margins.top,
+			left: this.offset.left - this.margins.left
+		};
+
+		// Only after we got the offset, we can change the helper's position to absolute
+		// TODO: Still need to figure out a way to make relative sorting possible
+		this.helper.css("position", "absolute");
+		this.cssPosition = this.helper.css("position");
+
+		$.extend(this.offset, {
+			click: { //Where the click happened, relative to the element
+				left: event.pageX - this.offset.left,
+				top: event.pageY - this.offset.top
+			},
+			parent: this._getParentOffset(),
+			relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper
+		});
+
+		//Generate the original position
+		this.originalPosition = this._generatePosition(event);
+		this.originalPageX = event.pageX;
+		this.originalPageY = event.pageY;
+
+		//Adjust the mouse offset relative to the helper if 'cursorAt' is supplied
+		if(o.cursorAt)
+			this._adjustOffsetFromHelper(o.cursorAt);
+
+		//Cache the former DOM position
+		this.domPosition = { prev: this.currentItem.prev()[0], parent: this.currentItem.parent()[0] };
+
+		//If the helper is not the original, hide the original so it's not playing any role during the drag, won't cause anything bad this way
+		if(this.helper[0] != this.currentItem[0]) {
+			this.currentItem.hide();
+		}
+
+		//Create the placeholder
+		this._createPlaceholder();
+
+		//Set a containment if given in the options
+		if(o.containment)
+			this._setContainment();
+
+		if(o.cursor) { // cursor option
+			if ($('body').css("cursor")) this._storedCursor = $('body').css("cursor");
+			$('body').css("cursor", o.cursor);
+		}
+
+		if(o.opacity) { // opacity option
+			if (this.helper.css("opacity")) this._storedOpacity = this.helper.css("opacity");
+			this.helper.css("opacity", o.opacity);
+		}
+
+		if(o.zIndex) { // zIndex option
+			if (this.helper.css("zIndex")) this._storedZIndex = this.helper.css("zIndex");
+			this.helper.css("zIndex", o.zIndex);
+		}
+
+		//Prepare scrolling
+		if(this.scrollParent[0] != document && this.scrollParent[0].tagName != 'HTML')
+			this.overflowOffset = this.scrollParent.offset();
+
+		//Call callbacks
+		this._trigger("start", event, this._uiHash());
+
+		//Recache the helper size
+		if(!this._preserveHelperProportions)
+			this._cacheHelperProportions();
+
+
+		//Post 'activate' events to possible containers
+		if(!noActivation) {
+			 for (var i = this.containers.length - 1; i >= 0; i--) { this.containers[i]._trigger("activate", event, self._uiHash(this)); }
+		}
+
+		//Prepare possible droppables
+		if($.ui.ddmanager)
+			$.ui.ddmanager.current = this;
+
+		if ($.ui.ddmanager && !o.dropBehaviour)
+			$.ui.ddmanager.prepareOffsets(this, event);
+
+		this.dragging = true;
+
+		this.helper.addClass("ui-sortable-helper");
+		this._mouseDrag(event); //Execute the drag once - this causes the helper not to be visible before getting its correct position
+		return true;
+
+	},
+
+	_mouseDrag: function(event) {
+
+		//Compute the helpers position
+		this.position = this._generatePosition(event);
+		//console.log(this.position); //b-hind
+		this.positionAbs = this._convertPositionTo("absolute");
+
+		if (!this.lastPositionAbs) {
+			this.lastPositionAbs = this.positionAbs;
+		}
+
+		//Do scrolling
+		if(this.options.scroll) {
+			var o = this.options, scrolled = false;
+			if(this.scrollParent[0] != document && this.scrollParent[0].tagName != 'HTML') {
+
+				if((this.overflowOffset.top + this.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity)
+					this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop + o.scrollSpeed;
+				else if(event.pageY - this.overflowOffset.top < o.scrollSensitivity)
+					this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop - o.scrollSpeed;
+
+				if((this.overflowOffset.left + this.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity)
+					this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft + o.scrollSpeed;
+				else if(event.pageX - this.overflowOffset.left < o.scrollSensitivity)
+					this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft - o.scrollSpeed;
+
+			} else {
+
+				if(event.pageY - $(document).scrollTop() < o.scrollSensitivity)
+					scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed);
+				else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity)
+					scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed);
+
+				if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity)
+					scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed);
+				else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity)
+					scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed);
+
+			}
+			
+			if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour)
+				$.ui.ddmanager.prepareOffsets(this, event);
+		}
+
+		//Regenerate the absolute position used for position checks
+		this.positionAbs = this._convertPositionTo("absolute");
+		
+		//Set the helper position
+		if(!this.options.axis || this.options.axis != "y") this.helper[0].style.left = this.position.left+'px';
+		if(!this.options.axis || this.options.axis != "x") this.helper[0].style.top = this.position.top+'px';
+
+		//Rearrange
+		
+		for (var i = this.items.length - 1; i >= 0; i--) {
+			
+			//Cache variables and intersection, continue if no intersection
+			var item = this.items[i], itemElement = item.item[0], intersection = this._intersectsWithPointer(item);
+			if (!intersection) continue;
+			if(itemElement != this.currentItem[0] //cannot intersect with itself
+				&&	this.placeholder[intersection == 1 ? "next" : "prev"]()[0] != itemElement //no useless actions that have been done before
+				&&	!$.ui.contains(this.placeholder[0], itemElement) //no action if the item moved is the parent of the item checked
+				&& (this.options.type == 'semi-dynamic' ? !$.ui.contains(this.element[0], itemElement) : true)
+			) {
+				
+				this.direction = intersection == 1 ? "down" : "up";
+				//b-hind : here we must also check 
+				
+				//var level = this._getLevel(item.item);
+				//console.log($.ui.isOverAxis(this.positionAbs.left, item.left, item.width));
+				//var haschildNode = this._hasChildNodes(item.item);
+				//console.log("haschildNode : "+haschildNode);
+				//moved to _rearrange
+				
+				
+				if (this.options.tolerance == "pointer" || this._intersectsWithSides(item)) {
+					this._rearrange(event, item);
+				} else {
+					break;
+				}
+
+				this._trigger("change", event, this._uiHash());
+				break;
+			}
+		}
+
+		//Post events to containers
+		this._contactContainers(event);
+
+		//Interconnect with droppables
+		if($.ui.ddmanager) $.ui.ddmanager.drag(this, event);
+
+		//Call callbacks
+		this._trigger('sort', event, this._uiHash());
+
+		this.lastPositionAbs = this.positionAbs;
+		return false;
+
+	},
+
+	_mouseStop: function(event, noPropagation) {
+
+		if(!event) return;
+
+		//If we are using droppables, inform the manager about the drop
+		if ($.ui.ddmanager && !this.options.dropBehaviour)
+			$.ui.ddmanager.drop(this, event);
+
+		if(this.options.revert) {
+			var self = this;
+			var cur = self.placeholder.offset();
+
+			self.reverting = true;
+
+			$(this.helper).animate({
+				left: cur.left - this.offset.parent.left - self.margins.left + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollLeft),
+				top: cur.top - this.offset.parent.top - self.margins.top + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollTop)
+			}, parseInt(this.options.revert, 10) || 500, function() {
+				self._clear(event);
+			});
+		} else {
+			this._clear(event, noPropagation);
+		}
+
+		return false;
+
+	},
+
+	cancel: function() {
+
+		var self = this;
+
+		if(this.dragging) {
+
+			this._mouseUp();
+
+			if(this.options.helper == "original")
+				this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper");
+			else
+				this.currentItem.show();
+
+			//Post deactivating events to containers
+			for (var i = this.containers.length - 1; i >= 0; i--){
+				this.containers[i]._trigger("deactivate", null, self._uiHash(this));
+				if(this.containers[i].containerCache.over) {
+					this.containers[i]._trigger("out", null, self._uiHash(this));
+					this.containers[i].containerCache.over = 0;
+				}
+			}
+
+		}
+
+		//$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node!
+		if(this.placeholder[0].parentNode) this.placeholder[0].parentNode.removeChild(this.placeholder[0]);
+		if(this.options.helper != "original" && this.helper && this.helper[0].parentNode) this.helper.remove();
+
+		$.extend(this, {
+			helper: null,
+			dragging: false,
+			reverting: false,
+			_noFinalSort: null
+		});
+
+		if(this.domPosition.prev) {
+			$(this.domPosition.prev).after(this.currentItem);
+		} else {
+			$(this.domPosition.parent).prepend(this.currentItem);
+		}
+
+		return true;
+
+	},
+
+	serialize: function(o) {
+
+		var items = this._getItemsAsjQuery(o && o.connected);
+		var str = []; o = o || {};
+		if(this.options.nested){
+			var level = 0;
+			var levels = [];
+			var key = 0;
+			for(var i=0;i<items.length;i++){
+				var itemlevel = this._getLevel($(items[i]));
+				if(level== itemlevel){
+					var res = ($(o.item || items[i]).attr(o.attribute || 'id') || '').match(o.expression || (/(.+)[-=_](.+)/));
+					if(res) str.push((o.key || res[1]+(itemlevel==1?"":"_"+levels[levels.length-1])+'[]')+'='+(o.key && o.expression ? res[1] : res[2]));
+					if(res) key = res[2];
+				}else if(itemlevel > level){
+					level = itemlevel;
+					var res = ($(o.item || items[i]).attr(o.attribute || 'id') || '').match(o.expression || (/(.+)[-=_](.+)/));
+					if(res) levels[levels.length] =  key;
+					if(res) str.push((o.key || res[1]+(itemlevel==1?"":"_"+levels[levels.length-1])+'[]')+'='+(o.key && o.expression ? res[1] : res[2]));
+					if(res) key = res[2];
+				}else{
+					
+					do{
+						levels.pop();
+						key = levels[levels.length-1];
+						level--;
+					
+					}while(level > itemlevel);
+					var res = ($(o.item || items[i]).attr(o.attribute || 'id') || '').match(o.expression || (/(.+)[-=_](.+)/));
+					if(res) str.push((o.key || res[1]+(itemlevel==1?"":"_"+key)+'[]')+'='+(o.key && o.expression ? res[1] : res[2]));
+					if(res) key = res[2];
+				}
+				
+			}
+		}else{
+			$(items).each(function() {
+				var res = ($(o.item || this).attr(o.attribute || 'id') || '').match(o.expression || (/(.+)[-=_](.+)/));
+				if(res) str.push((o.key || res[1]+'[]')+'='+(o.key && o.expression ? res[1] : res[2]));
+			});
+		}
+		
+		return str.join('&');
+
+	},
+
+	toArray: function(o) {
+
+		var items = this._getItemsAsjQuery(o && o.connected);
+		var ret = []; o = o || {};
+		var self = this;
+		//add first item is always level 1
+		
+		
+		if(this.options.nested){
+	
+			var level = 1;
+			var currentAr = ret;
+			var levels = [];
+			
+			for(var i=0;i<items.length;i++){
+				var item = items[i];
+				var itemlevel = this._getLevel($(item));
+				
+				if(itemlevel == level){
+					currentAr.push([$(o.item || item).attr(o.attribute || 'id') || '',[]]);
+					
+				}else if(itemlevel > level){
+					
+					level = itemlevel;
+					levels[levels.length] = currentAr;
+					// get last element
+					currentAr = currentAr[currentAr.length-1][1];
+					currentAr.push([$(o.item || item).attr(o.attribute || 'id') || '',[]]);
+				}else{
+					
+					do{
+						currentAr = levels[levels.length-1];
+						levels.pop();
+						level--;
+					}while(level > itemlevel);
+					
+					currentAr.push([$(o.item || item).attr(o.attribute || 'id') || '',[]]);
+				}
+			}
+		
+
+		}else{
+				items.each(function() { ret.push($(o.item || this).attr(o.attribute || 'id') || ''); });
+		}
+
+	
+		return ret;
+
+	},
+
+	/* Be careful with the following core functions */
+	_intersectsWith: function(item) {
+
+		var x1 = this.positionAbs.left,
+			x2 = x1 + this.helperProportions.width,
+			y1 = this.positionAbs.top,
+			y2 = y1 + this.helperProportions.height;
+
+		var l = item.left,
+			r = l + item.width,
+			t = item.top,
+			b = t + item.height;
+
+		var dyClick = this.offset.click.top,
+			dxClick = this.offset.click.left;
+
+		var isOverElement = (y1 + dyClick) > t && (y1 + dyClick) < b && (x1 + dxClick) > l && (x1 + dxClick) < r;
+
+		if(	   this.options.tolerance == "pointer"
+			|| this.options.forcePointerForContainers
+			|| (this.options.tolerance != "pointer" && this.helperProportions[this.floating ? 'width' : 'height'] > item[this.floating ? 'width' : 'height'])
+		) {
+			return isOverElement;
+		} else {
+
+			return (l < x1 + (this.helperProportions.width / 2) // Right Half
+				&& x2 - (this.helperProportions.width / 2) < r // Left Half
+				&& t < y1 + (this.helperProportions.height / 2) // Bottom Half
+				&& y2 - (this.helperProportions.height / 2) < b ); // Top Half
+
+		}
+	},
+	/* check of the pointer  is over an other element  (while dragging) */
+	_intersectsWithPointer: function(item) {
+
+		var isOverElementHeight = $.ui.isOverAxis(this.positionAbs.top + this.offset.click.top, item.top, item.height),
+			isOverElementWidth = $.ui.isOverAxis(this.positionAbs.left + this.offset.click.left, item.left, item.width),
+			isOverElement = isOverElementHeight && isOverElementWidth,
+			verticalDirection = this._getDragVerticalDirection(),
+			horizontalDirection = this._getDragHorizontalDirection();
+
+		if (!isOverElement)
+			return false;
+
+		return this.floating ?
+			( ((horizontalDirection && horizontalDirection == "right") || verticalDirection == "down") ? 2 : 1 )
+			: ( verticalDirection && (verticalDirection == "down" ? 2 : 1) );
+
+	},
+	/* check of the dragged element is over an other element */
+	_intersectsWithSides: function(item) {
+
+		var isOverBottomHalf = $.ui.isOverAxis(this.positionAbs.top + this.offset.click.top, item.top + (item.height/2), item.height),
+			isOverRightHalf = $.ui.isOverAxis(this.positionAbs.left + this.offset.click.left, item.left + (item.width/2), item.width),
+			verticalDirection = this._getDragVerticalDirection(),
+			horizontalDirection = this._getDragHorizontalDirection();
+
+		if (this.floating && horizontalDirection) {
+			return ((horizontalDirection == "right" && isOverRightHalf) || (horizontalDirection == "left" && !isOverRightHalf));
+		} else {
+			return verticalDirection && ((verticalDirection == "down" && isOverBottomHalf) || (verticalDirection == "up" && !isOverBottomHalf));
+		}
+
+	},
+
+	_getDragVerticalDirection: function() {
+		var delta = this.positionAbs.top - this.lastPositionAbs.top;
+		return delta != 0 && (delta > 0 ? "down" : "up");
+	},
+
+	_getDragHorizontalDirection: function() {
+		var delta = this.positionAbs.left - this.lastPositionAbs.left;
+		return delta != 0 && (delta > 0 ? "right" : "left");
+	},
+
+	refresh: function(event) {
+		this._refreshItems(event);
+		this.refreshPositions();
+	},
+
+	_connectWith: function() {
+		var options = this.options;
+		return options.connectWith.constructor == String
+			? [options.connectWith]
+			: options.connectWith;
+	},
+	
+	_getItemsAsjQuery: function(connected) {
+
+		var self = this;
+		var items = [];
+		var queries = [];
+		var connectWith = this._connectWith();
+
+		if(connectWith && connected) {
+			for (var i = connectWith.length - 1; i >= 0; i--){
+				var cur = $(connectWith[i]);
+				for (var j = cur.length - 1; j >= 0; j--){
+					var inst = $.data(cur[j], 'sortable');
+					if(inst && inst != this && !inst.options.disabled) {
+						queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element) : $(inst.options.items, inst.element).not(".ui-sortable-helper"), inst]);
+					}
+				};
+			};
+		}
+
+		queries.push([$.isFunction(this.options.items) ? this.options.items.call(this.element, null, { options: this.options, item: this.currentItem }) : $(this.options.items, this.element).not(".ui-sortable-helper"), this]);
+
+		for (var i = queries.length - 1; i >= 0; i--){
+			queries[i][0].each(function() {
+				items.push(this);
+			});
+		};
+		
+
+		return $(items);
+
+	},
+
+	_removeCurrentsFromItems: function() {
+
+		var list = this.currentItem.find(":data(sortable-item)");
+
+		for (var i=0; i < this.items.length; i++) {
+
+			for (var j=0; j < list.length; j++) {
+				if(list[j] == this.items[i].item[0])
+					this.items.splice(i,1);
+			};
+
+		};
+
+	},
+
+	_refreshItems: function(event) {
+
+		this.items = [];
+		this.containers = [this];
+		var items = this.items;
+		var self = this;
+		var queries = [[$.isFunction(this.options.items) ? this.options.items.call(this.element[0], event, { item: this.currentItem }) : $(this.options.items, this.element), this]];
+		var connectWith = this._connectWith();
+
+		if(connectWith) {
+			for (var i = connectWith.length - 1; i >= 0; i--){
+				var cur = $(connectWith[i]);
+				for (var j = cur.length - 1; j >= 0; j--){
+					var inst = $.data(cur[j], 'sortable');
+					if(inst && inst != this && !inst.options.disabled) {
+						queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element[0], event, { item: this.currentItem }) : $(inst.options.items, inst.element), inst]);
+						this.containers.push(inst);
+					}
+				};
+			};
+		}
+
+		for (var i = queries.length - 1; i >= 0; i--) {
+			var targetData = queries[i][1];
+			var _queries = queries[i][0];
+
+			for (var j=0, queriesLength = _queries.length; j < queriesLength; j++) {
+				var item = $(_queries[j]);
+
+				item.data('sortable-item', targetData); // Data for target checking (mouse manager)
+
+				items.push({
+					item: item,
+					instance: targetData,
+					width: 0, height: 0,
+					left: 0, top: 0
+				});
+			};
+		};
+
+	},
+
+	refreshPositions: function(fast) {
+
+		//This has to be redone because due to the item being moved out/into the offsetParent, the offsetParent's position will change
+		if(this.offsetParent && this.helper) {
+			this.offset.parent = this._getParentOffset();
+		}
+
+		for (var i = this.items.length - 1; i >= 0; i--){
+			var item = this.items[i];
+
+			//We ignore calculating positions of all connected containers when we're not over them
+			if(item.instance != this.currentContainer && this.currentContainer && item.item[0] != this.currentItem[0])
+				continue;
+
+			var t = this.options.toleranceElement ? $(this.options.toleranceElement, item.item) : item.item;
+
+			if (!fast) {
+				item.width = t.outerWidth();
+				item.height = t.outerHeight();
+			}
+
+			var p = t.offset();
+			item.left = p.left;
+			item.top = p.top;
+		};
+
+		if(this.options.custom && this.options.custom.refreshContainers) {
+			this.options.custom.refreshContainers.call(this);
+		} else {
+			for (var i = this.containers.length - 1; i >= 0; i--){
+				var p = this.containers[i].element.offset();
+				this.containers[i].containerCache.left = p.left;
+				this.containers[i].containerCache.top = p.top;
+				this.containers[i].containerCache.width	= this.containers[i].element.outerWidth();
+				this.containers[i].containerCache.height = this.containers[i].element.outerHeight();
+			};
+		}
+
+	},
+
+	_createPlaceholder: function(that) {
+
+		var self = that || this, o = self.options;
+
+		if(!o.placeholder || o.placeholder.constructor == String) {
+			var className = o.placeholder;
+			o.placeholder = {
+				element: function() {
+
+					var el = $(document.createElement(self.currentItem[0].nodeName))
+						.addClass(className || self.currentItem[0].className+" ui-sortable-placeholder")
+						.removeClass("ui-sortable-helper")[0];
+
+					if(!className)
+						el.style.visibility = "hidden";
+
+					return el;
+				},
+				update: function(container, p) {
+
+					// 1. If a className is set as 'placeholder option, we don't force sizes - the class is responsible for that
+					// 2. The option 'forcePlaceholderSize can be enabled to force it even if a class name is specified
+					if(className && !o.forcePlaceholderSize) return;
+
+					//If the element doesn't have a actual height by itself (without styles coming from a stylesheet), it receives the inline height from the dragged item
+					if(!p.height()) { p.height(self.currentItem.innerHeight() - parseInt(self.currentItem.css('paddingTop')||0, 10) - parseInt(self.currentItem.css('paddingBottom')||0, 10)); };
+					if(!p.width()) { p.width(self.currentItem.innerWidth() - parseInt(self.currentItem.css('paddingLeft')||0, 10) - parseInt(self.currentItem.css('paddingRight')||0, 10)); };
+				}
+			};
+		}
+
+		//Create the placeholder
+		self.placeholder = $(o.placeholder.element.call(self.element, self.currentItem));
+
+		//Append it after the actual current item
+		/**********************************************
+		b-hind patch : append it after or as a child if nested is true
+		check position of element
+		
+		problem : on deep nested items what is te depth of the required item to place
+		first solution: create a visible location after each depth -> requires a fyical height and chacges the layout of the nested tree:(
+		second solution : check the indent from the helper, but what if the nesteditems dont have an indent
+		
+		We go for the second solution  !!!
+		
+		so what tot do: check the indent of each read left -padding or left -margin
+		if the helper (left side is between th left side of the parent en itself put it as an extra element of the parent if it is larger than itself put it as a child/
+		
+		**********************************************/
+		
+		self.currentItem.after(self.placeholder);
+
+		//Update the size of the placeholder (TODO: Logic to fuzzy, see line 316/317)
+		o.placeholder.update(self, self.placeholder);
+
+	},
+
+	_contactContainers: function(event) {
+		for (var i = this.containers.length - 1; i >= 0; i--){
+
+			if(this._intersectsWith(this.containers[i].containerCache)) {
+				if(!this.containers[i].containerCache.over) {
+
+					if(this.currentContainer != this.containers[i]) {
+
+						//When entering a new container, we will find the item with the least distance and append our item near it
+						var dist = 10000; var itemWithLeastDistance = null; var base = this.positionAbs[this.containers[i].floating ? 'left' : 'top'];
+						for (var j = this.items.length - 1; j >= 0; j--) {
+							if(!$.ui.contains(this.containers[i].element[0], this.items[j].item[0])) continue;
+							var cur = this.items[j][this.containers[i].floating ? 'left' : 'top'];
+							if(Math.abs(cur - base) < dist) {
+								dist = Math.abs(cur - base); itemWithLeastDistance = this.items[j];
+							}
+						}
+
+						if(!itemWithLeastDistance && !this.options.dropOnEmpty) //Check if dropOnEmpty is enabled
+							continue;
+
+						this.currentContainer = this.containers[i];
+						itemWithLeastDistance ? this._rearrange(event, itemWithLeastDistance, null, true) : this._rearrange(event, null, this.containers[i].element, true);
+						this._trigger("change", event, this._uiHash());
+						this.containers[i]._trigger("change", event, this._uiHash(this));
+
+						//Update the placeholder
+						this.options.placeholder.update(this.currentContainer, this.placeholder);
+
+					}
+
+					this.containers[i]._trigger("over", event, this._uiHash(this));
+					this.containers[i].containerCache.over = 1;
+				}
+			} else {
+				if(this.containers[i].containerCache.over) {
+					this.containers[i]._trigger("out", event, this._uiHash(this));
+					this.containers[i].containerCache.over = 0;
+				}
+			}
+
+		};
+	},
+
+	_createHelper: function(event) {
+
+		var o = this.options;
+		var helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event, this.currentItem])) : (o.helper == 'clone' ? this.currentItem.clone() : this.currentItem);
+
+		if(!helper.parents('body').length) //Add the helper to the DOM if that didn't happen already
+			$(o.appendTo != 'parent' ? o.appendTo : this.currentItem[0].parentNode)[0].appendChild(helper[0]);
+
+		if(helper[0] == this.currentItem[0])
+			this._storedCSS = { width: this.currentItem[0].style.width, height: this.currentItem[0].style.height, position: this.currentItem.css("position"), top: this.currentItem.css("top"), left: this.currentItem.css("left") };
+
+		if(helper[0].style.width == '' || o.forceHelperSize) helper.width(this.currentItem.width());
+		if(helper[0].style.height == '' || o.forceHelperSize) helper.height(this.currentItem.height());
+
+		return helper;
+
+	},
+
+	_adjustOffsetFromHelper: function(obj) {
+		if(obj.left != undefined) this.offset.click.left = obj.left + this.margins.left;
+		if(obj.right != undefined) this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
+		if(obj.top != undefined) this.offset.click.top = obj.top + this.margins.top;
+		if(obj.bottom != undefined) this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
+	},
+
+	_getParentOffset: function() {
+
+
+		//Get the offsetParent and cache its position
+		this.offsetParent = this.helper.offsetParent();
+		var po = this.offsetParent.offset();
+
+		// This is a special case where we need to modify a offset calculated on start, since the following happened:
+		// 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent
+		// 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that
+		//    the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag
+		if(this.cssPosition == 'absolute' && this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) {
+			po.left += this.scrollParent.scrollLeft();
+			po.top += this.scrollParent.scrollTop();
+		}
+
+		if((this.offsetParent[0] == document.body) //This needs to be actually done for all browsers, since pageX/pageY includes this information
+		|| (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() == 'html' && $.browser.msie)) //Ugly IE fix
+			po = { top: 0, left: 0 };
+
+		return {
+			top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0),
+			left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0)
+		};
+
+	},
+
+	_getRelativeOffset: function() {
+
+		if(this.cssPosition == "relative") {
+			var p = this.currentItem.position();
+			return {
+				top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(),
+				left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft()
+			};
+		} else {
+			return { top: 0, left: 0 };
+		}
+
+	},
+
+	_cacheMargins: function() {
+		this.margins = {
+			left: (parseInt(this.currentItem.css("marginLeft"),10) || 0),
+			top: (parseInt(this.currentItem.css("marginTop"),10) || 0)
+		};
+	},
+
+	_cacheHelperProportions: function() {
+		this.helperProportions = {
+			width: this.helper.outerWidth(),
+			height: this.helper.outerHeight()
+		};
+	},
+
+	_setContainment: function() {
+
+		var o = this.options;
+		if(o.containment == 'parent') o.containment = this.helper[0].parentNode;
+		if(o.containment == 'document' || o.containment == 'window') this.containment = [
+			0 - this.offset.relative.left - this.offset.parent.left,
+			0 - this.offset.relative.top - this.offset.parent.top,
+			$(o.containment == 'document' ? document : window).width() - this.helperProportions.width - this.margins.left,
+			($(o.containment == 'document' ? document : window).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top
+		];
+
+		if(!(/^(document|window|parent)$/).test(o.containment)) {
+			var ce = $(o.containment)[0];
+			var co = $(o.containment).offset();
+			var over = ($(ce).css("overflow") != 'hidden');
+
+			this.containment = [
+				co.left + (parseInt($(ce).css("borderLeftWidth"),10) || 0) + (parseInt($(ce).css("paddingLeft"),10) || 0) - this.margins.left,
+				co.top + (parseInt($(ce).css("borderTopWidth"),10) || 0) + (parseInt($(ce).css("paddingTop"),10) || 0) - this.margins.top,
+				co.left+(over ? Math.max(ce.scrollWidth,ce.offsetWidth) : ce.offsetWidth) - (parseInt($(ce).css("borderLeftWidth"),10) || 0) - (parseInt($(ce).css("paddingRight"),10) || 0) - this.helperProportions.width - this.margins.left,
+				co.top+(over ? Math.max(ce.scrollHeight,ce.offsetHeight) : ce.offsetHeight) - (parseInt($(ce).css("borderTopWidth"),10) || 0) - (parseInt($(ce).css("paddingBottom"),10) || 0) - this.helperProportions.height - this.margins.top
+			];
+		}
+
+	},
+
+	_convertPositionTo: function(d, pos) {
+
+		if(!pos) pos = this.position;
+		var mod = d == "absolute" ? 1 : -1;
+		var o = this.options, scroll = this.cssPosition == 'absolute' && !(this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);
+
+		return {
+			top: (
+				pos.top																	// The absolute mouse position
+				+ this.offset.relative.top * mod										// Only for relative positioned nodes: Relative offset from element to offset parent
+				+ this.offset.parent.top * mod											// The offsetParent's offset without borders (offset + border)
+				- ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod)
+			),
+			left: (
+				pos.left																// The absolute mouse position
+				+ this.offset.relative.left * mod										// Only for relative positioned nodes: Relative offset from element to offset parent
+				+ this.offset.parent.left * mod											// The offsetParent's offset without borders (offset + border)
+				- ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ) * mod)
+			)
+		};
+
+	},
+
+	_generatePosition: function(event) {
+
+		var o = this.options, scroll = this.cssPosition == 'absolute' && !(this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);
+
+		// This is another very weird special case that only happens for relative elements:
+		// 1. If the css position is relative
+		// 2. and the scroll parent is the document or similar to the offset parent
+		// we have to refresh the relative offset during the scroll so there are no jumps
+		if(this.cssPosition == 'relative' && !(this.scrollParent[0] != document && this.scrollParent[0] != this.offsetParent[0])) {
+			this.offset.relative = this._getRelativeOffset();
+		}
+
+		var pageX = event.pageX;
+		var pageY = event.pageY;
+
+		/*
+		 * - Position constraining -
+		 * Constrain the position to a mix of grid, containment.
+		 */
+
+		if(this.originalPosition) { //If we are not dragging yet, we won't check for options
+
+			if(this.containment) {
+				if(event.pageX - this.offset.click.left < this.containment[0]) pageX = this.containment[0] + this.offset.click.left;
+				if(event.pageY - this.offset.click.top < this.containment[1]) pageY = this.containment[1] + this.offset.click.top;
+				if(event.pageX - this.offset.click.left > this.containment[2]) pageX = this.containment[2] + this.offset.click.left;
+				if(event.pageY - this.offset.click.top > this.containment[3]) pageY = this.containment[3] + this.offset.click.top;
+			}
+
+			if(o.grid) {
+				var top = this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1];
+				pageY = this.containment ? (!(top - this.offset.click.top < this.containment[1] || top - this.offset.click.top > this.containment[3]) ? top : (!(top - this.offset.click.top < this.containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top;
+
+				var left = this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0];
+				pageX = this.containment ? (!(left - this.offset.click.left < this.containment[0] || left - this.offset.click.left > this.containment[2]) ? left : (!(left - this.offset.click.left < this.containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left;
+			}
+
+		}
+
+		return {
+			top: (
+				pageY																// The absolute mouse position
+				- this.offset.click.top													// Click offset (relative to the element)
+				- this.offset.relative.top												// Only for relative positioned nodes: Relative offset from element to offset parent
+				- this.offset.parent.top												// The offsetParent's offset without borders (offset + border)
+				+ ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ))
+			),
+			left: (
+				pageX																// The absolute mouse position
+				- this.offset.click.left												// Click offset (relative to the element)
+				- this.offset.relative.left												// Only for relative positioned nodes: Relative offset from element to offset parent
+				- this.offset.parent.left												// The offsetParent's offset without borders (offset + border)
+				+ ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ))
+			)
+		};
+
+	},
+
+	_rearrange: function(event, i, a, hardRefresh) {
+		
+		var haschildNode = this._hasChildNodes(i.item);
+		// do this if is
+		if(this.options.nested && this.error){
+			if(this._storedCursor) $('body').css("cursor", this._storedCursor);
+			this.error = false;
+		}
+		if(!this.options.nested){
+			a ? a[0].appendChild(this.placeholder[0]) : i.item[0].parentNode.insertBefore(this.placeholder[0], (this.direction == 'down' ? i.item[0] : i.item[0].nextSibling));
+		}else{
+			var level = this._getLevel(i.item);
+			var childlevels = this._getChildLevels(this.helper);
+			// aantal items op deze level
+			
+			
+			if(this.options.maxLevels <= level+childlevels){
+				if(this.error != true){
+					this._storedCursor = $('body').css("cursor");
+					$('body').css("cursor", "not-allowed"); //Reset cursor
+					this.error = true;
+				}
+			}else{
+				if(!$.ui.isOverAxis(this.positionAbs.left, i.left, i.width)){
+					
+					if(this.options.maxItems.length <= level-1 || (i.item.closest(this.options.nested).children(this.options.items).not(".ui-sortable-helper,.ui-sortable-placeholder").length < this.options.maxItems[level-1])){ // als maxitems niet berijkt voor level 
+						a ? a[0].appendChild(this.placeholder[0]) : i.item[0].parentNode.insertBefore(this.placeholder[0], (this.direction == 'down' ? i.item[0] : i.item[0].nextSibling));
+					}else{
+						this._storedCursor = $('body').css("cursor");
+						$('body').css("cursor", "not-allowed"); //Reset cursor
+						this.error = true;
+					}
+				}else{
+					
+					if(i.item.find(this.options.nested).siblings().length<=0){
+						var element = document.createElement(this.options.nested);
+						
+						i.item.append($(element));
+						
+					}
+					
+					
+					if(this.options.maxItems.length <= level || (i.item.children(this.options.nested).children(this.options.items).not(".ui-sortable-helper,.ui-sortable-placeholder").length < this.options.maxItems[level])){
+						//i.item.find(this.options.nested)[0].appendChild(this.placeholder[0],i.item.find(this.options.nested)[0].firstChild);
+						i.item.find(this.options.nested)[0].insertBefore(this.placeholder[0],i.item.find(this.options.nested)[0].firstChild);
+					}else{
+						this._storedCursor = $('body').css("cursor");
+						$('body').css("cursor", "not-allowed"); //Reset cursor
+						this.error = true;
+					}
+					
+				}
+			}
+			
+			
+			//a ?  a[0].appendChild(this.placeholder[0])
+		}
+		//Various things done here to improve the performance:
+		// 1. we create a setTimeout, that calls refreshPositions
+		// 2. on the instance, we have a counter variable, that get's higher after every append
+		// 3. on the local scope, we copy the counter variable, and check in the timeout, if it's still the same
+		// 4. this lets only the last addition to the timeout stack through
+		this.counter = this.counter ? ++this.counter : 1;
+		var self = this, counter = this.counter;
+
+		window.setTimeout(function() {
+			if(counter == self.counter) self.refreshPositions(!hardRefresh); //Precompute after each DOM insertion, NOT on mousemove
+		},0);
+
+	},
+	/*b-hind function : get level from element */
+	_getLevel:function(item){
+		
+		var level =1;
+		if(this.options.nested){
+			var list = item.closest(this.options.nested);
+			//.ui-sortable
+			while(!list.is(".ui-sortable") && level < this.options.maxLevels){
+					level++;
+					list = list.parent().closest(this.options.nested);
+			}
+		}
+		return level;
+	},
+	_getChildLevels:function(item){
+		
+			levels = item.find(this.options.items).filter(this.options.items+":first-child").length;
+
+			return levels;
+	},
+	_getItemsOnLevel:function(item){
+		//console.log(item.closest(this.options.nested).html())
+		return item.closest(this.options.nested).children(this.options.items).not('.ui-sortable-placeholder').length;
+	},
+	_hasChildNodes:function(item){
+		if(this.options.nested){
+			if(item.find(this.options.nested) && item.find(this.options.nested).children(this.options.items).length>0){
+				return true;	
+			}else{
+				return false;	
+			}
+		}
+	},
+
+	_clear: function(event, noPropagation) {
+
+		this.reverting = false;
+		// We delay all events that have to be triggered to after the point where the placeholder has been removed and
+		// everything else normalized again
+		var delayedTriggers = [], self = this;
+
+		// We first have to update the dom position of the actual currentItem
+		// Note: don't do it if the current item is already removed (by a user), or it gets reappended (see #4088)
+		if(!this._noFinalSort && this.currentItem[0].parentNode) this.placeholder.before(this.currentItem);
+		this._noFinalSort = null;
+
+		if(this.helper[0] == this.currentItem[0]) {
+			for(var i in this._storedCSS) {
+				if(this._storedCSS[i] == 'auto' || this._storedCSS[i] == 'static') this._storedCSS[i] = '';
+			}
+			this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper");
+		} else {
+			this.currentItem.show();
+		}
+
+		if(this.fromOutside && !noPropagation) delayedTriggers.push(function(event) { this._trigger("receive", event, this._uiHash(this.fromOutside)); });
+		if((this.fromOutside || this.domPosition.prev != this.currentItem.prev().not(".ui-sortable-helper")[0] || this.domPosition.parent != this.currentItem.parent()[0]) && !noPropagation) delayedTriggers.push(function(event) { this._trigger("update", event, this._uiHash()); }); //Trigger update callback if the DOM position has changed
+		if(!$.ui.contains(this.element[0], this.currentItem[0])) { //Node was moved out of the current element
+			if(!noPropagation) delayedTriggers.push(function(event) { this._trigger("remove", event, this._uiHash()); });
+			for (var i = this.containers.length - 1; i >= 0; i--){
+				if($.ui.contains(this.containers[i].element[0], this.currentItem[0]) && !noPropagation) {
+					delayedTriggers.push((function(c) { return function(event) { c._trigger("receive", event, this._uiHash(this)); };  }).call(this, this.containers[i]));
+					delayedTriggers.push((function(c) { return function(event) { c._trigger("update", event, this._uiHash(this));  }; }).call(this, this.containers[i]));
+				}
+			};
+		};
+
+		//Post events to containers
+		for (var i = this.containers.length - 1; i >= 0; i--){
+			if(!noPropagation) delayedTriggers.push((function(c) { return function(event) { c._trigger("deactivate", event, this._uiHash(this)); };  }).call(this, this.containers[i]));
+			if(this.containers[i].containerCache.over) {
+				delayedTriggers.push((function(c) { return function(event) { c._trigger("out", event, this._uiHash(this)); };  }).call(this, this.containers[i]));
+				this.containers[i].containerCache.over = 0;
+			}
+		}
+
+		//Do what was originally in plugins
+		if(this._storedCursor) $('body').css("cursor", this._storedCursor); //Reset cursor
+		if(this._storedOpacity) this.helper.css("opacity", this._storedOpacity); //Reset cursor
+		if(this._storedZIndex) this.helper.css("zIndex", this._storedZIndex == 'auto' ? '' : this._storedZIndex); //Reset z-index
+
+		this.dragging = false;
+		if(this.cancelHelperRemoval) {
+			if(!noPropagation) {
+				this._trigger("beforeStop", event, this._uiHash());
+				for (var i=0; i < delayedTriggers.length; i++) { delayedTriggers[i].call(this, event); }; //Trigger all delayed events
+				this._trigger("stop", event, this._uiHash());
+			}
+			return false;
+		}
+
+		if(!noPropagation) this._trigger("beforeStop", event, this._uiHash());
+
+		//$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node!
+		this.placeholder[0].parentNode.removeChild(this.placeholder[0]);
+
+		if(this.helper[0] != this.currentItem[0]) this.helper.remove(); this.helper = null;
+
+		if(!noPropagation) {
+			for (var i=0; i < delayedTriggers.length; i++) { delayedTriggers[i].call(this, event); }; //Trigger all delayed events
+			this._trigger("stop", event, this._uiHash());
+		}
+		//b-hind clear empty nested elements
+		if(this.options.nested){
+			
+			this.element.find(this.options.nested+":empty").remove();
+			
+		}
+		this.fromOutside = false;
+		return true;
+
+	},
+
+	_trigger: function() {
+		if ($.widget.prototype._trigger.apply(this, arguments) === false) {
+			this.cancel();
+		}
+	},
+
+	_uiHash: function(inst) {
+		var self = inst || this;
+		return {
+			helper: self.helper,
+			placeholder: self.placeholder || $([]),
+			position: self.position,
+			absolutePosition: self.positionAbs, //deprecated
+			offset: self.positionAbs,
+			item: self.currentItem,
+			sender: inst ? inst.element : null
+		};
+	}
+
+}));
+
+$.extend($.ui.sortable, {
+	getter: "serialize toArray",
+	version: "1.7.2",
+	eventPrefix: "sort",
+	defaults: {
+		appendTo: "parent",
+		axis: false,
+		cancel: ":input,option",
+		connectWith: false,
+		containment: false,
+		cursor: 'auto',
+		cursorAt: false,
+		delay: 0,
+		distance: 1,
+		
+		dropOnEmpty: true,
+		forcePlaceholderSize: false,
+		forceHelperSize: false,
+		grid: false,
+		handle: false,
+		helper: "original",
+		items: '> *',
+		opacity: false,
+		placeholder: false,
+		revert: false,
+		scroll: true,
+		scrollSensitivity: 20,
+		scrollSpeed: 20,
+		scope: "default",
+		tolerance: "intersect",
+		zIndex: 1000,
+		nested:false,
+		maxLevels: 100,
+		maxItems : []
+		}
+});
+
+})(jQuery);
