jQuery.extend({
    tooltip: {
        SetToolTipWidthOnIE: function(_width){
        
            $($.TTContentMgr.DOM).find("#xbcontent").eq(0).css('width', _width + "px");
            $($.TTContentMgr.DOM).find('.hStretch').each(function(){
                $(this).css('width', _width + 12 + "px");
                
            })
            $($.TTContentMgr.DOM).find('.tooptipShadowTop').each(function(){
                $(this).css('width', _width + 22 + "px");
            })
            $($.TTContentMgr.DOM).find('.tooptipShadowBottom').each(function(){
                $(this).css('width', _width + 22 + "px");
            })
            
            
        },
        ToolTipContentsMgr: function(){
            var ToolTipVisibility = false;
            var DOM = this.DOM = "#ChVToolTip";
            this.LookupParsedContent = function(_key){
                var copiedElement;
                try {
                    copiedElement = document.getElementById(_key);
                    return {
                        element: copiedElement,
                        elementWidth: $(copiedElement).width(),
                        elementHeight: $(copiedElement).height(),
                        PlaceHolder: document.getElementById('tooltipContentsHolder')
                    };
                } catch (e) {
                    return false;
                }
            };
            this.SetToolTipVisibility = function(_bool){
                if (_bool) {
                    $(DOM).css('display', 'block');
                    
                    
                    
                } else if (!_bool) {
                    $(DOM).css('display', 'none');
                    try {
                        if ($($("#xbcontent").get(0).firstChild.length) > 0) $($("#xbcontent").get(0).firstChild).css('display', 'none');
                        if ($($("#xbcontent").get(0).firstChild.length) > 0) $($(DOM).data('ph').originalDOMaddress).append($("#xbcontent").get(0).firstChild);
                    } catch (e) {
                    }
                } else {
                    alert('Visibility State has been wrongly set');
                }
                ToolTipVisibility = _bool;
                
            };
            this.GetVisibilityState = function(){
                return ToolTipVisibility;
            };
        }
    }
});



(function(){
    //chVToolTip is specifically made for login tooltips.
    //For other tooltips eg; Request, Please refer to tooltip
    
    //Unfortunately It is done this way, because
    //UX requirements never been constantly changed over a period of time
    //Bohdan has written HTML that is best suit for not using this method.
    
    $.fn.chVToolTip = function(_object){
        //Function that retrieves tooltip contents through Ajax requests
        
        if (_object.instruction == "login") Login();
        
        $("#tooltipContentsHolder #LoginTooltipContent").remove();
        var instructions = $(this).GetChVToolTipInstruction();
        
        //There should be two types of contents
        var queryStr = $.page.ui.url.ajaxRequestToolTipContent + instructions.ContentsRefID;
        
        //if contents are in the DOM return a cloned DOM
        var tooltipContentState = $.TTContentMgr.LookupParsedContent(instructions.ContentsRefID);
        
        $.getJSON(queryStr, function(data){
            var tempHTML;
            
            tempHTML = $(data.Content);
            $(tempHTML).attr('id', data.ID);
            
            var _object = {
                element: data.Content,
                elementWidth: $("#" + data.ID).width(),
                elementHeight: $("#" + data.ID).height()
            };
            
            $($.TTContentMgr.DOM).ShowToolTip(_object, instructions);
            
            var theIEWidth = $("#LoginTooltipContent").width();
            
            if ($.browser.msie) {
                $($.TTContentMgr.DOM).find("#xbcontent").eq(0).css('width', theIEWidth + "px");
                $($.TTContentMgr.DOM).find('.hStretch').each(function(){
                    $(this).css('width', theIEWidth + 12 + "px");
                    
                })
                $($.TTContentMgr.DOM).find('.tooptipShadowTop').each(function(){
                    $(this).css('width', theIEWidth + 22 + "px");
                })
                $($.TTContentMgr.DOM).find('.tooptipShadowBottom').each(function(){
                    $(this).css('width', theIEWidth + 22 + "px");
                })
            }
            
            // TODO event bubbling code needs to be rewritten 
            $($.TTContentMgr.DOM).find('[jsClass]').each(function(){
                $.getScript('js/' + $(this).attr('jsClass') + '.js');
            });
            
        });
        
        
        ////////  INITIALISE TOOLTIP CONTENTS ///////////
        function Login(){
            $('.LoginTooltipMain').css('display', 'block');
            $('.LoginTooltipSuccess').css('display', 'none');
            $('.LoginTooltipError').css('display', 'none');
            $('.LoginTooltipForgotenPsw').css('display', 'none');
            $('.LoginTooltipForgotenPswConfirm').css('display', 'none');
			
        }
    };
    
    $.fn.ShowToolTip = function(_object, _instruction){
        var ToolBox = "#ChVToolTip";
        if ($("#ChVToolTip").css('display') == "block") {
            $.TTContentMgr.SetToolTipVisibility(false);
        }
        
        //Returning the previous tooltip back into asset class object
        if ($("#xbcontent").get(0).firstChild != null) {
            $(".assets").append($("#xbcontent").get(0).firstChild);
        }
        
        $($.TTContentMgr.DOM).find("#xbcontent").empty();
        
        $($.TTContentMgr.DOM).data('ph', {
            originalDOMaddress: _object.PlaceHolder
        })
        
        $($.TTContentMgr.DOM).css({
            'top': _instruction.top + "px",
            'left': _instruction.left + "px"
        });
        $(_object.element).css({
            'display': 'block',
            'visibility': 'visible'
        });
        
        if (_instruction.VerticalDirection == 'ToDown') {
        
            $($.TTContentMgr.DOM).find('div.arrowTooltipBottom').css('display', 'none');
            $($.TTContentMgr.DOM).find('div.arrowTooltipTop').css('display', 'block');
        } else {
        
            $($.TTContentMgr.DOM).find('div.arrowTooltipBottom').css('display', 'block');
            $($.TTContentMgr.DOM).find('div.arrowTooltipTop').css('display', 'none');
        }
		var theClone = $(_object.element).clone()
        //Inject into the dom
        $($.TTContentMgr.DOM).find("#xbcontent").append(theClone);
        $(_object.element).css({
            'display': 'none',
            'visibility': 'hidden'
        });
        
       
        $.TTContentMgr.SetToolTipVisibility(true); 
		$('input#uname').focus();
    };
    
    
    $.fn.CloseToolTip = function(){
        $.TTContentMgr.SetToolTipVisibility(false);
		//$($.TTContentMgr.DOM).find("#xbcontent").eq(0).get(0)
    };
    
    $.fn.RemoveToolTipContent = function(){
    };
    
    
    
    $.fn.GetChVToolTipInstruction = function(){
    
        var profile = {
            theWidth: $(this).width(),
            theHeight: $(this).height(),
            thePosition: {
                top: $(this).offset().top,
                left: $(this).offset().left
            },
            theClientWidth: document.body.clientWidth,
            theClientHeight: document.body.clientHeight,
            type: 'short',
            contentReferenceID: $(this).attr('data'),
            tooltipType: $(this).attr('TTtype'),
            maxWidth: 300,
            maxHeight: 500,
            direction: ''
        };
        
        return GetTTPlacingInstruction();
        
        function GetTTPlacingInstruction(){
        
            var horizontalValue = EvaluateToolTipLeftPosition(profile);
            var verticalValue = EvaluateToolTipTopPosition(profile);
            
            profile.direction = horizontalValue.direction; //Set the direction value for later retrieval by subsequent contents
            $($.TTContentMgr.DOM).data("PosProperty", {
                HorizontalDirection: horizontalValue.direction,
                top: verticalValue.position,
                left: horizontalValue.position
            });
            
            var returnInstructions = {
                ContentsRefID: profile.contentReferenceID,
                HorizontalDirection: horizontalValue.direction,
                top: verticalValue.position,
                left: horizontalValue.position,
                VerticalDirection: verticalValue.direction
            };
            
            return returnInstructions;
            
            function EvaluateToolTipLeftPosition(_param){
            
                var leftPos;
                var HorizontalDirectionForTransitions;
                
                if (parseInt(_param.thePosition.left + _param.maxWidth) < _param.theClientWidth) {
                    leftPos = _param.thePosition.left;
                    HorizontalDirectionForTransitions = 'ToRight';
                    
                    return {
                        position: leftPos,
                        direction: HorizontalDirectionForTransitions
                    };
                    
                } else {
                    leftPos = _param.thePosition.left - parseInt(_param.thePosition.left + _param.maxWidth - _param.theClientWidth);
                    
                    HorizontalDirectionForTransitions = 'ToLeft';
                    return {
                        position: leftPos,
                        direction: HorizontalDirectionForTransitions
                    };
                }
            }
            
            function EvaluateToolTipTopPosition(_param){
                var topPos;
                var VerticalDirectionForTransitions;
                if (_param.thePosition.top < parseInt(_param.maxHeight)) {
                    topPos = _param.thePosition.top + 20;
                    VerticalDirectionForTransitions = "ToDown";
                    
                } else {
                    topPos = _param.thePosition.top - parseInt(_param.maxHeight);
                    VerticalDirectionForTransitions = "ToUp";
                }
                return {
                    position: topPos,
                    direction: VerticalDirectionForTransitions
                };
            }
        };
        
        
            }
})(jQuery);


$(document).ready(function(){

    jQuery.extend({
        TTContentMgr: new $.tooltip.ToolTipContentsMgr()
    
    });
    document.body.onclick = function(){
        if ($.TTContentMgr.GetVisibilityState) {
            $($.TTContentMgr.DOM).CloseToolTip();
        }
    }
});

