﻿//-- Container for XMLHTTPRequest
var m_request;
//var m_requestURLBase	= "http://wxp-fr2gg1s.blr.amer.dell.com/glossary.aspx";
var m_overrideRequestMimeType = false;

//-- Lexicon containers
var m_container;
var m_contentContainer;
var m_header;
var m_title;
var m_busyIcon;
var m_containerTimeout	= 1500;
var m_hideMethodId;
var m_contentContainerDefault;

var m_opacityIdx = 10;
var m_fadeMethodId;
var m_prevRequestUrl;

if ( typeof ( addOnLoad ) != "undefined" )
{
    addOnLoad ( InitLexicon );
}
//-- ######################################################
//-- Base event delegates
//-- ######################################################
function InitLexicon()
{
  	//-- Wire up the AJAX event model
	InitXMLHTTPRequest();

	if(!SupportsAjax())
	{
	    return;
	}

	if ( typeof( m_ttipAutoDetect ) != "undefined" )
	{
	    setTimeout ( AttachTooltips, 100 );
	}
	else
	{
	    TTipBindEvents();
	}
}

function TTipBindEvents ()
{
    hasTooltips = false;

	//-- Bind up all the glossary links in the document
	//var glossaryItems = document.getElementsByName( "gl" );
	var glossaryItems = document.getElementsByTagName( "span" );
	var glItem;
	
	for( var item = 0; item < glossaryItems.length; item++ )
	{
	    if ( glossaryItems[item].attributes.glid )
	    {
    	    glItem = glossaryItems[item];
    	    if ( typeof(glItem.attributes.glnodeco) == "undefined" )
    	    {
                glItem.className = "glossaryitem";
            }
            else
            {
                glItem.className = "glossaryitem_nodecoration";
            }
            
		    glItem.onmouseover = function() { ShowGlossaryTip( this ); return false; }
		    glItem.onmouseout = function() { HideGlossaryTip(); }
		    
		    hasTooltips = true;
		}
	}
	
	if ( hasTooltips )
	{
	    // Render tooltip container
	    var elem        = document.createElement ( "div" );
	    var container   = "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" id=\"glcontainer\" class=\"glossarycontainer\">";
        container       += "<tr><td id=\"glpointer\"><img src=\"" + m_imgPfx + "/images/global/brand/icons/pointer.gif\" class=\"pointer\"/></td></tr>";
        container       += "<tr><td id=\"glheader\" class=\"rowsolid glheader\"><h2 class=\"titlestylesolid\"><span id=\"gltitle\" style=\"float:left\"></span><span><a class='closeglossaryitem' href='javascript:TTHide();'>" + m_popClose + "</a></span></h2></td></tr>";
        container       += "<tr><td id=\"glcontent\" class=\"glossarycontent\"><div id=\"glbusyicon\" style=\"text-align:center\">";
        container       += "<img src=\"" + m_imgPfx + "/images/global/brand/icons/busyicon.gif\" class=\"busyicon\" /><br />Loading</div></div></td></tr></table>";
        elem.innerHTML  = container;
        if ( document.body )
        {
            document.body.appendChild(elem);
        }
    	
	    //-- Bind up the containers
	    m_container = document.getElementById( "glcontainer" );
	    m_busyIcon = document.getElementById( "glbusyicon" );
	    m_contentContainer = document.getElementById( "glcontent" );	
	    m_header = document.getElementById( "glheader" );
	    m_title = document.getElementById( "gltitle" );
    		
	    m_contentContainerDefault = m_contentContainer.innerHTML;
    	
	    m_container.onmouseout = function() { HideGlossaryTip(); }
	    m_container.onblur = function() { HideGlossaryTip(); }
	    m_container.onmouseover = function() { LockTimer(); }
	    m_contentContainer.onmouseover = function() { LockTimer(); }
    }
}

function SupportsAjax()
{
    return m_request != undefined;
}

//-- ######################################################
//-- Tooltip handlers
//-- ######################################################

var ttip_responseCollection = new Object();

//-- Show the glossary container and move it to the right position
function ShowGlossaryTip( src )
{
	if( m_container != null )
	{
		if( m_hideMethodId != null )
		{
			window.clearTimeout( m_hideMethodId );
		}
		
		m_contentContainer.innerHTML = m_contentContainerDefault;
		
		m_container.style.opacity = 1.0;
		//m_container.style.left = src.offsetLeft + 2 + "px";
		//m_container.style.top = src.offsetTop + src.offsetHeight + 1 + "px";

	    if ( src.attributes.glwidth )
	    {
	        m_container.style.width = src.attributes.glwidth.value;
	    }
	    else
	    {
	        m_container.style.width = "342px";
	    }
	    
	    if ( src.attributes.gltitle )
	    {
	        m_title.innerHTML = src.attributes.gltitle.value;
	    }

		m_container.style.display = "block";
		
		if ( ttip_responseCollection[src.attributes.glid.value] )
		{
		    ttipresponsetemp = ttip_responseCollection[src.attributes.glid.value];
		    if ( typeof( ttipresponsetemp["title"] ) != "undefined" && ttipresponsetemp["title"] != "" )
		    {
		        m_title.innerHTML = ttipresponsetemp["title"];
		    }
		    
		    var responseText = ttipresponsetemp["content"];
		    var moredetailscont = ttipresponsetemp["moredetails"];
   	        if ( typeof( moredetailscont ) != "undefined" && moredetailscont != "" )
   	        {
                responseText += "<div style=\"float:right; padding-right:20px;\">";
                responseText += moredetailscont;
                responseText += "</div>";
   	        }
		    
		    m_contentContainer.innerHTML = responseText;
		    m_busyIcon.style.display = "none";
		    PositionContainer(src);
		}
		else
		{
    		m_busyIcon.style.display = "block";
		    PositionContainer ( src );
			GetLexiconTerm( src );				
		}
	}
}

function truebody()
{
    return ( document.compatMode && document.compatMode!="BackCompat" )? document.documentElement : document.body
}

// Position the container smartly based on the available space
function PositionContainer (src)
{
    var scrollTop  = (document.all)? ( truebody().scrollTop) : window.pageYOffset;
    var scrollLeft = (document.all)? ( truebody().scrollLeft) : window.pageXOffset;
    var clientHeight = (document.all)? ( truebody().clientHeight) : document.body.clientHeight;
    var clientWidth = (document.all)? ( truebody().clientWidth) : document.body.clientWidth;
    var m_pointer = document.getElementById ( 'glpointer' );

    var left=0, top=0;
    var parent = src;
    
    while ( parent )
    {
        left += parent.offsetLeft;
        top += parent.offsetTop;
        parent = parent.offsetParent;
    }
    
    if ( m_pointer )
    {
        m_pointer.style.display = "block";
    }

    var conWidth    = m_container.offsetWidth;
    var conHeight   = m_container.offsetHeight;

    if ( top - 2 - conHeight > scrollTop )
    {
        if ( m_pointer )
        {
            conHeight -= m_pointer.offsetHeight;
            m_pointer.style.display = "none";
        }
        
        m_container.style.top = top - 2 - conHeight + "px";
    }
    else
    {
		m_container.style.top = top + src.offsetHeight + 1 + "px";
    }
    
    if ( (left + (10) + conWidth > scrollLeft + clientWidth)
            && ( (left + src.offsetWidth) - (10) - conWidth > scrollLeft ) )
    {
        m_container.style.left = (left + src.offsetWidth) - (10) - conWidth + "px";
        if ( m_pointer )
        {
            m_pointer.style.display = "none";
        }
    }
    else
    {
        m_container.style.left = left + (10) + "px";
    }
}

//-- Hide the glossary tip based on a delay
function HideGlossaryTip()
{
	m_hideMethodId = window.setTimeout( TTHide, m_containerTimeout );
}

//-- Clears the method timeout to "pin" the window open while active
function LockTimer()
{	
	window.clearTimeout( m_hideMethodId );
}

//-- Hide the glossary container and clear the timeout
function TTHide()
{
	if( m_container != null )
	{	
		m_container.style.display = "none";		
		window.clearTimeout( m_hideMethodId );
		m_contentContainer.innerHTML = m_contentContainerDefault;
		m_hideMethodId = null;			
	}
}

//-- Bind the returned content to the glossary container
function BindContent(src)
{
	//-- Waiting for content to come back
	if( m_request.readyState < 4 )
	{ 		
		return;
	}

	if( m_request.readyState == 4 ) 
	{
	    m_prevRequestUrl = null;
	    if( m_request.status == 200 && m_request.responseText )
	    {
	        try
	        {
	            eval ( m_request.responseText ); 	        
	        
	            if ( typeof(ttipresponse) != "undefined" )
                {
                    var responseText                = ttipresponse["content"];

                    var moredetailscont = ttipresponse["moredetails"];
                    if ( typeof( moredetailscont ) != "undefined" && moredetailscont != "" )
                    {
                        responseText += "<div style=\"float:right; padding-right:20px;\">";
                        responseText += moredetailscont;
                        responseText += "</div>";
                    }

                    if ( typeof( ttipresponse["title"] ) != "undefined" && ttipresponse["title"] != "" )
	                {
	                    m_title.innerHTML = ttipresponse["title"];
	                }
                    m_contentContainer.innerHTML    = responseText;
           	        
	                m_busyIcon.style.display        = "none";
	                PositionContainer(src);
	                ttip_responseCollection[src.attributes.glid.value] = ttipresponse;
	            }
		    }
	        catch ( ex )
	        {
	            if ( !m_production  )
	            {
	                alert ( "Exception occured in [BindContent]: \n" + ex.message );
	            }
	            TTHide( );
	        }
		}
		else
		{
		    TTHide( );
		}
	}
}



//-- ######################################################
//-- AJAX handlers
//-- ######################################################

//-- Instantiate the XMLHttpRequest
function InitXMLHTTPRequest()
{
	if( window.XMLHttpRequest )
	{			
		m_request	= new XMLHttpRequest();
		
		if( m_overrideRequestMimeType && m_request.overrideMimeType )
		{
			m_request.overrideMimeType( "text/xml" );
		}
	}
	else if( window.ActiveXObject )
	{
		m_request = new ActiveXObject( "Microsoft.XMLHTTP" );								
	}	
}

function GetUrl(src)
{
    var requestUrl = m_requestURLBase + "&~ttid=" + escape( src.attributes.glid.value );
	if ( src.attributes.glmoredetails )
	{
	    var ref = src.attributes.glmoredetails.value;
	    ref = ref.replace ( /:/g, "~" );
	    requestUrl += "&~ttref=" + ref;
	}
	
	return requestUrl;
}

//-- Delegate for grabbing content
function GetLexiconTerm( src )
{
	if( m_request != null )
	{
	    try
	    {
   	        var requestUrl = GetUrl ( src );

            if ( m_prevRequestUrl == null || requestUrl != m_prevRequestUrl )
            {
	            m_request.abort();
	            m_request.onreadystatechange = function() { BindContent(src) };
	            m_request.open( "GET", requestUrl, true );
	            m_request.send( null );
	        }
	    }
	    catch ( ex )
	    {
	       if ( !m_production  )
	       {
	            alert ( "Exception occured in [GetLexiconTerm]: \n" + ex.message );
	       }
	       
	       src.className="";
	       src.onmouseover=null;
	       src.onmouseout=null;
	       TTHide(); 
	    }
	}
}


var m_ttregex;
var m_ttkeys;

// Iterate thru the DOM and assign tooltips
function AttachTooltips ()
{
    if ( typeof(TTRegEx) != "undefined" )
    {     
        m_ttregex = new RegExp ( TTRegEx, "g" );
        m_ttkeys = TTKeys;
        SearchReplaceInDOM ( document.body, 0 );
        TTipBindEvents();
    }
}

// Recursive function to iterate DOM and match keywords and assign tooltips.
function SearchReplaceInDOM( obj )
{
	for (var i=0; i<obj.childNodes.length; i++) 
	{
		var childObj = obj.childNodes[i];

		if ( childObj.nodeName == "#text" )
		{
		    nodeVal = childObj.nodeValue;
		    
            var matches = m_ttregex.exec ( nodeVal );
            var prevmatch = 0;
            var ttid;
            var found = false;
            var ttipHolderSpan;
            while ( matches != null )                        
            {
                found = true;
                ttid = m_ttkeys[matches[0]];
                ttipHolderSpan = document.createElement("span");
                var ttipSpan = document.createElement("span");
                ttipSpan.setAttribute("glid", ttid);

                var ttipText = document.createTextNode ( matches[0] );
                var beforeText = document.createTextNode ( nodeVal.substring (prevmatch, matches.index) );
                
                ttipSpan.appendChild ( ttipText ); 
                ttipHolderSpan.appendChild ( beforeText );
                ttipHolderSpan.appendChild ( ttipSpan );
                prevmatch = matches.index + matches[0].length;
                
                matches = m_ttregex.exec ( nodeVal );
            }
            
            if ( found  )
            {
                if ( prevmatch < nodeVal.length )
                {
                    var afterText = document.createTextNode ( nodeVal.substring ( prevmatch, nodeVal.length +1) );
                    ttipHolderSpan.appendChild ( afterText );
                }
                
                obj.insertBefore ( ttipHolderSpan, childObj );
                obj.removeChild ( childObj );
                continue;             
            }
		}
		SearchReplaceInDOM(childObj );
	}
}