/******************************************************************************
 * Brouse ratings data
 *
 * kp, 10/08
 */

stdjs.include('/lib/js/std/xml.js');

/**
 * Toggle brewery opened and closed (to show beer entries)
 */
function brewery_drilldown(img, brewery_id, divID)
{
    //alert(brewery_id);
    //alert(divID);

    var beerData = new RatingData();

    beerData.setDivID(divID);
    beerData.setURL('/kpscellar/ratings/ratingdata.php?breweryID='+brewery_id);

    beerData.toggle(img);
}

/**
 * Toggle beer opened and closed (to show ratings)
 */
function beer_drilldown(img, beer_id, divID)
{
    //alert(beer_id);

    var ratingData = new RatingData();

    ratingData.setDivID(divID);
    ratingData.setURL('/kpscellar/ratings/ratingdata.php?beerID='+beer_id);

    ratingData.toggle(img);
}

/**
 * Toggle rating opened and closed (to show details)
 */
function rating_drilldown(img, rating_id, divID)
{
    //alert(rating_id);

    var ratingData = new RatingData();

    ratingData.setDivID(divID);
    ratingData.setURL('/kpscellar/ratings/ratingdata.php?ratingID='+rating_id);

    ratingData.toggle(img);
}

/**
 * Toggle other field (style, etc) opened and closed (to show details)
 */
function search_drilldown(img, search_parm, divID)
{
    var ratingData = new RatingData();

    ratingData.setDivID(divID);
    ratingData.setURL('/kpscellar/ratings/ratingdata.php?'+search_parm);

    ratingData.toggle(img);
}

/******************************************************************************
/******************************************************************************
/**
 * Create a new Rating Data object.
 */

function RatingData()
{
    // Map of XML main element tag to the inner tag names and draw functions.
    this.tagmap = 
    {
        breweries:
        {
            tag: 'brewery',
            draw: this.drawBrewery
        },
        beers:
        {
            tag: 'beer',
            draw: this.drawBeers
        },
        brbeers:
        {
            tag: 'beer',
            draw: this.drawBrBeers
        },
        ratings:
        {
            tag: 'rating',
            draw: this.drawRatings
        },
        rating:
        {
            tag: 'rating',
            draw: this.drawRatingDetail
        },
        recent:
        {
            tag: 'beer',
            draw: this.drawRecent
        },
        inventory:
        {
            tag: 'item',
            draw: this.drawInventory
        }
    };
}

new RatingData();  // Must have this to be able to define prototype items

RatingData.prototype.divID = null;
RatingData.prototype.div = null;
RatingData.prototype.tag = null;
RatingData.prototype.draw = null;
RatingData.prototype.url = null;

/**
 * Set options
 */
RatingData.prototype.setDivID = function(divID)
{
    this.divID = divID;
    this.div = document.getElementById(divID);
    this.div.RatingData = this;

    if (!this.div)
    {
        alert('invalid div ID - '+divID);
    }
}

RatingData.prototype.setTag = function(tag)
{
    this.tag = tag;
}

RatingData.prototype.setURL = function(url)
{
    this.url = url;
}

//RatingData.prototype.setDraw = function(draw)
//{
//    this.draw = draw;
//}

/******************************************************************************
/**
 * Show or hide div
 */
RatingData.prototype.toggle = function(img)
{
    if (img.src.indexOf("closed") > 0)
    {
        img.src = "/kpscellar/image/list_opened.gif";
        this.getData();
    }
    else
    {
        img.src = "/kpscellar/image/list_closed.gif";
        this.div.innerHTML = '';
    }
}

/******************************************************************************
/**
 * Trigger data download and eventual display.
 */
RatingData.prototype.getData = function(url, method, tag)
{
    var me = this;
    var callback = function(xmlDoc) { me.LoadData(xmlDoc) };

    this.div.innerHTML = '<img src="/kpscellar/image/hourglass-spinning.gif"> Loading...';

    this.xml = new xmlFetch(this.url, callback);
}

/**
 * Load XML data.
 */
RatingData.prototype.LoadData = function(xmlDoc)
{
    if (!this.tagmap[xmlDoc.documentElement.nodeName])
    {
        this.div.innerHTML = '<i>Unknown tag type: '+xmlDoc.documentElement.nodeName+'</i>';
        return;
    }

    var tm = this.tagmap[xmlDoc.documentElement.nodeName];

    //alert('draw '+tm.tag+' using '+tm.draw);

    this.elements = xmlDoc.documentElement.getElementsByTagName(tm.tag);

    if (this.elements.length > 0)
    {
        this.draw = tm.draw;
        this.draw(this.elements);
    }
    else
    {
        this.div.innerHTML = '<i>No matches</i>';
    }
}

/******************************************************************************
/**
 * Display breweries.
 */
RatingData.prototype.drawBrewery = function(elements)
{
    var html = ' \
        <table class=data cellpadding="1" cellspacing="1" width="100%">';

    //var columns = 
    //[
    //    {
    //        fun: 'RBbrewery',
    //    },
    //    {
    //        attribute: 'name',
    //        drilldown: 'brewery_drilldown'
    //        drilldownAttribute: 'brewery_id'
    //    },
    //    {
    //        attribute: 'location',
    //        drilldown: 'search_drilldown'
    //        searchAttribute: 'location'
    //        drilldownAttribute: 'location'
    //    },
    //];

    var headings = 
    [
        {
        },
        {
            text: 'Brewery',
            span: 2
        },
        {
            text: 'Location',
            span: 2
        }
    ];

    html += this.drawHeadings(headings);

    for (var i = 0; (i < elements.length); ++i)
    {
        var entry = elements[i];

        var drilldownDivID = 'beers' + entry.getAttribute('brewery_id') + 'Div';

        html += '<tr>';

        html += drawRBBreweryLink(entry);

        html += drawDrilldown('brewery_drilldown', entry.getAttribute('brewery_id'), drilldownDivID);
        html += '<td>'+entry.getAttribute('name')+'</td>';

        html += drawDrilldown('search_drilldown', 'location='+entry.getAttribute('location'), drilldownDivID);
        html += '<td>'+entry.getAttribute('location')+'</td>';

        html += '</tr>';

        html += drawDivRow(4, drilldownDivID);
    }

    html += '</table>';

    this.div.innerHTML = html;
}

//RatingData.prototype.drawDetail = function(columns)
//{
//}

/******************************************************************************
/**
 * Display beers.
 */
RatingData.prototype.drawBeers = function(elements)
{
    this.drawBeersBob(elements, 0);
}

/******************************************************************************
/**
 * Display beers with brewery.
 */
RatingData.prototype.drawBrBeers = function(elements)
{
    this.drawBeersBob(elements, 1);
}

/******************************************************************************
/**
 * Display beers with brewery.
 */
RatingData.prototype.drawBeersBob = function(elements, showBrewery)
{
    var html = ' \
        <table class=data cellpadding="1" cellspacing="0" width="95%" bgcolor=#eeeeee>';

    var headings = 
    [
        {
            text: 'Beer',
            span: 2
        },
        {
            text: 'Style',
            span: 2
        },
        {
            text: 'ABV',
            span: 1
        },
        {
            text: 'Score',
            span: 2
        }
    ];

    if (showBrewery)
    {
        headings.unshift({ text: 'Brewery', span: 2 });
    }

    html += this.drawHeadings(headings);

    for (var i = 0; (i < elements.length); ++i)
    {
        var entry = elements[i];

        var drilldownDivID = 'ratings' + entry.getAttribute('beer_id') + 'Div';

        html += '<tr>';

        if (showBrewery)
        {
            html += drawDrilldown('brewery_drilldown', entry.getAttribute('brewery_id'), drilldownDivID);
            html += '<td>'+entry.getAttribute('brewery_name')+'</td>';
        }

        html += drawDrilldown('beer_drilldown', entry.getAttribute('beer_id'), drilldownDivID);
        html += '<td>'+entry.getAttribute('name')+'</td>';

        html += drawDrilldown('search_drilldown', 'style='+entry.getAttribute('style'), drilldownDivID);
        html += '<td>'+entry.getAttribute('style')+'</td>';

        html += '<td align=right>'+entry.getAttribute('abv')+'%</td>';

        html += '<td align=right>'+entry.getAttribute('ratebeer_score')+'</td>';
        html += drawRBBeerLink(entry);

        html += '</tr>';

        html += drawDivRow(9, drilldownDivID);
    }

    html += '</table>';

    this.div.innerHTML = html;
}

/******************************************************************************
/**
 * Display recent ratings.
 */
RatingData.prototype.drawRecent = function(elements, showBrewery)
{
    var html = ' \
        <table class=data cellpadding="1" cellspacing="0" width="95%" bgcolor=#eeeeee>';

    var headings = 
    [
        {
        },
        {
            text: 'Date',
            span: 2
        },
        {
            text: 'Brewery',
            span: 2
        },
        {
            text: 'Beer',
            span: 2
        },
        {
            text: 'Score',
            span: 1
        },
        {
        }
    ];

    html += this.drawHeadings(headings);

    for (var i = 0; (i < elements.length); ++i)
    {
        var entry = elements[i];

        var drilldownDivID = 'rdetails' + entry.getAttribute('rating_id') + 'Div';

        html += '<tr>';

        html += '<td>' + ((entry.getAttribute('rating_count') == 1) ? '<image src="/image/new.jpeg">' : '&nbsp;') + '</td>';

        html += drawDrilldown('rating_drilldown', entry.getAttribute('rating_id'), drilldownDivID);
        html += '<td>'+entry.getAttribute('rating_date')+'</td>';

        html += drawDrilldown('brewery_drilldown', entry.getAttribute('brewery_id'), drilldownDivID);
        html += '<td>'+entry.getAttribute('brewery_name')+'</td>';

        html += drawDrilldown('beer_drilldown', entry.getAttribute('beer_id'), drilldownDivID);
        html += '<td>'+entry.getAttribute('name')+'</td>';

        html += '<td align=right>'+entry.getAttribute('ratebeer_score')+'</td>';
        html += drawRBBeerLink(entry);

        html += '</tr>';

        html += drawDivRow(8, drilldownDivID);
    }

    html += '</table>';

    this.div.innerHTML = html;
}

/******************************************************************************
/**
 * Display ratings.
 */
RatingData.prototype.drawRatings = function(elements)
{
    var hasVersion = false;
    var hasVintage = false;
    var hasMode = false;
    var hasSource = false;
    var hasChain = false;

    for (var i = 0; (i < elements.length); ++i)
    {
        var entry = elements[i];

        if (entry.getAttribute('version')) hasVersion = true;
        if (entry.getAttribute('vintage')) hasVintage = true;
        if (entry.getAttribute('mode')) hasMode = true;
        if (entry.getAttribute('source')) hasSource = true;
        if (entry.getAttribute('chain')) hasChain = true;
    }

    var headings = '';
    if (hasVersion) headings += '<th>Version</th>';
    if (hasVintage) headings += '<th>Vintage</th>';
    if (hasMode)   headings += '<th>Mode</th>';
    if (hasSource)   headings += '<th>Source</th>';
    if (hasChain)   headings += '<th>Chain</th>';

    var html = ' \
        <table class=data border=1 cellpadding="1" cellspacing="0" width="95%" bgcolor=#dddddd> \
        <tr> \
          <th>&nbsp;</th> \
          <th>Rated</th> \
          '+headings+' \
          <th>ABV</th> \
          <th>Score</th> \
          <th>&nbsp;</th> \
        </tr>';

    for (var i = 0; (i < elements.length); ++i)
    {
        var entry = elements[i];

        var drilldownDivID = 'details' + entry.getAttribute('rating_id') + 'Div';

        html += '<tr>';

        html += drawDrilldown('rating_drilldown', entry.getAttribute('rating_id'), drilldownDivID);
        html += '<td>'+entry.getAttribute('rating_date')+'</td>';

        if (hasVersion) html += '<td>'+entry.getAttribute('version')+'&nbsp;</td>';
        if (hasVintage) html += '<td>'+entry.getAttribute('vintage')+'&nbsp;</td>';
        if (hasMode) html += '<td>'+entry.getAttribute('mode')+'&nbsp;</td>';
        if (hasSource) html += '<td>'+entry.getAttribute('source')+'&nbsp;</td>';
        if (hasChain) html += '<td>'+entry.getAttribute('chain')+'&nbsp;</td>';

        if (entry.getAttribute('abv') > 0)
            html += '<td align=right>'+entry.getAttribute('abv')+'%</td>';
        else
            html += '<td>&nbsp;</td>';

        if (entry.getAttribute('ratebeer_score') > 0)
            html += '<td align=right>'+entry.getAttribute('ratebeer_score')+'</td>';
        else if (entry.getAttribute('rating') > 0)
            html += '<td align=right>'+entry.getAttribute('rating')+'</td>';
        else if (entry.getAttribute('score'))
            html += '<td align=right>'+entry.getAttribute('score')+'</td>';
        else
            html += '<td>&nbsp;</td>';

        html += drawRBBeerLink(entry);

        html += '</tr>';

        html += drawDivRow(7, drilldownDivID);
    }

    html += '</table>';

    this.div.innerHTML = html;
}

/******************************************************************************
/**
 * Display rating detail.
 */
RatingData.prototype.drawRatingDetail = function(elements)
{
    var entry = elements[0];

    var html = '<div style="background: #ffffff;">';

    var noteAttributes = ["appearance","aroma","body","flavor","drinkability","overall"];


    html += '<table width="100%"> \
            <tr> \
              <td valign=top>';

    // Display notes
    html += '<table width="90%">';
    for (var i in noteAttributes)
    {
        var attrName = noteAttributes[i];
        var text = entry.getAttribute(attrName);

        if (text)
        {
            var attrHeading = attrName.substring(0,1).toUpperCase() + attrName.substring(1);

            text.replace("\n", '<br>');

            html += '<tr><td colspan=2><b>' + attrHeading + '</b></td></tr>';
            html += '<tr><td width=25></td><td>' + text + '</td></tr>';
        }
    }
    html += '</table>';

    html += '</td> \
             <td valign=top align=right>';

    // Display scores
    html += '<table border="1">';

    if (entry.getAttribute('ratebeer_score') > 0)
    {
       for (var i in noteAttributes)
       {
           var attrName = noteAttributes[i];
           var attrScore = attrName+'_score';
           var attrHeading = attrName.substring(0,1).toUpperCase() + attrName.substring(1);

           var score = (entry.getAttribute(attrScore) > 0) ? entry.getAttribute(attrScore) : 'n/a';

           html += ' \
               <tr> \
                 <td>'+attrHeading+'</td> \
                 <td align=right>'+score+'</td> \
               </tr>';
       }

       html += ' \
           <tr> \
             <td>Score</td> \
             <td align=right>'+entry.getAttribute('ratebeer_score')+'</td> \
           </tr>';
    }

    if (entry.getAttribute('score') 
        && (entry.getAttribute('ratebeer_score') > 0 
            || !(entry.getAttribute('ratebeer_score') || entry.getAttribute('rating'))))
    {
         html += ' \
             <tr> \
               <td>Rating</td> \
               <td>'+entry.getAttribute('score')+'</td> \
             </tr>';
    }

//    if (entry.getAttribute('rating') > 0)
//    {
//         html += ' \
//             <tr> \
//               <td>Rating</td> \
//               <td>'+entry.getAttribute('rating')+'</td> \
//             </tr>';
//    }

    html += '</table>';

    html += '</td></tr></table>';

    // Display additional information
    if (entry.getAttribute('note'))
    {
        html += entry.getAttribute('note')+'<br>';
    }

    if (entry.getAttribute('rerate') > 0)
    {
        html += '<i>I would like to rerate this beer.</i><br>';
    }

    if (entry.getAttribute('auto_score') > 0)
    {
        html += '<i>Individual attribute scores were automatically generated from the notes.</i><br>';
    }

    var rbl = 'http://ratebeer.com/Ratings/Beer/Beer-Ratings.asp?BeerID='+entry.getAttribute('ratebeer_id')+'&FanOfID=5356';
    html += '<i>Rating was last updated on '+entry.getAttribute('last_update');
    if (entry.getAttribute('last_upload'))
    {
        html += ' and last uploaded to <a href="'+rbl+'" target=_blank>RateBeer</a> on '+entry.getAttribute('last_upload');
    }
    html += '</i><br>';

    html += '</div>';

    this.div.innerHTML = html;
}

/******************************************************************************
/**
 * Display recent ratings.
 */
RatingData.prototype.drawInventory = function(elements, showBrewery)
{
    var html = ' \
        <table class=data cellpadding="1" cellspacing="0" width="95%" bgcolor=#eeeeee>';

    var headings = 
    [
        {
            text: 'Brewery',
            span: 1
        },
        {
            text: 'Beer',
            span: 1
        },
        {
            text: 'Vintage',
            span: 1
        },
        {
            text: 'Version',
            span: 1
        },
        {
            text: 'Size',
            span: 1
        },
        {
            text: 'Quantity',
            span: 1
        }
    ];

    html += this.drawHeadings(headings);

    for (var i = 0; (i < elements.length); ++i)
    {
        var entry = elements[i];

        html += '<tr>';

        html += '<td>'+entry.getAttribute('brewery_name')+'</td>';
        html += '<td>'+entry.getAttribute('beer_name')+'</td>';
        html += '<td>'+entry.getAttribute('vintage')+'</td>';
        html += '<td>'+entry.getAttribute('version')+'</td>';
        html += '<td align=right>'+entry.getAttribute('size')+'</td>';
        html += '<td align=right>'+entry.getAttribute('quantity')+'</td>';

        html += '</tr>';

        if (entry.getAttribute('notes'))
        {
            html += '<tr>';
            html += '<td colspan=6><i><font size=-1>'+entry.getAttribute('notes')+'</font></i></td>';
            html += '</tr>';
        }
    }

    html += '</table>';

    this.div.innerHTML = html;
}

/******************************************************************************
/**
 * Display headings (soon with sort toggles).
 */
RatingData.prototype.drawHeadings = function(headings)
{
    var html = '<tr>';

    for (var i = 0; (i < headings.length); ++i)
    {
        var heading = headings[i];

        if (heading['text'])
        {
            //var funky = function(a) { resort(me, heading); };
            //html += '<th class=data colspan='+heading['span']+'><a class=menu onclick="resort(\''+this.divID+'\',\''+heading['text']+'\');">'+heading['text']+'</a></th>';
            html += '<th class=data colspan='+heading['span']+'>'+heading['text']+'</th>';
        }
        else
        {
            html += '<th class=data>&nbsp</th>';
        }
    }

    html += '</tr>';

    return html;
}

function resort(divID,headingText)
{
    alert(divID);
    alert(headingText);

    var div = document.getElementById(divID);

    if (!div)
    {
        alert('invalid div ID - '+divID);
    }

    //dumpObject(div.RatingData.elements);
    dumpObject(div);
}

function dumpObject(a)
{
    //alert(typeof a);
    //a = a['parentNode']['parentNode'];
    //a = a['ownerDocument'];
    document.write(typeof a);
    document.write('<br>');
    document.write('<br>');
    for (var key in a)
    {
        document.write(key+'='+a[key]+'<br>');
    }
    //alert('sory by '+heading);
    document.close();

    return false;
}

/******************************************************************************
/**
 * Helper functions.
 */

function drawRBBeerLink(entry)
{
    if (entry.getAttribute('ratebeer_id') == 0)
    {
        return '<td width="20px" height="16px">&nbsp;</td>';
    }
    else
    {
        return '<td width="20px" height="16px"><a href="http://ratebeer.com/Ratings/Beer/Beer-Ratings.asp?BeerID='+entry.getAttribute('ratebeer_id')+'&FanOfID=5356" target=_blank><img src="/kpscellar/image/rbicon.ico" border=0></a></td>';
    }
}

function drawRBBreweryLink(entry)
{
    if (entry.getAttribute('ratebeer_id') == 0)
    {
        return '<td width="20px" height="16px">&nbsp;</td>';
    }
    else
    {
        return '<td width="20px" height="16px"><a href="http://ratebeer.com/brewers/x/'+entry.getAttribute('ratebeer_id')+'/" target=_blank><img src="/kpscellar/image/rbicon.ico" border=0></a></td>';
    }
}

function drawDrilldown(ddFunction, ddAttribute, ddDiv)
{
    return '<td width="12px" height="12px"><img src="/kpscellar/image/list_closed.gif" border=0 onClick="'+ddFunction+'(this, \''+ddAttribute+'\', \''+ddDiv+'\')"></td>';
}

function drawDivRow(span, divID)
{
    return ' \
        <tr> \
          <td></td> \
          <td colspan='+span+'><div id="'+divID+'" style="overflow: auto; width: 100%;"></td> \
        </tr>';
}


