
/*--- MyProjectList Sort --------------------*/
function OnChangeSortType(dropdown) {

    var myindex  = dropdown.selectedIndex
    var SelValue = dropdown.options[myindex].value
    
    top.location.href = SelValue;
    
    return true; 
}

/*--- List Detail Sort --------------------*/
function onChangeSortTypeSubmit(dropdown) {
    document.registry.submit(); 
}

/*--- Check all functionality for check box --------------------*/


/*--- TODO: this  type="checkbox" onClick="checkUncheckAll(this);" class="form_checkbox" name="checkAll" value="" />
      should  not be  on the jsp, add event using jquery and after use Util.js
  ---*/
function checkUncheckAll(e) {

     var theForm = e.form, x = 0;
     for(x=0; x<theForm.length;x++){
         if(theForm[x].type == 'checkbox' && theForm[x].name != 'checkall' &&  theForm[x].name != 'isPrivate'){
            theForm[x].checked = e.checked;
         }
     }
}



/*--- Assumes that jquery.js  and Util.js are available  ----*/



/*------------- WishList -------------------------------*/

// Adding events  to  elements  the jquery way.
 
// $(document).ready lauches BEFORE onload() event for the page
// it's a jquery function that executes  when the dom is ready to be  manipulated.
// It does not wait for big images.
// Perhaps  we need a better naming convention so we 
// do not have  name space name  collisions
var wishListActivator = null;

var registerRegistryEvents = function () {
	 $(".wishListToggleBtn").click( function(event) {
        if (wishListActivator != null && event.target !== wishListActivator) {
            toggleListScroller(event, true);
        } else {
            toggleListScroller(event);
        }
        if ($(event.target).css("display") != "none")
            wishListActivator = event.target
        event.preventDefault();
    });
   
   $("#addItemMainFormFloating").submit(function(event) {
       var registryIdSelected = $("input[@name=registryId]:checked").val();
       var newList = registryIdSelected == "new_list"; 

       if (newList && jQuery.trim(($("#new_wishlist_name").val())).length == 0) {
           $("#errorMessage").html("Please specify a name for the new list.");
           $("#importantMessageBox").show();
           return false; 
       }
       
       return true;
   });
}

$(document).ready (
  function() {
	  toolTipManager.initialize();
	  registerRegistryEvents.call();

	  $("#cancelLink").click( function(event) {  
		  toggleListScroller(event);
		  return  false
	  });

	  $("#createNewListBtnFloating").click(function (){ doCreateNewListRequest();return  false;});

	  //turn on javascript menu for sortBy functionality [My ProjectList page]
	  $("#sortByMenuJS").css("display","block");
	  $("#sortByMenuJS").attr("name", "sortBy");
 
  }
);

function toggleListScroller(event, forceOpen) {
    $("#importantMessageBox").hide();
 
    var offset = $(event.target).offset();
    var box =  $("#listOfWishlistFloating");

    if (forceOpen || box.css("display") == "none") {
        box.show();
        var offsetParent = box.offsetParent().offset();
	    // 22 is  the height of the button, we want to the box right below
	    box.css("top", offset.top - offsetParent.top + 22 +"px");
	    box.css("left", offset.left - offsetParent.left + "px");
    } else {
        box.toggle();
    }
}

function addItemToListRequest() {
    // Obtain the selected registryId from the radio buttons selected
    
    var formData = $("#addItemMainFormFloating").serialize();
    
    jQuery.ajax({
         data: formData,
         
         dataType: 'html',                     
         
         error: function (xhr, textStatus, errorThrown) {
            //xhr.status == 302 will happen when log in is required(or the page did move)
            if(xhr.status == 302) {
                window.location = xhr.getResponseHeader("Location");
            } else {
                $("#errorMessage").html(xhr.status + " - " + xhr.statusText);
                $("#importantMessageBox").toggle();
            }                
         },
          
         success: function(data, textStatus) {    
            if (newList) {
                document.location.reload();
            } else {        
                $('#listOfWishlistFloating').toggle();
            }                
         },
         
         type: 'POST',
         url: '/wishlistAddItemsAjax'
    });

}

var toolTipManager = {
   defaultEvent : "hover",
   xOffset : 5,
   yOffset : 10,
   width: 300,
   contents : {},
   tooltip :  $('<div id="tooltip" class="hintBox" style="display:none"><a href="#" onclick="toolTipManager.hideTooltip();return false;" class="close">Close</a><dt>Quick Hint</dt><dd><ul></ul></dd></div>'),
   initialize : function() {
       //console.log("Initializing ToolTipManager");
       this.registerContent('default', 'Sorry but no help is available for this topic.');
       $('body').append(this.tooltip);
       $('#tooltip').hover(function() {
         $('div#tooltip').stop(true,false).fadeTo('fast',1);
       }, function() {
         $('div#tooltip').stop(true, true).fadeOut('fast');
       });
   },
   registerTooltip : function(targetElementId, content, onEvent) {
     //console.log("registering %s with %s", targetElementId, content);
        this.registerContent(targetElementId, content);
        var target = $('#'+targetElementId);
        var manager = this;
        var callbackShow = function(e) {
            //console.log("click fired");
            var target = $(e.target);
            var id = target.attr("id");
            manager.showTooltip(id, target);
            target.blur();
            e.stopPropagation();
            e.preventDefault();
        }

        var callbackHide = function() {
            $("div#tooltip").fadeOut(200);
        }

        if ('click' == onEvent) {
            target.unbind().click(callbackShow);
            target.mouseleave(callbackHide);
        } else {
            target.unbind().hover(callbackShow, callbackHide);
        }
        //console.log(target);
   },
   registerContent : function(tooltipId, content) {
	   if (typeof(content) == "string") {
		   this.contents[tooltipId] = unescape(content);
	   } else {
		   if (content.content) {
			    content.content = unescape(content.content);
		   }
		   this.contents[tooltipId] = content;
	   }
   },
   getContent : function(tooltipId) {
       //console.log("Retrieving content for %s.", tooltipId);
        var content = this.contents[tooltipId];
        //console.log("content is %s", content);
        if (!content)
            content = this.contents['default'];
        return content;
   },
   showTooltip : function(tooltipId, target) {
       //console.log("showing %s for %s:%o", tooltipId, target.attr("id"), target);
        var registeredContent = this.getContent(tooltipId);
        var container = $($('div#tooltip')[0]);
        //console.log(content);
        var title = "";
        var content = "";
        if (typeof(registeredContent) == "string") {
            content = registeredContent;            
        } else {
            if (registeredContent.title) {
            	title = registeredContent["title"];
            }
            content = registeredContent["content"];
        }
        $("dt", this.tooltip).html(title);
        $("ul", this.tooltip).html(content);
        
        
        container.stop(true, false).show().fadeTo(0,1);

        var offset = target.offset();
        var top = (offset.top) - this.yOffset;
        var left = (offset.left + this.xOffset + target.outerWidth());
        var windowWidth = $(window).width();
        var windowScrollLeft = $(window).scrollLeft();
        var spaceToTheLeft = offset.left - windowScrollLeft;
        var spaceToTheRight = windowWidth + windowScrollLeft - offset.left;
        
        if (left + container.outerWidth() > (windowScrollLeft + windowWidth)) {
            //not enough space to display in the normal fashion
            if (spaceToTheLeft >= (container.outerWidth() + this.xOffset)) {
                left = offset.left - this.xOffset - container.outerWidth();
            } else if (windowWidth < container.width()) {
                left = windowScrollLeft;
            } else {
                left = windowScrollLeft + (windowWidth/2) - (container.width()/2);
            }
        }
        
        container.css("top", top+"px").css("left", left+"px");
   },
   hideTooltip : function() {
       this.tooltip.hide();
   },
   isVisible : function() {
       return this.tooltip.style.display != "none";
   }
};
