/*============================================*/
/* ASTON MARTIN CONFIGURATOR
   Bronwen Reid, Symbiosis, 2005
------------------------------------------
Functions
    onload_car
    OutputCarDetails

    InfoOn ( id )
    InfoOff ( id )

    ShowMenuBlock ( id )
    setContentHeight

    SetupColourBlock ( idFrom, idTo )
    cellHighlightOn( cellid, text, classname )
    cellHighlightOff( cellid, classname )
    cellColourOn( cellid )
    cellColourOver(cellid,bgcol,text)
    cellColourOut( cellid )
    cellInit ( blockid )
    cellOn( id, hexcode )
    cellOver( id )
    cellOut( id)

    getRGB ( hexcode )
    vmpColourAnim ( hexcode, material_name, secs )


Control Viewpoint model
    rotateUp
    rotateUpOff
    rotateLeft
    rotateLeftOff
    rotateRight
    rotateRightOff
    rotateDown
    rotateDownOff
    moveUp
    moveUpOff
    moveLeft
    moveLeftOff
    moveRight
    moveRightOff
    moveDown
    moveDownOff
    zoomIn
    timerZoomIn
    zoomInOff
    zoomOut
    timerZoomOut
    zoomOutOff
    preload
    postevent
    triggeranim
    snatchCamera


Build Menus
    goNextMenu
    goPrevMenu
    showMenu(id)
    hiCurrentLink ( id )
    IncludeMenu ( id, display )
    SetMenuOption ( id, display )
    buildMenus ( topmenu )
    Menu (obj, parentId)
/*============================================*/

// position the colour blocks
var LEFT = 8 ;
var DOWN = -5 ;
var DOWNTEXT = 45 ;

var d = null ;  // shortcut to document.hiddenform
var vmp = null; // viewpoint mtsplugin obj

//-----------------------
// onload_car
// called from viewpoint when car has finished loading
//-----------------------
function onload_car () {
    frames['car'].hide('onloading');
    vmp = frames['car'].vmp ;
    if (!d) d = document.hiddenform ;
    postevent('show_car');
    postevent('view_default');
    vmpDefaults ();
    // show nav buttons
    var el = document.getElementById('navbuttons'); if (el) el.style.display = "block" ;
}


//-----------
// OutputCarDetails
// get details of selected car from hidden form
// output - either on page or in new window
//-----------
function OutputCarDetails () {

    // swap button set
    document.getElementById('navbuttons').style.display = "none" ;
    document.getElementById('viewbuttons').style.display = "block" ;
    
    // disable mouse
    SetMouse (0);
    // default background and view
    vmpBackground('default');postevent('view_default')

    // car specific - in db9.js, etc.
    var cardetails = getCarDetails() ;

    // IE - expand size of div to show cardetails
    if (! document.getElementById('showcardetails') ) return ;
    document.getElementById('getcardetails').style.display = 'none' ;
    document.getElementById('showcardetails').style.visibility = 'visible' ;
    document.getElementById('showcardetails').style.display = 'block' ;
    document.getElementById('showcardetails').innerHTML = cardetails ;

    // increase height
    var height = document.getElementById('showcardetails').offsetHeight;
    // extra space for title & warning at bottom

    // weird duplicate height rules in css stop this working properly in opera/mozilla browsers
    height += 100 ;
    
    document.getElementById('carcontent').style.height = height+'px' ;
}


//-------------
// setContentHeight
// collapse/expand height of content div to make room for cardetails
function HideCarDetails () {

    // get output div
    var el = document.getElementById('showcardetails');

    // if already visible, hide it
    if (el && el.style.visibility && el.style.visibility=='visible') {
        // hide
        document.getElementById('getcardetails').style.display = 'block' ;
        document.getElementById('showcardetails').style.visibility = 'hidden' ;
        document.getElementById('showcardetails').style.display = 'none' ;

        document.getElementById('viewbuttons').style.display = "none" ;
        document.getElementById('navbuttons').style.display = "block" ;

        document.getElementById('carcontent').style.height = '0px' ;

        // turn off the background
        vmpBackground('');
        // enable the mouse
        SetMouse(1);
    }
    
}



//-----------------------
// Show Hide the Information Blocks
var info = null ;
function InfoOn ( id ) {

    // don't hide the current block
    if (id==info) { return;}

    // hide previous infoblock
    if (info) InfoOff(info);

    // can have picture or text or both - keep them in sync
    if ( document.getElementById(id+'_info') ) {
        var el = document.getElementById(id+'_info');
        el.style.visibility='visible' ;
    }
    if ( document.getElementById(id+'_text') ) {
        var el = document.getElementById(id+'_text');
        el.style.visibility='visible' ;
    }
    info = id ;
}

function InfoOff ( id ) {
    if ( document.getElementById(id+'_info') ) {
        document.getElementById(id+'_info').style.visibility='hidden' ;
    }
    if ( document.getElementById(id+'_text') ) {
        document.getElementById(id+'_text').style.visibility='hidden' ;
    }
    info = null ;
}



//-----------------------
// Show Hide menus
var elMenu   = null ;
function ShowMenuBlock ( id ) {
    var el = document.getElementById(id);
    if (el) {
        if (elMenu) elMenu.style.visibility = 'hidden';
        elMenu = el ;
        elMenu.style.visibility = 'visible';
    }

    if (info) InfoOff (info)
    
    // hide the colourwarning block (show it if colourmenu displayed)
    if (document.getElementById('colourwarning')) document.getElementById('colourwarning').style.visibility = 'hidden';

    // extra - used to control the showcardetails div
    HideCarDetails () ;
}


//-----------------------
// Setup Colour blocks
// nasty bit of code
var elCols = null ;
var elLabel = null ;
var elLink = null ;

function SetupColourBlock ( idFrom, idTo ) {

    var elFrom = document.getElementById(idFrom);
    if (!elFrom) { alert('no '+idFrom); return ; }
    var elTo = document.getElementById(idTo+'boxes');
    if (!elTo)  { alert('no '+idTo); return ; }

    // reset previous colourbox (avoid duplicating cellids)
    if (elCols) elCols.innerHTML = ''
    elCols = elTo ;
    // copy block
    elTo.innerHTML = elFrom.innerHTML ;

    // hide existing label
    if (elLabel) elLabel.style.display = 'none' ;

    // set colour label
    elLabel = ( document.getElementById(idFrom+'_label') ?
        document.getElementById(idFrom+'_label') :
        null );

    // show current cell
    var cellid  = d[gHiddenCol + "_cellid"].value
    var colname = d[gHiddenCol + "_name"].value
    if (cellid) {
        cellHighlightOn( cellid, colname )
    }

    if (idFrom == 'LTH')
        SetSelectedColours () ;
    else
        ShowColourWarning ( idFrom );
}

//---
// hide colour block - used for turned thrd colours on/off
//---
function hideColourBlock () {
    if (elLabel) elLabel.style.display = 'none' ;
    if (elCols) elCols.innerHTML = ''
    if (document.getElementById('colourwarning')) document.getElementById('colourwarning').style.visibility = 'hidden';
}

//---
// ShowColourWarning - select and display an appropriate colour warning
function ShowColourWarning ( colType ) {

    var elColourWarning = document.getElementById('colourwarning')
    if (!elColourWarning) return ;

    elColourWarning.style.visibility = 'hidden';

    if ( colType =='stitching') {
        elColourWarning.innerHTML = "Fine Stitching is not represented visually on the car model." ;
        elColourWarning.className = 'warning' ;
    }
    else if ( colType == 'THRD' ) {
        elColourWarning.innerHTML = "Fine Stitching is not represented visually on the car model.<br />These colours are a visual representation and may not match the actual vehicle colours." ;
        elColourWarning.className = 'warning2lines' ;
    }
    else if ( colType == 'LTH' && SelectedColours.length>2 ) {
        elColourWarning.innerHTML = "<strong>Warning: There is a two colour limit for leather interior.</strong><br />These colours are a visual representation and may not match the actual vehicle colours" ;
        elColourWarning.className = 'warning2lines' ;
    }
    else {
        elColourWarning.innerHTML = "These colours are a visual representation and may not match the actual vehicle colours." ;
        elColourWarning.className = 'warning' ;
    }
    // and show info about 'buy your extra colours' now
    elColourWarning.style.visibility = 'visible';
}
    






//--------
// Returns true if 's' is contained in the array 'a'
// @author Johan Känngård, http://dev.kanngard.net
//---------
function in_array(a, e) {
    for(var i=0;i<a.length;i++)if(a[i]==e)return true;
    return false;
}


var gHiddenCol = null ;
var gColName = null ;
var gColHexcode = null ;
var gColCellId = null ;
var gColMenuId = null ; // currently displayed menu block


function cellHighlightOn( cellid, text, classname ) {
    if (!classname) classname="colourcellOn" ;

    var cell = document.getElementById(cellid) ;
    if (!cell) return ;
    var top = parseInt(cell.style.top) ;
    var left = parseInt(cell.style.left) ;

    // cell is already highlighted, do not move it
    if ( cell.className != classname ) {
        left -= LEFT; top -= DOWN;
        cell.style.left = left + "px"
        cell.style.top = top + "px"
        cell.className = classname
    }


    if (elLabel && text) {
        elLabel.innerHTML = (parseInt(left)>420) 
            ? text
            : '<nobr>' + text + '</nobr>' ;

        elLabel.style.left = left + "px"
        elLabel.style.top = (top+DOWNTEXT)+"px";
        elLabel.style.display = "block"
    }
}

//------------
// Emphasis cell (as previously selected in previous page)
function cellSelected( cellid ) {
    // is it the currently highlighted cell?
    if ( cellid == d[gHiddenCol + "_cellid"].value) return ;

    // is cellid a selected leather colour?
    if ( !in_array(SelectedColours, cellid)) return ;
    var classname = "colourcellSel"

    var cell = document.getElementById(cellid) ;
    if (!cell) return ;
    cell.className = classname
    return ;
}


function cellHighlightOff( cellid, classname ) {
    if (!classname) classname="colourcell" ;
    var cell = document.getElementById(cellid) ;
    if (!cell) return ;

    // cell is already highlighted
    if ( cell.className == classname )
        return ;
    cell.className = classname

    var top = parseInt(cell.style.top) ;
    var left = parseInt(cell.style.left) ;
    left += LEFT; top += DOWN;

    cell.style.left = left + "px"
    cell.style.top = top + "px"

    if (elLabel) {
        elLabel.style.display = "none"
    }
}

//---------
// select this colour for car material
function cellColourOn( cellid, menutype ) {
    var selCellId = d[gHiddenCol + "_cellid"].value ;

    // possible to set upper colour, override (part) with customtrim, and want to override override
    if (cellid==selCellId) return ;

    // if different cell already selected, reset it
    if ( selCellId ) {
        cellHighlightOff( selCellId )
    }

    cellHighlightOn( cellid, gColName )

    d[gHiddenCol + "_name"].value = gColName
    d[gHiddenCol + "_hexcode"].value = gColHexcode
    d[gHiddenCol + "_cellid"].value = gColCellId
    d[gHiddenCol + "_menu"].value = menutype

    vmpSetColour(gHiddenCol);

    // add cellid to list of unique colours for car interior
    // do this after vmpSetColour - upper/lower colour changes cascade onwards
    SetSelectedColours() ;
}


function cellColourOver(cellid,bgcol,text) {
    if (gHiddenCol) {
        // if cell is already selected (& highlighted), return
        var selCell = d[gHiddenCol + "_cellid"].value ;
        if (cellid==selCell) return ;
    }

    // highlight cell
    cellHighlightOn( cellid, text )

    gColName    = text ;
    gColHexcode = bgcol ;
    gColCellId  = cellid ;
}


//----------------
function cellColourOut( cellid ) {
    var selCellId ;

    selCellId = 0 ;
    if (gHiddenCol) {
        // if cell is already selected (& highlighted), return
        var selCellId = d[gHiddenCol + "_cellid"].value ;
        if (cellid==selCellId) return ;
    }
    // reset currently highlighted cell to default position
    cellHighlightOff( cellid )

    if (selCellId) {
        // show text for currently selected cell
        var text = d[gHiddenCol + "_name"].value
        cellHighlightOn( selCellId, text )
    }
    cellSelected( cellid )
}

//----------------
// getCookieColour
// use cookie to read cell,hex,name,menu
function getCookieColour ( colname ) {
    if ( carcookie.get(colname) ) {
        // cell, hex, name, menu
        var a = carcookie.get(colname).split('||');
        if (d[colname+'_cellid']) d[colname+'_cellid'].value = a[0];
        if (d[colname+'_hexcode']) d[colname+'_hexcode'].value = a[1];
        if (d[colname+'_name']) d[colname+'_name'].value = a[2];
        if (d[colname+'_menu']) d[colname+'_menu'].value = a[3];
    }
}

//----------------
// setCookieColour
// save cell,hex,name,menu to cookie
function setCookieColour ( colname ) {
    var colourvalue = '' ;
    if (d[colname+'_cellid'])  colourvalue += d[colname+'_cellid'].value + '||';
    if (d[colname+'_hexcode']) colourvalue += d[colname+'_hexcode'].value + '||';
    if (d[colname+'_name'])    colourvalue += d[colname+'_name'].value + '||';
    if (d[colname+'_menu'])    colourvalue += d[colname+'_menu'].value + '||';
    if (carcookie) carcookie.set(colname,colourvalue);
}



// Wide cells (not from database)
var hiCell = null;
var selCell = null ;

function cellInit ( blockid ) {
    gHiddenCol = blockid ;
    elLabel = document.getElementById(gHiddenCol + '_label');
    selCell  = d[gHiddenCol + "_cellid"].value

    if (selCell && colourname[selCell]) {
        cellHighlightOn( selCell, colourname[selCell],'widecellOn' )
    }
}


function cellOn( id, hexcode ) {
    if (id == selCell) return ;
    if (selCell) cellHighlightOff( selCell, 'widecell' )

    selCell = id ;
    cellHighlightOn( selCell, colourname[selCell], 'widecellOn' )

    d[gHiddenCol + "_name"].value = colourname[selCell]
    d[gHiddenCol + "_cellid"].value = selCell
    if (hexcode) d[gHiddenCol + "_hexcode"].value = hexcode

    vmpSetColour(gHiddenCol);
}


function cellOver( id ) {
    if (selCell == id ) return ;

    if (hiCell && hiCell!=selCell)
        cellHighlightOff(hiCell, 'widecell') ;

    hiCell = id ;
    cellHighlightOn( hiCell, colourname[id], 'widecellOn' )
}

function cellOut( id) {
    if (selCell == id ) return ;
    cellHighlightOff( id, 'widecell' )
    if (selCell) {
        // show text for currently selected cell
        cellHighlightOn( selCell, colourname[selCell], 'widecellOn' )
    }
}


//-----------
// fast track or comtemporary
function fc ( s ) {
    var c = s.slice(-1) // last char
    switch (c) {
        case 'F' :  return ' (Fast Track)';
        case 'C' :  return ' (Contemporary)';
        case 'E' :  return ' (DBS Exclusive)';
        case 'S' :  return ' (Aston Martin Special Colours)';
    }
    return '' ;
}




//----------
// convert hexcode to a [r g b] string for viewpoint
//----------
function getRGB ( hexcode ) {
    // check for leading '#'
    if (hexcode.indexOf('#')==0)
        hexcode = hexcode.substr(1,6)

    if ( hexcode == "" ) {
        // default colour = Nondescript Grey
        r = g = b = 0.8
    }
    else {

        // convert hex to r g b for mtx
        r = parseInt( '0x' + hexcode.substr(0,2) ) * 0.0039 ;
        r = Math.round(r*1000) / 1000 ;

        g = parseInt( '0x' + hexcode.substr(2,2) ) * 0.0039 ;
        g = Math.round(g*1000) / 1000 ;

        b = parseInt( '0x' + hexcode.substr(4,2) ) * 0.0039 ;
        b = Math.round(b*1000) / 1000 ;
    }
    var rgb = r + ' ' + g + ' ' + b
    return rgb ;
}


function vmpColourAnim ( hexcode, material_name, secs ) {

    if (!vmp) return ;
    if (material_name == "") return ;

    var rgb = getRGB ( hexcode ) ;
    /*
    if (vmp) {
        vmp.SetProperty('MTSMaterial.'+material_name, 'difc', rgb );
        vmp.Render();
    }
    */
    if (!secs) secs="0.1"
    var mtx =
        '<MTSTimeElem Type=\\"Keyframe\\"  On=\\"1\\" >' +
        '<Target Name=\\"MTSMaterial.' + material_name + '\\" Property=\\"difc\\"  Timeline=\\"colourchange_T1\\" />' +
        '<Time> 0  ' + secs + ' </Time>' +
        '<Timeline Name=\\"colourchange_T1\\"  Type=\\"3D\\" >' +
        '*  [ ' + rgb + ' ]' +
        '</Timeline>' +
        '</MTSTimeElem>'
        
    // if (material_name=='GrilleColour') prompt ( 'mtx=', mtx);
    if (vmp) vmp.Execute(mtx);
    return false;
}






/*--------------------------
  Move Viewpoint Model - Highlight navigation icons
---------------------------*/
function rotateUp() {
    document.images['rotate_u'].src = 'images/bt_rotate_up_on.gif' ;
    if (vmp) vmp.SetProperty("MTSTimeElem.rotate_up", "trgr", 1, "mts_int");
}
function rotateUpOff() {
    document.images['rotate_u'].src = 'images/bt_rotate_up_off.gif' ;
    if (vmp) vmp.SetProperty("MTSTimeElem.rotate_up", "runs", 0, "mts_int");
}
function rotateLeft() {
    document.images['rotate_l'].src = "images/bt_rotate_left_on.gif";
    if (vmp) vmp.SetProperty("MTSTimeElem.rotate_left", "trgr", 1, "mts_int");
}
function rotateLeftOff() {
    document.images['rotate_l'].src = "images/bt_rotate_left_off.gif";
    if (vmp) vmp.SetProperty("MTSTimeElem.rotate_left", "runs", 0, "mts_int");
}
function rotateRight() {
    document.images['rotate_r'].src = "images/bt_rotate_right_on.gif";
    if (vmp) vmp.SetProperty("MTSTimeElem.rotate_right", "trgr", 1, "mts_int");
}
function rotateRightOff() {
    document.images['rotate_r'].src = "images/bt_rotate_right_off.gif";
    if (vmp) vmp.SetProperty("MTSTimeElem.rotate_right", "runs", 0, "mts_int");
}
function rotateDown() {
    document.images['rotate_d'].src = "images/bt_rotate_down_on.gif";
    if (vmp) vmp.SetProperty("MTSTimeElem.rotate_down", "trgr", 1, "mts_int");
}
function rotateDownOff() {
    document.images['rotate_d'].src = "images/bt_rotate_down_off.gif";
    if (vmp) vmp.SetProperty("MTSTimeElem.rotate_down", "runs", 0, "mts_int");
}

function moveUp() {
    document.images['move_u'].src = "images/bt_move_up_on.gif";
    if (vmp) vmp.SetProperty("MTSTimeElem.trans_up", "trgr", 1, "mts_int");
}
function moveUpOff() {
    document.images['move_u'].src = "images/bt_move_up_off.gif";
    if (vmp) vmp.SetProperty("MTSTimeElem.trans_up", "runs", 0, "mts_int");
}
function moveLeft() {
    document.images['move_l'].src = "images/bt_move_left_on.gif";
    if (vmp) vmp.SetProperty("MTSTimeElem.trans_left", "trgr", 1, "mts_int");
}
function moveLeftOff() {
    document.images['move_l'].src = "images/bt_move_left_off.gif";
    if (vmp) vmp.SetProperty("MTSTimeElem.trans_left", "runs", 0, "mts_int");
}
function moveRight() {
    document.images['move_r'].src = "images/bt_move_right_on.gif";
    if (vmp) vmp.SetProperty("MTSTimeElem.trans_right", "trgr", 1, "mts_int");
}
function moveRightOff() {
    document.images['move_r'].src = "images/bt_move_right_off.gif";
    if (vmp) vmp.SetProperty("MTSTimeElem.trans_right", "runs", 0, "mts_int");
}
function moveDown() {
    document.images['move_d'].src = "images/bt_move_down_on.gif";
    if (vmp) vmp.SetProperty("MTSTimeElem.trans_down", "trgr", 1, "mts_int");
}
function moveDownOff() {
    document.images['move_d'].src = "images/bt_move_down_off.gif";
    if (vmp) vmp.SetProperty("MTSTimeElem.trans_down", "runs", 0, "mts_int");
}

// could also build an anim.
var tZoom ; // timer zoom ID
function zoomIn() {
    // don't put image swap in timer
    document.images['zoom_in'].src = "images/bt_zoom_in_on.gif";
    timerZoomIn();
    //vmp.SetProperty("MTSTimeElem.zoom_in", "trgr", 1, "mts_int");
}
function timerZoomIn () {
    var cdst = parseFloat(vmp.GetProperty('MTSScene', 'cdst', 'mts_pnt1d'));
    if (cdst > 0.2) cdst -= 0.01 ;
    if (vmp) vmp.SetProperty('MTSScene', 'cdst', cdst);
    tZoom = setTimeout('timerZoomIn()',20);
}
function zoomInOff() {
    document.images['zoom_in'].src = "images/bt_zoom_in_off.gif";
    clearTimeout(tZoom);
}

function zoomOut() {
    document.images['zoom_out'].src = "images/bt_zoom_out_on.gif";
    if (vmp) timerZoomOut();
}
function timerZoomOut () {
    var cdst = parseFloat(vmp.GetProperty('MTSScene', 'cdst', 'mts_pnt1d'));
    if (cdst < 4.5) cdst += 0.01  ;
    if (vmp) vmp.SetProperty('MTSScene', 'cdst', cdst);
    tZoom = setTimeout('timerZoomOut()',20);
}
function zoomOutOff() {
    document.images['zoom_out'].src = "images/bt_zoom_out_off.gif";
    clearTimeout(tZoom);
}

// use these so we can test for existance of viewpoint
function postevent( event, delay ) { 
    if (!delay) delay=0; 
    if (vmp) vmp.PostEvent(event,delay); 
}
function triggeranim( event ) {  if (vmp) vmp.TriggerAnim(event); }


// snatchCamera from Paul
function snatchCamera(){
    var orbd = String(vmp.GetProperty('MTSScene', 'orbd', 'mts_pnt1d'));
    var a_rot  = String(vmp.GetProperty('MTSScene', 'rot_', 'mts_pnt3d')).split(' ');
    var a_tra  = String(vmp.GetProperty('MTSScene', 'tra_', 'mts_pnt3d')).split(' ');

    var details ='orbd  [' + orbd + ']' ;
    details += '\nrot_ [' + a_rot[0] + ' ' + a_rot[1] + ' ' + a_rot[2] + ']' ;
    details += '\ntra_ [' + a_tra[0] + ' ' + a_tra[1] + ' ' + a_tra[2] + ']' ;

    prompt ( 'Snatched', details );
}


/*==========================*/
/* Build menus for configurator
/*==========================*/
var currentLink ;
var currentMenuId ;
var firstMenuId , lastMenuId ;

// given an ID in the menu tree, find the next
function goNextMenu() {

    if (!currentMenuId) {
        currentMenuId = firstMenuId ;
    }
    else if ( Menus[currentMenuId].nextId ) {
        currentMenuId = Menus[currentMenuId].nextId
        while ( ( Menus[currentMenuId].isParent || !Menus[currentMenuId].isOption )  && Menus[currentMenuId].nextId ) {
            currentMenuId = Menus[currentMenuId].nextId
        }
    }

    showMenu ( currentMenuId ) ;
}


function goPrevMenu() {

    if (!currentMenuId) {
        currentMenuId = lastMenuId ;
    }
    else if ( Menus[currentMenuId].prevId ) {
        currentMenuId = Menus[currentMenuId].prevId
        while ( ( Menus[currentMenuId].isParent || !Menus[currentMenuId].isOption ) && Menus[currentMenuId].prevId ) {
            currentMenuId = Menus[currentMenuId].prevId
        }
    }

    showMenu ( currentMenuId ) ;
}



function showMenu(id) {

    if (!Menus[id]) return ;

    // collapse all
    for (var menuId in Menus) {
        if (Menus[menuId].isParent ) {
            // enclosing ul block
            var menu = document.getElementById(menuId+'menu') ;
            menu.style.display = "none" ;
            // li listitem + a leading to block
            Menus[menuId].obj.className = "parent" ;
        }
    }

    // show all parents of current item
    var parentId =  id ;
    while ( parentId != 'mainmenu' ) {
        if ( Menus[parentId].isParent ) {
            var menu = document.getElementById(parentId+'menu') ;
            menu.style.display = "block";
            // li listitem + a leading to block
            Menus[parentId].obj.className = "parenton" ;
        }
        parentId = Menus[parentId].parentId;
    }

    // Expand current menuitem to show all the children
    var childId = id ;
    while ( Menus[childId].isParent ) {
        var menu = document.getElementById(childId+'menu') ;
        if (menu) menu.style.display = "block";
        childId = Menus[childId].children[0];
    }

    hiCurrentLink( childId );

    Menus[childId].onshow();

    // show next and previous links
    document.images['next'].src = (Menus[id].nextId==null ?
        "images/next_off.gif" :
        "images/next_on.gif" );
    document.images['prev'].src = (Menus[id].prevId==null ?
        "images/prev_off.gif" :
        "images/prev_on.gif" );

}


function hiCurrentLink ( id ) {

    var item = Menus[id].obj

    // set class style
    var links=item.getElementsByTagName("A");
    if (currentLink) currentLink.className = '';
    links[0].className = "selected" ;

    currentLink = links[0] ;
    currentMenuId = id ;
}



//------------------------
// IncludeMenu - take this in/out of navigation list
//------------------------
function SetMenuBlock ( id, display ) {
    if (!Menus[id]) return ;
    Menus[id].obj.style.display = (display ? 'inline' : 'none' );
    SetMenuOption ( id, display ) ;
}


//-------------
// set_menu_nav
// recursive function to set nav property for menu and all children
//-------------
function SetMenuOption ( id, display ) {

    if ( Menus[id].isParent ) {
        //alert(id+' '+Menus[id].children.length);
        for (var i=0; i<Menus[id].children.length; i++) {
            SetMenuOption ( Menus[id].children[i], display );
         }
    }
    else {
        Menus[id].isOption = display ;
    }
}




var Menus = new Array () ;

function buildMenus ( topmenu ) {
    var menuroot = document.getElementById(topmenu);
    var items = menuroot.childNodes ;

    for (var i=0; i<items.length; i++) {
        var itemId = items[i].id ;
        if ( items[i].tagName =='LI' && items[i].id && items[i].parentNode.id ) {
            Menus[ itemId ] = new Menu( items[i], topmenu ) ;
        }
    }

    var items = menuroot.getElementsByTagName("LI");
    for (var i=0; i<items.length; i++) {
        var itemId = items[i].id ;

        if (i>0) prevId = items[i-1].id; else prevId = null ;
        Menus[itemId].prevId = prevId ;

        if (i<items.length-1) nextId = items[i+1].id; else nextId = null ;
        Menus[itemId].nextId = nextId ;
    }
    firstMenuId = items[0].id ;
    lastMenuId = items[items.length-1].id ;
}



//-----------------------
//  Menu
//    id
//    obj
//    isParent
//    parentId
//    isOption - is this a current option - is menu available ?
//    children = array
//    prevId, nextId
//
//    onshow() - on activation, do this
//-----------------------

function Menu (obj, parentId) {
    this.id  = obj.id ;
    this.obj = obj;
    this.parentId = parentId ;
    this.isOption = true ;

    if (obj.className == 'parent' ) {
        this.isParent = true ;
        this.children = new Array ();
    }
    else {
        this.isParent = false ;
        this.children = null ;
    }

    // link leading to menu
    if ( obj.firstChild.tagName=="A" ) {
        var link = obj.firstChild ;
        // multiple events for onclick
        var orgFunct = (link.onclick) ? link.onclick : function () {};
        var id = this.id ;
        link.onclick = function () { showMenu(id); }
        // set menu method
        this.onshow = function () { orgFunct(); }
    }

    // build the array of children
    if ( this.isParent ) {

        var iChildren = 0;
        var menuitems = document.getElementById(obj.id+'menu').childNodes;
        for (var i=0;i<menuitems.length;i++) {
            var menuId = menuitems[i].id ;
            if ( menuitems[i].id && menuitems[i].tagName=='LI' ) {
                Menus[ menuId ] = new Menu ( menuitems[i], this.id );
                this.children[iChildren++] = menuId ;
            }
        }
    }

}


//---------------
// Cookie Handling

function CookieObj(name, hours, path, domain, secure) {
    // predefined properties start with '$'
    this.$name = name ;
    this.$suffix = "";
    this.$values = new Array () ;
    var self = this;    // make object available to private methods

    if( hours ) {
        var date = new Date();
        var curTime = new Date().getTime();
        date.setTime(curTime + (1000 * 60 * 60 * hours));
        this.$suffix = "; expires=" + date.toGMTString();
    }

    if( path ) {
        this.$suffix += "; path=" + path;
    }

    if ( domain ) {
        this.$suffix += "; domain=" + domain;
    }

    if ( secure ) {
        this.$suffix += "; secure=" + secure;
    }

    // load () ;

    function load ( ) {
        var cookiestr = "" ;

        // all cookies for this document / server
        var allcookies = document.cookie.split('; ');
        for (var i=0; i<allcookies.length; i++) {
            // split each array element by '='
            var inside = allcookies[i].split('=');
            // if name matches , return value
            if (self.$name == inside[0]) cookiestr = inside[1] ;
        }
        if (cookiestr == "") return ;
        var a = cookiestr.split('&');
        for (var i=0; i<a.length; i++) {
            var inside = a[i].split(':');
            self.$values[ inside[0] ] = unescape ( inside[1] );
        }
    }

    this.read = function ( ) {
        if (! self.exists() ) return false ;

        var cookiestr = "" ;

        // all cookies for this document / server
        var allcookies = document.cookie.split('; ');
        for (var i=0; i<allcookies.length; i++) {
            // split each array element by '='
            var inside = allcookies[i].split('=');
            // if name matches , return value
            if (self.$name == inside[0]) cookiestr = inside[1] ;
        }
        if (cookiestr == "") return ;
        var a = cookiestr.split('&');
        for (var i=0; i<a.length; i++) {
            var inside = a[i].split(':');
            self.$values[ inside[0] ] = unescape ( inside[1] );
        }
    }

    this.exists = function() {
        var m = document.cookie.indexOf(this.$name+'=')
        return m != -1 ? true : false ;
    }

    this.set = function ( name, value ) {
        this.$values [ name ] = value ;

        var cookiestr = "" ;
        for ( var key in this.$values ) {
            if (cookiestr != "" ) cookiestr += '&' ;
            cookiestr += key + ':' + escape (this.$values[key] );
        }
        // store cookie
        // prompt ( 'cookie', this.$name + '=' + cookiestr + this.$suffix );
        document.cookie = this.$name + '=' + cookiestr + this.$suffix
    }

    this.get = function ( name ) {
        if (this.$values[name])
            return this.$values[name] ;
        else
            return '';
    }


   this.remove = function() {
      var date = new Date();
      date.setFullYear(date.getYear() - 1);
      var cookie = this.$name + "=noop; expires=" + date.toGMTString();
      document.cookie = cookie ;
   }

}


//------------
// update form elements
function setRadio ( radio, selected ) {
    for (var i = 0; i < radio.length; i++) {
        if (radio[i].value == selected) radio[i].checked = true ;
    }
}

function setSelect ( selectbox, selected ) {
    for (var i = 0; i < selectbox.length; i++) {
        if (selectbox.options[i].text == selected || selectbox.options[i].value == selected) { selectbox.selectedIndex = i ;}
    }
}




var HYPERVIEW_TIMEOUT = 10 ;
//--- Hyperview
function hyperview_on() {
    postevent('hyperview_on');
    /*
    // coord = CoordinateSystem : 0=viewpoint window, 1=browser window, 2=full desktop (property coord)
    vmp.SetProperty('MTSBaseComponent','coor','2','mts_int');
    // cort - rectangle relative to viewing port
    vmp.SetProperty('MTSBaseComponent','cort','[0 0 0 0]','mts_real');
    // activate hyperview
    vmp.SetProperty('MTSBaseComponent','smod','1','mts_int');
    */
    // and off in xx seconds
    // setTimeout("hyperview_off()", HYPERVIEW_TIMEOUT*1000);
}

function hyperview_off() {
    postevent('hyperview_off');
    // vmp.SetProperty('MTSBaseComponent','smod','0','mts_int');
}


//---------
// hyperview_browser_on
// make car fill browser window
//---------
function hyperview_browser_on () {
    /*
    <MTSBaseComponent CoordinateSystem="1" Rect="0 0 0 0" PreserveCamera="3"/>
    coor - coordinatesystem (1=browser window, 0=viewpoint, 2=desktop)
    cort - rectange
    prmc - preserve camera
    smod - activate hyperview
    */
    vmp.SetProperty('MTSBaseComponent','coor','1','mts_int');
    vmp.SetProperty('MTSBaseComponent','cort','[0 0 0 0]','mts_real');
    vmp.SetProperty('MTSBaseComponent','smod','1','mts_int');
}


//-------------
// Enable/disable vmp mouse
function SetMouse ( value ) {
    if (!vmp) return ;
    if (value)
        vmp.SetProperty('MTSInteractor.DisableMouseDrag', 'actv', 0, 'mts_int');
    else
        vmp.SetProperty('MTSInteractor.DisableMouseDrag', 'actv', 1, 'mts_int');
}


//---------------
// Set Viewpoint background - used for print page
function vmpBackground ( bg ) {
    if (!vmp) return ;
    //vmp.SetProperty('MTSPanorama.CarBackground', 'clps', 0, 'mts_int');
    if ( bg == '' ) {
        var img = 'images/bg.jpg';
    }
    else {
        var img = 'images/vmpbg_' + bg + '.jpg';
    }
    vmp.SetProperty('MTSTimeElem.CarBackgroundImg', 'Path', img, 'mts_str');
    vmp.TriggerAnim('MTSTimeElem.CarBackgroundImg');
}


function hide ( id ) {
    var el = document.getElementById(id);   
    if (el) el.style.display = 'none'
}

function show ( id ) {
    var el = document.getElementById(id);   
    if (el) el.style.display = 'block'
}
