// Functions for item tooltips.
// Highly hacked together in an amateurish and inadvisable way by Genstein.
//
// Copyright (c) 2007 by Genstein. Not reusable without prior, written permission.
//
// This notice must remain intact.

function trace(s)
{
    document.title = s;
}

function getElementText(element)
{
    if ( document.all )
    {
        return element.innerText;
    }
    else if (element.textContent)
    {
        return element.textContent;
    }        
    else
    {
        return "";
    }
}

function setElementText(element, text)
{
    if (element.innerText)
    {
        element.innerText = text;
    }
    else if (element.textContent)
    {
        element.textContent = text;
    }
}

function setElementText(element, text)
{
    while (element.hasChildNodes())
    {
        element.removeChild(element.lastChild);
    }
    var doc = element.ownerDocument || document;
    element.appendChild(doc.createTextNode(text));
}

function isInteger(expr)
{
    if ( isNaN(parseInt(expr)) )
    {
        return false;
    }
    return true;
}

function replaceLootElements()
{
    if(!document.getElementById)
        return;

    var objArray = getLootElements();
    //trace("Has " + objArray.length + " elements");
    if ( !objArray.length )
    {
        return;
    }

    for (var i=0; i<objArray.length; i++)
    {
        var element = objArray[i];

        var params = element.className.split(" ");
        var quality = params[1];
        var itemNumber = 0;
        if ( isInteger( params[2] ) )
            itemNumber = parseInt( params[2] );

        var newClass = getClassForQuality(quality);
        var itemName = getElementText(element);

        // create a "span" with our image and link, and a hidden span for our tooltip data.
        //
        // child order is:
        // - span
        // ---- image span
        // ---- hidden span
        // ---- link span
        //
        var span = document.createElement("span");

        var imageSpan = createFramedQuestionMarkImage();
        imageSpan.onmouseover = imageSpan_onMouseOver;
        
        span.appendChild(imageSpan);
        
        // create our hidden span, initially containing the item name/number for which we want data
        var hiddenSpan = document.createElement("span");
        if ( itemNumber != 0 )
            setElementText(hiddenSpan,itemNumber);
        else
            setElementText(hiddenSpan,itemName);
            
        hiddenSpan.style.display = "none";
        hiddenSpan.id = "lootData" + i; // we assign a unique ID so we can use TagToTip() later
        span.appendChild(hiddenSpan);

        if ( itemNumber != 0 )
            span.appendChild(createWowheadItemLink(itemName, itemNumber));
        else
            span.appendChild(createWowheadSearchLink(itemName));

        //newElement.setAttribute("class", newClass); // does not work in IE for some reason! using below alternative
        span.className = newClass;

        // now update the element to contain the new span
        //
        element.className = "egoitem";
        setElementText(element, "");
        element.appendChild(span);
    }

    // fix up transparency for IE
    //fixup_pngs();
}

function imageSpan_onMouseOver()
{
    // Find our hidden span and link span, relative to ourselves    
    var hiddenSpan = getHiddenSpanFromParent(this.parentNode);
    var linkElement = getLinkElementFromParent(this.parentNode);

    // Pull the item name/number from the body of the hidden span    
    var itemNameOrNumber = getElementText(hiddenSpan);
    setElementText(hiddenSpan, "Loading...");
    
    // Now swap our image to 'loading';
    // replace our "on mouse over" handler with a new one
    // and invoke that one immediately (to display its tooltip).
    setImageSpanImage(this, getLoadingImagePath());
    this.onmouseover = function() { imageSpan_onMouseOver2(this); }
    
    // Now load loot data for that item, asynchronously.
    // When it's ready, dump it in the hidden span.
    loadLootData(itemNameOrNumber, hiddenSpan, this, linkElement);
    
    imageSpan_onMouseOver2(this);
    
    return;
    
//    var newImageSpan = createFramedImage("/wow/wowimages/loading.jpg");
//    newImageSpan.onmouseover = imageSpan_onMouseOver2;
//    newImageSpan.id = "lootImage" + i;
//    this.parentNode.replaceChild(newImageSpan,this);
//    //fixup_pngs();
}

function imageSpan_onMouseOver2(This)
{
    if (This)
    {
        TagToTip( getHiddenSpanFromParent(This.parentNode).id );
    }
}

function getImageSpanFromParent(theParent)
{
    return theParent.firstChild;
}

function getHiddenSpanFromParent(theParent)
{
    return theParent.firstChild.nextSibling;
}

function getLinkElementFromParent(theParent)
{
    return theParent.firstChild.nextSibling.nextSibling;
}

// Retrieve all DOM elements with a class beginning "loot"
function getLootElements()
{
    a = document.getElementsByTagName("*");

    objs = new Array();
    j = 0;
    for (i=0; i<a.length; i++)
    {
        element = a[i];

        c = element.className;
        if ( c != "" )
        {
            if ( c.indexOf("loot") == 0 )
            {
                objs[j++] = element;
            }
        }
    }
    return objs;
}

function getClassForQuality(quality)
{
    if ( !quality )
        quality = "q1";

    var newClass = "q1";

    if (quality.indexOf("q") == 0 )
    {
        // if quality begins "q", assume "q0", "q1", "q2" etc. and leave as is
        newQuality = quality;
    }
    else if ( quality == "poor" )
        newClass = "q0";
    else if ( quality == "gray" )
        newClass = "q0";
    else if ( quality == "grey" )
        newClass = "q0";
    else if ( quality == "common" )
        newClass = "q1";
    else if ( quality == "white" )
        newClass = "q1";
    else if ( quality == "uncommon" )
        newClass = "q2";
    else if ( quality == "superior" )
        newClass = "q2";
    else if ( quality == "green" )
        newClass = "q2";
    else if ( quality == "rare" )
        newClass = "q3";
    else if ( quality == "blue" )
        newClass = "q3";
    else if ( quality == "epic" )
        newClass = "q4";
    else if ( quality == "purple" )
        newClass = "q4";
    else if ( quality == "legendary" )
        newClass = "q5";
    else if ( quality == "orange" )
        newClass = "q5";
    else if ( quality == "artifact" )
        newClass = "q6";
    else if ( quality == "gold" )
        newClass = "q6";

    return newClass;
}

function createWowheadSearchLink(itemName)
{
    var textLink = document.createElement("a");
    setElementText( textLink, itemName );
    textLink.setAttribute("href", "http://www.wowhead.com/?search=" + itemName);
    return textLink;
}

function createWowheadItemLink(itemName, itemNumber)
{
    var textLink = document.createElement("a");
    setElementText( textLink, itemName );
    textLink.setAttribute("href", "http://www.wowhead.com/?item=" + itemNumber);
    return textLink;
}

function createFramedImage(imageUrl, mouseOverCode)
{
    var borderImageUrl = "/wow/wowimages/icon_border_medium.png";

    var span = document.createElement("span");
    
    var html = "<style>img, div { behavior: url(iepngfix.htc); }</style>";
    html = html + "<table style=\"display: inline; vertical-align: -7px\">";
    html = html + "<tbody><tr><td>";
//    html = html + "<div class=\"imageDiv\" style=\"width: 44px; height: 44px; background-position: 4px 4px; background-repeat: no-repeat; behavior: url(/wow/iepngfix.htc);\">";
    html = html + "<div class=\"imageDiv\" style=\"width: 44px; height: 44px; background-position: 0px 0px; background-repeat: no-repeat; behavior: url(/wow/iepngfix.htc);\">";
    html = html + "<div style=\"width: 44px; height: 44px; background-repeat: no-repeat; behavior: url(/wow/iepngfix.htc);\">";
    html = html + "</div>";
    html = html + "</div>";
    html = html + "</tbody></td></tr>";
    html = html + "</table>";
        
    span.innerHTML = html;
    
    setImageSpanBorderImage(span, borderImageUrl);
    setImageSpanImage(span, borderImageUrl);
    setImageSpanImage(span, getQuestionMarkImagePath());
    
    return span;    
}

function setImageSpanImage(imageSpan, imageUrl)
{    
    var imageDiv = findImageDiv(imageSpan);        
    if ( imageDiv )
    {
        imageDiv.style.backgroundImage = "url(" + imageUrl + ")";
    }    
}

function setImageSpanBorderImage(imageSpan, borderImageUrl)
{
    var imageDiv = findImageDiv(imageSpan);        
    if ( imageDiv )
    {
        var borderDiv = imageDiv.firstChild;
        if ( borderDiv )
        {
            borderDiv.style.backgroundImage = "url(" + borderImageUrl + ")";
        }
    }    
}

function findImageDiv(imageSpan)
{
    var list = imageSpan.getElementsByTagName("div");
    for (var i=0; i<list.length; i++)
    {
        var element = list[i];
        if ( element.className == "imageDiv" )
        {
            return element;
        }
    }
    return null;
}

function createFramedImage_old(imageUrl, mouseOverCode)
{
    // Note: for IE pre 7 compatibility, the onmouseover tag has to be on a span
    // containing the image rather than the image. This works fine in other browsers too.
    // (This is because fixup_pngs() will replace the image tag with a span containing
    // a new image tag, losing our onmouseover! So we put the onmouseover outside the
    // image, which means it stays outside any span that may be inserted inside it
    // by fixup_pngs().)
    //
    var borderImageUrl = "/wow/wowimages/icon_border_medium.png";

    var image = document.createElement("img");
    image.setAttribute("src", borderImageUrl);

    // IE:
    //     image.style["background-repeat"] = "no-repeat;";
    //     image.style["background-position"] = "3px 3px;";
    // Firefox:
    //     image.style.backgroundRepeat = "no-repeat;";
    //     image.style.backgroundPosition = "3px 3px;";
    // Both:
    image.className = "itemImage";

    image.style.backgroundImage = "url(" + imageUrl + ")";

    var span = document.createElement("span");
    span.innerHTML = "<style>.itemImage {background-repeat: no-repeat; background-position: 3px 3px;}</style>";

    if ( mouseOverCode )
        span.onmouseover = mouseOverCode;

    span.insertBefore(image, span.firstChild);
    return span;
}

function createFramedQuestionMarkImage()
{
    return createFramedImage(getQuestionMarkImagePath());
}

function getQuestionMarkImagePath()
{
    //return "/wow/wowimages/questionmark_medium.jpg";
    return "http://www.wowarmory.com/images/icons/43x43/inv_misc_questionmark.png";
}

function getLoadingImagePath()
{
    //return "/wow/wowimages/loading.jpg";
    return "";//"http://www.wowarmory.com/images/icons/43x43/inv_misc_gift_02.png";    
}

function getMissingImagePath()
{
    //return "/wow/wowimages/missing.jpg";
    return "http://www.wowarmory.com/images/icons/43x43/inv_misc_thegoldencheep.png";    
}

function loadLootData(itemNameOrNumber, dataOutElement, imageOutSpan, nameOutLink)
{
  var xmlObj = null;

  if(window.XMLHttpRequest)
  {
      xmlObj = new XMLHttpRequest ();
  }
  else if (window.ActiveXObject)
  {
      xmlObj = new ActiveXObject("Microsoft.XMLHTTP");
  }
  else
  {
      return;
  }

  xmlObj.onreadystatechange = function()
  {
    if(xmlObj.readyState == 4)
    {
       if (xmlObj.status == 200)
       {
         var response = xmlObj.responseText;
         
         var parts = response.split("|<-->|");
         var tooltipData = parts[0];
         var itemName = parts[1];
         var imageName = parts[2];

         if ( dataOutElement && tooltipData )
         {
             dataOutElement.innerHTML = tooltipData;
             
             // in case user is still hovering over item...
             
             // hide existing tooltip if any
             tt_HideTip();
         }
         
         if ( imageName && imageOutSpan )
         {
             var imageUrl = getWowheadImageUrlForImageName(imageName);
             setImageSpanImage(imageOutSpan, imageUrl);
         }
         else
         {
            setImageSpanImage(imageOutSpan, getMissingImagePath());
         }
         
         if ( itemName && nameOutLink )
         {
             itemName = itemName;       
             setElementText(nameOutLink, itemName);
         }
         
         //fixup_pngs(); // required in IE pre 7: sorts out the image specified by gethtml_image() so that transparency works.  
       }
       else
       {
           if ( dataOutElement )
               dataOutElement.innerHTML = "Unable to retrieve data: " + xmlObj.statusText;
       }
    }
  }
  
  var url = "/wow/Item.aspx?Item=" + itemNameOrNumber;
  xmlObj.open ('GET', url, true);
  xmlObj.send (null);
}

function getWowheadImageUrlForImageName(imageName)
{
    //return "http://www.wowhead.com/images/icons/medium/" + imageName + ".jpg";
    return "http://www.wowarmory.com/images/icons/43x43/" + imageName.toLowerCase() + ".png";
}

/*
addLoadEvent

Courtesy of http://simonwillison.net/2004/May/26/addLoadEvent/
*/

function addLoadEvent(func) 
{
    var oldonload = window.onload;
    if (typeof window.onload != 'function') 
    {
        window.onload = func;
    } 
    else 
    {
        window.onload = function() 
        {
            oldonload();
            func();
        }
    }
}

/*

Correctly handle PNG transparency in Win IE 5.5 & 6.
http://homepage.ntlworld.com/bobosola. Updated 18-Jan-2006.

Use in <HEAD> with DEFER keyword wrapped in conditional comments:
<!--[if lt IE 7]>
<script defer type="text/javascript" src="pngfix.js"></script>
<![endif]-->

*/
function fixup_pngs()
{
    var arVersion = navigator.appVersion.split("MSIE")
    var version = parseFloat(arVersion[1])

    if ((version >= 5.5) && (document.body.filters))
    {
    for(var i=0; i<document.images.length; i++)
    {
        var img = document.images[i]
        var imgName = img.src.toUpperCase()
        if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
        {
            var imgID = (img.id) ? "id='" + img.id + "' " : ""
            var imgClass = (img.className) ? "class='" + img.className + "' " : ""
            var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
            var imgStyle = "display:inline-block;" + img.style.cssText
            if (img.align == "left") imgStyle = "float:left;" + imgStyle
            if (img.align == "right") imgStyle = "float:right;" + imgStyle
            if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
            var strNewHTML = "<span " + imgID + imgClass + imgTitle
            + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
            + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
            + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>"
            img.outerHTML = strNewHTML
            i = i-1
        }
    }
    }
}
