FLUIDIMAGECACHE = [];
MINPASSWORDLENGTH = 6;

(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;});
         }
      });
   });

   $.preLoadImagesFromArray = function(images) {
      var args_len = images.length;
      for (var i = 0; i < args_len; i++) {
         var cacheImage = document.createElement('img');
         cacheImage.src = images[i];
         FLUIDIMAGECACHE.push(cacheImage);
      }
   }


   $.preLoadImages = function() {
      var args_len = arguments.length;
      for (var i = args_len; i--;) {
         var cacheImage = document.createElement('img');
         cacheImage.src = arguments[i];
         FLUIDIMAGECACHE.push(cacheImage);
      }
   }

   $.extend($.fn.loading = function() {
      $(this).html("<center><img src=\"/images/loading.gif\"></center>");
   });

   $.extend($.fn.cornered = function() {
      $(this).append('<div class="corner cornerTL"></div><div class="corner cornerTR">' +
         '</div><div class="corner cornerBL"></div><div class="corner cornerBR"></div>');
   });

   $.extend($.fn.cornerbordered = function() {
      var contents = $(this).html();

      $(this).html('<div class="cornerBTB"></div><div class="cornerBBody">' +
         contents + '</div><div class="cornerBTB"></div><div class="corner cornerBTL">' +
         '</div><div class="corner cornerBTR"></div><div class="corner cornerBBL">' + 
         '</div><div class="corner cornerBBR"></div>');
   });

/*

   // Define all object functions here
   var ncLoaderFunctions = {
      init : function(options) { 
         //$.extend( ncLoaderFunctions, options );
      },
      test : function() {
         confirm("TEST");
      }
   };

   $.extend($.fn.ncload = function( method ) {
    
      // Method calling logic
      if ( ncLoaderFunctions[method] ) {
         return ncLoaderFunctions[ method ].apply( 
            this, Array.prototype.slice.call( arguments, 1 )
         );
      } else if ( typeof method === 'object' || ! method ) {
         return ncLoaderFunctions.init.apply( this, arguments );
      } else {
         $.error( 'Method ' +  method + ' does not exist on jQuery.ncLoad' );
      }    
   });
*/



})();

// Ajaxfileupload

jQuery.extend({
   

    createUploadIframe: function(id, uri)
   {
         //create frame
            var frameId = 'jUploadFrame' + id;
            var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"';
         if(window.ActiveXObject)
         {
                if(typeof uri== 'boolean'){
               iframeHtml += ' src="' + 'javascript:false' + '"';

                }
                else if(typeof uri== 'string'){
               iframeHtml += ' src="' + uri + '"';

                } 
         }
         iframeHtml += ' />';
         jQuery(iframeHtml).appendTo(document.body);

            return jQuery('#' + frameId).get(0);         
    },
    createUploadForm: function(id, fileElementId, data)
   {
      //create form  
      var formId = 'jUploadForm' + id;
      var fileId = 'jUploadFile' + id;
      var form = jQuery('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');   
      if(data)
      {
         for(var i in data)
         {
            jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);
         }        
      }     
      var oldElement = jQuery('#' + fileElementId);
      var newElement = jQuery(oldElement).clone();
      jQuery(oldElement).attr('id', fileId);
      jQuery(oldElement).before(newElement);
      jQuery(oldElement).appendTo(form);


      
      //set attributes
      jQuery(form).css('position', 'absolute');
      jQuery(form).css('top', '-1200px');
      jQuery(form).css('left', '-1200px');
      jQuery(form).appendTo('body');      
      return form;
    },

    ajaxFileUpload: function(s) {
        // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout     
        s = jQuery.extend({}, jQuery.ajaxSettings, s);
        var id = new Date().getTime()        
      var form = jQuery.createUploadForm(id, s.fileElementId, (typeof(s.data)=='undefined'?false:s.data));
      var io = jQuery.createUploadIframe(id, s.secureuri);
      var frameId = 'jUploadFrame' + id;
      var formId = 'jUploadForm' + id;    
        // Watch for a new set of requests
        if ( s.global && ! jQuery.active++ )
      {
         jQuery.event.trigger( "ajaxStart" );
      }            
        var requestDone = false;
        // Create the request object
        var xml = {}   
        if ( s.global )
            jQuery.event.trigger("ajaxSend", [xml, s]);
        // Wait for a response to come back
        var uploadCallback = function(isTimeout)
      {        
         var io = document.getElementById(frameId);
            try 
         {           
            if(io.contentWindow)
            {
                xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
                   xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
                
            }else if(io.contentDocument)
            {
                xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
                  xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
            }                 
            }catch(e)
         {
            jQuery.handleError(s, xml, null, e);
         }
            if ( xml || isTimeout == "timeout") 
         {           
                requestDone = true;
                var status;
                try {
                    status = isTimeout != "timeout" ? "success" : "error";
                    // Make sure that the request was successful or notmodified
                    if ( status != "error" )
               {
                        // process the data (runs the xml through httpData regardless of callback)
                        var data = jQuery.uploadHttpData( xml, s.dataType );    
                        // If a local callback was specified, fire it and pass it the data
                        if ( s.success )
                            s.success( data, status );
    
                        // Fire the global callback
                        if( s.global )
                            jQuery.event.trigger( "ajaxSuccess", [xml, s] );
                    } else
                        jQuery.handleError(s, xml, status);
                } catch(e) 
            {
                    status = "error";
                    jQuery.handleError(s, xml, status, e);
                }

                // The request was completed
                if( s.global )
                    jQuery.event.trigger( "ajaxComplete", [xml, s] );

                // Handle the global AJAX counter
                if ( s.global && ! --jQuery.active )
                    jQuery.event.trigger( "ajaxStop" );

                // Process result
                if ( s.complete )
                    s.complete(xml, status);

                jQuery(io).unbind()

                setTimeout(function()
                           {  try 
                              {
                                 jQuery(io).remove();
                                 jQuery(form).remove();  
                                 
                              } catch(e) 
                              {
                                 jQuery.handleError(s, xml, null, e);
                              }                          

                           }, 100)

                xml = null

            }
        }
        // Timeout checker
        if ( s.timeout > 0 ) 
      {
            setTimeout(function(){
                // Check to see if the request is still happening
                if( !requestDone ) uploadCallback( "timeout" );
            }, s.timeout);
        }
        try 
      {

         var form = jQuery('#' + formId);
         jQuery(form).attr('action', s.url);
         jQuery(form).attr('method', 'POST');
         jQuery(form).attr('target', frameId);
            if(form.encoding)
         {
            jQuery(form).attr('encoding', 'multipart/form-data');             
            }
            else
         {  
            jQuery(form).attr('enctype', 'multipart/form-data');        
            }        
            jQuery(form).submit();

        } catch(e) 
      {        
            jQuery.handleError(s, xml, null, e);
        }
      
      jQuery('#' + frameId).load(uploadCallback );
        return {abort: function () {}};   

    },

    uploadHttpData: function( r, type ) {
        var data = !type;
        data = type == "xml" || data ? r.responseXML : r.responseText;
        // If the type is "script", eval it in global context
        if ( type == "script" )
            jQuery.globalEval( data );
        // Get the JavaScript object, if JSON is used.
        if ( type == "json" )
            eval( "data = " + data );
        // evaluate scripts within html
        if ( type == "html" )
            jQuery("<div>").html(data).evalScripts();

        return data;
    }
})



var FORMCHECK = {
   isValidPassword : function(input) {
      var val = trim(input.val());

      if (val.length >= 5)
         FORMCHECK.setValid(input);
      else
         FORMCHECK.setInvalid(input);
   },

   hasInput : function(input) {
      var val = trim(input.val());

      if (val.length >= 1)
         FORMCHECK.setValid(input);
      else
         FORMCHECK.setInvalid(input);
   },

   isValidEmail : function(input) {
      var email = input.val();

      if (FORMCHECK.emailSyntaxIsValid(email))
         FORMCHECK.setValid(input);
      else
         FORMCHECK.setInvalid(input);
   },

   emailSyntaxIsValid : function(email) {

      var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
      return pattern.test(email);
   },

   confirmEmail : function(input) {
      var email = $('#formValue_email').val();
      var value = input.val();

      if (value.indexOf(email) >= 0 && email.length == value.length)
         FORMCHECK.setValid(input);
      else
         FORMCHECK.setInvalid(input);
   },

   setValid : function(input) {
      var idParts = input.attr("id").split("_");
      var id = idParts[1];

      if (!$('#formCheck_' + id).is(":hidden"))
         return;

      $('#formCheck_' + id).css('opacity',0).show().animate(
         {opacity : 1.0},500);
   },

   setInvalid : function(input) {

      var idParts = input.attr("id").split("_");
      var id = idParts[1];

      if ($('#formCheck_' + id).is(":hidden"))
         return;

      $('#formCheck_' + id).animate(
         {opacity : 0.0},500,function() {
         $(this).hide();
      });
   }
}

var SOCIAL = {
   getRecentPosts : function(listingid) {

      var longOutput = 0;
      var contentBody = "#socialPostsContent";
      if ($('#socialPostsFullBlock').length > 0) {
         longOutput = 1;
         contentBody = "#socialPostsFullBlock";
      }

      var firstPost = $('.socialPostRow:first',contentBody);

      var lpi = 0;

      if (firstPost.length > 0) {
         lpi = firstPost.attr("id").split("_");
         lpi = lpi[1];
      }

      var salt = getSalt();


      $.get('/ajax_social.php', { salt : salt, lpi : lpi, listingid : 
         listingid, longoutput : longOutput, c : 'getrecentposts' }, 
         function(data) {

         var json = evalJSON(data);

         if (check(json)) {
            $('#socialStartSharing').hide();

            // Prepend the content to the social posts block
            $(contentBody).prepend(unescape(json.content));

            $('#socialPostsContent').css("top", "0px");
            $('#socialPostsScrollerDrag').css("top", "0px");


            // Now make the first ones visible
            $('.socialPostRow:hidden', contentBody).css(
               "opacity", 0).show().animate({ opacity : 1 }, 500, function() {

               SOCIAL.init();
            });
         }
      });

   },

   getOlderPosts : function() {
      if ($('#socialPostsGetMore').is(":hidden"))
         return;

      // Are we obtaining the long or short?
      var longOutput = 0;
      if ($('#socialPostsFullBlock').length > 0)
         longOutput = 1;

      var lastPost = $('.socialPostRow:last','#socialBody');
      var lpi = 0;

      if (lastPost.length > 0) {
         lpi = lastPost.attr("id").split("_");
         lpi = lpi[1];
      }

      $('#socialPostsGetMore').hide();
      SOCIAL.loading();
      var salt = getSalt();

      $.get('/ajax_social.php', { salt : salt, lpi : lpi,
         longoutput : longOutput, c : 'getolderposts' }, 
         function(data) {

         var json = evalJSON(data);
         SOCIAL.unloading();

         if (check(json)) {
            // Prepend the content to the social posts block
            $('#socialPostsGetMore').before(unescape(json.content));

            if (parseInt(json.foundmore) == 1)
               $('#socialPostsGetMore').show();

            SOCIAL.init();
         }
      });
   },

   loading : function() {
      $('#socialPostsLoading').show();
   },

   unloading : function() {
      $('#socialPostsLoading').hide();
   },

   createPost : function(content, listingid) {
      var salt = getSalt();

      $.post('/ajax_social.php', { salt : salt, content : content,
         listingid : listingid, c : 'createpost' }, 
         function(data) {

         var json = evalJSON(data);

         if (check(json)) {
            SOCIAL.getRecentPosts(listingid);
         } else {
            confirm("An error occured while attempting to post. Refresh and try again");
         }
      });
   },

   init : function() {
      SOCIAL.initializeScroller();
      SOCIAL.initializeLayout();
   },

   initializeWindowScroll : function() {
      $(window).scroll(function() {
         if ($('#socialPostsGetMore').is(":hidden"))
            $(this).unbind('scroll');

         if ($(this).height() + $(this).scrollTop() == $(document).height())
            SOCIAL.getOlderPosts();
      });

   },

   initializeLayout : function() {
      $('#socialPostsGetMore').unbind().click(function() {
         SOCIAL.getOlderPosts();
      });

      $('.socialPostRow').unbind().mouseenter(function() {
         $(this).addClass("socialPostRowOn");

         $('.socialPostInfoControls', this).show();
         $('.socialPostInfoOptions', this).show();
      }).mouseleave(function() {
         $(this).removeClass("socialPostRowOn");

         $('.socialPostInfoControls', this).hide();
         $('.socialPostInfoOptions', this).hide();
      });

      $('.socialPostComment').unbind().click(function() {
         var id = SOCIAL.getPostID($(this));

         SOCIAL.postCommentLoad(id);
      });

      $('.socialPostCommentToggle').unbind().click(function() {
         var id = SOCIAL.getPostID($(this));

         $('#socialCommentSubmitBlock_' + id).show();
      });


      $('.socialPostLike').unbind().click(function() {
         var id = SOCIAL.getPostID($(this));

         SOCIAL.likePost(id);
      });

      $('.socialPostUnlike').unbind().click(function() {
         var id = SOCIAL.getPostID($(this));

         SOCIAL.unlikePost(id);
      });

      $('.socialPostDelete img').unbind().mouseenter(function() {
         $(this).attr("src", "/images/deleteon.png");
      }).mouseleave(function() {
         $(this).attr("src", "/images/delete.png");
      }).click(function() {
         var id = SOCIAL.getPostID($(this));

         SOCIAL.deletePost(id);
      });

      $('.socialPostHasComments').unbind().click(function() {
         var id = SOCIAL.getPostID($(this));

         SOCIAL.postCommentLoad(id);
      });

      SOCIAL.initializeContent();

      NESTCUBE.initializeLinks();
   },

   postCommentLoad : function(postid) {

      var salt = getSalt();

      $.get('/ajax_social.php', { salt : salt, pid : postid,
         c : 'postcommentload' }, function(data) {


         var json = evalJSON(data);

         if (check(json)) {
            overlayShow(unescape(json.content));
         }
      });

   },

   postCommentSubmit : function(postid) {
      var salt = getSalt();

      var input = $("input[name='comment']", '#socialCommentSubmitBlock_' + postid);

      $("input[name='submit']",'#socialCommentSubmitBlock_' + postid).attr(
         "disabled", true).val("submitting...");

      var content = escape(input.val());
/*
      var content = escape($("input[name='comment']", 
         '#socialCommentSubmitBlock').val());
*/

      $.post('/ajax_social.php', { salt : salt, pid : postid, 
         content : content, c : 'postcommentsubmit' }, function(data) {

         var json = evalJSON(data);

         if (check(json)) {
            // At the end of the comments block, insert
            $('.socialCommentSubmit', '#socialcomments_' + postid).before(
               unescape(json.content));

            // Now have it fade in
            $('#socialcommentrow_' + json.commentid).css(
               "opacity", 0).show().animate({ opacity: 100 }, 500);

            // update the base
            $('.socialPostHasComments', '#socialpost_' + postid).html(
               unescape(json.commentcount));

            input.val('').blur();
            FORMCHECK.hasInput(input);

            SOCIAL.initializeContent();
         }

         $("input[name='submit']",'#socialCommentSubmitBlock_' + postid).attr(
            "disabled", false).val("comment");

      });
   },

   postCommentDelete : function(commentid) {
      if (!confirm("Are you sure you wish to delete this comment?"))
         return;

      var salt = getSalt();

      $.get('/ajax_social.php', { salt : salt, cid : commentid,
         c : 'postcommentdelete' }, 
         function(data) {

         var json = evalJSON(data);

         if (check(json)) {
            // update the base
            $('.socialPostHasComments', '#socialpost_' + json.postid).html(
               unescape(json.commentcount));

            // Remove the comment 
            $('#socialcommentrow_' + commentid).animate(
               { opacity : 0 }, 500, function() {
               $(this).remove();
            });

            SOCIAL.initializeScroller();
         }
      });


   },

   deletePost : function(postid) {
      if (!confirm("Are you sure you wish to delete this post?"))
         return;

      var salt = getSalt();

      $.get('/ajax_social.php', { salt : salt, pid : postid,
         c : 'deletepost' }, 
         function(data) {

         var json = evalJSON(data);

         if (check(json)) {
            // Remove the post
            $('#socialpost_' + postid).animate({ opacity : 0 }, 500, function() {
               $(this).remove();
            });

            SOCIAL.initializeScroller();
         }
      });

   },

   likePost : function(postid) {

      var salt = getSalt();

      $.get('/ajax_social.php', { salt : salt, pid : postid,
         c : 'likepost' }, 
         function(data) {

         var json = evalJSON(data);

         if (check(json)) {
            $('.socialPostHasLikes', '#socialpost_' + postid).html(
               unescape(json.content));

            // Set the like to unlike
            $('.socialPostLike', '#socialpost_' + postid).html('unlike'
               ).removeClass("socialPostLike").addClass("socialPostUnlike");

            SOCIAL.initializeLayout();
         }
      });
   },


   unlikePost : function(postid) {

      var salt = getSalt();

      $.get('/ajax_social.php', { salt : salt, pid : postid,
         c : 'unlikepost' }, 
         function(data) {

         var json = evalJSON(data);

         if (check(json)) {
            $('.socialPostHasLikes', '#socialpost_' + postid).html(
               unescape(json.content));

            // Set the like to unlike
            $('.socialPostUnlike', '#socialpost_' + postid).html('like'
               ).removeClass("socialPostUnlike").addClass("socialPostLike");

            SOCIAL.initializeLayout();
         }
      });
   },


   getCommentID : function(obj) {
      for (var i = 0; i < 10; i++) {
         if (obj.hasClass('socialCommentRow'))
            break;

         obj = obj.parent();
      }

      if (!obj.hasClass('socialCommentRow'))
         return false;

      var id = obj.attr("id").split("_");
      return id[1];

   },



   getPostID : function(obj) {
      for (var i = 0; i < 10; i++) {
         if (obj.hasClass('socialPostRow'))
            break;

         obj = obj.parent();
      }

      if (!obj.hasClass('socialPostRow'))
         return false;

      var id = obj.attr("id").split("_");
      return id[1];

   },

   initializeContent : function() {

      $('.socialCommentSubmit input').unbind().focus(function() {
         var defaultS = "comment";

         if ($(this).val().indexOf(defaultS) == 0 && 
            $(this).val().length == defaultS.length) {
            $(this).removeClass("socialCommentSubmitDefault");
            $(this).addClass("socialCommentSubmitFocus");
            $(this).val('');
         }
      }).keyup(function(e) {
         if (e.keyCode == 13) {
            var id = SOCIAL.getPostID($(this));
            SOCIAL.postCommentSubmit(id);

            $(this).blur().removeClass("socialCommentSubmitFocus"
               ).addClass("socialCommentSubmitDefault").val('comment');
         }
      });



      $('.socialCommentLastToggle').unbind().mouseenter(function() {
         $(this).addClass("socialCommentRowOn");
      }).mouseleave(function() {
         $(this).removeClass("socialCommentRowOn");
      }).click(function() {
         var id = this.id.split("_");
         var postid = id[1];
         var lastcommentid = id[2];

         $(this).hide();
         $('#sociallastcomments_' + postid).show();
      });

      $('form', '#socialCommentSubmitBlock').unbind().submit(function(e) {
         e.preventDefault();
      });

      $('input', '#socialCommentSubmitBlock').unbind().keyup(function(e) {
         if (e.keyCode == 13) {
            var postid = $("input[name='postid']", "#socialCommentSubmitBlock").val();

            SOCIAL.postCommentSubmit(postid);
         }
      });

      $('.socialCommentRow').unbind().mouseenter(function() {
         $('.socialCommentControls span').hide();
         $('.socialCommentControls span', this).show();
      }).mouseleave(function() {
         $('.socialCommentControls span', this).hide();
      });

      $('.socialCommentDelete img').unbind().mouseenter(function() {
         $(this).attr("src", "/images/deleteon.png");
      }).mouseleave(function() {
         $(this).attr("src", "/images/delete.png");
      }).click(function() {
         var id = SOCIAL.getCommentID($(this));

         SOCIAL.postCommentDelete(id);
      });

      NESTCUBE.initializeButtons();
   },

   initializeScroller : function() {
      if ($('#socialPostsBlock').length == 0)
         return;

      // Figure out the height of the posts block
      var visibleHeight = $('#socialPostsBlock').height();
      var fullHeight = $('#socialPostsContent').height();

      if (visibleHeight > fullHeight) {
         $('#socialPostsScrollerContainer').hide();
         $('#socialPostsScrollerUp').hide();
         $('#socialPostsScrollerDown').hide();
         return;
      }

      $('#socialPostsScrollerContainer').show();
         $('#socialPostsScrollerUp').show();
         $('#socialPostsScrollerDown').show();

      var percentVisible = visibleHeight / fullHeight;
      var arrowHeights = 2*$('#socialPostsScrollerUp').outerHeight(true);
      var scrollerContainerHeight = visibleHeight - arrowHeights;


      // Set the container height
      $('#socialPostsScrollerContainer').height(scrollerContainerHeight);
      $('#socialPostsScrollerDragStrip').height(scrollerContainerHeight);

      // Now make that the scroller height
      //var scrollerContainerHeight = $('#socialPostsScrollerContainer').height();
      var scrollerDragHeight = Math.round(scrollerContainerHeight * percentVisible);
      var moveableArea = scrollerContainerHeight - scrollerDragHeight;
      var contentMoveableArea = fullHeight - visibleHeight;

      // Initialize the scroll position
      var currentContentPosition = - $('#socialPostsContent').position().top;
      var currentContentPercent = currentContentPosition / contentMoveableArea;
      var scrollPosition = Math.round(currentContentPercent * moveableArea);


      $('#socialPostsScrollerDrag').css("top", scrollPosition + "px"
         ).height(scrollerDragHeight).draggable({
         axis: 'y',
         //containment: '#socialPostsScrollerDragStrip',
         containment: 'parent',
         drag : function(event, ui) {
            // Move the main content area the same percent
            var currentPosition = ui.position.top;
            var percentFromTop = currentPosition / moveableArea;
            var contentOffset = - Math.round(percentFromTop * contentMoveableArea);

            $('#socialPostsContent').css("top", contentOffset + "px");

            if (!$('#socialPostsGetMore').is(":hidden") && percentFromTop == 1)
               SOCIAL.getOlderPosts();               
         },
         stop : function(event, ui) {
            //confirm(ui.position.top);
         }
      });

   }
}

var AGENTPROFILE = {
   jQuery : $,

   manageTimeout : null,

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

   initializeOutput : function() {
      $('.messageAgent').click(function() {
         var id = $(this).attr("id");
         AGENTPROFILE.messageForm(id);
      });
   },

   initializeLayout : function() {
      $('.profileManageExpand').click(function() {
         NESTCUBE.manageGetContent("profile", $(this).attr("id"));
      });

   },

   initializeContent : function() {
      NESTCUBE.initializeWYSIWYG('profileManageBiography');

      // Initialize any photos
      $('.profileManagePhoto').unbind().mouseenter(function() {
         $('.managePhotoOptions', this).show();
         $(this).css('cursor', 'pointer');

         if ($('.managePhotoBorderOn', this).length > 0)
            return;

         $('.managePhotoBorder', this).addClass("managePhotoBorderHover");
      }).mouseleave(function() {
         $('.managePhotoOptions', this).hide();

         $('.managePhotoBorder', this).removeClass("managePhotoBorderHover");
      }).click(function() {
         if ($('.managePhotoBorderOn', this).length > 0)
            return;

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

         var salt = getSalt();

         // Set as the main photo
         $.post('/ajax_profiles.php', { c : "managesetphoto",
            salt : salt, photoid : photoid }, 
            function(data) {

            var json = evalJSON(data);
            if (check(json)) {
               $('.managePhotoBorderOn').removeClass("managePhotoBorderOn");

               $('.managePhotoBorder', '#agentprofilephoto_' + photoid).removeClass(
                  "managePhotoBorderHover").addClass("managePhotoBorderOn");
            } else
               confirm("An error occured. Refresh and try again");
         });
      });

      $('#profileManageFirmTitle').keydown(function(e) {
         switch(e.keyCode) {
            case 38: // up
               AGENTPROFILE.manageFirmResultUp();
            break;

            case 40: // down
               AGENTPROFILE.manageFirmResultDown();
            break;

            case 13: // return
               if ($('.profileManageFirmTitleResultOn').length == 0)
                  return;
               AGENTPROFILE.manageFirmSelectResult($('.profileManageFirmTitleResultOn').attr("id")); 
            break;

            case 9: // tab
               $('#profileManageFirmTitleResults').html('').hide();
            break;

            default:
               if (AGENTPROFILE.manageTimeout)
                  clearTimeout(AGENTPROFILE.manageTimeout);

               // Do nothing with these
               if (e.keyCode == 46 || e.keyCode > 8 && e.keyCode < 32)
                  return;

               AGENTPROFILE.manageTimeout = setTimeout(function() {
                  // Get some results
                  var value = escape($('#profileManageFirmTitle').val());

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

                     if (check(json)) {
                        if ($('#profileManageFirmTitleResults').is(":hidden")) {
                           // We need to set the information

                           var pos = $('#profileManageFirmTitle').position();
                           var height = $('#profileManageFirmTitle').outerHeight(true);
                           var width = $('#profileManageFirmTitle').outerWidth(true);

                           $('#profileManageFirmTitleResults').css(
                              { top : pos.top + height, left: pos.left, width : width - 6 }
                           );

                        }

                        $('#profileManageFirmTitleResults').html(unescape(json.content)).show();

                        // Now make them clickable!
                        $('.profileManageFirmTitleResult').unbind().mouseenter(function() {

                           $('.profileManageFirmTitleResultOn').removeClass(
                              'profileManageFirmTitleResultOn').addClass(
                              'profileManageFirmTitleResultOff');

                           $('span', this).removeClass('profileManageFirmTitleResultOff').addClass(
                              'profileManageFirmTitleResultOn');
                        }).click(function() {
                           AGENTPROFILE.manageFirmSelectResult($('span',this).attr("id"));
                        });
                     } else {
                        $('#profileManageFirmTitleResults').hide();
                     }
                  });




               }, 200);
            break;
         }
      });

      $('.profileManagePhotoDelete').unbind().click(function() {
         if (!confirm("Are you sure you wish to delete this photo?"))
            return;

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

         var salt = getSalt();
         // Delete it
         // Now setup the ajax to submit
         $.post('/ajax_profiles.php', { c : "deletephoto",
            salt : salt, photoid : photoid }, 
            function(data) {

            var json = evalJSON(data);
            if (check(json)) {
               // Animate it to disappear
               $('#agentprofilephoto_' + photoid).animate({opacity: 0}, 500, function() {
                  $('#agentprofilephoto_' + photoid).remove();

                  // Do we have a new set?
                  var selectedPhoto = parseInt(json.selectedphoto);

                  if (selectedPhoto > 0) {
                     $('.managePhotoBorderOn').removeClass("managePhotoBorderOn");
                     $('#agentprofilephoto_' + selectedPhoto).addClass("managePhotoBorderOn");
                  }

                  AGENTPROFILE.manageRefreshStatus();

                  AGENTPROFILE.initializeContent();
               });
            } else
               confirm("An error occured. Refresh and try again");
         });

      });
   },

   manageFirmSelectResult : function(id) {
      var html = $('#' + id, '#profileManageFirmTitleResults').html().replace(/&amp;/g, 
         "&").replace(/&gt;/g, ">").replace(/&lt;/g, "<").replace(/&quot;/g, '"');


      // Set the value to the span title
      $('#profileManageFirmTitle').val(html);

      // Hide results
      $('#profileManageFirmTitleResults').html('').hide();
      $('#profileManageFirmPicture').loading();

      var salt = getSalt();
      // Delete it
      // Now setup the ajax to submit
      $.post('/ajax_profiles.php', { c : "managefirmselectpublic",
         salt : salt, firmid : id }, 
         function(data) {

         var json = evalJSON(data);
         if (check(json)) {
            // Set the logo
            $('#profileManageFirmPicture').html(unescape(json.logo));
         } else
            confirm("An error occured. Refresh and try again");
      });



   },

   manageFirmResultUp : function() {
      // Make sure there are results
      if ($('.profileManageFirmTitleResult').length == 0)
         return;


      // Highlight the last one
      if ($('.profileManageFirmTitleResultOn').length == 0) {
         $('.profileManageFirmTitleResultOff:last').removeClass(
            'profileManageFirmTitleResultOff').addClass('profileManageFirmTitleResultOn');
      // Find current one, then do one previous to that to highlight
      } else {
         // Just one result...nothing to do
         if ($('.profileManageFirmTitleResult').length == 1)
            return;

         var currentID = parseInt($('.profileManageFirmTitleResultOn').attr("id")); 

         $('.profileManageFirmTitleResultOn').removeClass(
            'profileManageFirmTitleResultOn').addClass('profileManageFirmTitleResultOff');

         var lastID = 0;



         $('span', '#profileManageFirmTitleResults').each(function() {
            if (parseInt($(this).attr('id')) == currentID) {
               if (lastID != 0) {
                  $('#' + lastID, '#profileManageFirmTitleResults').removeClass(
                     'profileManageFirmTitleResultOff').addClass('profileManageFirmTitleResultOn');

               // We're on the first one, SO set it to the last one
               } else {
                  $('.profileManageFirmTitleResultOff:last').removeClass(
                     'profileManageFirmTitleResultOff').addClass('profileManageFirmTitleResultOn');
               }
            }

            lastID = parseInt($(this).attr("id"));
         });

      }
   },

   manageFirmResultDown : function() {
      // Make sure there are results
      if ($('.profileManageFirmTitleResult').length == 0)
         return;


      // Start with nothing, then we're on the first one
      if ($('.profileManageFirmTitleResultOn').length == 0) {
         $('.profileManageFirmTitleResultOff:first').removeClass(
            'profileManageFirmTitleResultOff').addClass('profileManageFirmTitleResultOn');

      // Find current one, then do one after~
      } else {
         // Just one result...nothing to do
         if ($('.profileManageFirmTitleResult').length == 1)
            return;

         var currentID = parseInt($('.profileManageFirmTitleResultOn').attr("id")); 

         $('.profileManageFirmTitleResultOn').removeClass(
            'profileManageFirmTitleResultOn').addClass('profileManageFirmTitleResultOff');

         // If we're the last one, then we want to set the first one
         if (parseInt($('span:last', '#profileManageFirmTitleResults').attr("id")) == currentID) {
            $('.profileManageFirmTitleResultOff:first').removeClass(
               'profileManageFirmTitleResultOff').addClass('profileManageFirmTitleResultOn');
         } else {
            var found = false;
            $('span', '#profileManageFirmTitleResults').each(function() {
               if (found) {
                  $(this).removeClass(
                     'profileManageFirmTitleResultOff').addClass('profileManageFirmTitleResultOn');

                  // prevent anything else from activating
                  found = false;
               } if (parseInt($(this).attr('id')) == currentID)
                  found = true;

            });
         }

      }

   },

   manageSettingsSave : function() {
      var values = "";
      $('.formInputError').removeClass("formInputError");

      $('select,textarea,input','#manageSection_settings').each(function() {
         var name = $(this).attr("name");
         var value = trim($(this).val());

         if ($(this).attr("type") == "radio" &&
            !$(this).is(":checked"))
            return;

         if (name.indexOf("button") >= 0)
            return;

         if ((name.indexOf("email") != -1 || name.indexOf("password") == 0) 
            && value.length == 0) {
            $(this).addClass("formInputError");
            return;
         }

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

         if (name.indexOf("password") != -1 && value.length > 0) {
            // Check the length of this then
            if (value.length < MINPASSWORDLENGTH)
               $(this).addClass("formInputError");

            value = md5(value);
         }

         values += name + "=" + escape(value);
      });

      // Check if the passwords match
      var npw1 = trim($('input[name="newpassword"]', '#manageSection_settings').val());
      var npw2 = trim($('input[name="newpasswordconfirm"]', '#manageSection_settings').val());

      if (npw1.length > 0) {
         if (npw1.length != npw2.length || npw1.indexOf(npw2) != 0) {

            $('input[name="newpassword"]', '#manageSection_settings').addClass("formInputError");
            $('input[name="newpasswordconfirm"]', '#manageSection_settings').addClass("formInputError");
         }
      }

      if ($('.formInputError').length > 0)
         return;

      $("input[name='buttonSave']", '#manageSection_settings').val(
         "Saving...").attr("disabled", true);

      // Now setup the ajax to submit
      var salt = getSalt();
      $.post('/ajax_profiles.php', { c : "managesettingssave",
         salt : salt, values : values }, function(data) {

         var json = evalJSON(data);

         if (check(json)) {
            confirm("Account settings saved\n" + unescape(json.content));

            AGENTPROFILE.manageRefreshStatus();
            NESTCUBE.manageExpandCloseAnimate();
         } else {
            confirm("An error occured. Please check your values and try again.");

            $("input[name='buttonSave']", '#manageSection_settings').val(
               "Save").attr("disabled", false);
         }
      });
   },

   manageDetailsSave : function() {
      var values = "";
      $('.formInputError').removeClass("formInputError");

      $('select,textarea,input','#manageSection_details').each(function() {
         var name = $(this).attr("name");
         var value = trim($(this).val());

         if (name.indexOf("button") >= 0)
            return;

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

         values += name + "=" + escape(value);
      });

      if ($('.formInputError').length > 0)
         return;

      $("input[name='buttonSave']", '#manageSection_details').val(
         "Saving...").attr("disabled", true);

      // Now setup the ajax to submit
      var salt = getSalt();
      $.post('/ajax_profiles.php', { c : "managedetailssave",
         salt : salt, values : values }, function(data) {

         var json = evalJSON(data);

         if (check(json)) {
            confirm("Saved");

            AGENTPROFILE.manageRefreshStatus();
            NESTCUBE.manageExpandCloseAnimate();
         } else {
            confirm("An error occured. Refresh and try again");

            $("input[name='buttonSave']", '#manageSection_details').val(
               "Save").attr("disabled", false);
         }
      });


   },


   manageFirmTitleSave : function() {
      $("input[name='buttonSave']", '#manageSection_firm').val(
         "Saving...").attr("disabled", true);

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

      // Now setup the ajax to submit
      var salt = getSalt();
      $.post('/ajax_profiles.php', { c : "managesetfirmtitlemanual",
         salt : salt, title : title }, function(data) {

         var json = evalJSON(data);

         if (check(json)) {
            confirm("Saved");

            if ($('#manageFirmLogoBlock').is(":hidden")) {
               $('#manageFirmLogoBlock').css("opacity", 0).show().animate(
                  {opacity: 1}, 500);
            }

         } else {
            confirm("An error occured. Refresh and try again");

         }
         $("input[name='buttonSave']", '#manageSection_firm').val(
            "Save").attr("disabled", false);
      });


   },

   manageFirmLogoUpload : function() {
      $("#profileManageFirmUploadLoading").ajaxStart(function(){
         $('#profileManageFirmUploadForm').hide();
         $(this).show().loading();
      }).ajaxComplete(function(){
         $(this).hide();
         $('#profileManageFirmUploadForm').show();

         $(this).unbind();
      });

      $.ajaxFileUpload (
         {
            url:'/ajax_profiles.php?c=managefirmphotoupload',
            secureuri:false,
            fileElementId:'profileManageFirmLogoFile',
            dataType: 'json',
            //data:{name:'logan', id:'id'},
            success: function (data, status)
            {
/*
               if(typeof(data.error) != 'undefined') {
                  if(data.error != '') {
                     alert(data.error);
                  } else {
                     alert(data.content);
                  }
               }

               confirm(unescape(data.content));
*/
               if (check(data))
                  $('#profileManageFirmPicture').html(unescape(data.content));
               else
                  confirm("An error occured. We recommend uploading JPG files");
            },
            error: function (data, status, e)
            {
               alert(e);
            }
         }
      )
      
      return false;

   },

   manageRefreshStatus : function() {
      $('#profileManageStatus').loading();

      var salt = getSalt();
      // Set as read
      $.get('/ajax_profiles.php', {salt : salt, 
         c : "managegetstatus" }, function(data) {

         var json = evalJSON(data);

         if (check(json))
            $('#profileManageStatus').html(unescape(json.content));
         else
            $('#profileManagestatus').html("Error. Refresh page");
      });



   },

   messageForm : function(apid) {
      var salt = getSalt();

      // call ajax to obtain the information for getting invited
      $.get('/ajax_profilecontent.php', { salt : salt,
         c : "messageform", apid : apid }, function(data) {

         var json = evalJSON(data);

         if (check(json)) {
            overlayShow(unescape(json.content));
         } else {
         }
      });

   },

   sendMessage : function(apid) {
      var salt = getSalt();

      $('.formInputError', '#messageBlock').removeClass("formInputError");

      var values = "";

      //  Obtain all of the input non buttons
      $('textarea,input', '#messageBlock').each(function() {
         var name = $(this).attr("name");
         var required = parseInt($(this).attr("id"));

         var value = trim($(this).val());

         if (name.indexOf("button") != -1)
            return;


         if (required == 1 && value.length == 0)
            $(this).addClass("formInputError");

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

         values += name + "=" + escape(value);
      });

      if ($('.formInputError', '#messageBlock').length > 0) {
         confirm("Please fill out all required fields");
         return;
      }

      // call ajax to obtain the information for getting invited
      $.post('/ajax_profilecontent.php', { salt : salt, values : values,
         c : "sendmessage", apid : apid }, function(data) {

         var json = evalJSON(data);

         if (check(json)) {
            overlayShow(unescape(json.content));
         } else {
            confirm("There was an error sending the message to the agent");
         }
      });



   }



}

var LISTING = {
   jQuery : $,

   init : function () {
      LISTING.initializeLayout();
      LISTING.initializeContent();
   },
   initializeLayout : function() {
      $('.listingManageExpand').click(function() {
         NESTCUBE.manageGetContent("listing", $(this).attr("id"));
      });
   },

   initializeContent : function() {
      NESTCUBE.initializeWYSIWYG('listingManageDescription');

      // Initialize any photos
      $('.listingManagePhoto').unbind().mouseenter(function() {
         $('.managePhotoOptions', this).show();

         $(this).css('cursor', 'move');
      }).mouseleave(function() {
         $('.managePhotoOptions', this).hide();
      });


      // Sortable colujns for listings
      $('#listingManagePhotos').sortable({ 
         items : 'li',
         cursor: 'move',
         helper: "clone",
         appendTo: "body",
         opacity : 1 
         }, { 
         start : function(event, ui) {
            $('.managePhotoOptions', ui.helper).hide();
         },
         update : function(event, ui) {
            var photos = "";
            var count = 1;
            $("li", this).each(function() {
               if (photos.length > 0)
                  photos += ",";

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

               photos += listingid + "=" + count;
               count++;
            });

            // Now setup the ajax to submit
            var salt = getSalt();
            $.post('/ajax_listings.php', { c : "updatephotosortorders",
               salt : salt, photos : photos, listingid : LISTINGID }, 
               function(data) {

               var json = evalJSON(data);

               if (!check(json))
                  confirm("An error occured. Refresh and try again");
            });

         }
      }).disableSelection();

      $('.listingManagePhotoDelete').unbind().click(function() {
         if (!confirm("Are you sure you wish to delete this photo?"))
            return;

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

         var salt = getSalt();
         // Delete it
         // Now setup the ajax to submit
         $.post('/ajax_listings.php', { c : "deletephoto",
            salt : salt, photoid : photoid, listingid : LISTINGID }, 
            function(data) {

            var json = evalJSON(data);
            if (check(json)) {
               // Animate it to disappear
               $('#listingphoto_' + photoid).animate({opacity: 0}, 500, function() {
                  $('#listingphoto_' + photoid).remove();

                  LISTING.manageRefreshStatus();
               });
            } else
               confirm("An error occured. Refresh and try again");
         });
      });

      $('.listingManageDesignChoice').unbind().mouseenter(function() {
         if ($(this).hasClass("listingManageDesignChoiceSelected"))
            return;

         $(this).removeClass("listingManageDesignChoiceOff").addClass(
            "listingManageDesignChoiceOn");
      }).mouseleave(function() {
         if ($(this).hasClass("listingManageDesignChoiceSelected"))
            return;

         $(this).removeClass("listingManageDesignChoiceOn").addClass(
            "listingManageDesignChoiceOff");
      }).click(function() {
         if ($(this).hasClass("listingManageDesignChoiceSelected"))
            return;

         $('.listingManageDesignChoiceSelected').removeClass(
            'listingManageDesignChoiceSelected').addClass("listingManageDesignChoiceOff");

         $(this).addClass("listingManageDesignChoiceSelected");
         $(this).removeClass("listingManageDesignChoiceOn");

         var url = "/dp/" + $(this).attr("id") + "/" + getSalt();

         $("#listingManageDesignPreview").attr("src", url);
      });

   },

   newListingAddressChange : function() {
      $('#listingNewAddressSaved').hide();
      $('#listingNewAddressInput').show();
   },

   newListingAddressSave : function() {
      //setLoading('listingNewAddressBlock');
      $('#listingNewAddressBlock').loading();

      // Now setup the ajax to submit
      var salt = getSalt();
      $.get('/ajax_listings.php', { c : "newlistingsaveaddress",
         salt : salt }, function(data) {

         var json = evalJSON(data);

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

            $('#listingNewAddressInput').hide();
            $('#listingNewAddressSaved').show();
         } else
            confirm("An error occured. Refresh and try again");

      });

   },

   newListingAddressQuery : function() {
      var values = "";

      $('.formInputError', '#listingNewAddress').removeClass("formInputError");

      //  Obtain all of the input non buttons
      $('select,input', '#listingNewAddress').each(function() {
         var name = $(this).attr("name");
         var value = trim($(this).val());

         if (name.indexOf("button") != -1)
            return;

         if (name != "unit" && value.length == 0)
            $(this).addClass("formInputError");

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

         values += name + "=" + escape(value);
      });

      // Check for any errors
      if ($('.formInputError', '#listingNewAddress').length > 0)
         return;

      $("input[name=buttonQuery]", '#listingNewAddress').attr("disabled", true);

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

      // Now setup the ajax to submit
      var salt = getSalt();
      $.post('/ajax_listings.php', { c : "newlistingqueryaddress",
         salt : salt, values : values }, function(data) {

         var json = evalJSON(data);

         if (check(json)) {
            // Show the results of the query
            $('#listingNewAddressResults').html(unescape(json.content)).css(
               "opacity", 0).show().animate({opacity: 1}, 800, function() {
               NESTCUBE.initializeButtons();
            });

            // Initialize the google map
            var center = new google.maps.LatLng(json.latitude, json.longitude);

            var myOptions = {
               zoom: 14,
               center: center,
               mapTypeId: google.maps.MapTypeId.ROADMAP
            }

            var map = new google.maps.Map(document.getElementById("listingNewAddressMap"),
               myOptions);
               
            var marker = new google.maps.Marker({
               position: center,
               map: map
            });


         } else
            confirm("An error occured. Refresh and try again");

         $("input[name=buttonQuery]", '#listingNewAddress').attr("disabled", false);
      });
   },

   newListingSubmitDetails : function(nextstepnumber) {
      $('.formInputError', '#listingNewBlock').removeClass("formInputError");

      // Preflight checks
      // Check that there is a title
      var titleInput = $("input[name='listingNewTitle']", '#listingNewBlock');
      var titleValue = trim(titleInput.val());

      if (titleValue.length == 0)
         titleInput.addClass("formInputError");

      // Check taht the address is saved
      if ($('#listingNewAddressSaved').is(":hidden"))
         $('input,select','#listingNewAddressInput').addClass("formInputError");

      if ($('.formInputError', '#listingNewBlock').length)
         return false;

      titleValue = escape(titleValue);

      // Now setup the ajax to submit
      var salt = getSalt();
      $.post('/ajax_listings.php', { c : "newlistingdetailssubmit",
         salt : salt, title : titleValue }, function(data) {

         var json = evalJSON(data);

         if (check(json)) {
            location.href = "/listings/new/" + nextstepnumber + "/";
         } else
            confirm("An error occurred while saving. Refresh and try again");
      });

   },

   newListingURLChange : function() {
      $('#listingNewURLSaved').hide();
      $('#listingNewURLBlock').show();
   },

   newListingSubmitURL : function(nextstepnumber) {
      $('.formInputError', '#listingNewURLBlock').removeClass("formInputError");
      $('.listingNewURLResponse').hide();

      if ($('#listingNewURLSaved').is(":hidden")) {

         // Check what we have selected
         var urlRadio = $("input[name='url']:checked", "#listingNewURLBlock");

         if (urlRadio.length == 0) {
            confirm("Please select an option above");
            return;
         }

         var urlValue = urlRadio.val().split(",");
         var urlDomain = urlValue[0];
         var urlType = urlValue[1];
         var urlHostQuery = urlDomain;
         var userDefined = 0;

/*
         var userDefined = "";
         var urlID = 0;
         var userInput = "";
         var userInputValue = "";
*/

         if (urlType == "usrd") {
            urlID = urlValue[2];
            userInput = $("#usrd_" + urlID);
            userInputValue = trim(userInput.val());

            // Create the host query
            urlHostQuery = userInputValue + "." + urlDomain;

            // Set bit
            userDefined = 1;

   /*
            if (userInputValue.length < 5) {
               userInput.addClass("formInputError");
               $("#usrd_" + urlID + "_response").html(
                  "Minimum of five letters and/or numbers").show();
               return false;
            }
   */

            $("#usrd_" + urlID + "_response").html(
               "<img src=\"/images/loading.gif\">").show();

            //userDefined = escape(userInputValue);
         }

         //urlName = escape(urlName);

         $("input[name='stepNextButton']", '#listingNewBlock').attr(
            "disabled", true).val("checking availability...");

         urlHostQuery = escape(urlHostQuery);

         // Now setup the ajax to submit
         var salt = getSalt();
         $.post('/ajax_listings.php', { c : "newlistingurlsubmit",
            //salt : salt, urldomain : urlDomain, urlname : urlName,
            salt : salt, urlhost : urlHostQuery,
            userdefined : userDefined }, function(data) {

            var json = evalJSON(data);

            if (check(json)) {
               location.href = "/listings/new/" + nextstepnumber + "/";
            } else {
               $("input[name='stepNextButton']", '#listingNewBlock').attr(
                  "disabled", false).val("checkout >");

               if (urlType == "usrd") {
                  userInput.addClass("formInputError");
                  $("#usrd_" + urlID + "_response").html(
                     " - " + unescape(json.content)).show();
               } else
                  confirm(unescape(json.content));
            }

         });
      } else
         location.href = "/listings/new/" + nextstepnumber + "/";
   },

   newListingSubmitCheckout : function() {
      $("input[name='stepNextButton']", '#listingNewBlock').attr(
         "disabled", true).val("creating...");

      // Now setup the ajax to submit
      var salt = getSalt();
      $.post('/ajax_listings.php', { c : "newlistingcheckoutsubmit",
         salt : salt }, function(data) {

         var json = evalJSON(data);

         if (check(json)) {
            location.href = unescape(json.content);
         } else {
            $("input[name='stepNextButton']", '#listingNewBlock').attr(
               "disabled", false).val("create listing >");

            confirm(unescape(json.content));
         }

      });
   },

   manageDesignSave : function() {
      var did = $('.listingManageDesignChoiceSelected').attr("id").split("/");
      did = did[1];

      $("input[name='buttonSave']", '#manageSection_design').val(
         "Saving...").attr("disabled", true);

      // Now setup the ajax to submit
      var salt = getSalt();
      $.post('/ajax_listings.php', { c : "managedesignsave", designid : did,
         salt : salt, listingid : LISTINGID }, function(data) {

         var json = evalJSON(data);

         if (check(json)) {
            confirm("Saved");

            NESTCUBE.manageExpandCloseAnimate();

            LISTING.manageRefreshStatus();
         } else {
            confirm("An error occured. Refresh and try again");

            $("input[name='buttonSave']", '#manageSection_design').val(
               "Save").attr("disabled", false);
         }
      });

   },

   manageRefreshStatus : function() {
      $('#listingManageStatus').loading();

      var salt = getSalt();
      // Set as read
      $.get('/ajax_listings.php', {salt : salt, 
         listingid : LISTINGID, c : "managegetstatus" }, function(data) {

         var json = evalJSON(data);

         if (check(json))
            $('#listingManageStatus').html(unescape(json.content));
         else
            $('#listingManagestatus').html("Error. Refresh page");
      });



   },


   manageFileDelete : function(listingfileid) {
      if (!confirm("Are you sure you wish to delete this file?"))
         return;

      $("input[name='buttonDelete']", '#listingManageFile_' + listingfileid).val(
         "deleting...").attr("disabled", true);

      // Now setup the ajax to submit
      var salt = getSalt();
      $.post('/ajax_listings.php', { c : "managefiledelete", 
         lfid : listingfileid, salt : salt, listingid : LISTINGID }, function(data) {

         var json = evalJSON(data);

         if (check(json)) {
            $('#listingManageFile_' + listingfileid).animate({opacity : 0}, 500, function() {
               $(this).remove();
            });
         } else {
            confirm("An error occured. Refresh and try again");

            $("input[name='buttonDelete']", '#listingManageFile_' + listingfileid).val(
               "Delete").attr("disabled", false);
         }
      });
   },


   manageFileSave : function(listingfileid) {
      var title = escape($('input[name="title"]', '#listingFileFields_' + listingfileid).val());

      $("input[name='buttonSave']", '#listingManageFile_' + listingfileid).val(
         "Saving...").attr("disabled", true);

      // Now setup the ajax to submit
      var salt = getSalt();
      $.post('/ajax_listings.php', { c : "managefilesave", title : title,
         lfid : listingfileid, salt : salt, listingid : LISTINGID }, function(data) {

         var json = evalJSON(data);

         if (check(json))
            confirm("Saved");
         else
            confirm("An error occured. Refresh and try again");

         $("input[name='buttonSave']", '#listingManageFile_' + listingfileid).val(
            "Save").attr("disabled", false);
      });
   },

   manageDetailsSave : function() {
      var values = "";
      $('.formInputError').removeClass("formInputError");

      $('select,textarea,input','#manageSection_details').each(function() {
         var name = $(this).attr("name");
         var value = trim($(this).val());


         if (name.indexOf("button") >= 0)
            return;

         if (name.indexOf("title") != -1 && value.length == 0) {
            $(this).addClass("formInputError");
            return;
         }

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

         values += name + "=" + escape(value);
      });

      if ($('.formInputError').length > 0)
         return;

      $("input[name='buttonSave']", '#manageSection_details').val(
         "Saving...").attr("disabled", true);

      // Now setup the ajax to submit
      var salt = getSalt();
      $.post('/ajax_listings.php', { c : "managedetailssave",
         salt : salt, values : values, listingid : LISTINGID }, function(data) {

         var json = evalJSON(data);

         if (check(json)) {
            confirm("Saved");

            LISTING.manageRefreshStatus();
            NESTCUBE.manageExpandCloseAnimate();
         } else {
            confirm("An error occured. Refresh and try again");

            $("input[name='buttonSave']", '#manageSection_details').val(
               "Save").attr("disabled", false);
         }
      });
   }
}

var NESTCUBE = {
   jQuery : $,
   
   settings : {
   },

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

      var splashImages = $('.splashImage').size();
      if (splashImages > 0)
         initializeSplashImages(splashImages);
   },


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

      $('#splashArrowL,#splashArrowR').unbind().mouseenter(function() {
         $(this).css('background-position','0px -35px');
      }).mouseleave(function() {
         $(this).css('background-position','0px 0px');
      }).click(function() {
      });

/*
      $('.login').unbind().click(function() {
         NESTCUBE.overlayLoadContent("login");
      });
*/

      $('input','#loginBlock').unbind().keyup(function(e) {
         if (e.keyCode == 13)
            loginSubmit();
      });

      $('#loginSubmit').unbind().click(function() {
         loginSubmit();
      });

      $('.menuItem').unbind().mouseenter(function() {
         $('span',this).addClass("menuItemOn");
      }).mouseleave(function() {
         $('span',this).removeClass("menuItemOn");
      });

      $('.notificationIcon').unbind().mouseenter(function() {
         $(this).css('cursor', 'pointer');
      }).mouseleave(function() {
         $(this).css('cursor', '');
      }).click(function() {
         if ($('.notificationPopup').is(":hidden")) {
            $('.notificationPopup').show();

            // Mark them as read
            var imgsrc = $(this).attr("src");

            // That means we need to set this as read
            if (imgsrc.indexOf("off.gif") < 0) {
               $(this).attr("src", "/images/notificationoff.gif");

               var salt = getSalt();
               // Set as read
               $.get('/ajax_notification.php', 
                  { salt : salt, c : "load" }, function(data) {
                  var json = evalJSON(data);


               });

            }
         } else
            $('.notificationPopup').hide();
      });

      $('.notificationClose').unbind().mouseenter(function() {
         $(this).css('cursor', 'pointer');
         $(this).css('background-color', '#f10000');
      }).mouseleave(function() {
         $(this).css('cursor', '');
         $(this).css('background-color', '#d30000');
      }).click(function() {
         $('.notificationPopup').hide();
      });

      $('.cornered').unbind().cornered();
      $('.cornerbordered').unbind().cornerbordered();


      $('#getInvited').click(function() {
         NESTCUBE.overlayLoadContent("getinvited");
      });

      $('input', '#shareSomething').unbind().focus(function() {
         var beenFocused = parseInt($(this).attr("beenFocused"));

         if (beenFocused == 0) {
            $(this).removeClass("shareSomethingDefault");
            $(this).addClass("shareSomethingFocus");
            $(this).val('');
         }

         $(this).attr("beenFocused", 1);
/*

         var defaultS = "share something";

         if ($(this).val().indexOf(defaultS) == 0 && 
            $(this).val().length == defaultS.length) {
            $(this).val('');
         }
*/
      }).keyup(function(e) {
         if (e.keyCode == 13) {
            var id = $(this).attr("id").split(",");
            var listingid = id[1];

            SOCIAL.createPost($(this).val(), listingid);
            var defaultValue = $(this).attr("defaultValue");

            $(this).blur().removeClass("shareSomethingFocus"
               //).addClass("shareSomethingDefault").val('share something');
               ).addClass("shareSomethingDefault").val(defaultValue);
         }
      });

      $('.listOptionHeader').disableSelection();

      // Sortable colujns for listings
      $('#listingsActive').unbind().sortable({ 
         handle: '.listOptionHeaderDefault',
         items : 'li',
         cursor: 'move',
         items: "li",
         helper: "clone",
         appendTo: "body",
         opacity : 0.5
         }, { 
/*
         change : function(event, ui) {
            var beforeCol = ui.item.parent().attr("id");
            var afterCol = ui.helper.parent().attr("id");

            confirm("Before: " + beforeCol + " & after: " + afterCol);
         },
         stop : function(event, ui) {
            confirm(ui.item.attr("id") + " => " + ui.item.parent().attr("id"));
         }
*/
         update : function(event, ui) {
            var listings = "";
            var count = 1;
            $("li", this).each(function() {
               if (listings.length > 0)
                  listings += ",";

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

               listings += listingid + "=" + count;
               count++;
            });

            // Now setup the ajax to submit
            var salt = getSalt();
            $.post('/ajax_listings.php', { c : "updateactivesortorders",
               salt : salt, listings : listings }, function(data) {

               var json = evalJSON(data);

               if (!check(json))
                  confirm("An error occured. Refresh and try again");
            });


         }
      });

      NESTCUBE.initializeButtons();

      NESTCUBE.initializeLinks();

      //NESTCUBE.initializeButtons();

      SOCIAL.init();

      LISTING.init();

      AGENTPROFILE.init();
   },
/*
   initializeButtons : function() {
      var buttons = new Array(
         "Listings", "Profile"
         );

      var links = new Array(
         "/listings/", "/profile/"
         );

      for (var i = 0; i < buttons.length; i++) {
         var name = buttons[i];
         var link = links[i];


         // Already unbound by buttonSmall and such
         $('#manage' + name).click(function() {
            location.href = $('a', this).attr("href");
            //location.href = link;
         });
      }
   },
*/
   initializeButtons : function() {
      $('.inputBOn').mouseenter(function() {
         $(this).css("background-color", "#9cbf49");
      }).mouseleave(function() {
         $(this).css("background-color", "#8cac41");
      });

      $('.inputBOff').mouseenter(function() {
         $(this).css("background-color", "#cccccc");
      }).mouseleave(function() {
         $(this).css("background-color", "#dddddd");
      });


      $('.bS').mouseenter(function() {
         $(this).css("background-color", "#9cbf49");
      }).mouseleave(function() {
         $(this).css("background-color", "#8cac41");
      }).click(function() {
         if ($('a', this).length <= 0)
            return;

         var url = $('a', this).attr("href");

         location.href = url;
      });



   },

   initializeLinks : function() {

      $('.link').mouseenter(function() {
         $(this).css('cursor','pointer');
         $(this).css('text-decoration','underline');
      }).mouseleave(function() {
         $(this).css('text-decoration','none');
      });

   },

   overlayLoadContent : function(type) {
      var salt = getSalt();

      // call ajax to obtain the information for getting invited
      $.get('/ajax_content.php', { salt : salt,
         type : type }, function(data) {

         var json = evalJSON(data);

         if (check(json)) {
            overlayShow(unescape(json.content));
         } else {
         }
      });
   },

   initializeContent : function() {
      SOCIAL.initializeContent();

      $('form', '#loginBlock').unbind().submit(function(e) {
         e.preventDefault();
      });


      $('input','#loginBlock').unbind().keyup(function(e) {
         if (e.keyCode == 13)
            loginSubmit();
      });
   },

   manageExpandCloseAnimate : function() {
      $('.manageContent').animate({opacity: 0}, 500, function() {
         $(this).hide();
      });
   },

   manageExpandClose : function() {
      $('.manageContent').hide();
   },

   manageGetContent : function(type, id) {
      id = id.split("_");
      var name = id[1];


      var content = $('#manageContent_' + name);

      if (!content.is(":hidden"))
         return;

      // Hide all
      $('.manageContent').html("").hide();

      // Expand and allow the loading animation
      content.css("opactiy", 0).html(''
         ).show().css("opacity", 1).loading();

      // Load the content into it
      var salt = getSalt();

      var id = 0;

      if (type == "listing")
         id = LISTINGID;

      $.get('/ajax_' + type + 's.php', { c : "managegetcontent",
         salt : salt, section : name, id : id }, 
         function(data) {

         var json = evalJSON(data);

         if (check(json)) {
            content.html(unescape(json.content));

            if (type == "listing")
               LISTING.initializeContent();
            else
               AGENTPROFILE.initializeContent();

            NESTCUBE.initializeButtons();

            if (parseInt(json.uploadsystem) == 1)
               NESTCUBE.initializeUploadSystem(type + "uploadify",
                  json.uploadtype, json.secure, json.uploadid);

            // Now scroll to this area
            var offset = $('#manageSection_' + name).offset().top;
            //$(document).scrollTop(offset);
            $('html,body').animate({scrollTop: offset}, 500);
         } else
            confirm("An error occured. Refresh and try again");
      });


   },



   initializeUploadSystem : function(id, type, secure, lid) {
      $('#' + id).uploadify({
         'folder': ',' + type + ',' + secure + ',' + lid
      });
   },

   startUploadSystem : function(id) {
      $('#' + id).uploadifyUpload();

      // Now disable the button
      $("input[name='upload']", '#uploadifyOverlay').val("Uploading..."
         ).attr("disabled", true);


   },

   cancelUploadSystemQueue : function(id) {
      $('#' + id).uploadifyClearQueue();
      overlayClose();

   },

   testWYSIWYG : function(id) {
      var content = $('#' + id).wysiwyg("getContent");

      $('#target').html(content);
   },

   initializeWYSIWYG : function(id) {
      $('#' + id).wysiwyg({
         css: '/jwysiwyg/style.css',
         initialContent: $('#' + id).val(),
         brIE: false,
         controls: {
            bold: { visible: true},
            italic: { visible: true},
            underline: { visible: true},
            justifyLeft: { visible: true},
            justifyRight: { visible: true},
            justifyCenter: { visible: true},
            justifyFull: { visible: true},
            undo: { visible: true},
            redo: { visible: true},
            insertOrderedList: { visible: true},
            insertUnorderedList: { visible: true},
            increaseFontSize: { visible: true},
            decreaseFontSize: { visible: true},
            underline: { visible: true},

            indent: { visible: false},
            outdent: { visible: false},
            h1: { visible: false},
            h2: { visible: false},
            h3: { visible: false},
            code: { visible: false},
            strikeThrough: { visible: false},
            subscript: { visible: false},
            superscript: { visible: false},
            insertHorizontalRule: { visible: false},
            createLink: { visible: false},
            insertImage: { visible: false},
            paragraph: { visible: false},
            cut: { visible: false},
            copy: { visible: false},
            paste: { visible: false},
            html: { visible: false},
            removeFormat: { visible: false},
            insertTable: { visible: false}
         }
      });

   }
};

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

function overlayShow(content) {
   // Load it first into it
   //$('.cornerBBody','#screenOverlayContent').hide().html(content);
   $('#screenOverlayContent').hide().html(content);
/*
   $('#screenOverlayBG').show().css("filter", "alpha(opacity=70)").fadeIn(500, function() {

      confirm("Done");
   });
   return;
*/

   $('html,body').animate({scrollTop: 0}, 500);

   $('#screenOverlayBG').css("opacity", 0).show().animate({opacity: 0.7}, 
   //$('#screenOverlayBG').show().fadeIn(
      500, function() {
      //$('.cornerBBody','#screenOverlayContent').show();
      $('#screenOverlayContent').show();
      $('#screenOverlay').css("opacity", 0).show().animate({opacity: 1.0}, 
      //$('#screenOverlay').show().fadeIn(
         500, function() {


         NESTCUBE.initializeContent();
      });
   });
}

function overlayClose() {
   $('#screenOverlay').animate({opacity: 0.0}, 500, function() {
      $(this).hide();

      $('#screenOverlayBG').animate({opacity: 0.0}, 500, function() {
         $(this).hide();
         //$('.cornerBBody','#screenOverlayContent').html('');
         $('#screenOverlayContent').html('');
      });
   });
}

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

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

   return numZeropad;
}

function disableSelect(objectName) {
   if ($.browser.mozilla){//Firefox
      $('#' + objectName).css('MozUserSelect','none');
   } else if($.browser.msie){//IE
       $('#' + objectName).bind('selectstart',function(){return false;});
   }
}

function removeApos(string) {
   return string.replace(/'/g, "");
}

function loading() {
   show("loading");
}

function unloading() {
   hide("loading");
}

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 fadeRefresh(objectName, objectContent) {
   $('#' + objectName).animate({
      opacity: 0
   },function() {
      $(this).html(objectContent);

      NESTCUBE.initializeLayout();

      $(this).animate({
         opacity: 100
      });
   });
}

function fadeOut(objectName) {
   $('#' + objectName).animate({
      opacity: 0
   }, 2000);
}

function fadeIn(objectName) {
   $('#' + objectName).animate({
      opacity: 100
   }, 2000);
}

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 setLoading(objectName) {
   $('#' + objectName).html('<center><img src="/images/loading.gif"></center>');
}


//----------------------------
// Login
function loginSubmit() {

   var unO = $("input[name='un']", '#loginBlock');
   var pwO = $("input[name='pw']", '#loginBlock');
   var rm = $("input[name='rememberme']", '#loginBlock').is(":checked") ? 1 : 0;

   var un = unO.val();
   var pw = pwO.val();

   $('.formInputError').removeClass("formInputError");

   if (pw.length < 5)
      pwO.addClass("formInputError");

   if (!FORMCHECK.emailSyntaxIsValid(un))
      unO.addClass("formInputError");

   if ($('.formInputError').length > 0)
      return;

   $("#loginSubmit").html("verifying...");

   pw = md5(pw);
   un = escape(un);

   var salt = getSalt();

   $.post('/ajax_login.php', { salt : salt, un : un, pw : pw, rm : rm }, 
      function(data) {

      var json = evalJSON(data);

      if (check(json)) {
         $("#loginSubmit").html("success...");
         setTimeout("refresh()", 1000);
      } else {
         $("#loginSubmit").html("login");
      }
   });

}

//----------------------------
// Invite
function inviteRequest() {
   var values = "";

   $('input','#inviteBlock').each(function() {
      var name = $(this).attr("name");
      var value = trim($(this).val());

      var error = false;


      // Email has to be an email validation
      if (name.indexOf("email") >= 0) {
         if (!FORMCHECK.emailSyntaxIsValid(value))
            error = true;
      // Otherwise continue on with checking if it has input
      } else {
         if (value.length == 0)
            error = true;
      }

      if (error)
         $(this).addClass("formInputError");
      else
         $(this).removeClass("formInputError");


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

      values += name + "=" + escape(value);
   });

   // Compare the emails
   var email = trim($("input[name='email']",'#inviteBlock').val());
   var emailConfirm = trim($("input[name='emailconfirm']",'#inviteBlock').val());

   if (email.indexOf(emailConfirm) < 0 || email.length != emailConfirm.length) {
      $("input[name='email']",'#inviteBlock').addClass("formInputError");
      $("input[name='emailconfirm']",'#inviteBlock').addClass("formInputError");
      return false;
   }

   if ($('.formInputError','#inviteBlock').length > 0)
      return false;

   var salt = getSalt();
   $("input[name='request']",'#inviteBlock').val("submitting...").attr("disabled", true);

   $.post('/ajax_content.php', { salt : salt, values : values,
      type : "getinvitedhandle" }, 
      function(data) {

      confirm(data);

      var json = evalJSON(data);

      if (check(json)) {
         $('#inviteBlock').html(unescape(json.content));
      } else {
         $("input[name='request']",'#inviteBlock').attr("disabled", false).val("request");
         confirm(unescape(json.content));
      }
   });


}

//----------------------------
// Contact form
function contactFormSubmit() {
   var error = false;
   var values = "";
   $("input[name='submit']",'.contactFormBlock').attr("disabled", true);
   $('input,textarea','.contactFormBlock').each(function() {
      if (values.length > 0)
         values += ",";

      var value = trim($(this).val());

      if (value.length <= 0)
         error = true;

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

   if (error) {
      confirm("All fields are required for valid submission");
      $("input[name='submit']",'.contactFormBlock').attr("disabled", false);
      return false;
   }

   $("input[name='submit']",'.contactFormBlock').val("submitting...");

   var salt = getSalt();

   $.post('/ajax_contactform.php', { salt : salt, values : values }, function(data) {
      var json = evalJSON(data);

      if (check(json)) {
         $('.contactFormBlock').html("<strong>" + json.response + "</strong>");
      } else {
         confirm(json.response);
         $("input[name='submit']",'.contactFormBlock').val("submit").attr("disabled", false);
      }
   });

}


//----------------------------
// Splash images
var SPLASHIMAGES = 0;
var SPLASHIMAGECURRENT = 1;
var SPLASHIMAGEMANUALSELECT = false;
var SPLASHIMAGESLOADING = false;

function initializeSplashImages(splashCount) {
   SPLASHIMAGES = splashCount;

   $('#splashImageCaption1').animate({left: 10},600,function() {});

   if (splashCount > 1)
      setTimeout("splashImagesNext()", 7000);
}

function splashImagesNext() {
   if (!SPLASHIMAGES || SPLASHIMAGEMANUALSELECT)
      return;

   next = SPLASHIMAGECURRENT + 1;

   if (next > SPLASHIMAGES)
      next = 1;

   splashImagesLoad(next);
}

function splashImagesLoad(next) {
   if (SPLASHIMAGESLOADING)
      return;

   SPLASHIMAGESLOADING = true;
   var current = 'splashImage' + SPLASHIMAGECURRENT;
   var currentCaption = 'splashImageCaption' + SPLASHIMAGECURRENT;
   var currentDot = 'splashImageDot' + SPLASHIMAGECURRENT;

   SPLASHIMAGECURRENT = next;
   var next = 'splashImage' + SPLASHIMAGECURRENT;
   var nextCaption = 'splashImageCaption' + SPLASHIMAGECURRENT;
   var nextDot = 'splashImageDot' + SPLASHIMAGECURRENT;


   // Update the dot
   $('#' + currentDot + ' img').attr('src', "/images/dotgray.gif");
   $('#' + nextDot + ' img').attr('src', "/images/dotred.gif");

   // Show the next one
   $('#' + next).css('opacity',1.0).show();

   // Remove the old caption
   $('#' + currentCaption).animate({left: -500}, 600, function() {

      // Fade out the current
      $('#' + current).animate({ opacity: 0.0 }, 400, function() {

         // Strip current of the class
         $('#' + current).removeClass('active lastActive').hide();

         $('#' + next).addClass('active');

         // Place in the new caption
         $('#' + nextCaption).animate({left: 10},600, function() {
            SPLASHIMAGESLOADING = false;

            if (SPLASHIMAGES && !SPLASHIMAGEMANUALSELECT)
               setTimeout("splashImagesNext()", 6000);

         });


      });
   });
}

//----------------------------
// Popup dialogue
function popupShow(top, left, width, content, arrowdir) {
   $('#popupBox').unbind();
   $('#popupBox').css('top', top + 'px');
   $('#popupBox').css('left', left + 'px');
   $('#popupBox').css('width', width + 'px');
   $('#popupBox').html(content);

   if (arrowdir == 'left' || arrowdir == 'right')
      var arrow = "LR";
   else
      var arrow = "TB";

   $('#popupBoxArrow' + arrow).css('top', (top + 2) + 'px');
   $('#popupBoxArrow' + arrow).css('left', (left - 5) + 'px');

   $('#popupBoxArrow' + arrow).html('<img src="/images/popupboxarrow' + arrowdir + '.gif">');
   $('#popupBoxArrow' + arrow).show();
   $('#popupBox').show();
}

function popupHide() {
   $('#popupBox').hide();
   $('#popupBoxArrowLR').hide();
   $('#popupBoxArrowTB').hide();
}

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;
} 


