var pos = 0
var ari = 'http://hirise.lpl.arizona.edu/'
var ias = 'http://hirise.lpl.arizona.edu/iasclient/ares31.jsp?file=/PDS/EXTRAS/RDR'
var pds = 'http://hirise-pds.lpl.arizona.edu/PDS/EXTRAS/RDR'
var rex = /^(\w{3})_(\d{6})_(\d{4})$/

function first()
{
    update(pos=0)
}

function last()
{
    update(pos=images.length-1)
}

function back()
{
    if(pos>0)
    {
        update(--pos)
    }
    else last()
}

function next()
{
    if(pos<images.length-1)
    {
        update(++pos)
    }
    else first()
}

function lpad(str, chr, len)
{
    var ret = ""
    for (i = 0 ; i < len - str.length ; i++)
    {
        ret = ret + chr
    }

    return ret + str
}

function update()
{
    arr = images[pos][0].match(rex)
    phs = arr[1]
    orb = arr[2]
    min = Math.floor(orb/100.0) * 100.0
    max = min + 99.0
    orb = "ORB_" + lpad("" + min, '0', 6) + "_" + lpad("" + max, '0', 6)
    url = '/' + phs + '/' + orb + '/' + images[pos][0] + '/'
    src = pds + url + images[pos][0] + '_RGB.NOMAP.browse.jpg'

    lnk = document.getElementById('link')
    lnk.setAttribute('href', ari + images[pos][0])
    lnk.textContent = images[pos][0]

    div = document.getElementById('main')
    img = document.createElement('img')
    hrf = document.createElement('a')
    hrf.setAttribute('title', 'Open in high-res with IAS')
    hrf.setAttribute('href', ias + url + images[pos][0] + '_RGB.NOMAP.JP2')
    // firefox prob on ar above 40:1img.setAttribute('width', '512')
    img.setAttribute('src', src)

    hrf.appendChild(img)

    if (div.firstChild) div.removeChild(div.firstChild)
    div.appendChild(hrf)

    document.getElementById('drop').options[pos].selected=true
}

function init()
{
    if (! document.getElementById) return;

    div = document.getElementById('main')

    if (window.innerHeight)
    {
       div.style.height = "" + (window.innerHeight - 75) + "px"
    }
    else if (document.documentElement.clientHeight > 0)
    {
      div.style.height = "" + (document.documentElement.clientHeight - 125) + "px"
    }
    else if (document.body.clientHeight)
    {
       div.style.height = "" + (document.body.clientHeight - 125) + "px"
    }

    oid = window.location.hash

    if (oid.length < 1)
    {
        first()
        return
    }

    oid = oid.substring(1, oid.length)

    for (i = 0 ; i < images.length ; i++)
    {
        if (images[i][0] == oid)
        {
            update(pos=i)
            break
        }
    }
}
