$.fn.replaceWithAndReturnNew = function(html){
   var div = document.createElement('div');
   var replaced = this[0];
   replaced.parentNode.replaceChild(div, replaced);
   div.innerHTML = html;
   var replacer = div.firstChild;
   div.parentNode.replaceChild(replacer, div);
   return $(replacer);
};

// Need this workaround because aspectRatio for resizable cannot
// be set after the resizable is initiated
(function() {
   // Work around http://dev.jqueryui.com/ticket/4186
   var oldSetData = $.ui.resizable.prototype._setData;
   $.ui.resizable.prototype._setData = function(key, value) {
      oldSetData.apply(this, arguments);
      if (key === "aspectRatio") {
         this._aspectRatio = !!value;
      }
   };

   // Fix for nested draggables
   // http://dev.jqueryui.com/ticket/4333
   $.extend($.ui.draggable.prototype, (function (orig) {
     return {
       _mouseCapture: function (event) {
         var result = orig.call(this, event);
         if (result && $.browser.msie) event.stopPropagation();
         return result;
       }
     };
   })($.ui.draggable.prototype["_mouseCapture"]));

   $.extend($.fn.disableTextSelect = function() {
      return this.each(function(){
         if($.browser.mozilla){//Firefox
            $(this).css('MozUserSelect','none');
         }else if($.browser.msie){//IE
            $(this).bind('selectstart',function(){return false;});
         }else{//Opera, etc.
            $(this).mousedown(function(){return false;});
         }
      });
   });

})();


// Global variables
var TOGGLEATHAND = false;        // False if not showing
var DATASPHEREMANAGING = false;
var ATHANDSECTION = "";
var ATHANDPAGE = "";
var ATHANDDISPLAYED = false;
var DATAPOINTMINSIZE = 20;
var MANAGECURRENTZ = 0;
var RESIZING = false;
var DATAID = 0;
var DATATYPE = "";
var DATALINKCREATABLE = false;
var CONTENTSPAWNABLE = false;
var CONTENTOVERLAYDISPLAYID = 0;
var ORGANIZERLOADED = false;
var ATHANDCUSTOMDROP = false;
var DATAPOINTSCROLLING = false;
var DATASTREAMPANELCOUNT = [];
var DATASTREAMPANELDURATION = [];
var DATASTREAMLASTTIMEOUT = [];
var DATASPHEREDISPLAYID = 0;
var DATASPHERESORTMETHOD = 0;
var DATASPHEREREQUIREREFRESH = false;

var PSSYS = {
   jQuery : $,

   settings : {
   },

   init : function () {
      this.initializeLayout();
   },

   initializeLayout : function() {
      var PSSYS = this,
         $ = this.jQuery,
         settings = this.settings;

      $('#login').unbind().mouseenter(function() {
         $(this).css('cursor', 'pointer');
         $(this).css('color', '#f8f8f8');
      }).mouseleave(function() {
         $(this).css('color', '#b0b0b0');
      }).click(function() {
         // Setup the chimney
         $('#loginChimney').width($(this).width() + 10);

         $('#loginBlock').show();
         return false;
      });

      $('#loginun,#loginpw').unbind().keypress(function(e) {
         if (e.which == 13 || e.which == 10)
            loginQuery();
      });

      $('#quicksearchquery').unbind().keypress(function(e) {
         if (e.which == 13 || e.which == 10)
            quicksearchGo();
      });

      $('#register').unbind().mouseenter(function() {
         $(this).css('cursor', 'pointer');
         $(this).css('color', '#f8f8f8');
      }).mouseleave(function() {
         $(this).css('color', '#b0b0b0');
      }).click(function() {
         // Fade in to allow registration
         $('#contentOverlayBG').show().animate({ opacity: 0.8 }, 500, function() {
            var salt = getSalt();
            $('#contentOverlay').html('<center>loading...</center>').show();

            $.get('/ajax_register.php', { salt : salt, c : "terms" }, function(data) {
               var json = evalJSON(data);


               if (check(json)) {
                  $('#contentOverlay').html(json.content);
               } else
                  confirm("Registration may not be accepted at this time");
            });
         });
         return false;
      });


      $('#headerpsOn').unbind().mouseenter(function() {
         $(this).css('cursor', 'pointer');

         var current = $('img', this).attr("src").split(".");
         var ext = current[1];
         $('img', this).attr("src", "/images/pointspherehover." + ext);

      }).mouseleave(function() {
         var current = $('img', this).attr("src").split(".");
         var ext = current[1];
         $('img', this).attr("src", "/images/pointsphere." + ext);
      }).click(function() {
         if (TOGGLEATHAND)
            atHandUnload();
         else
            atHandLoad();

         TOGGLEATHAND = !TOGGLEATHAND;

         return false;
      });

/*
      $('.headerSphere').unbind().mouseenter(function() {
         $(this).css('cursor', 'pointer');
      }).click(function() {
         var id = this.id.split("_");
         var datasphereid = id[1];

         datasphereLoad(datasphereid, false, false);

         return false;
      });
*/

/*
 * Removed due to removal of single button at top
      $('.datasphereManageToggle').unbind().mouseenter(function() {
         $(this).css('cursor','pointer');
      }).mouseleave(function() {

      }).click(function() {
         if (DATASPHEREMANAGING)
            datasphereLoad(DATASPHEREID);
         //else if (confirm("Enable management of datasphere?")) {
         else {
            datasphereLoad(DATASPHEREID, true); // True for managing
         }

         return false;
      });
*/

      $('.datasphereSymToggle').unbind().mouseenter(function() {
         var current = $('img', this).attr("src").split(".");
         var ext = current[1];
         $('img', this).attr("src", "/images/arrowdownhover." + ext);

         // Display the options
         var top = $(this).offset().top;

         $('#headerOptions').css({ top: top}).show();
      }).mouseleave(function() {
      });

      $('#headerOptions').unbind().mouseleave(function() {
         var current = $('img', '.datasphereSymToggle').attr("src").split(".");
         var ext = current[1];
         $('img', '.datasphereSymToggle').attr("src", "/images/arrowdown." + ext);

         $(this).hide();
      });

      $('.headerOption').unbind().mouseenter(function() {
         $(this).css('cursor','pointer');
         $(this).css('text-decoration', 'underline');
      }).mouseleave(function() {
         $(this).css('text-decoration', 'none');
      }).click(function() {
         var id = this.id.split("_");
         var command = id[1];

         if (command == 'manage') {
            if (DATASPHEREMANAGING) {
               datasphereLoad(DATASPHEREID, false, false);
            //} else if (confirm("Enable management of datasphere?")) {
            } else {
               datasphereLoad(DATASPHEREID, true, false); // True for managing
            }
         } else if (command == 'displaytype') {
            // Load the display type area
            var salt = getSalt();
            $('#datasphereOptionsOverlay').html('loading...').css('opacity', 0).show().animate({ opacity: 1 }, 500, function() {

               $.get('/ajax_datasphere.php', { salt : salt, dsid : DATASPHEREID, 
                     current : DATASPHEREDISPLAYID, c : 'displaytype' }, 
                     function(data) {

                  var json = evalJSON(data);

                  if (check(json)) {
                     $('#datasphereOptionsOverlay').html(json.content);

                     // now initialize it all
                     $('.datasphereDisplayOptionsClose').mouseenter(function() {
                        $(this).css('cursor','pointer');
                     }).mouseleave(function() {
                        $(this).css('cursor','');
                     }).click(function() {
                        $('#datasphereOptionsOverlay').hide();
                        return false;
                     });

                     $('.datasphereDisplayOption').mouseenter(function() {
                        $(this).css('cursor','pointer');
                     }).mouseleave(function() {
                        $(this).css('cursor','');
                     }).click(function() {
                        var id = this.id.split("_");
                        var dsid = id[1];
                        var dtypeid = id[2];

                        // update the datasphere display id
                        DATASPHEREDISPLAYID = dtypeid;

                        // now load the dS. No manage, no overlay
                        datasphereLoad(dsid, false, false);

                        return false;
                     });


                  } else
                     confirm("An error occured while loading display options");

               });
            });

         } else if (command == 'sortorder') {
            // Load the display type area
            var salt = getSalt();
            $('#datasphereOptionsOverlay').html('loading...').css('opacity', 0).show().animate({ opacity: 1 }, 500, function() {

               $.get('/ajax_datasphere.php', { salt : salt, dsid : DATASPHEREID, 
                     current : DATASPHERESORTMETHOD, c : 'sortorder' }, 
                     function(data) {

                  var json = evalJSON(data);

                  if (check(json)) {
                     $('#datasphereOptionsOverlay').html(json.content);

                  } else
                     confirm("An error occured while loading sorting options");

               });
            });


         } else if (command == 'delete') {
            if (confirm("Are you sure you wish to delete the datasphere?"))
               datasphereDelete(DATASPHEREID);
         } else if (command == 'settings') {
            $('#contentOverlayBG').show().animate({ opacity: 0.8 }, 500, function() {
               $('#contentOverlay').html('').show();

               // Get the settings for this datasphere
               manageLoad("datasphere", "", DATASPHEREID);
            });
         } else if (command == "df") {
            var dfaid = id[2];
            var pointid = id[3];
            var type = id[4];
            dataFunctionRun(dfaid, type, pointid);
         } else if (command == 'dataquerymanage') {
            var symqueryid = id[2];
            if (!TOGGLEATHAND) {
               // Initialize the draggability of the content
               PSSYS.initializeContentDraggable();

               atHandRollDown();
            }

            atHandBrowse("dataquery", "wizard_" + symqueryid);
         } else if (command == 'userpms') {
            $('#contentOverlayBG').show().animate({ opacity: 0.8 }, 500, function() {
               $('#contentOverlay').html('').show();
               manageLoad("pms", "inbox", "", "");
            });
         } else if (command == 'usersettings') {
            $('#contentOverlayBG').show().animate({ opacity: 0.8 }, 500, function() {
               $('#contentOverlay').html('').show();
               manageLoad("user", "profile", "", "");
            });
         } else if (command == 'datapointmanage') {
            $('#contentOverlayBG').show().animate({ opacity: 0.8 }, 500, function() {
               $('#contentOverlay').html('').show();
               manageLoad("datapoint", "", DATAPOINTID);
            });
         }

         var current = $('#headerOptionsArrow').attr("src").split(".");
         var ext = current[1];
         $('#headerOptionsArrow').attr("src", "/images/arrowdown." + ext);

         $('#headerOptions').hide();

         return false;
      });

      PSSYS.initializeContent();
   },

   initializeContent : function() {
/*
      // TODO: ALLOW THIS TO WORK
      // Dragging into the ATHAND bar no longer works properly with
      // the below code in place

      $('.contentDatapoint').unbind().mouseenter(function() {
         // Set the last current Z
         $('.datapointCurrent').css('zIndex', MANAGECURRENTZ);

         // Update the current
         $('.datapointCurrent').removeClass('datapointCurrent');

         // Set this one
         $(this).addClass('datapointCurrent');

         MANAGECURRENTZ = $(this).css('zIndex');

         $(this).css('zIndex', 99);

      }).mouseleave(function() {
         if ($(this).hasClass('ui-resizable-resizing') ||
            !$(this).is(":visible") || RESIZING)
            return;

         // Hide all
         //$('.datapointOptions').hide();

         // Set the last current Z
         $('.datapointCurrent').css('zIndex', MANAGECURRENTZ);

         // Update the current
         $('.datapointCurrent').removeClass('datapointCurrent');

         MANAGECURRENTZ = 0;
      });
*/

      // Display the option toggle
      $('.contentDatapoint,.contentSymbolic').mouseenter(function() {
         $('.datapointOptionToggle', this).show();
      }).mouseleave(function() {
         $('.datapointOptionToggle', this).hide();

      });

      // Browsing
      $('.datapointOptionToggle').unbind().mouseenter(function() {
         var current = $('img', this).attr("src").split(".");
         var ext = current[1];

         $('img', this).attr("src", "/images/pointspheresmhover." + ext);

         $(this).css('cursor', 'pointer');

         var id = this.id.split("_");
         id = id[1];

         var options = $('#datapointOptions_' + id);
         var optionid = 'datapointOptions_' + id;
         clearTimeout(DATAPOINTOPTIONSTIMEOUTS[optionid]);

         // Figure out where to place the options menu
/*
         var position = $(this).position();
         var width = $(this).width();
         var left = position.left + width;
*/
         var position = $(this).offset();
         var width = $(this).width();

         var contentObj = $('#content');
         if ($('#contentOverlay').is(':visible'))
            contentObj = $('#contentOverlay');

         var contentOffset = contentObj.offset();

         // Does not account for scrolling with the offset function
         var scrolledUp = contentObj.scrollTop();
         var scrolledLeft = contentObj.scrollLeft();

         var top = position.top - contentOffset.top + scrolledUp;
         var left = position.left + width + scrolledLeft;


         // Check for the options going outside of the window width
         // If this is the case, then we want to move it left instead of right
         var windowWidth = $(window).width();
         var optionsWidth = options.width();
         if (optionsWidth + left > windowWidth)
            left -= (optionsWidth + width);


         options.css({ 'left': left, 'top' : top, 'z-index' : 50}).show();

         //confirm(top + " " + left);

/*
         if ($('#contentOverlay').is(':visible'))
            options.appendTo('#contentOverlay');
         else
            options.appendTo('#content');
*/
         options.appendTo(contentObj);
/*
         var clone = options.clone();
         clone.attr('id', optionid + "_clone").appendTo('#contentEnd');
         clone.show();
*/

         return false;

      }).mouseleave(function() {
         var current = $('img', this).attr("src").split(".");
         var ext = current[1];
         $('img', this).attr("src", "/images/pointspheresm." + ext);

         var id = this.id.split("_");
         id = id[1];

         var optionid = 'datapointOptions_' + id;
         var tid = setTimeout("datapointOptionClose('" + optionid + "')", 1000);
         DATAPOINTOPTIONSTIMEOUTS[optionid] = tid;
/*
         var options = $('#datapointOptions_' + id);
         if (options.is(":visible")) {
            options.hide();
            //$(this).parent().removeClass("datapointTop");
            //$('#dataspherepoint_' + id).removeClass("datapointTop");
         }
*/
      }).click(function(event) {
      });

      $('.datapointOptions').unbind().mouseenter(function() {
         DATAPOINTOPTIONSHOVERING[this.id] = 1;

         // Clear any timeouts that this object may have
         clearTimeout(DATAPOINTOPTIONSTIMEOUTS[this.id]);
      }).mouseleave(function() {
         DATAPOINTOPTIONSHOVERING[this.id] = 0;
         setTimeout("datapointOptionClose('" + this.id + "')", 1000);
      });

      // Options
      $('.datapointOption').unbind().mouseenter(function() {
         var id = this.id.split("_");
         var command = id[0];

         if (command.length == 0)
            return;

         $(this).css('cursor','pointer');
         $(this).css('text-decoration', 'underline');
      }).mouseleave(function() {
         $(this).css('text-decoration', 'none');
      }).click(function() {
         var id = this.id.split("_");
         var command = id[0];

         if (command.length == 0)
            return;

         if (command == "datafunction") {
            var dfaid = id[1];
            var pointid = id[2];
            var type = id[3];
            dataFunctionRun(dfaid, type, pointid);
         } else if (command == 'managedatapoint') {
            var dpid = id[1];
            $('#contentOverlayBG').show().animate({ opacity: 0.8 }, 500, function() {
               $('#contentOverlay').html('').show();

               // Get the settings for this datapoint
               manageLoad("datapoint", "", dpid);
            });
         } else {
            var pointid = id[1];
            var type = id[2];

            datapointOptionLoad(pointid, type, command);
         }

         return false;
      });

      // Overlay close button
      $('.contentOverlayClose').unbind().mouseenter(function() {
         $(this).css('cursor','pointer');
      }).mouseleave(function() {

      }).click(function() {
         contentOverlayClose();
         return false;
      });

      $('.datalinkOverlayDisplayToggleinactive').mouseenter(function() {
         $(this).css('cursor','pointer');
      }).click(function() {
         var id = this.id.split("_");

         // datalink_id_typeid_displaytypeid
         var pointid = id[1];
         var typeid = id[2];
         var displaytypeid = id[3];

         datalinkGetRelevant(pointid, typeid, displaytypeid);

         return false;
      });


      // Datastreams
      $('.dataStreamPrev').mouseenter(function() {
         $(this).css('cursor','pointer');
         $(this).css('text-decoration', 'underline');
      }).mouseleave(function() {
         $(this).css('text-decoration', 'none');
      }).click(function() {
         var id = this.id.split("_");
         var dsid = id[1];

         // Stop it
         datastreamStop(dsid);

         // Hide current and get current
         var current = datastreamHideCurrent(dsid);

         // Now show this one
         var prev = (current - 1 > 0) ? current - 1 : DATASTREAMPANELCOUNT[dsid];
         datastreamShow(dsid, prev);

         return false;
      }).disableTextSelect();

      $('.dataStreamNext').mouseenter(function() {
         $(this).css('cursor','pointer');
         $(this).css('text-decoration', 'underline');
      }).mouseleave(function() {
         $(this).css('text-decoration', 'none');
      }).click(function() {
         var id = this.id.split("_");
         var dsid = id[1];

         // Stop it
         datastreamStop(dsid);

         // Hide current and get current
         var current = datastreamHideCurrent(dsid);

         // Now show this one
         var next = (current + 1 <= DATASTREAMPANELCOUNT[dsid]) ? current + 1 : 1;

         datastreamShow(dsid, next);
         return false;
      }).disableTextSelect();

      $('.dataStreamStop').mouseenter(function() {
         $(this).css('cursor','pointer');
         $(this).css('text-decoration', 'underline');
      }).mouseleave(function() {
         $(this).css('text-decoration', 'none');
      }).click(function() {
         var id = this.id.split("_");
         var dsid = id[1];

         // See if we are stopped or not
         var content = $('#dataStreamStop_' + dsid).html();

         if (content == '[stop]')
            datastreamStop(dsid);
         else
            datastreamStart(dsid);

         return false;
      }).disableTextSelect();

   },

   initializeProwler : function(containerid) {
      $('.prowlerContentDatapoint', '#' + containerid).mousedown(function(e) {
/*
          if($.browser.msie) {
               e.stopPropagation();
          }
*/

      }).mouseenter(function() {
         $(this).css('cursor','move');
      }).draggable({
         revert: "invalid",
         cursor: "move",
         appendTo: "body",
         scroll: false,

         helper : function(event, ui) {
            var clone = $(this).clone();
            clone.css('margin', 0);
            clone.css('zIndex', 21);
            clone.css('position', 'absolute');
            clone.css('opacity', 0.5);
            clone.attr('id', $(this).attr('id') + "_clone");
            return clone;
         },
         start : function(event, ui) {
            //$(this).css('opacity',0.5);
         },
         stop : function(event, ui) {
            //$(this).css('opacity',1);
         }
      });

   },

   initializeSym : function() {
      $('.datasphereSym').mouseenter(function() {
         $(this).css('cursor','move');
      }).draggable({
         revert: "invalid",
         cursor: "move",
         appendTo: "body",
         scroll: false,
         helper: function(event, ui) {
            var clone = $(this).clone();
            clone.css('margin', 0);
            clone.css('zIndex', 99);
            clone.css('position', 'absolute');
            clone.attr('id', $(this).attr('id') + "_clone");
            return clone;

         },
         start : function(event, ui) {
            $(this).css('opacity',0.5);
         },
         stop : function(event, ui) {
            $(this).css('opacity',1);
         }
      });

   },

   initializeManage : function() {
      var PSSYS = this,
         $ = this.jQuery,
         settings = this.settings;

      $('.manageLinkButton').unbind().mouseenter(function() {
         $(this).css('cursor','pointer');
         $(this).css('text-decoration','underline');
      }).mouseleave(function() {
         $(this).css('text-decoration','none');
      }).click(function() {
         var id = this.id.split(",");
         manageLoad(id[0],id[1],id[2],id[3]);
         return false;
      });


      $('.manageClose').unbind().mouseenter(function() {
         $(this).css('cursor','pointer');
         $(this).css('text-decoration','underline');
      }).mouseleave(function() {
         $(this).css('text-decoration','none');
      }).click(function() {
         contentOverlayClose();
         return false;
      });


      $('.toggleContentOverlays').unbind().mouseenter(function() {
         $(this).css('font-weight','bold');
         $(this).css('cursor','pointer');
      }).mouseleave(function() {
         $(this).css('font-weight','');
      }).click(function() {
         var id = this.id.split(",");
         $(this).html("updating...");

         var salt = getSalt();

         $.get('/ajax_datasphere.php', { salt : salt, 
            c : "togglecontentoverlays", 
            dsid : id[0], current : id[1] }, function(data) {

            var json = evalJSON(data);

            if (check(json)) {
               $('.toggleContentOverlays').html(json.content).attr("id", json.value);
               DATASPHEREREQUIREREFRESH = true;
            } else
               confirm("Invalid management call");
         });



         return false;
      });


      $('.manageValueToggle').unbind().mouseenter(function() {
         $(this).css('font-weight','bold');
         $(this).css('cursor','pointer');
      }).mouseleave(function() {
         $(this).css('font-weight','');
      }).click(function() {
         var id = this.id.split(",");
         $(this).html("updating...");
         manageToggle(id[0],id[1],id[2],id[3],id[4],this);
         return false;
      });

      $('.manageValueEdit').unbind().mouseenter(function() {
         $(this).css('font-weight','bold');
         $(this).css('cursor','pointer');
      }).mouseleave(function() {
         $(this).css('font-weight','');
      }).click(function() {
         $('.manageValueEditField', $(this).parent()).show();
         return false;
      });

      $('.manageRow').mouseenter(function() {
         var id = this.id.split("_");
         var dfid = id[1];
         var pid = id[2];
         var num = id[3];


         // We want to make a chimney popup
         var offset = $(this).offset();

         // Figure out the content
         var content = $('.manageDescription', this).html();

         if (content.length <= 0)
            return;

         content = '<div style="white-space: nowrap;">' + content + '</div>';

         popupShow(offset.top + 16, offset.left, content);
      }).mouseleave(function() {
         popupHide();
      });

      // Config for datasphere display type
      $('#datasphereStreamThumbBlock').sortable({
         opacity: 0.6,
         cursor: 'move',
         items: 'li',
         appendTo: 'body',
         update : function() {
            var order = "";
            var count = 0;
            $('li', this).each(function() {
               count++;
               if (order.length)
                  order += "&";

               order += count + "=" + this.id;
            });

            order = escape(order);
            var salt = getSalt();

            loadingOn();
            // Now submit   
            $.post('/ajax_datasphere.php', { salt : salt,
               c : 'streamorder', order : order, dsid : DATASPHEREID },
               function(data) {

               var json = evalJSON(data);

               if (check(json)) {
                  datasphereLoad(DATASPHEREID, false, true);
               } else
                  confirm("An error occured while sorting the stream");
               loadingOff();
            });


         }
      });

      // Private messages
      $('.pmInboxRow').mouseenter(function() {
         $(this).css('background-color', '#555555');
         $(this).css('cursor','pointer');
      }).mouseleave(function() {
         $(this).css('background-color', '#333333');
      }).click(function() {
         var id = this.id.split("_");

         var type = id[0];
         var threadid = id[1];

         pmLoadMessage(type, threadid);


         return false;
      });
   },

   initializeAtHand : function() {
      var PSSYS = this,
         $ = this.jQuery,
         settings = this.settings;

      popupHide();

      $('.athandLink', '#athand').unbind().mouseenter(function() {
         $(this).css('cursor','pointer');
         $(this).css('text-decoration','underline');
      }).mouseleave(function() {
         $(this).css('text-decoration','none');
      }).click(function() {
         var id = this.id.split(",");
         atHandBrowse(id[0],id[1]);
         return false;
      });

      // Left menu buttons
      $('.athandLinkButtonActive', '#athand').unbind().mouseenter(function() {
         // In case this is a sphere link
         $('.athandDatasphereDelete', this).show();

      }).mouseleave(function() {
         // In case this is a sphere link
         $('.athandDatasphereDelete', this).hide();
      });

      $('.athandLinkButton', '#athand').unbind().mouseenter(function() {
         $(this).css('cursor','pointer');
         $(this).css('text-decoration','underline');

         // In case this is a sphere link
         $('.athandDatasphereDelete', this).show();

      }).mouseleave(function() {
         $(this).css('text-decoration','none');

         // In case this is a sphere link
         $('.athandDatasphereDelete', this).hide();
      }).click(function() {
         var id = this.id.split(",");
         atHandBrowse(id[0],id[1]);
         return false;
      });

      // Datapoints in the athand spheres
      $('.athandDatapoint', '#athand').mouseenter(function() {
         $(this).css('cursor','move');
         $('.athandDatapointDelete', this).show();
         $('.athandDatapointView', this).show();
      }).mouseleave(function() {
         $('.athandDatapointDelete', this).hide();
         $('.athandDatapointView', this).hide();
      }).draggable({
         revert: "invalid",
         cursor: "move",
         appendTo: "body",
         scroll: false,
         helper: function(event, ui) {
            var clone = $(this).clone();
            clone.css('margin', 0);
            clone.css('zIndex', 99);
            clone.css('position', 'absolute');
            clone.attr('id', $(this).attr('id') + "_clone");

            return clone;

         },
         start : function(event, ui) {
            $(this).css('opacity',0.5);

            // Make the dataspheres droppable for organization
            // in the at hand bar. Done in the START area because of
            // something relating to updatepanels?
            // http://stackoverflow.com/questions/1202180/is-there-still-a-bug-in-ie8-with-jquery-droppables
            $('.athandSphere').droppable({
               accept: '.athandDatapoint',
               tolerance: 'pointer',
               over : function(event, ui) {
                  if (!$(this).hasClass("athandLinkButtonActive"))
                     $(this).css('background-color', '#ffffff');
               },
               out : function(event, ui) {
                  if (!$(this).hasClass("athandLinkButtonActive"))
                     $(this).css('background-color', '#aaaaaa');

               },
               drop : function(event, ui) {
                  if (!$(this).hasClass("athandLinkButtonActive")) {
                     $(this).css('background-color', '#aaaaaa');

                     // Move this datapoint to the new sphere
                     var id = $(this).attr('id').split(",");
                     var sphereid = parseInt(id[1]);
                     var did = ui.helper.attr("id").split("_");
                     did = did[2];

                     //confirm("Dropping to " + sphereid + " of " + ui.helper.attr("id"));
                     atHandDatapointMove(did, sphereid);
                  }

                  return false;
               }
            });

         },
         drag : function(event, ui) {
            //confirm("Dragging...");
         },
         stop : function(event, ui) {
            //confirm("Stopped");
            $(this).css('opacity',1);

            // Remove ability to drop into the athandSpheres
            $('.athandSphere').droppable('destroy');
         }
      });

      // Delete a datasphere in the organize area
      $('.athandDatasphereDelete', '#athand').mouseenter(function() {
         $(this).css('background-color', '#cccccc');
         $(this).css('cursor','pointer');
      }).mouseleave(function() {
         $(this).css('background-color', '#777777');
      }).click(function() {
         var athandsphereid = this.id.split("_");
         athandsphereid = athandsphereid[1];

         if (confirm("Are you sure you wish to remove this datasphere and its contents from the at hand bar?"))
            atHandDatasphereDelete(athandsphereid);
         return false;
      });

      // Delete a datapoint in the athand datasphere area
      $('.athandDatapointDelete', '#athand').mouseenter(function() {
         $(this).css('background-color', '#cccccc');
         $(this).css('cursor','pointer');
      }).mouseleave(function() {
         $(this).css('background-color', '#777777');
      }).click(function() {
         var athandpointid = this.id.split("_");
         athandpointid = athandpointid[1];

         if (confirm("Are you sure you wish to remove this datapoint from the at hand bar?"))
            atHandDatapointDelete(athandpointid);
         return false;
      });

      // Entire area as a whole is droppable
      $('#athand').droppable({
         accept: '.contentDatapoint, .datasphereSym, .contentDatasphere, .contentSymbolic, .prowlerContentDatapoint',
         tolerance: 'pointer',
         over : function(event, ui) {
            if (ATHANDCUSTOMDROP)
               return;
            var pointid = ui.helper.attr('id').split("_");
            pointid = pointid[1];

            ui.helper.css('opacity', 1.0);
         },
         out : function(event, ui) {
            if (ATHANDCUSTOMDROP)
               return;
            var pointid = ui.helper.attr('id').split("_");
            pointid = pointid[1];
            ui.helper.css('opacity', 0.5);
         },


         drop : function(event, ui) {
            if (ATHANDCUSTOMDROP)
               return;

            var pointid = ui.helper.attr('id').split("_");
            var typeid = pointid[0];

            if (typeid == 'dataspheresym') {
               pointid = pointid[1];
               atHandDatasphereSymAdd(pointid);
            } else if (typeid == 'dataspherepoint') {
               pointid = pointid[1];
               atHandDataspherepointAdd(pointid);
            } else if (typeid == 'prowlerPoint') {
               prowlerImport(ui.helper.html());
            } else if (typeid == 'datapoint') {
               pointid = pointid[1];
               atHandDatapointAdd(pointid);
            } else if (typeid == 'datasphere') {
               pointid = pointid[1];
               atHandDatasphereSymAdd(pointid);
            }

            return false;
         }
      });

      $('#athandOrganizeDatasphereAdd', '#athand').unbind().mouseenter(function() {
         $(this).css('text-decoration', 'underline');
         $(this).css('cursor','pointer');
      }).mouseleave(function() {
         $(this).css('text-decoration', 'none');
      }).click(function() {
         atHandBrowse("organize", "athanddatasphereadd");
         return false;
      });

      // Dataqueries
      $('.dataqueryWizardDelete').unbind().mouseenter(function() {
         $(this).css('text-decoration','underline');
         $(this).css('cursor','pointer');

      }).mouseleave(function() {
         $(this).css('text-decoration','none');
      }).click(function() {
         var id = this.id.split("_");
         var dqid = id[1];
         var pid = id[2];

         dataqueryWizardRemovePart(dqid, pid);
         return false;
      });

      $('.dataqueryWizardBit').unbind().mouseenter(function() {
         $(this).css('text-decoration','underline');
         $(this).css('cursor','pointer');
      }).mouseleave(function() {
         $(this).css('text-decoration','none');
      }).click(function() {
         var id = this.id.split("_");
         var dqid = id[1];
         var pid = id[2];

         dataqueryWizardToggleBit(dqid, pid);
         return false;
      });
/*
      $('.originateDataqueryLoadOrganizer').unbind().mouseenter(function() {
         $(this).css('text-decoration','underline');
         $(this).css('cursor','pointer');
      }).mouseleave(function() {
         $(this).css('text-decoration','none');
      }).click(function() {
         dataqueryWizardLoadOrganizer();
         return false;
      });
*/

      // Dropping into the dataquery area
      $('.dataqueryWizardPartNew').droppable({
         accept: '.contentDatapoint, .datasphereSym, .contentDatasphere, .contentSymbolic, .athandDatapoint',
         tolerance: 'pointer',
         over : function(event, ui) {
            var pointid = ui.helper.attr('id').split("_");
            pointid = pointid[1];

            ui.helper.css('opacity', 0.8);

            $(this).css('border', '1px solid #ff0000');
         },
         out : function(event, ui) {
            var pointid = ui.helper.attr('id').split("_");
            pointid = pointid[1];
            ui.helper.css('opacity', 0.5);
            $(this).css('border', '1px solid #ffffff');
         },


         drop : function(event, ui) {
            if (!ATHANDCUSTOMDROP)
               return;

            $(this).css('border', '1px solid #ffffff');

            var pointid = ui.helper.attr('id').split("_");
            var typeid = pointid[0];

            var type = typeid;
            var id = 0;

            if (typeid == 'athanddatasphere' ||
               typeid == 'athanddatapoint') {
               id = pointid[2];
               type = "athandpoint";
            } else if (typeid == 'dataspherepoint') {
               id = pointid[1];
               type = "dataspherepoint";
            } else if (typeid == 'datapoint') {
               id = pointid[1];
            } else if (typeid == 'datasphere') {
               id = pointid[1];
            }

            // Set the datapoint
            $('#dataqueryWizardPartDropped', this).val(type + "_" + id);

            // Hide the field
            $('#dataqueryWizardPartField', this).hide();

            $('#dataqueryWizardPartDroppedReceived').show();

            return false;
         }
      });

      $('.dataqueryWizardPartRemoveDropped').unbind().mouseenter(function() {
         $(this).css('text-decoration','underline');
         $(this).css('cursor','pointer');
      }).mouseleave(function() {
         $(this).css('text-decoration','none');
      }).click(function() {
         // Set the datapoint
         $('#dataqueryWizardPartDropped').val('');

         // Hide the field
         $('#dataqueryWizardPartDroppedReceived').hide();

         // Now show
         $('#dataqueryWizardPartField').show();

         return false;
      });

      // Datafunctions
      $('.dataFunctionPart').unbind().mouseenter(function() {
         var id = this.id.split("_");
         var dfid = id[1];
         id = id[2];

         // Display the delete
         $('#dataFunctionPartDelete_' + dfid + "_" + id).show();
         $('#dataFunctionPartUp_' + dfid + "_" + id).show();
         $('#dataFunctionPartDown_' + dfid + "_" + id).show();
      }).mouseleave(function() {
         var id = this.id.split("_");
         var dfid = id[1];
         id = id[2];

         // Display the delete
         $('#dataFunctionPartDelete_' + dfid + "_" + id).hide();
         $('#dataFunctionPartUp_' + dfid + "_" + id).hide();
         $('#dataFunctionPartDown_' + dfid + "_" + id).hide();
      });

      $('.dataFunctionPartDown').unbind().click(function() {
         var id = this.id.split("_");
         var dfid = id[1];
         id = id[2];

         dataFunctionPartMove(dfid, id, 1);

         return false;
      });

      $('.dataFunctionPartUp').unbind().click(function() {
         var id = this.id.split("_");
         var dfid = id[1];
         id = id[2];

         dataFunctionPartMove(dfid, id, -1);

         return false;
      });

      $('.dataFunctionPartDelete').unbind().click(function() {
         var id = this.id.split("_");
         var dfid = id[1];
         id = id[2];

         if (confirm("Are you sure you wish to delete this dataFunction part?")) {
            $(this).parent().animate({opacity : 0.0}, 500, function() {
               dataFunctionPartDelete(dfid, id);
            });
         }

         return false;
      });

      $('.dataFunctionPartValue').mouseenter(function() {
         $(this).css('text-decoration', 'underline');
         $(this).css('cursor','pointer');
      }).mouseleave(function() {
         $(this).css('text-decoration', '');
      }).click(function() {
         var id = this.id.split("_");
         var dfid = id[1];
         var pid = id[2];
         var num = id[3];


         // We want to make a chimney popup
         var offset = $(this).offset();

         // Figure out the content
         var val = $('#dataFunctionValue_' + dfid + "_" + pid + "_" + num).val();
         var content = "";

         content += $('#dataFunctionVariableLibrary_' + dfid + "_" + pid + "_" + num).html();
         content += '<input type="text" id="dataFunctionPartValuePopupInput" style="width: 130px;" value="' + val + '">';
         content += '<br/><input type="button" value="update" onclick="dataFunctionValueUpdate(' +
            dfid + ',' +  pid + ',' +  num + ');">';
         content += '<input type="button" value="cancel" onclick="$(\'#contentPopupBlock\').hide();">';

         //$('#contentPopup').html(block).show();

         popupShow(offset.top + 16, offset.left, content);

         // Initialize the content
         $('.dataFunctionPartValueVariableChoice').mouseenter(function() {
            $(this).css('text-decoration', 'underline');
            $(this).css('cursor','pointer');
         }).mouseleave(function() {
            $(this).css('text-decoration', '');
         }).click(function() {
            var id = this.id.split("_");
            var dfid = id[0];
            var pid = id[1];
            var num = id[2];
            var string = id[3];

            dataFunctionValueUpdateWith(dfid, pid, num, string);

            return false;
         });




         return false;

      }).droppable({
         accept: '.contentDatapoint, .datasphereSym, .contentDatasphere, .contentSymbolic, .athandDatapoint',
         tolerance: 'pointer',
         over : function(event, ui) {
            var pointid = ui.helper.attr('id').split("_");
            pointid = pointid[1];
            ui.helper.css('opacity', 0.8);
            $(this).css('background-color', '#aa0000');
         },
         out : function(event, ui) {
            var pointid = ui.helper.attr('id').split("_");
            pointid = pointid[1];
            ui.helper.css('opacity', 0.5);
            $(this).css('background-color', '#888888');
         },


         drop : function(event, ui) {
            if (!ATHANDCUSTOMDROP)
               return;

            $(this).css('background-color', '#888888');

            var pointid = ui.helper.attr('id').split("_");
            var typeid = pointid[0];

            var id = this.id.split("_");
            var dfid = id[1];
            var pid = id[2];
            var num = id[3];


            var type = "";
            var id = 0;

            if (typeid == 'athanddatasphere' ||
               typeid == 'athanddatapoint') {
               id = pointid[2];
               type = "athandpoint";
            } else if (typeid == 'dataspherepoint') {
               id = pointid[1];
               type = "dataspherepoint";
            } else if (typeid == 'dataspheresym') {
               id = pointid[1];
               type = "datasphere";
            } else if (typeid == 'datapoint') {
               id = pointid[1];
               type = "datapoint";
            } else if (typeid == 'datasphere') {
               id = pointid[1];
               type = "datasphere";
            }

            dataFunctionValueDrop(dfid, pid, num, type, id);

            return false;
         }
      });

      $('.dataFunctionPartValueDF').mouseenter(function() {
         $(this).css('text-decoration', 'underline');
         $(this).css('cursor','pointer');
      }).mouseleave(function() {
         $(this).css('text-decoration', '');
      }).click(function() {
         var id = this.id.split("_");
         var dfid = id[1];
         var pid = id[2];
         var num = id[3];

         // We want to make a chimney popup
         var offset = $(this).offset();

         // Figure out the content
         var contentid = 'dataFunctionPartValueDF_' + dfid + '_' + pid + '_' + num;
         var content = '<div id="' + contentid + '">';
         content += $('#dataFunctionPartValueDFLibrary').html();
         content += '</div>';

         var val = $('#dataFunctionValue_' + dfid + "_" + pid + "_" + num).val();
         content += '<br/><input type="text" id="dataFunctionPartValuePopupInput" style="width: 130px;" value="' + val + '">';
         content += '<br/><input type="button" value="update" onclick="dataFunctionValueUpdate(' +
            dfid + ',' +  pid + ',' +  num + ');">';
         content += '<input type="button" value="cancel" onclick="$(\'#contentPopupBlock\').hide();">';



         popupShow(offset.top + 16, offset.left, content);

         // Initialize the content
         $('.dataFunctionPartValueDFChoice').mouseenter(function() {
            $(this).css('text-decoration', 'underline');
            $(this).css('cursor','pointer');
         }).mouseleave(function() {
            $(this).css('text-decoration', '');
         }).click(function() {
            var parent = $(this).parent();

            var pid = parent.attr('id');

            var id = pid.split("_");
            var dfid = id[1];
            var pid = id[2];
            var num = id[3];

            dataFunctionValueUpdateWith(dfid, pid, num, this.id);

            return false;
         });



         return false;
      });


      $('.dataFunctionPartValueText').mouseenter(function() {
         $(this).css('text-decoration', 'underline');
         $(this).css('cursor','pointer');
      }).mouseleave(function() {
         $(this).css('text-decoration', '');
      }).click(function() {
         var id = this.id.split("_");
         var dfid = id[1];
         var pid = id[2];
         var num = id[3];

         // We want to make a chimney popup
         var offset = $(this).offset();

         // Figure out the content
         var val = $('#dataFunctionValue_' + dfid + "_" + pid + "_" + num).val();

         var content = '<textarea id="dataFunctionPartValuePopupInput" style="width: 300px;" rows=\"5\">' + val + '</textarea>';
         content += '<br/><input type="button" value="update" onclick="dataFunctionValueUpdate(' +
            dfid + ',' +  pid + ',' +  num + ');">';
         content += '<input type="button" value="cancel" onclick="$(\'#contentPopupBlock\').hide();">';

         popupShow(offset.top + 16, offset.left, content);

         return false;
      });


      $('.dataFunctionLinkRow').mouseenter(function() {
         var id = this.id.split("_");
         id = id[1];

         var offset = $(this).offset();
         var content = $('#dataFunctionDescription_' + id).html();
         popupShow(offset.top + 16, offset.left, content);
      }).mouseleave(function() {
         popupHide();
      });



      $('.dataFunctionLibraryRow').mouseenter(function() {
         var id = this.id.split("_");
         id = id[1];

         var offset = $(this).offset();
         var content = $('#dataFunctionDescription_' + id).html();
         popupShow(offset.top + 16, offset.left, content);

         $(this).css('cursor','pointer');
      }).mouseleave(function() {
         popupHide();
      }).click(function() {
         var id = this.id.split("_");
         id = id[1];

         atHandBrowse("datafunction", id);
         return false;
      });

      // DF Shares
      $('.originateDataFunctionDisableShare').mouseenter(function() {
         $(this).css('cursor','pointer');
         $(this).css('text-decoration','underline');
      }).mouseleave(function() {
         $(this).css('text-decoration','none');
      }).click(function() {
         dataFunctionShareDisable(this.id);
         return false;
      });

      $('.originateDataFunctionShareLink').mouseenter(function() {
         $(this).css('cursor','pointer');
         $(this).css('text-decoration','underline');
      }).mouseleave(function() {
         $(this).css('text-decoration','none');
      }).click(function() {
         var id = this.id.split("_");
         var hash = id[0];
         var userid = id[1];
         dataFunctionShareUserRemove(hash, userid);
         return false;
      });

      $('.dataFunctionShareLinkRemove').mouseenter(function() {
         $(this).css('cursor','pointer');
         $(this).css('text-decoration','underline');
      }).mouseleave(function() {
         $(this).css('text-decoration','none');
      }).click(function() {
         dataFunctionShareRemoveOwn(this.id);
         return false;
      });


      $('.dfIcon').mouseenter(function() {
         $(this).css('background-color', '#cccccc');
         $(this).css('cursor','pointer');
      }).mouseleave(function() {
         $(this).css('background-color', '#777777');
      });


      $('.deleteIcon').mouseenter(function() {
         $(this).css('background-color', '#cccccc');
         $(this).css('cursor','pointer');
      }).mouseleave(function() {
         $(this).css('background-color', '#777777');
      });

   },

   // Essentially is the same as initializeAtHand without delete
   // and we aim at just the content overlay
   initializeOrganizer : function() {
      var PSSYS = this,
         $ = this.jQuery,
         settings = this.settings;

      $('.athandLink', '#contentOverlay').unbind().mouseenter(function() {
         $(this).css('cursor','pointer');
         $(this).css('text-decoration','underline');
      }).mouseleave(function() {
         $(this).css('text-decoration','none');
      }).click(function() {
         var id = this.id.split(",");
         organizerBrowse(id[1]);
         return false;
      });

      $('.athandLinkButton', '#contentOverlay').unbind().mouseenter(function() {
         $(this).css('cursor','pointer');
         $(this).css('text-decoration','underline');
      }).mouseleave(function() {
         $(this).css('text-decoration','none');
      }).click(function() {
         var id = this.id.split(",");
         organizerBrowse(id[1]);
         return false;
      });

      // Datapoints in the athand spheres
      $('.athandDatapoint', '#contentOverlay').mouseenter(function() {
         $(this).css('cursor','move');
      }).mouseleave(function() {
      }).draggable({
         revert: "invalid",
         cursor: "move",
         appendTo: "body",
         scroll: false,
         helper: function(event, ui) {
            var clone = $(this).clone();
            clone.css('margin', 0);
            clone.css('zIndex', 99);
            clone.css('position', 'absolute');
            clone.attr('id', $(this).attr('id') + "_clone");

            return clone;

         },
         start : function(event, ui) {
            $(this).css('opacity',0.5);

            // Make the dataspheres droppable for organization
            // in the at hand bar. Done in the START area because of
            // something relating to updatepanels?
            // http://stackoverflow.com/questions/1202180/is-there-still-a-bug-in-ie8-with-jquery-droppables
/*
            $('.athandSphere').droppable({
               accept: '.athandDatapoint',
               over : function(event, ui) {
                  if (!$(this).hasClass("athandLinkButtonActive"))
                     $(this).css('background-color', '#ffffff');
               },
               out : function(event, ui) {
                  if (!$(this).hasClass("athandLinkButtonActive"))
                     $(this).css('background-color', '#aaaaaa');

               },
               drop : function(event, ui) {
                  if (!$(this).hasClass("athandLinkButtonActive")) {
                     $(this).css('background-color', '#aaaaaa');

                     // Move this datapoint to the new sphere
                     var id = $(this).attr('id').split(",");
                     var sphereid = parseInt(id[1]);
                     var did = ui.helper.attr("id").split("_");
                     did = did[2];

                     //confirm("Dropping to " + sphereid + " of " + ui.helper.attr("id"));
                     atHandDatapointMove(did, sphereid);
                  }

                  return false;
               }
            });
*/

         },
         drag : function(event, ui) {
            //confirm("Dragging...");
         },
         stop : function(event, ui) {
            //confirm("Stopped");
            $(this).css('opacity',1);

            // Remove ability to drop into the athandSpheres
            //$('.athandSphere').droppable('destroy');
         }
      });

      // Private messaging

      $('.organizerClose').unbind().mouseenter(function() {
         $(this).css('cursor','pointer');
         $(this).css('text-decoration','underline');
      }).mouseleave(function() {
         $(this).css('text-decoration','none');
      }).click(function() {
         contentOverlayClose();
         return false;
      });


   },


   initializeContentDraggable : function() {
      // Make sure you uninitialize all of these during the atHandUnload
      //$('.contentDatapoint,.contentSymbolic,.contentDatasphere').draggable({
      $('.contentDatapoint,.contentSymbolic').draggable({
         revert: "invalid",
         appendTo: "body",
         cursor: "move",
         helper : function(event, ui) {
            var clone = $(this).clone();
            clone.css('margin', 0);
            clone.css('zIndex', 21);
            clone.css('position', 'absolute');
            clone.css('opacity', 0.5);
            clone.attr('id', $(this).attr('id') + "_clone");
            return clone;
         },
         start : function(event, ui) {
            //$(this).css('opacity', 0.5);
         },
         stop : function (event, ui) {
            //$(this).css('opacity', 1);
         }
      });

      // Now make all datapoints inside a content datasphere not draggable
      //$('.contentDatapoint', '.contentDatasphere').draggable("destroy");
/*
      $('.contentDatapoint', '.contentDatasphere').each(function() {
         $(this).draggable("destroy");
      });
*/
   },

   initializeOverlayDroppable : function() {

      // Disable the content droppable
      //$('#content').droppable( "option", "disabled", true);

      // Make the content droppable
      $('#contentOverlay').droppable({
         drop: function(event, ui) {
            var draggable = ui.draggable;
            var helper = ui.helper;

            var dpPosition = ui.offset;

            var contentPosition = $(this).offset();
            var dpPositionT = dpPosition.top - contentPosition.top;
            var dpPositionL = dpPosition.left - contentPosition.left;

            draggable.css('opacity', 1);
            //confirm(helper.attr('id'));

            var dpid = helper.attr('id').split('_');
            var type = dpid[0];  // Enable support for dropping spheres
            dpid = dpid[1];

            // Pass the width and height
            var dpwidth = helper.width();
            var dpheight = helper.height();

            if (confirm("Create new datalink to this datapoint?"))
               datalinkCreate(DATAID, DATATYPE, ui.helper.attr('id'));
         },
         over : function(event, ui) {
            //$(this).css('background-color', '#aeaeae');

            // Change the helper
            var dpid = ui.helper.attr('id').split('_');
            var type = dpid[0];
            dpid = dpid[1];

            $('#' + type + '_thumb_' + dpid, ui.helper).hide();
            $('#' + type + '_default_' + dpid, ui.helper).show();

            
         },
         out : function(event, ui) {
            //ui.helper.css('width', 100);

            // Change the helper back
            var dpid = ui.helper.attr('id').split('_');
            var type = dpid[0];
            dpid = dpid[1];

            $('#' + type + '_default_' + dpid, ui.helper).hide();
            $('#' + type + '_thumb_' + dpid, ui.helper).show();
         },
         accept: ".athandDatapoint"
      });
   },



   initializeContentDroppable : function() {
      // Make the content droppable
      $('#content').droppable({
         drop: function(event, ui) {
            if (!DATALINKCREATABLE && !CONTENTSPAWNABLE)
               return;

            // Do not allow drops when organizer loaded
            if (ORGANIZERLOADED)
               return;

            var draggable = ui.draggable;
            var helper = ui.helper;

            var dpPosition = ui.offset;

            var contentPosition = $(this).offset();
            var dpPositionT = dpPosition.top - contentPosition.top;
            var dpPositionL = dpPosition.left - contentPosition.left;

            draggable.css('opacity', 1);
            //confirm(helper.attr('id'));

            var dpid = helper.attr('id').split('_');
            var type = dpid[0];  // Enable support for dropping spheres
            var athandpointid = dpid[2];

            dpid = dpid[1];

            // Pass the width and height
            var dpwidth = helper.width();
            var dpheight = helper.height();

            if (DATALINKCREATABLE) {
               if (confirm("Create new datalink to this datapoint?"))
                  datalinkCreate(DATAID, DATATYPE, athandpointid);
            } else if (CONTENTSPAWNABLE) {
               if (type == 'athanddatapoint') {
                  // Drop the point into the sphere
                  datasphereAddDatapoint(DATASPHEREID, dpid, dpPositionT, 
                     dpPositionL, dpwidth, dpheight);
               } else if (type == 'athanddatasphere') {
                  // Prompt user if its a sphere link or content

/*
                  var symLink = 0;
                  if (confirm("Do you wish to add as a link?"))
                     symLink = 1;
*/

                  var cmd = "datasphereAddDatasphere(" + DATASPHEREID + 
                     ", " + dpid + ", " +  dpPositionT + ", " +
                     dpPositionL + ", " + dpwidth + ", " + 
                     dpheight + ", ";

                  var cmdLink = cmd + "1);";
                  var cmdEmbed = cmd + "0);";


                  var content = '<div class="promptBlockContainer"><div class="promptBlock">How do you wish to add this datasphere?<br/><br/><input type="button" value="Add as Link" onclick="' + cmdLink + '">&nbsp;<input type="button" value="Embed" onclick="' + cmdEmbed + '">&nbsp;<input type="button" value="Cancel" onclick="datasphereAddDatasphereCancel();"></div></div>';

                  $('#contentOverlayBG').show().animate({ 
                     opacity: 0.8 }, 500, function() {

                     $('#contentOverlay').html('').show().html(content);
                  });

               }
            }
         },
         over : function(event, ui) {
            if (!DATALINKCREATABLE && !CONTENTSPAWNABLE)
               return;

            // Do not allow drops when organizer loaded
            if (ORGANIZERLOADED)
               return;

            //$(this).css('background-color', '#aeaeae');

            // Change the helper
            var dpid = ui.helper.attr('id').split('_');
            var type = dpid[0];
            dpid = dpid[1];

            $('#' + type + '_thumb_' + dpid, ui.helper).hide();
            $('#' + type + '_default_' + dpid, ui.helper).show();
         },
         out : function(event, ui) {
            if (!DATALINKCREATABLE && !CONTENTSPAWNABLE)
               return;

            //ui.helper.css('width', 100);

            // Change the helper back
            var dpid = ui.helper.attr('id').split('_');
            var type = dpid[0];
            dpid = dpid[1];

            $('#' + type + '_default_' + dpid, ui.helper).hide();
            $('#' + type + '_thumb_' + dpid, ui.helper).show();
         },
         accept: ".athandDatapoint"
      });


   },

   initializeContentManage : function() {
      var PSSYS = this,
         $ = this.jQuery,
         settings = this.settings;

      // Add datasphere functionality here to manage
      // Dont unbind since it cauess some heartache
      $('.datapointManage').css({
         'background-color' : '#aeaeae',
         'border' : '1px solid #ff0000'
      }).mouseenter(function() {
         if (RESIZING)
            return;

         // Set the last current Z
         $('.datapointManageCurrent').css('zIndex', MANAGECURRENTZ);

         // Update the current
         $('.datapointManageCurrent').removeClass('datapointManageCurrent');

         // Set this one
         $(this).addClass('datapointManageCurrent');

         MANAGECURRENTZ = $(this).css('zIndex');

         $(this).css('zIndex', 99);

      }).mouseleave(function() {
         if ($(this).hasClass('ui-resizable-resizing') ||
            !$(this).is(":visible") || RESIZING)
            return;

         // Hide all
         //$('.datapointManageOptions').hide();

         // Set the last current Z
         $('.datapointManageCurrent').css('zIndex', MANAGECURRENTZ);

         // Update the current
         $('.datapointManageCurrent').removeClass('datapointManageCurrent');

         // Set this one
         //$(this).addClass('datapointManageCurrent');

         //MANAGECURRENTZ = $(this).css('zIndex');
         MANAGECURRENTZ = 0;
      });

      $('.datapointManageResizable').resizable({
         minHeight: DATAPOINTMINSIZE,
         minWidth : DATAPOINTMINSIZE,
         resize : function(event, ui) {
            var width = ui.size.width;
            var height = ui.size.height;

            // Updated so the manage toggle doesnt change size
            $('img', this).each(function() {
               if (!$(this).parent().hasClass("datapointManageOptionToggle")) {
                  $(this).width(width);
                  $(this).height(height);
               }
            });

            $('.datapoint', this).width(width);
            $('.datapoint', this).height(height);

         },
         start : function(event, ui) {
            RESIZING = true;
         },
         stop : function(event, ui) {
            RESIZING = false;
            //confirm($(this).resizable('option','aspectRatio'));
            var width = Math.round(ui.size.width);
            var height = Math.round(ui.size.height);

            // Updated so the manage toggle doesnt change size
            $('img', this).each(function() {
               if (!$(this).parent().hasClass("datapointManageOptionToggle")) {
                  $(this).width(width);
                  $(this).height(height);
               }
            });


            $('.datapoint', this).width(width);
            $('.datapoint', this).height(height);

            var pointid = this.id.split("_");
            pointid = pointid[1];

            datapointResize(DATASPHEREID, pointid, width, height);
         }
      });

      $('.datapointManageDraggable').mouseenter(function() {
         $(this).css('cursor', 'move');
      }).draggable({
         cancel: ".datapointManageOptionToggle,.datapointManageOptions,.datapointManageOption",
         appendTo: "body",
         cursor: "move",
         helper : function(event, ui) {
            var clone = $(this).clone();
            clone.css('margin', 0);
            clone.css('zIndex', 100);
            clone.css('position', 'absolute');
            clone.attr('id', $(this).attr('id') + "_clone");
            return clone;
         },
         start : function(event, ui) {
            $(this).hide();
         },
         stop : function(event, ui) {
            var pointid = this.id.split("_");
            pointid = pointid[1];

            var contentObj = $('#content');
            var scrolledUp = contentObj.scrollTop();
            var scrolledLeft = contentObj.scrollLeft();

            var offset = $('#content').offset();
            var top = ui.position.top - offset.top + scrolledUp;

            // Check the height of this thing against the top position

            //confirm("Position top: " + ui.position.top + " - " + offset.top + " = " + top);

            if (top <= -1 * $(this).height()) {
               //confirm("stopped dragging but top position is bad");
               confirm("Dragged out of the window. Returning");
               $(this).show();
               return false;
            }

            // Redisplay the original but move the position
            // This is to avoid the "blink" when refreshing
            $(this).css('top', top);
            $(this).css('left', ui.position.left + scrolledLeft);
            $(this).show();

            datapointMove(DATASPHEREID, pointid, top, ui.position.left);
         }
      });

      $('.datapointManageKeepRatio').resizable("option", "aspectRatio", true);

      // Destroy the resizing ability for dataspheres
      $('.datapointManageDatasphere').resizable('destroy');

      // Toggle for the datapoint manage options

      $('.datapointManageOptionToggle').unbind().mouseenter(function() {
         $(this).css('cursor', 'pointer');

         var current = $('img', this).attr("src").split(".");
         var ext = current[1];
         $('img', this).attr("src", "/images/pointspheresmhover." + ext);
      }).mouseleave(function() {
         var current = $('img', this).attr("src").split(".");
         var ext = current[1];
         $('img', this).attr("src", "/images/pointspheresm." + ext);

      }).click(function(event) {
         var id = this.id.split("_");
         id = id[1];

         var options = $('#datapointManageOptions_' + id);

         if (options.is(":visible")) {
            options.hide();
         } else {

            // Figure out where to place the options menu
            var position = $(this).position();
            var width = $(this).width();


            var left = position.left + width;

            // Display the options menu
            options.css('left', left).show();
         }

         return false;
      });

      // Options
      $('.datapointManageOption').mouseenter(function() {
         $(this).css('cursor','pointer');
         $(this).css('text-decoration', 'underline');
      }).mouseleave(function() {
         $(this).css('text-decoration', 'none');
      }).click(function() {
         var id = this.id.split("_");
         var command = id[0];
         var pointid = id[1];

         if (command == 'remove') {
            if (!confirm("Are you sure you wish to remove this datapoint?")) {
               return false;
            } else {
               // Fade it out
               $(this).parent().parent().animate({ opacity : 0.0 }, 500, function() {
                  dataspherePointUpdate(pointid, command);
               });
            }
         } else
            dataspherePointUpdate(pointid, command);

         return false;
      });

   }
};


$(document).ready(function() {
   PSSYS.init(); 
});

function locationHash(hash) {
   document.location.hash = hash;
}

function zeroPad(num, count) {
   var numZeropad = num + '';

   while(numZeropad.length < count)
      numZeropad = "0" + numZeropad;

   return numZeropad;
}

function getSalt() {
   return Math.floor(Math.random()*1000);
}

function evalJSON(responseText) {
   var json = eval('(' + responseText + ')');

   return json;
}

function check(json) {
   var check = parseInt(json.check);
   if (check == 0)
      return false;
                  
   return true;
}                 

function refresh() {
   location.reload(true);
}

function contentOverlayClose() {
   $('#contentOverlay').animate({ opacity: 0.0 }, 500, function() {
      $('#contentOverlay').hide().html('').css('opacity', 1.0);
      $('#contentOverlayBG').hide().css('opacity', 0.0);

      $('#content').droppable( "option", "disabled", false);
      DATALINKCREATABLE = false;
      CONTENTOVERLAYDISPLAYID = 0;

      ORGANIZERLOADED = false
      if (DATASPHEREREQUIREREFRESH) {
         datasphereLoad(DATASPHEREID);
      }
   });
}


function loadingOn() {
   $('#contentLoading').css('opacity', 0).show().animate({ opacity: 1 }, 500, function() {
   });
}

function loadingOff() {
   $('#contentLoading').animate({ opacity: 0 }, 500, function() {
      $(this).hide();
   });
}

//-----------------------
function pmComposeSend() {
   var salt = getSalt();

   var to = escape($('#pmComposeTo').val());
   var subject = escape($('#pmComposeSubject').val());
   var body = escape($('#pmComposeBody').val());

   loadingOn();
   $.post('/ajax_pm.php', { salt : salt, to : to, subject : subject,
         c : "compose", body : body }, function(data) {

      var json = evalJSON(data);

      if (check(json)) {
         confirm("Your message has been sent");
         manageLoad("pms", "sent");
      } else
         confirm("An error occured while sending the message. Ensure the username exists and try again.");

      loadingOff();
   });
}

function pmComposeSendReply(threadid) {
   var salt = getSalt();

   var body = escape($('#pmComposeBody').val());

   loadingOn();
   $.post('/ajax_pm.php', { salt : salt, threadid : threadid,
         c : "reply", body : body }, function(data) {

      var json = evalJSON(data);

      if (check(json)) {
         confirm("Your message has been sent");
         manageLoad("pms", "inbox", "", threadid);
      } else
         confirm("An error occured while sending the message.");
      loadingOff();
   });
}


function pmLoadMessage(type, threadid) {
   manageLoad("pms", type, "", threadid);
}

//-----------------------
function userProfileFieldsUpdate() {
   var salt = getSalt();

   var fn = escape($('#profileFirstName').val());
   var ln = escape($('#profileLastName').val());

   if (fn.length <= 0 || ln.length <= 0) {
      confirm("Invalid name entered");
      return false;
   }

   loadingOn();
   $.post('/ajax_user.php', { salt : salt, fn : fn, ln : ln,
         c : "profilefields" }, function(data) {

      var json = evalJSON(data);

      if (check(json)) {
         confirm("Profile updated");
         manageLoad("user", "profile", "", "");
      } else
         confirm("An error occured while updating. Refresh and try again");
      loadingOff();
   });
}

function userProfileEmailUpdate() {
   var salt = getSalt();

   var email = $('#profileEmail').val();
   var confirmF =$('#profileEmailConfirm').val();

   if (email.length <= 5 || confirmF.length <= 5 || 
      email.length != confirmF.length) {
      confirm("Invalid email entered");
      return false;
   }

   if (email != confirmF) {
      confirm("Email does not match");
      return false;
   }

   $.post('/ajax_user.php', { salt : salt, email : email,
         c : "email" }, function(data) {

      var json = evalJSON(data);

      if (check(json)) {
         confirm("Email updated");
         manageLoad("user", "profile", "", "");
      } else
         confirm("An error occured while updating. Refresh and try again");
   });
}

function userProfilePasswordUpdate() {
   var salt = getSalt();

   var password = md5($('#profilePassword').val());
   var confirmF = md5($('#profilePasswordConfirm').val());
   var minlength = parseInt($('#profilePasswordMin').val());

   if (password.length <= minlength || confirmF.length <= minlength || 
      password.length != confirmF.length) {
      confirm("Invalid password entered");
      return false;
   }

   if (password != confirmF) {
      confirm("Passwords do not match");
      return false;
   }

   $.post('/ajax_user.php', { salt : salt, password : password,
         c : "password" }, function(data) {

      var json = evalJSON(data);

      if (check(json)) {
         confirm("Password updated");
         manageLoad("user", "profile", "", "");
      } else
         confirm("An error occured while updating. Refresh and try again");
   });
}

function userDisplayUpdate() {
   var salt = getSalt();
   var displayid = $('#userDisplaytypeid').val();

   $.post('/ajax_user.php', { salt : salt, displayid : displayid,
         c : "displayupdate" }, function(data) {

      var json = evalJSON(data);

      if (check(json)) {
         confirm("Default display type saved");
         manageLoad("user", "display", "", "");
      } else
         confirm("An error occured while updating. Refresh and try again");
   });
}


//-----------------------

function popupShow(top, left, content) {

   // Update the content and set the offset
   $('#contentPopup').css({ top: top + "px", 
                           left : left + "px"});
   $('#contentPopupContent').html(content);

   // Display block
   $('#contentPopupBlock').show();
}

function popupHide() {
   $('#contentPopupBlock').hide();
}

//-----------------------
function atHandLoad() {
   //confirm("athandheight: " + atHandHeight + "\nHeader: " + headerHeight);

   // Initialize the draggability of the content
   PSSYS.initializeContentDraggable();

   // Initialize the draggability of the Sym
   PSSYS.initializeSym();

   // Prowler content default
   $('.prowlerContainer').each(function() {
      // Go through each and obtain the container id
      // then initialize Prowler
      PSSYS.initializeProwler(this.id);

   });

   // Load the at hand content
   var blank = "";
   atHandBrowse(blank, blank);

   atHandRollDown();

}

function atHandRollDown() {

   // Clear the athand content
   $('#athand').html('');
   ATHANDDISPLAYED = true;

   // Animate the content to move down to the height of the at hand area
   var atHandHeight = $('#athand').outerHeight();
   var headerHeight = $('#header').outerHeight();
   var marginTopValue = atHandHeight + headerHeight;


   $('.contentBody').animate({ marginTop : marginTopValue }, 500, function() {
      // Now fade in the at hand bar
      $('#athand').show().animate({ opacity : 1.0 }, 500, function() {
      });
   });


}

function atHandUnload() {
   // Animate the content to move down to the height of the at hand area
   var headerHeight = $('#header').outerHeight();
   var marginTopValue = headerHeight;

   // Fade out the at hand bar
   $('#athand').animate({ opacity : 0.0 }, 500, function() {
      // Now hide it
      $(this).hide();

      // Now move the content upwards
      $('.contentBody').animate({ marginTop : marginTopValue }, 500, function() {

      });
   });

   // Disable the draggable in the content
   $('.contentDatapoint,.contentDatasphere,.contentSymbolic').draggable("destroy");

   // Disable draggability of the sym
   $('.datasphereSym').draggable("destroy");

   // Disable prowler
   $('.prowlerContentDatapoint').draggable("destroy");

   // Remove dropping into the content
   //$('#content').droppable("destroy");

   CONTENTSPAWNABLE = false;
}

// passes current datasphereid for management pointsphere purposes
function atHandBrowse(section, page) {
   var salt = getSalt();

   loadingOn();

   $.get('/ajax_athand.php', { salt : salt, s : section, dsid : DATASPHEREID, 
                               c : 'load', p : page }, function(data) {

      //confirm("Loading: " + section + "\nPage: " + page + "\n\n" + unescape(data));

      var json = evalJSON(data);

      $('#athand').html(unescape(json.response));

      PSSYS.initializeAtHand();

      var dataspheremanage = parseInt(json.dataspheremanage);

      ATHANDSECTION = section;
      ATHANDPAGE = page;

      // We can drop datapoints into the current content sphere
      if (dataspheremanage == 1)
         CONTENTSPAWNABLE = true;
      else
         CONTENTSPAWNABLE = false;

      var customdrop = parseInt(json.customdrop);

      if (customdrop == 1)
         ATHANDCUSTOMDROP = true;
      else
         ATHANDCUSTOMRDOP = false;

      PSSYS.initializeContentDroppable();
      loadingOff();
   });
}

// Remove a datapoint from the athand bar
function atHandDatapointDelete(athandpointid) {
   var salt = getSalt();

   // Fade the parent
   $('#athandDatapointDelete_' + athandpointid).parent().parent().animate(
      { opacity : 0.0 }, 1000, function() {
      $.get('/ajax_athand.php', { salt : salt, s : ATHANDSECTION, dsid : DATASPHEREID, 
                                  c : 'datapointdelete', p : ATHANDPAGE,
                                  ahpid : athandpointid }, function(data) {
         var json = evalJSON(data);

         if (!check(json))
            confirm("An error occured while removing the datapoint");

         $('#athand').html(unescape(json.response));

         PSSYS.initializeAtHand();
/*
         var dataspheremanage = parseInt(json.dataspheremanage);

         // We can drop datapoints into the current content sphere
         if (dataspheremanage == 1) {
            PSSYS.initializeContentDroppable();
         }
*/

      });
   });
}

// Add a datasphere to the athand bar as a datapoint
function atHandDatasphereSymAdd(datasphereid) {
   var salt = getSalt();

   // Fade the parent
   $.get('/ajax_athand.php', { salt : salt, s : ATHANDSECTION, dsid : DATASPHEREID, 
                               c : 'datasphereadd', p : ATHANDPAGE,
                               dsaddid : datasphereid }, function(data) {
      var json = evalJSON(data);

      if (!check(json))
         confirm("An error occured while adding the datapoint. It may already exist.");

      $('#athand').html(unescape(json.response));

      PSSYS.initializeAtHand();
   });
}

// Add a datapoint from the content bar
function atHandDatapointAdd(datapointid) {
   var salt = getSalt();

   // Fade the parent
   $.get('/ajax_athand.php', { salt : salt, s : ATHANDSECTION, dsid : DATASPHEREID,
                               c : 'datapointadd', p : ATHANDPAGE,
                               dpid : datapointid }, function(data) {
      var json = evalJSON(data);

      if (!check(json))
         confirm("An error occured while adding the datapoint. It may already exist.");

      $('#athand').html(unescape(json.response));

      PSSYS.initializeAtHand();
   });
}


// Add a datapoint from the athand bar
function atHandDataspherepointAdd(dataspherepointid) {
   var salt = getSalt();

   // Fade the parent
   $.get('/ajax_athand.php', { salt : salt, s : ATHANDSECTION, dsid : DATASPHEREID, 
                               c : 'dataspherepointadd', p : ATHANDPAGE,
                               dppid : dataspherepointid }, function(data) {
      var json = evalJSON(data);

      if (!check(json))
         confirm("An error occured while adding the datapoint. It may already exist.");

      $('#athand').html(unescape(json.response));

      PSSYS.initializeAtHand();
   });
}

// Move a datapoint to another sphere
function atHandDatapointMove(athandpointid, athandsphereid) {

   var salt = getSalt();

   // Fade the parent
   $.get('/ajax_athand.php', { salt : salt, s : ATHANDSECTION, dsid : DATASPHEREID, 
                               c : 'datapointmove', p : ATHANDPAGE,
                               ahpid : athandpointid, ahsid : athandsphereid }, 
                               function(data) {
      var json = evalJSON(data);

      if (!check(json))
         confirm("An error occured while moving the datapoint.");

      $('#athand').html(unescape(json.response));

      PSSYS.initializeAtHand();
   });


}

// Add a new organization sphere to the at hand bar
function atHandDatasphereAdd() {
   var salt = getSalt();
   var title = escape($('#athandDatasphereTitle').val());

   // Fade the parent
   $.get('/ajax_athand.php', { salt : salt, dsid : DATASPHEREID, title : title,
                               c : 'athanddatasphereadd', p : ATHANDPAGE 
                             }, function(data) {
      var json = evalJSON(data);

      if (!check(json))
         confirm("An error occured while creating the datasphere.");

      $('#athand').html(unescape(json.response));

      PSSYS.initializeAtHand();

      // Set the page
      ATHANDPAGE = json.page;

   });
}

function atHandDatasphereDelete(athandsphereid) {
   var salt = getSalt();

   // Fade the parent
   $('#athandDatasphereDelete_' + athandsphereid).parent().animate(
      { opacity : 0.0 }, 1000, function() {
      $.get('/ajax_athand.php', { salt : salt, s : ATHANDSECTION, dsid : DATASPHEREID, 
                                  c : 'dataspheredelete', p : ATHANDPAGE,
                                  ahsid : athandsphereid }, function(data) {
         var json = evalJSON(data);

         if (!check(json))
            confirm("An error occured while removing the datasphere");

         $('#athand').html(unescape(json.response));

         PSSYS.initializeAtHand();

         // Set the current at hand page to no sphere id
         ATHANDPAGE = 0;
      });
   });
}





//-----------------------
function originateDatapoint() {
   var typeid = $('#originateDatapointTypeid').val();
   var title = escape($('#originateDatapointTitle').val());
   var content = escape($('#originateDatapointContent').val());
   var salt = getSalt();
   loadingOn();

   $.post('/ajax_originatedatapoint.php', { salt : salt, typeid : typeid,
                            title : title, content : content }, function(data) {
      var json = evalJSON(data);

      if (check(json)) {
         atHandBrowse("organize", "");
      } else
         confirm("An error occured");
      loadingOff();
   });

}

function originateFileUpload() {
/*
   var title = escape($('#originateDatapointTitle').val());
   var salt = getSalt();

   $.post('/ajax_originatedatapoint.php', { salt : salt,
                            title : title, content : content }, function(data) {

   });
*/
}

function originateDatapointFail() {
   confirm("There was a problem during the upload");

}

function originateDatapointSuccess() {
   confirm("Successfully uploaded the file");

   atHandBrowse("organize", "");
}

//-----------------------
// Registration

function trim(str, chars) {
   return ltrim(rtrim(str, chars), chars);
}        
      
function ltrim(str, chars) {
   chars = chars || "\\s";
   return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}           
         
function rtrim(str, chars) {
   chars = chars || "\\s";
   return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function registrationCancel() {
   $('#contentOverlay').animate({ opacity: 0.0 }, 500, function() {
      $('#contentOverlay').hide().html('').css('opacity', 1.0);
      $('#contentOverlayBG').hide().css('opacity', 0.0);
   });
}

function registrationAccept() {
   var salt = getSalt();
   $('#contentOverlay').html('<center>loading...</center>').show();

   $.get('/ajax_register.php', { salt : salt, c : "query" }, function(data) {
      var json = evalJSON(data);

      if (check(json)) {
         $('#contentOverlay').html(json.content);
      } else
         confirm("Registration may not be accepted at this time");
   });

}

function registrationGo() {
   var salt = getSalt();

   var values = "";
   var error = false;

   $('select,input','#registerFields').each(function() {
      var value = trim($(this).val());

      if (value.length < 1) {
         error = true;
         $(this).css('background-color', '#ccaaaa');
      } else
         $(this).css('background-color', '');

      if (values.length)
         values += ",";

      values += $(this).attr('name') + "=" + escape(value);
   });

   if (error) {
      confirm("You must fill out all of the fields with valid input");
      return false;
   }

   $.post('/ajax_register.php', { salt : salt, c : "register",
      values : values }, function(data) {

      var json = evalJSON(data);

      if (check(json)) {
         $('#contentOverlay').html(json.content);
      } else
         confirm("Registration failed. Either you have an error with your input or registration may not be accepted at this time");
   });
}
 

//-----------------------
function prowlerLoad(url, container) {
   var salt = getSalt();

   $('#' + container).html("Loading...");

   $.get('/ajax_prowler.php', { c : "load", salt : salt,
      url : url, container : container }, function(data) {

      var json = evalJSON(data);

      if (check(json)) {
         $('#' + container).html(json.content);
         PSSYS.initializeProwler(container);
      } else
         confirm("Invalid prowler call - URL may not exist");
   });
}

function prowlerImport(content) {
   var salt = getSalt();

   loadingOn();
   $.post('/ajax_prowler.php', { c : "importdp", salt : salt,
      content : escape(content) }, function(data) {

      var json = evalJSON(data);

      if (check(json)) {
         $('#athand').html(unescape(json.response));

         PSSYS.initializeAtHand();
      } else
         confirm("Your attempt to import the datapoint has failed.");
      loadingOff();
   });
}

//-----------------------


function manageLoad(category, section, variable,variablesub) {
   var salt = getSalt();

   loadingOn();
   $.get('/ajax_manage.php', { salt : salt, c : "load", category : category,
      section : section, variable : variable, variablesub : variablesub
      }, function(data) {


      var json = evalJSON(data);
      DATASPHEREREQUIREREFRESH = false;

      if (check(json)) {
         $('#contentOverlay').html(unescape(json.content));
         PSSYS.initializeManage();
      } else
         confirm("Invalid management call");

      loadingOff();
   });
}

function manageToggle(category, section, variable,variablesub, name,obj) {
   var salt = getSalt();

   $.get('/ajax_manage.php', { salt : salt, c : "toggle", category : category,
      section : section, variable : variable, variablesub : variablesub,
      name : name}, function(data) {

      var json = evalJSON(data);

      if (check(json)) {
         // Update the value
         $(obj).html(json.content);

         if (DATASPHEREID)
            DATASPHEREREQUIREREFRESH = true;
      } else
         confirm("Invalid management call");
   });

}

function manageValueEditUpdate(category, section, variable,variablesub, name,obj) {
   var val = $('.manageValueInput', obj).val();

   var salt = getSalt();

   loadingOn();
   $.post('/ajax_manage.php', { salt : salt, c : "editupdate", category : category,
      section : section, variable : variable, variablesub : variablesub,
      val : escape(val), name : name}, function(data) {

      var json = evalJSON(data);

      if (check(json)) {
         // Update the value
         $(obj).hide();
         $('.manageValueEdit',obj.parent()).html(json.content);

         if (DATASPHEREID)
            DATASPHEREREQUIREREFRESH = true;
      } else
         confirm("Invalid management call");
      loadingOff();
   });
}

function manageTextareaEditUpdate(category, section, variable,variablesub, name,obj) {
   var val = $('.manageValueInput', obj).val();

   var salt = getSalt();
   loadingOn();

   $.post('/ajax_manage.php', { salt : salt, c : "editupdate", category : category,
      section : section, variable : variable, variablesub : variablesub,
      val : escape(val), name : name}, function(data) {

      var json = evalJSON(data);

      if (check(json)) {
         confirm("Value updated");

         if (DATASPHEREID)
            DATASPHEREREQUIREREFRESH = true;
      } else
         confirm("Invalid management call");
      loadingOff();
   });
}


//-----------------------
// Manage datapoint
function manageDatapointFileFail() {
   confirm("There was a problem during the upload");

}

function manageDatapointFileSuccess(dpid) {
   confirm("Successfully uploaded the file");

   manageLoad("datapoint", "content", dpid);
   if (DATASPHEREID)
      datasphereLoad(DATASPHEREID, false, true);
}

function datapointBackgroundCSS(dpid) {
   var salt = getSalt();
   var value = escape($('#dpbgcss').val());

   loadingOn();
   $.post('/ajax_datapoint.php', { c : "setbackground", datapointid : dpid,
      salt : salt, value : value}, function(data) {

      var json = evalJSON(data);

      if (check(json)) {
         confirm("Background updated successfully");
         if (DATASPHEREID)
            datasphereLoad(DATASPHEREID, false, true);
      } else {
         $('#manageContentSaveError').html(unescape(json.updateerror)).show();
         //confirm("Update failed. Refresh and try again");
      }
      loadingOff();
   });

}

function datapointManageContentSave(dpid) {
   var salt = getSalt();
   var value = escape($('#datapointManageContent').val());

   loadingOn();
   $.post('/ajax_datapoint.php', { c : "content", datapointid : dpid,
      salt : salt, value : value}, function(data) {

      //confirm(data);

      var json = evalJSON(data);

      if (check(json)) {
         confirm("Content updated successfully");
         if (DATASPHEREID)
            datasphereLoad(DATASPHEREID, false, true);
      } else {
         $('#manageContentSaveError').html(unescape(json.updateerror)).show();
         //confirm("Update failed. Refresh and try again");
      }
      loadingOff();
   });
}


function datapointDeleteBackground(dpid) {
   if (!confirm("Are you sure you wish to delete the background?"))
      return;

   var salt = getSalt();
   loadingOn();

   $.post('/ajax_datapoint.php', { c : "deletebackground", datapointid : dpid,
      salt : salt}, function(data) {

      var json = evalJSON(data);

      if (check(json)) {
         manageLoad("datapoint", "datapointbackground", dpid);
      } else
         confirm("Delete failed. Refresh and try again");

      loadingOff();
   });
}

function datapointManageTitleSave(dpid) {
   var salt = getSalt();
   var value = escape($('#datapointManageTitle').val());
   loadingOn();

   $.post('/ajax_datapoint.php', { c : "title", datapointid : dpid,
      salt : salt, value : value}, function(data) {

      var json = evalJSON(data);

      if (check(json)) {
         confirm("Title updated successfully");

         if (DATASPHEREID)
            datasphereLoad(DATASPHEREID, false, true);
      } else
         confirm("Update failed. Refresh and try again");
      loadingOff();
   });
}

function datapointManageDelete(dpid) {
   var salt = getSalt();

   if (!confirm("Are you SURE?"))
      return false;

   $.post('/ajax_datapoint.php', { c : "delete", datapointid : dpid,
      salt : salt } , function(data) {

      var json = evalJSON(data);

      if (check(json)) {
         confirm("Datapoint has been deleted");
         if (DATASPHEREID)
            datasphereLoad(DATASPHEREID, false);
      } else
         confirm("Delete failed. Refresh and try again");
   });

}

function datapointPermissionAdd(dpid) {
   var values = "";
   // Obtain all of the fields
   $('select,input','.manageDatapointPermissionsAdd').each(function() {
      if (values.length)
         values += ",";

      values += $(this).attr('name') + "=" + $(this).val();
   });

   values = escape(values);
   var salt = getSalt();

   $.post('/ajax_datapointpermissions.php', {
      values : values, c : "new", dpid : dpid }, function(data) {

      var json = evalJSON(data);

      if (check(json)) {

         $('#contentOverlay').html(json.content);
         PSSYS.initializeManage();

      } else
         confirm("An error occured while attempting to set permissions");
   });
}


function datapointPermissionUpdate(dpid) {
   var values = "";
   // Obtain all of the fields
   $('select,input','.manageDatapointPermissionsAdd').each(function() {
      if (values.length)
         values += ",";

      values += $(this).attr('name') + "=" + $(this).val();
   });

   values = escape(values);
   var salt = getSalt();

   $.post('/ajax_datapointpermissions.php', { 
      values : values, c : "update", dpid : dpid }, function(data) {

      var json = evalJSON(data);

      if (check(json)) {

         $('#contentOverlay').html(json.content);
         PSSYS.initializeManage();

      } else
         confirm("An error occured while attempting to set permissions");
   });
}



function datapointPermissionDelete(dpid) {
   if (!confirm("Are you sure you wish to delete this permission rule?"))
      return false;

   var values = "";
   // Obtain all of the fields
   $('select,input','.manageDatapointPermissionsAdd').each(function() {
      if (values.length)
         values += ",";

      values += $(this).attr('name') + "=" + $(this).val();
   });

   values = escape(values);
   var salt = getSalt(dpid);

   $.post('/ajax_datapointpermissions.php', { 
      values : values, c : "delete", dpid : dpid }, function(data) {

      var json = evalJSON(data);

      if (check(json)) {

         $('#contentOverlay').html(json.content);
         PSSYS.initializeManage();

      } else
         confirm("An error occured while attempting to set permissions");
   });
}

function datapointDFPermissionAdd(dpid) {
   var values = "";
   // Obtain all of the fields
   $('select,input','.manageDatafunctionPermissionsForm').each(function(pid) {
      if (values.length)
         values += ",";

      values += $(this).attr('name') + "=" + $(this).val();
   });

   values = escape(values);
   var salt = getSalt();

   $.post('/ajax_datafunctionpermissions.php', { category : "datapoint",
      values : values, c : "new", dpid : dpid }, function(data) {


      var json = evalJSON(data);

      if (check(json)) {

         $('#contentOverlay').html(json.content);
         PSSYS.initializeManage();

      } else
         confirm("An error occured while attempting to set permissions");
   });
}


function datapointDFPermissionUpdate(dpid) {
   var values = "";
   // Obtain all of the fields
   $('select,input','.manageDatafunctionPermissionsForm').each(function() {

      if (values.length)
         values += ",";

      values += $(this).attr('name') + "=" + $(this).val();
   });

   values = escape(values);
   var salt = getSalt();

   $.post('/ajax_datafunctionpermissions.php', { category : "datapoint",
      values : values, c : "update", dpid : dpid }, function(data) {

      var json = evalJSON(data);

      if (check(json)) {
         $('#contentOverlay').html(json.content);
         PSSYS.initializeManage();

      } else
         confirm("An error occured while attempting to set permissions");
   });
}

function datapointDFPermissionDelete(dpid) {
   if (!confirm("Are you sure you wish to delete this permission rule?"))
      return false;

   var values = "";
   // Obtain all of the fields
   $('select,input','.manageDatafunctionPermissionsForm').each(function() {
      if (values.length)
         values += ",";

      values += $(this).attr('name') + "=" + $(this).val();
   });

   values = escape(values);
   var salt = getSalt();

   $.post('/ajax_datafunctionpermissions.php', { category : "datapoint",
      values : values, c : "delete", dpid : dpid }, function(data) {


      var json = evalJSON(data);

      if (check(json)) {

         $('#contentOverlay').html(json.content);
         PSSYS.initializeManage();

      } else
         confirm("An error occured while attempting to set permissions");
   });
}

function datapointDFDelete(dfaid, dpid) {
   if (!confirm("Are you sure you wish to delete this dataFunction assignment?"))
      return false;

   var salt = getSalt();

   $.post('/ajax_datafunctionpermissions.php', { category : "datapoint",
      c : "deleteassignment", dfaid : dfaid, dpid : dpid }, function(data) {

      var json = evalJSON(data);

      if (check(json)) {
         $('#contentOverlay').html(json.content);
         PSSYS.initializeManage();
      } else
         confirm("An error occured while attempting to set permissions");
   });
}



//-----------------------
function dataqueryWizardAddPart(queryid) {
   var values = "";
   $('input,select','.dataqueryWizardPartNew').each(function() {
      if (values.length)
         values += ",";

      values += $(this).attr('name') + "=" + $(this).val();
   });

   values = escape(values);
   var salt = getSalt();
   loadingOn();

   $.post('/ajax_dataquery.php', { c : "addpart", values : values,
      qid : queryid, salt : salt, dsid : DATASPHEREID }, function(data) {

      var json = evalJSON(data);

      if (check(json)) {
         $('#originateDataqueryWizardBlock').html(json.content);
         PSSYS.initializeAtHand();

         if (parseInt(json.ispublished) == 1)
            datasphereLoad(DATASPHEREID, false, false);
      } else
         confirm("Invalid option or value");
      loadingOff();
   });
}

function dataqueryWizardRemovePart(queryid, partid) {
   if (!confirm("Are you sure you wish to remove this part of the dataquery?"))
      return;

   var salt = getSalt();

   $('#dataqueryWizard_' + queryid + '_' + partid).animate({ opacity : 0.0 }, 500, 
      function() {

      $(this).remove();

      $.post('/ajax_dataquery.php', { c : "removepart", pid : partid,
         salt : salt, qid : queryid }, function(data) {

         var json = evalJSON(data);

         if (check(json)) {
            $('#originateDataqueryWizardBlock').html(json.content);
            PSSYS.initializeAtHand();

            if (parseInt(json.ispublished) == 1)
               datasphereLoad(DATASPHEREID, false, false);
         } else
            confirm("There was an error attempting to remove this part of the dataquery.");
      });
   });
}

function dataqueryWizardToggleBit(queryid, partid) {
   var salt = getSalt();
   loadingOn();

   $.post('/ajax_dataquery.php', { c : "togglebit", pid : partid,
      salt : salt, qid : queryid }, function(data) {

      var json = evalJSON(data);

      if (check(json)) {
         $('#dataqueryWizardBit_' + queryid + "_" + partid).html(json.content);

         if (parseInt(json.ispublished) == 1)
            datasphereLoad(DATASPHEREID, false, false);
      } else
         confirm("There was an error attempting to remove this part of the dataquery.");
      loadingOff();
   });
}

function updateDataqueryFromWizard(queryid) {
   var salt = getSalt();

   var title = escape($('#originateDataqueryTitle').val());

   if (title.length == 0) {
      confirm("Please enter a title for the dataquery");
      return;
   }

   loadingOn();
   $.post('/ajax_dataquery.php', { c : "updatefromwizard", title : title,
      dqid : queryid, salt : salt }, function(data) {


      var json = evalJSON(data);

      if (check(json)) {
         confirm("Dataquery has been updated");

         // Brought to the freefloating area
         datasphereLoad(DATASPHEREID, false, false);
      } else
         confirm("There was an error updating this dataquery.");
      loadingOff();
   });
}


function updateDataqueryFromSyntax(queryid) {
   var salt = getSalt();

   var title = escape($('#originateDataqueryTitle').val());

   if (title.length == 0) {
      confirm("Please enter a title for the dataquery");
      return;
   }

   var syntax = escape($('#originateDataquerySyntax').val());
   loadingOn();

   $.post('/ajax_dataquery.php', { c : "updatefromsyntax", title : title,
      dqid : queryid, syntax : syntax, salt : salt }, function(data) {

      var json = evalJSON(data);

      if (check(json)) {
         confirm("Dataquery has been updated");

         // Brought to the freefloating area
         datasphereLoad(DATASPHEREID, false, false);
      } else
         confirm("There was an error updating this dataquery.");
      loadingOff();
   });
}


function originateDataqueryFromSyntax() {
   var salt = getSalt();

   var title = escape($('#originateDataqueryTitle').val());

   if (title.length == 0) {
      confirm("Please enter a title for the dataquery");
      return;
   }

   var syntax = escape($('#originateDataquerySyntax').val());
   loadingOn();

   $.post('/ajax_dataquery.php', { c : "originatefromsyntax", title : title,
      syntax : syntax, salt : salt }, function(data) {

      var json = evalJSON(data);

      if (check(json)) {
         // Show confirmation in area
         $('#originateDataquerySyntaxBlock').html('Dataquery has been created');
         // Brought to the freefloating area
         datasphereLoad(json.datasphereid, false, false);
      } else
         confirm("There was an error originating this dataquery.");

      loadingOff();
   });
}

function originateDataqueryFromWizard() {
   var salt = getSalt();

   var title = escape($('#originateDataqueryTitle').val());

   if (title.length == 0) {
      confirm("Please enter a title for the dataquery");
      return;
   }

   loadingOn();

   $.post('/ajax_dataquery.php', { c : "originatefromwizard", title : title,
      salt : salt }, function(data) {

      var json = evalJSON(data);

      if (check(json)) {
         $('#originateDataqueryWizardBlock').html('Dataquery has been created');

         datasphereLoad(json.datasphereid, false, false);
      } else
         confirm("There was an error originating this dataquery.");
      loadingOff();
   });

}

//---------------------------------------
function avatarUpload() {

}

function avatarUploadFail() {
   confirm("Avatar failed to update. Possible wrong extension or invalid file.");
}

function avatarUploadSuccess(type, id, isUser) {
   if (isUser)
      manageLoad("user", "avatar");
   else
      manageLoad(type, type + "avatar", id);
}

//---------------------------------------
function dpbgUploadFail() {
   confirm("Background failed to update. Possible wrong extension or invalid file.");
}

function dpbgUploadSuccess(dpid) {
   manageLoad("datapoint", "datapointbackground", dpid);
}


//---------------------------------------
// dataFunctions
function dataFunctionShareCreate(datafunctionid) {
   var salt = getSalt();

   // Obtain the value
   var expire = parseInt($('#originateDataFunctionShareLinkExpire').val());

   $.get('/ajax_datafunction.php', { c : "sharecreate", dfid : datafunctionid,
      expire : expire, salt : salt }, function(data) {

      var json = evalJSON(data);

      if (check(json)) {
         $('#originateDataFunction_share').html(unescape(json.content));
         PSSYS.initializeAtHand();
      } else
         confirm("There was an error creating a share link.");
   });
}

function dataFunctionShareDisable(hash) {
   var salt = getSalt();

   $.get('/ajax_datafunction.php', { c : "sharedisable",
      hash : hash, salt : salt }, function(data) {

      var json = evalJSON(data);

      if (check(json)) {
         $('#originateDataFunction_share').html(unescape(json.content));
         PSSYS.initializeAtHand();
         confirm("Share has been updated");
      } else
         confirm("There was an error disabling this share link.");
   });
}

function dataFunctionShareRemoveOwn(hash) {
   var salt = getSalt();

   if (!confirm("Are you sure you wish to remove this dataFunction link?"))
      return false

   $.get('/ajax_datafunction.php', { c : "shareownremove", 
      hash : hash, salt : salt }, function(data) {

      var json = evalJSON(data);

      if (check(json)) {
         atHandBrowse("originate", "datafunction_library");
      } else
         confirm("There was an error removing this dataFunction link.");
   });
}


function dataFunctionShareUserRemove(hash, userid) {
   var salt = getSalt();

   if (!confirm("Are you sure you wish to remove this dataFunction from this user's library?"))
      return false

   $.get('/ajax_datafunction.php', { c : "shareuserremove", userid : userid,
      hash : hash, salt : salt }, function(data) {

      var json = evalJSON(data);

      if (check(json)) {
         $('#originateDataFunction_share').html(unescape(json.content));
         PSSYS.initializeAtHand();
      } else
         confirm("There was an error disabling the user for the share link.");
   });
}

function dataFunctionShareLinkCreate(hash) {
   var salt = getSalt();

   $('#dataFunctionShareLinkBlock').html("Validating...");

   $.get('/ajax_datafunction.php', { c : "sharelinkcreate", 
      hash : hash, salt : salt }, function(data) {

      var json = evalJSON(data);

      if (check(json)) {
         $('#dataFunctionShareLinkBlock').html("Successfully added dataFunction to library");
      } else {
         $('#dataFunctionShareLinkBlock').html("Error!");
         confirm("There was an error adding this dataFunction to your library. May already exist?");
      }
   });
}


function dataFunctionPartMove(datafunctionid, partid, offset) {
   var salt = getSalt();

   $.get('/ajax_datafunction.php', { c : "movepart", dfid : datafunctionid,
      partid : partid, salt : salt, offset : offset }, function(data) {

      var json = evalJSON(data);

      if (check(json)) {
         $('#originateDataFunctionBlock').html(unescape(json.content));
         PSSYS.initializeAtHand();
      } else
         confirm("There was an error moving the part.");
   });
}

function dataFunctionPartDelete(datafunctionid, partid) {
   var salt = getSalt();

   $.get('/ajax_datafunction.php', { c : "removepart", dfid : datafunctionid,
      partid : partid, salt : salt }, function(data) {

      var json = evalJSON(data);

      if (check(json)) {
         $('#originateDataFunctionBlock').html(unescape(json.content));
         PSSYS.initializeAtHand();
      } else
         confirm("There was an error deleting a part from this dataFunction.");
   });
}

function dataFunctionPartAdd(datafunctionid, type) {
   var salt = getSalt();

   // Obtaint he id
   var dftypeid = $('#originateDataFunctionOptions_' + type).val();

   $.get('/ajax_datafunction.php', { c : "addpart", dfid : datafunctionid,
      type : type, dftypeid : dftypeid, salt : salt }, function(data) {

      var json = evalJSON(data);

      if (check(json)) {
         $('#originateDataFunction_' + type).html(unescape(json.content));
         PSSYS.initializeAtHand();
      } else
         confirm("There was an error adding this part to this dataFunction.");
   });
}

function dataFunctionValueUpdateWith(datafunctionid, partid, num, value) {
   var salt = getSalt();

   value = escape(value);
   loadingOn();

   $.get('/ajax_datafunction.php', { c : "updatevalue", dfid : datafunctionid,
      partid : partid, value : value, num : num, salt : salt }, function(data) {

      var json = evalJSON(data);

      if (check(json)) {
         $('#originateDataFunctionBlock').html(unescape(json.content));
         PSSYS.initializeAtHand();

         popupHide();
      } else
         confirm("Incorrect value type or invalid variable used.");
      loadingOff();
   });
}


function dataFunctionValueUpdate(datafunctionid, partid, num) {
   var salt = getSalt();

   // Obtain the avlue
   var value = escape($('#dataFunctionPartValuePopupInput').val());
   loadingOn();

   $.get('/ajax_datafunction.php', { c : "updatevalue", dfid : datafunctionid,
      partid : partid, value : value, num : num, salt : salt }, function(data) {

      var json = evalJSON(data);

      if (check(json)) {
         $('#originateDataFunctionBlock').html(unescape(json.content));
         PSSYS.initializeAtHand();

         popupHide();
      } else
         confirm("Incorrect value type or invalid variable used.");
      loadingOff();
   });
}

function dataFunctionValueDrop(datafunctionid, partid, num, droptype, dropid) {
   var salt = getSalt();

   $.get('/ajax_datafunction.php', { c : "valuedrop", dfid : datafunctionid,
      partid : partid, droptype : droptype, dropid : dropid, num : num, 
      salt : salt }, function(data) {

      var json = evalJSON(data);

      if (check(json)) {
         $('#originateDataFunctionBlock').html(unescape(json.content));
         PSSYS.initializeAtHand();

         popupHide();
      } else
         confirm("Incorrect type dropped in.");
   });
}

function dataFunctionPublish(datafunctionid) {
   var salt = getSalt();

   loadingOn();
   $.get('/ajax_datafunction.php', { c : "publish", dfid : datafunctionid,
      salt : salt }, function(data) {

      var json = evalJSON(data);

      if (check(json)) {
         confirm("dataFunction has been published.");
         // browse to the at hand area for dF library
         atHandBrowse("originate", "datafunction_library");
      } else
         confirm("Failed to originate dataFunction. Possible values still needed.");
      loadingOff();
   });
}

function dataFunctionTitle(datafunctionid) {
   var salt = getSalt();

   var title = escape($('#originateDataFunctionTitle').val());

   $.get('/ajax_datafunction.php', { c : "settitle", dfid : datafunctionid,
      title : title, salt : salt }, function(data) {

      var json = evalJSON(data);

      if (check(json)) {
         confirm("dataFunction title has been saved.");
         $('#originateDataFunction_title').html(unescape(json.content));
      } else
         confirm("Failed to set the title. Refresh and try again.");
   });
}


function dataFunctionDelete(datafunctionid) {
   var salt = getSalt();

   if (!confirm("Are you sure you wish to delete this dataFunction?"))
      return;

   $.get('/ajax_datafunction.php', { c : "delete", dfid : datafunctionid,
      salt : salt }, function(data) {

      var json = evalJSON(data);

      if (check(json)) {
         confirm("dataFunction has been deleted.");

         // browse to the at hand area for dF library
         atHandBrowse("originate", "datafunction_library");
      } else
         confirm("Failed to delete dataFunction. Refresh and try again.");
   });
}

// We are running dfid on object type with id of id
function dataFunctionRun(datafunctionaid, type, id) {
   var salt = getSalt();
   loadingOn();

   $.get('/ajax_datafunction.php', { c : "run", dfaid : datafunctionaid,
      objtype : type, objid : id, salt : salt }, function(data) {

      var json = evalJSON(data);

      if (check(json)) {
         confirm("Successfully ran dataFunction.");
      } else
         confirm("Failed to run dataFunction. May not have passed dataFunction checks.");
      loadingOff();
   });
}




//---------------------------------------
// Organizer

function organizerLoad() {

   // Fade in the overlay
   $('#contentOverlayBG').show().animate({ opacity: 0.8 }, 500, function() {
      $('#contentOverlay').html('').show();

      ORGANIZERLOADED = true;
      organizerBrowse("");
   });
}

function organizerUnload() {

}

function organizerBrowse(page) {
   var salt = getSalt();

   // Now load the data
   $.get('/ajax_organizer.php', { p : page, salt : salt }, function(data) {
      var json = evalJSON(data);

      if (check(json)) {
         $('#contentOverlay').html(json.content);

         // Initialize the organizer
         PSSYS.initializeOrganizer();

      } else
         confirm("There was an error obtaining the athand information.");
   });


}

//-----------------------
// Manage a datapoint
function datapointResize(datasphereid, pointid, width, height) {
   if (width < DATAPOINTMINSIZE || height < DATAPOINTMINSIZE) {
      confirm("Must be larger than " + DATAPOINTMINSIZE + " pixels");
      return false;
   } 

   var salt = getSalt();

   $.get('/ajax_datasphere.php', { salt : salt, c : "resizepoint", pid : pointid,
      dsid : datasphereid, width : width, height : height }, function(data) {

      var json = evalJSON(data);
         
      if (check(json)) { 
         // Check if we need to refresh everything
         if (parseInt(json.refreshonupdate) == 1) {
            $('#content').html(json.content);

         // Replace the resized object with a new one
         } else
            $('#dataspherepoint_' + pointid).replaceWith(json.point);

         PSSYS.initializeContentManage();
      } else {
         confirm("There was an error resizing this datapoint. Try refreshing the page and trying again.");
      }
            
   });

}

function datapointMove(datasphereid, pointid, top, left) {
   var salt = getSalt();

   $.get('/ajax_datasphere.php', { salt : salt, c : "movepoint", pid : pointid,
      dsid : datasphereid, top : top, left: left }, function(data) {

      var json = evalJSON(data);
         
      if (check(json)) { 
         // Replace the resized object with a new one
         $('#dataspherepoint_' + pointid).replaceWith(json.point);


         PSSYS.initializeContentManage();
      } else {
         confirm("There was an error moving this datapoint. Try refreshing the page and trying again.");
      }
            
   });
}

function datapointOptionLoad(pointid, type, command) {
   var salt = getSalt();

   if (command == "showrelevant") {
      //$('#content').droppable( "option", "disabled", true);

      // Show the relevant data
      // We need to fade in the overlay content
      $('#contentOverlayBG').show().animate({ opacity: 0.8 }, 500, function() {
         $('#contentOverlay').html('').show();
         datalinkGetRelevant(pointid, type, 0); // 0 for default display type
      });
   } else if (command == 'deletelink') {
      if (confirm("Are you sure you wish to remove this dataLink?")) {
         // Obtain the actual link and then go to that link
         $.post('/ajax_admin.php', { salt : salt, c : "deletelink",
            pitcherid : DATAID, pitchertype : DATATYPE,
            catchertype : type, catcherid : pointid }, function(data) {

            var json = evalJSON(data);

            if (check(json)) {
               datalinkGetRelevant(DATAID, DATATYPE, CONTENTOVERLAYDISPLAYID);
            } else
               confirm("There was an error trying to view this point");

         });

      }

   } else if (command == 'view') {
      loadingOn();
      // Obtain the actual link and then go to that link
      $.get('/ajax_view.php', { salt : salt, c : "getlink",
         type : type, pointid : pointid }, function(data) {

         var json = evalJSON(data);

         if (check(json)) {
            location.href = json.href;

         } else
            confirm("There was an error trying to view this point");

         loadingOff();
      });

   } else
      confirm(command + " " + type + " " + pointid);
}

var DATAPOINTOPTIONSHOVERING = [];
var DATAPOINTOPTIONSTIMEOUTS = [];

function datapointOptionClose(id) {
   var options = $('#' + id);

   if (DATAPOINTOPTIONSHOVERING[id] == 1)
      return;

   if (options.is(":visible")) {
      options.hide();
   }

}

//----------------------
// Datalinks
function datalinkCreate(pitcherid, pitchertype, athandpointid) {
   var salt = getSalt();

   loadingOn();
   $.get('/ajax_datalink.php', { salt : salt, pitcherid : pitcherid,
                           pitchertype : pitchertype, ahpid : athandpointid,
                           displaytypeid : CONTENTOVERLAYDISPLAYID, 
                           c : "create"}, function(data) {

      var json = evalJSON(data);

      if (check(json)) {
         $('#contentOverlay').html(json.content);
         // Initialize all of the content that appears
         PSSYS.initializeContent();

         // Dont need to check about datalinkcreatable
         PSSYS.initializeContentDroppable();
      } else
         confirm("An error occured. The link may already exist");
      loadingOff();
   });
}

function datalinkGetRelevant(pointid, type, displaytypeid) {
   // Now load the data
   var salt = getSalt();
   loadingOn();

   $.get('/ajax_datalink.php', { salt : salt, dspid : pointid, c : "browse",
      displaytypeid : displaytypeid, dsid : DATASPHEREID, type : type }, 
      function(data) {

      var json = evalJSON(data);
         
      if (check(json)) { 
         // Replace the content with the new content returned in the json
         $('#contentOverlay').html(json.content);

         // Set the current datapoint id to assign links to it
         DATAID = json.id;
         DATATYPE = json.type;

         CONTENTOVERLAYDISPLAYID = json.displaytypeid;

         // Initialize all of the content that appears
         PSSYS.initializeContent();

         // If we have permissions to add datalinks, manage content
         if (parseInt(json.managedatalinks) == 1)
            DATALINKCREATABLE = true;
         else
            DATALINKCREATABLE = false;

         PSSYS.initializeContentDroppable();

      }
      loadingOff();

   });

}

//----------------------
function originateDatasphere(type) {
   var typeid = $('#originateDatasphereDisplaytypeid').val();
   var title = escape($('#originateDatasphereTitle').val());
   var content = escape($('#originateDatasphereContent').val());


   var salt = getSalt();

   $.post('/ajax_originatedatasphere.php', { salt : salt, displaytypeid : typeid,
                           content : content, type: type, 
                           title : title }, function(data) {
      var json = evalJSON(data);

      if (check(json)) {
         // GO to the datasphere and signal the manage
         // only manage if we can manage this type (ie queries, we cannot)
         datasphereLoad(json.datasphereid, parseInt(json.manage) == 1, false);
      } else
         confirm("An error occured");
   });

}



//-----------------------
// Add a datapoint to a datasphere
// Provide the datapointid and the drop coordinates
function datasphereAddDatapoint(datasphereid, datapointid, top, left, width, height) {
   var salt = getSalt();
   loadingOn();

   $.get('/ajax_datasphere.php', { salt : salt, c : "adddatapoint", dpid : datapointid,
      dsid : datasphereid, top : top, left : left, width : width, height : height }, function(data) {

      var json = evalJSON(data);
         
      if (parseInt(json.check) == 1) { 
         // Replace the content with the new content returned in the json
         $('#content').html(json.content);

         // initialize management
         if (parseInt(json.manage) == 1) {
            PSSYS.initializeContentManage();

            // Toggle managing the datasphere
            datasphereManaging(true);
         } else
            PSSYS.initializeContent();

      } else if (parseInt(json.check) == 2) { 
         // Load it
         $('#contentOverlayBG').show().animate({ opacity: 0.8 }, 500, function() {
            $('#contentOverlay').html('').show().html(json.content);

         });

      } else {
         confirm("There was an error adding the datapoint to the sphere. Try refreshing the page and trying again.");
      }
            
      loadingOff();
   });
}

function datasphereAddDatasphereCancel() {
   $('#contentOverlay').animate({ opacity: 0.0 }, 500, function() {
      $('#contentOverlay').hide().html('').css('opacity', 1.0);
      $('#contentOverlayBG').hide().css('opacity', 0.0);
   });
}


function datasphereAddDatasphere(tosphereid, datasphereid, top, left, width, height, symLink) {
   var salt = getSalt();

   // Hide the overlay
   datasphereAddDatasphereCancel();

   loadingOn();
   $.get('/ajax_datasphere.php', { salt : salt, c : "adddatasphere", dsid : tosphereid,
      symid : datasphereid, top : top, left : left, symlink : symLink,
      width : width, height : height }, function(data) {

      var json = evalJSON(data);
         
      if (check(json)) { 
         // Replace the content with the new content returned in the json
         $('#content').html(json.content);

         // initialize management
         if (parseInt(json.manage) == 1) {
            PSSYS.initializeContentManage();

            // Toggle managing the datasphere
            datasphereManaging(true);
         } else
            PSSYS.initializeContent();


      } else if (parseInt(json.check) == 2) { 
         // Load it
         $('#contentOverlayBG').show().animate({ opacity: 0.8 }, 500, function() {
            $('#contentOverlay').html('').show().html(json.content);
         });



      } else {
         confirm("There was an error adding the datapoint to the sphere. Try refreshing the page and trying again.");
      }
      loadingOff();
   });
}



// Load a datasphere
function datasphereLoad(datasphereid, manage, leaveoverlay) {
   manage = (manage) ? 1 : 0;

   if ($('#contentOverlay').is(':visible') && !leaveoverlay)
      contentOverlayClose();

   $('#datasphereOptionsOverlay').hide();

   datastreamStop(datasphereid);
   var salt = getSalt();

   // If the datasphereid is not the same one, we kill the display id
   if (datasphereid != DATASPHEREID) {
      DATASPHEREDISPLAYID = 0;
      DATASPHERESORTMETHOD = 0;
   }

   loadingOn();

   $.get('/ajax_datasphere.php', { salt : salt, c : "load", manage : manage,
      sortmethod : DATASPHERESORTMETHOD, displayid : DATASPHEREDISPLAYID, 
      dsid : datasphereid }, function(data) {
   
      var json = evalJSON(data);
         
      if (check(json)) { 
         // Loaded the datasphere
         DATASPHEREID = datasphereid;

         // Replace the content with the new content returned in the json
         $('#content').html(unescape(json.content));

         // Update the currently viewed datasphere Sym
         // If we are viewing a datasphereLabel then update it...
         if (!$('.datasphereLabel').hasClass('datasphereSym')) {
            $('.datasphereLabel').addClass('datasphereSym');

            $('.datasphereSym').html('<span id="datasphereSymAction">Viewing</span> <span id="datasphereSymTitle"></span>');
            $('.datasphereSym').attr('id', "dataspheresym_" + datasphereid);
         }

         $('#datasphereSymTitle').html(json.title);
         $('.datasphereSym').attr('id', "dataspheresym_" + datasphereid);

         locationHash("/sphere/" + json.name);

         $('#headerOptions').html(unescape(json.options));

         PSSYS.initializeLayout();

         // initialize management if we have permissions
         if (manage == 1 && parseInt(json.manage) == 1) {
            PSSYS.initializeContentManage();

            // Set the manage option at the top to enabled
            datasphereManaging(true);
         } else {
            // If the athand bar is out, initialize the draggable to it
            if (ATHANDDISPLAYED)
               PSSYS.initializeContentDraggable();

            PSSYS.initializeContent();
            datasphereManaging(false);
         }

         loadingOff();
      } else {
         confirm("There was an error loading the datasphere. Try refreshing the page and trying again.");
      }
            
      loadingOff();
   });
}

function datasphereManaging(enabled) {
   if (enabled) {

      // Set the manage option at the top to enabled
      $('.datasphereSym').css('background-color', '#ff0000');
      $('#datasphereSymAction').html("Managing");
      $('#headerOption_manage').html("View datasphere");
      DATASPHEREMANAGING = true;
   } else {
      DATASPHEREMANAGING = false;
      $('.datasphereSym').css('background-color', '#555555');
      $('#datasphereSymAction').html("Viewing");
      $('#headerOption_manage').html("Manage datasphere");
   }
}

// Update a datasphere point
function dataspherePointUpdate(pointid, command) {
   var salt = getSalt();

   loadingOn();
   $.get('/ajax_dataspherepoint.php', { salt : salt, c : command,
      dsid : DATASPHEREID, pid : pointid }, function(data) {

      var json = evalJSON(data);
         
      if (check(json)) { 
         // Replace the content with the new content returned in the json
         $('#content').html(json.content);

         // Initialize the content to manage
         PSSYS.initializeContentManage();
      } else {
         confirm("There was an error loading the datasphere. Try refreshing the page and trying again.");
      }
            
      loadingOff();
   });
}

function datasphereDelete(datasphereid) {
   var salt = getSalt();

   $.get('/ajax_datasphere.php', { salt : salt, c : "delete", 
      dsid : datasphereid }, function(data) {

      var json = evalJSON(data);

      if (check(json)) {
         datasphereLoad(json.defaultds, false, true);
      } else {
         confirm("There was an error while attempting to delete the datasphere");
      }
   });
}

function dataspherePermissionAdd(dsid) {
   var values = "";
   // Obtain all of the fields
   $('select,input','.manageDataspherePermissionsAdd').each(function() {
      if (values.length)
         values += ",";

      values += $(this).attr('name') + "=" + $(this).val();
   });

   values = escape(values);
   var salt = getSalt();

   $.post('/ajax_dataspherepermissions.php', {
      values : values, c : "new", dsid : DATASPHEREID }, function(data) {

      var json = evalJSON(data);

      if (check(json)) {

         $('#contentOverlay').html(json.content);
         PSSYS.initializeManage();

      } else
         confirm("An error occured while attempting to set permissions");
   });
}


function dataspherePermissionUpdate(dsid) {
   var values = "";
   // Obtain all of the fields
   $('select,input','.manageDataspherePermissionsAdd').each(function() {
      if (values.length)
         values += ",";

      values += $(this).attr('name') + "=" + $(this).val();
   });

   values = escape(values);
   var salt = getSalt();

   $.post('/ajax_dataspherepermissions.php', { 
      values : values, c : "update", dsid : DATASPHEREID }, function(data) {

      var json = evalJSON(data);

      if (check(json)) {

         $('#contentOverlay').html(json.content);
         PSSYS.initializeManage();

      } else
         confirm("An error occured while attempting to set permissions");
   });
}



function dataspherePermissionDelete(dsid) {
   if (!confirm("Are you sure you wish to delete this permission rule?"))
      return false;

   var values = "";
   // Obtain all of the fields
   $('select,input','.manageDataspherePermissionsAdd').each(function() {
      if (values.length)
         values += ",";

      values += $(this).attr('name') + "=" + $(this).val();
   });

   values = escape(values);
   var salt = getSalt();

   $.post('/ajax_dataspherepermissions.php', { 
      values : values, c : "delete", dsid : DATASPHEREID }, function(data) {

      var json = evalJSON(data);

      if (check(json)) {

         $('#contentOverlay').html(json.content);
         PSSYS.initializeManage();

      } else
         confirm("An error occured while attempting to set permissions");
   });
}


function datasphereDFPermissionAdd() {
   var values = "";
   // Obtain all of the fields
   $('select,input','.manageDatafunctionPermissionsForm').each(function() {
      if (values.length)
         values += ",";

      values += $(this).attr('name') + "=" + $(this).val();
   });

   values = escape(values);
   var salt = getSalt();

   $.post('/ajax_datafunctionpermissions.php', { category : "datasphere",
      values : values, c : "new", dsid : DATASPHEREID }, function(data) {

      var json = evalJSON(data);

      if (check(json)) {

         $('#contentOverlay').html(json.content);
         PSSYS.initializeManage();

      } else
         confirm("An error occured while attempting to set permissions");
   });
}


function datasphereDFPermissionUpdate() {
   var values = "";
   // Obtain all of the fields
   $('select,input','.manageDatafunctionPermissionsForm').each(function() {

      if (values.length)
         values += ",";

      values += $(this).attr('name') + "=" + $(this).val();
   });

   values = escape(values);
   var salt = getSalt();

   $.post('/ajax_datafunctionpermissions.php', { category : "datasphere",
      values : values, c : "update", dsid : DATASPHEREID }, function(data) {

      var json = evalJSON(data);

      if (check(json)) {
         $('#contentOverlay').html(json.content);
         PSSYS.initializeManage();

      } else
         confirm("An error occured while attempting to set permissions");
   });
}

function datasphereDFPermissionDelete() {
   if (!confirm("Are you sure you wish to delete this permission rule?"))
      return false;

   var values = "";
   // Obtain all of the fields
   $('select,input','.manageDatafunctionPermissionsForm').each(function() {
      if (values.length)
         values += ",";

      values += $(this).attr('name') + "=" + $(this).val();
   });

   values = escape(values);
   var salt = getSalt();

   $.post('/ajax_datafunctionpermissions.php', { category : "datasphere",
      values : values, c : "delete", dsid : DATASPHEREID }, function(data) {


      var json = evalJSON(data);

      if (check(json)) {

         $('#contentOverlay').html(json.content);
         PSSYS.initializeManage();

      } else
         confirm("An error occured while attempting to set permissions");
   });
}

function datasphereDFDelete(dfaid) {
   if (!confirm("Are you sure you wish to delete this dataFunction assignment?"))
      return false;

   var salt = getSalt();

   $.post('/ajax_datafunctionpermissions.php', { category : "datasphere",
      c : "deleteassignment", dfaid : dfaid, dsid : DATASPHEREID }, function(data) {

      var json = evalJSON(data);

      if (check(json)) {
         $('#contentOverlay').html(json.content);
         PSSYS.initializeManage();

      } else
         confirm("An error occured while attempting to set permissions");
   });
}

function datasphereUpdateType() {
   var salt = getSalt();

   // Display type id
   var value = $('#manageDatasphereType').val();

   loadingOn();

   $.get('/ajax_datasphere.php', { c : "spheretype", salt : salt,
      dsid : DATASPHEREID, displayid : value }, function(data) {

      var json = evalJSON(data);

      if (check(json)) {
         confirm("Display type set");
         manageLoad("datasphere", "spheretype", DATASPHEREID, "");
         datasphereLoad(DATASPHEREID, false, true);
      } else
         confirm("An error occured while attempting set display type");
   });
}

function datasphereStreamSetDurations() {
   var salt = getSalt();

   var values = "";
   // Obtain all of the fields
   var fail = false;
   $('input','#datasphereStreamDurations').each(function() {

      if ($(this).attr('name') == 'submit')
         return;

      if ($(this).val().length) {
         // Fix any non numbers?
         var num = parseInt($(this).val());

         if (num <= 0 || isNaN(num)) {
            confirm("Invalid input detected. Durations must either be greater than 0 or blank");
            fail = true;
            return false;
         }
      }

      if (values.length)
         values += ",";

      values += $(this).attr('name') + "=" + $(this).val();
   });

   if (fail)
      return false;

   values = escape(values);

   $.post('/ajax_datasphere.php', { values : values, c : "streamdurations", 
      dsid : DATASPHEREID }, function(data) {

      var json = evalJSON(data);

      if (check(json)) {
         confirm("Durations have been saved");
         datasphereLoad(DATASPHEREID, false, true);
      } else
         confirm("An error occured while attempting to save stream durations");
   });
}

function datasphereManageAvatarShowTitleSave() {
   var value = $('#manageAvatarShowTitle').is(':checked') ? 1 : 0;
   var salt = getSalt();

   $.post('/ajax_datasphere.php', { salt : salt, c : "avatarshowtitle", 
      value : value, dsid : DATASPHEREID }, function(data) {

      var json = evalJSON(data);
         
      if (check(json) == 1) { 
         confirm("Setting saved");
      } else {
         confirm("There was an error saving the setting. Refresh and try again");
      }
            
   });

}

function datasphereChangeSort() {
   var newsort = $('#datasphereSortMethodValue').val();
   var salt = getSalt();

   DATASPHERESORTMETHOD = newsort;
   datasphereLoad(DATASPHEREID, false, false);
}

function datasphereChangeSortCancel() {
   $('#datasphereOptionsOverlay').hide();
}

//-----------------------
function datasphereStreamPointsPerMinute() {
   // How many thumbs do we have?
   var panels = 0;
   $('li', '#datasphereStreamDurations').each(function() {
      panels++;
   });

   // Now get the value
   var perMinute = parseFloat($('#datasphereStreamPPMValue').val());
   var secondsPerPanel = Math.round(60.0 / perMinute * 100) / 100;

   $('li', '#datasphereStreamDurations').each(function() {
      $('input', this).each(function() {
         $(this).val(secondsPerPanel);
      });
   });
}

function datastreamLoad(datasphereid, number) {
   var last = (number - 1 > 0) ? number - 1 : DATASTREAMPANELCOUNT[datasphereid];
   var next = (number + 1 > DATASTREAMPANELCOUNT[datasphereid]) ? 1 : number + 1;

   $('#dataStream_' + datasphereid + "_" + last).hide();
/*
   $('#dataStream_' + datasphereid + "_" + number).show();
   $('#dataStreamCount_' + datasphereid).html(number + " / " + DATASTREAMPANELCOUNT[datasphereid]);
*/
   datastreamShow(datasphereid, number);

   if (last == number)
      return;

   var delay = DATASTREAMPANELDURATION[datasphereid][number] * 1000;
   DATASTREAMLASTTIMEOUT[datasphereid] = setTimeout('datastreamLoad(' + datasphereid + 
      ',' + next + ')', delay);

}

function datastreamStop(datasphereid) {
   clearTimeout(DATASTREAMLASTTIMEOUT[datasphereid]);

   DATASTREAMLASTTIMEOUT[datasphereid] = 0;

   $('#dataStreamStop_' + datasphereid).html("[start]");
}

function datastreamStart(datasphereid) {
   clearTimeout(DATASTREAMLASTTIMEOUT[datasphereid]);
   var i = 1;
   var current = 1;
   for (i; i <= DATASTREAMPANELCOUNT[datasphereid]; i++) {
      if ($('#dataStream_' + datasphereid + "_" + i).is(":visible")) {
         current = i;
         break;
      }
   }

   var next = (current + 1 > DATASTREAMPANELCOUNT[datasphereid]) ? 1 : current + 1;
   var delay = DATASTREAMPANELDURATION[datasphereid][current] * 1000;
   DATASTREAMLASTTIMEOUT[datasphereid] = setTimeout('datastreamLoad(' + datasphereid + 
      ',' + current + ')', delay);
   $('#dataStreamStop_' + datasphereid).html("[stop]");
}

function datastreamHideCurrent(datasphereid) {
   // Hide any visible
   var i = 1;
   var current = 1;
   for (i; i <= DATASTREAMPANELCOUNT[datasphereid]; i++) {
      if ($('#dataStream_' + datasphereid + "_" + i).is(":visible")) {
         current = i;
         $('#dataStream_' + datasphereid + "_" + i).hide();
      }
   }

   return current;
}

function datastreamShow(datasphereid, i) {
   $('#dataStream_' + datasphereid + "_" + i).show();
   $('#dataStreamCount_' + datasphereid).html(i + " / " + 
      DATASTREAMPANELCOUNT[datasphereid]);
}

function datasphereAddToManyCancel() {
   $('#contentOverlay').animate({ opacity: 0.0 }, 500, function() {
      $('#contentOverlay').hide().html('').css('opacity', 1.0);
      $('#contentOverlayBG').hide().css('opacity', 0.0);
   });
}

function datasphereAddToMany(type, typeid, symlink, width, height) {
   var salt = getSalt();
   var targets = "";

   $(':checkbox','.promptBlock').each(function() {
      if (targets.length)
         targets += ",";

      var value = 0;

      if ($(this).is(':checked'))
         value = 1;

      targets += $(this).attr('name') + "=" + value;
   });

   loadingOn();

   $.post('/ajax_datasphere.php', { salt : salt, c : "addtomany", type : type,
      typeid : typeid, symlink : symlink, targets : targets, dsid : DATASPHEREID,
      width : width, height : height }, function(data) {


      var json = evalJSON(data);
         
      if (check(json) == 1) { 
         $('#contentOverlay').animate({ opacity: 0.0 }, 500, function() {
            $('#contentOverlay').hide().html('').css('opacity', 1.0);
            $('#contentOverlayBG').hide().css('opacity', 0.0);
         });
      } else {
         confirm("There was an error adding the datapoint to the datasphere(s). Try refreshing the page and trying again.");
      }
            
      loadingOff();
   });

}

//-----------------------
function loginQuery() {
   var un = escape($('#loginun').val()); 
   var pw = md5($('#loginpw').val());

   var rm = $('#loginrememberme').attr('checked') ? 1 : 0;

   $('#loginResponse').html("verifying...");
   $('#loginsubmit').attr('disabled', true);

   var salt = getSalt();

   $.get('/ajax_loginquery.php', { salt : salt, rm : rm, un : un, pw : pw }, function(data) {
      var json = evalJSON(data);
         
      $('#loginResponse').html(json.response);
         
      if (check(json)) { 
         setTimeout("refresh()", 1000);
      } else
         $('#loginsubmit').attr('disabled', false);
            
   });
}

function loginCancel() {
   $('#loginBlock').hide();
}

//-----------------------

function quicksearchGo() {
   var query = trim($('#quicksearchquery').val());

   location.href = "/search.php?query=" + query;
}

//-----------------------

function md5(str) {
   var xl;
 
   var RotateLeft = function(lValue, iShiftBits) {
      return (lValue<<iShiftBits) | (lValue>>>(32-iShiftBits));
   };
 
   var AddUnsigned = function(lX,lY) {
      var lX4,lY4,lX8,lY8,lResult;
      lX8 = (lX & 0x80000000);
      lY8 = (lY & 0x80000000);
      lX4 = (lX & 0x40000000);
      lY4 = (lY & 0x40000000);
      lResult = (lX & 0x3FFFFFFF)+(lY & 0x3FFFFFFF);
      if (lX4 & lY4) {
         return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
      }
      if (lX4 | lY4) {
         if (lResult & 0x40000000) {
            return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
         } else {
            return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
         }
      } else {
         return (lResult ^ lX8 ^ lY8);
      }
   };
 
   var F = function(x,y,z) { return (x & y) | ((~x) & z); };
   var G = function(x,y,z) { return (x & z) | (y & (~z)); };
   var H = function(x,y,z) { return (x ^ y ^ z); };
   var I = function(x,y,z) { return (y ^ (x | (~z))); };
 
   var FF = function(a,b,c,d,x,s,ac) {
      a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac));
      return AddUnsigned(RotateLeft(a, s), b);
   };
 
   var GG = function(a,b,c,d,x,s,ac) {
      a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac));
      return AddUnsigned(RotateLeft(a, s), b);
   };
 
   var HH = function(a,b,c,d,x,s,ac) {
      a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac));
      return AddUnsigned(RotateLeft(a, s), b);
   };
 
   var II = function(a,b,c,d,x,s,ac) {
      a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac));
      return AddUnsigned(RotateLeft(a, s), b);
   };
 
   var ConvertToWordArray = function(str) {
      var lWordCount;
      var lMessageLength = str.length;
      var lNumberOfWords_temp1=lMessageLength + 8;
      var lNumberOfWords_temp2=(lNumberOfWords_temp1-(lNumberOfWords_temp1 % 64))/64;
      var lNumberOfWords = (lNumberOfWords_temp2+1)*16;
      var lWordArray=Array(lNumberOfWords-1);
      var lBytePosition = 0;
      var lByteCount = 0;
      while ( lByteCount < lMessageLength ) {
         lWordCount = (lByteCount-(lByteCount % 4))/4;
         lBytePosition = (lByteCount % 4)*8;
         lWordArray[lWordCount] = (lWordArray[lWordCount] | (str.charCodeAt(lByteCount)<<lBytePosition));
         lByteCount++;
      }
      lWordCount = (lByteCount-(lByteCount % 4))/4;
      lBytePosition = (lByteCount % 4)*8;
      lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80<<lBytePosition);
      lWordArray[lNumberOfWords-2] = lMessageLength<<3;
      lWordArray[lNumberOfWords-1] = lMessageLength>>>29;
      return lWordArray;
   };
 
   var WordToHex = function(lValue) {
      var WordToHexValue="",WordToHexValue_temp="",lByte,lCount;
      for (lCount = 0;lCount<=3;lCount++) {
         lByte = (lValue>>>(lCount*8)) & 255;
         WordToHexValue_temp = "0" + lByte.toString(16);
         WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length-2,2);
      }
      return WordToHexValue;
   };
 
   var x=Array();
   var k,AA,BB,CC,DD,a,b,c,d;
   var S11=7, S12=12, S13=17, S14=22;
   var S21=5, S22=9 , S23=14, S24=20;
   var S31=4, S32=11, S33=16, S34=23;
   var S41=6, S42=10, S43=15, S44=21;
 
   str = utf8_encode(str);
   x = ConvertToWordArray(str);
   a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476;
   
   xl = x.length;
   for (k=0;k<xl;k+=16) {
      AA=a; BB=b; CC=c; DD=d;
      a=FF(a,b,c,d,x[k+0], S11,0xD76AA478);
      d=FF(d,a,b,c,x[k+1], S12,0xE8C7B756);
      c=FF(c,d,a,b,x[k+2], S13,0x242070DB);
      b=FF(b,c,d,a,x[k+3], S14,0xC1BDCEEE);
      a=FF(a,b,c,d,x[k+4], S11,0xF57C0FAF);
      d=FF(d,a,b,c,x[k+5], S12,0x4787C62A);
      c=FF(c,d,a,b,x[k+6], S13,0xA8304613);
      b=FF(b,c,d,a,x[k+7], S14,0xFD469501);
      a=FF(a,b,c,d,x[k+8], S11,0x698098D8);
      d=FF(d,a,b,c,x[k+9], S12,0x8B44F7AF);
      c=FF(c,d,a,b,x[k+10],S13,0xFFFF5BB1);
      b=FF(b,c,d,a,x[k+11],S14,0x895CD7BE);
      a=FF(a,b,c,d,x[k+12],S11,0x6B901122);
      d=FF(d,a,b,c,x[k+13],S12,0xFD987193);
      c=FF(c,d,a,b,x[k+14],S13,0xA679438E);
      b=FF(b,c,d,a,x[k+15],S14,0x49B40821);
      a=GG(a,b,c,d,x[k+1], S21,0xF61E2562);
      d=GG(d,a,b,c,x[k+6], S22,0xC040B340);
      c=GG(c,d,a,b,x[k+11],S23,0x265E5A51);
      b=GG(b,c,d,a,x[k+0], S24,0xE9B6C7AA);
      a=GG(a,b,c,d,x[k+5], S21,0xD62F105D);
      d=GG(d,a,b,c,x[k+10],S22,0x2441453);
      c=GG(c,d,a,b,x[k+15],S23,0xD8A1E681);
      b=GG(b,c,d,a,x[k+4], S24,0xE7D3FBC8);
      a=GG(a,b,c,d,x[k+9], S21,0x21E1CDE6);
      d=GG(d,a,b,c,x[k+14],S22,0xC33707D6);
      c=GG(c,d,a,b,x[k+3], S23,0xF4D50D87);
      b=GG(b,c,d,a,x[k+8], S24,0x455A14ED);
      a=GG(a,b,c,d,x[k+13],S21,0xA9E3E905);
      d=GG(d,a,b,c,x[k+2], S22,0xFCEFA3F8);
      c=GG(c,d,a,b,x[k+7], S23,0x676F02D9);
      b=GG(b,c,d,a,x[k+12],S24,0x8D2A4C8A);
      a=HH(a,b,c,d,x[k+5], S31,0xFFFA3942);
      d=HH(d,a,b,c,x[k+8], S32,0x8771F681);
      c=HH(c,d,a,b,x[k+11],S33,0x6D9D6122);
      b=HH(b,c,d,a,x[k+14],S34,0xFDE5380C);
      a=HH(a,b,c,d,x[k+1], S31,0xA4BEEA44);
      d=HH(d,a,b,c,x[k+4], S32,0x4BDECFA9);
      c=HH(c,d,a,b,x[k+7], S33,0xF6BB4B60);
      b=HH(b,c,d,a,x[k+10],S34,0xBEBFBC70);
      a=HH(a,b,c,d,x[k+13],S31,0x289B7EC6);
      d=HH(d,a,b,c,x[k+0], S32,0xEAA127FA);
      c=HH(c,d,a,b,x[k+3], S33,0xD4EF3085);
      b=HH(b,c,d,a,x[k+6], S34,0x4881D05);
      a=HH(a,b,c,d,x[k+9], S31,0xD9D4D039);
      d=HH(d,a,b,c,x[k+12],S32,0xE6DB99E5);
      c=HH(c,d,a,b,x[k+15],S33,0x1FA27CF8);
      b=HH(b,c,d,a,x[k+2], S34,0xC4AC5665);
      a=II(a,b,c,d,x[k+0], S41,0xF4292244);
      d=II(d,a,b,c,x[k+7], S42,0x432AFF97);
      c=II(c,d,a,b,x[k+14],S43,0xAB9423A7);
      b=II(b,c,d,a,x[k+5], S44,0xFC93A039);
      a=II(a,b,c,d,x[k+12],S41,0x655B59C3);
      d=II(d,a,b,c,x[k+3], S42,0x8F0CCC92);
      c=II(c,d,a,b,x[k+10],S43,0xFFEFF47D);
      b=II(b,c,d,a,x[k+1], S44,0x85845DD1);
      a=II(a,b,c,d,x[k+8], S41,0x6FA87E4F);
      d=II(d,a,b,c,x[k+15],S42,0xFE2CE6E0);
      c=II(c,d,a,b,x[k+6], S43,0xA3014314);
      b=II(b,c,d,a,x[k+13],S44,0x4E0811A1);
      a=II(a,b,c,d,x[k+4], S41,0xF7537E82);
      d=II(d,a,b,c,x[k+11],S42,0xBD3AF235);
      c=II(c,d,a,b,x[k+2], S43,0x2AD7D2BB);
      b=II(b,c,d,a,x[k+9], S44,0xEB86D391);
      a=AddUnsigned(a,AA);
      b=AddUnsigned(b,BB);
      c=AddUnsigned(c,CC);
      d=AddUnsigned(d,DD);
   }
 
   var temp = WordToHex(a)+WordToHex(b)+WordToHex(c)+WordToHex(d);
 
   return temp.toLowerCase();
}

function utf8_encode(string) {
   string = (string+'').replace(/\r\n/g, "\n").replace(/\r/g, "\n");
 
   var utftext = "";
   var start, end;
   var stringl = 0;
 
   start = end = 0;
   stringl = string.length;
   for (var n = 0; n < stringl; n++) {
      var c1 = string.charCodeAt(n);
      var enc = null;
 
      if (c1 < 128) {
         end++;
      } else if((c1 > 127) && (c1 < 2048)) {
         enc = String.fromCharCode((c1 >> 6) | 192) + String.fromCharCode((c1 & 63) | 128);
      } else {
         enc = String.fromCharCode((c1 >> 12) | 224) + String.fromCharCode(((c1 >> 6) & 63) | 128) + String.fromCharCode((c1 & 63) | 128);
      }
      if (enc != null) {
         if (end > start) {
            utftext += string.substring(start, end);
         }
         utftext += enc;
         start = end = n+1;
      }
   }
 
   if (end > start) {
      utftext += string.substring(start, string.length);
   }
 
   return utftext;
} 


