
function renderViewports(){

$col = 1; $row = 1;

for(i=0; i<viewports.length; i++){
n = document.createElement('div');
//$('body').appendChild(n);
$('body').insertBefore(n,$('menu'))
n.setAttribute('id',viewports[i][0].toLowerCase());
n.style.width = viewportWidth +'px';
n.style.height = viewportHeight +'px';
n.style.background ='url('+viewports[i][1]+')';
n.style.left = $col * viewportWidth + 'px';
n.style.top = $row * viewportHeight + 'px';
n.className = 'viewport';
n.onselectstart = function() { return(false); };

// Sort Grid
$col=$col+1; if($col>4){$col=1; $row=$row+1;}

// Arrange Child nodes

for(u=0; u<viewports[i][2].length; u++){
thischild = viewports[i][2][u].split('<o>');
// ======= text ============   [0] div type | [1] content |  [2] left | [3] top | [4] width | [5] height | [6] class | [7] linkURL | [8] Title
if(thischild[0]=='text'){
c = document.createElement('div');
c.setAttribute('id',viewports[i][0]+'_text_'+u);
n.appendChild(c);
c.innerHTML = unescape(thischild[1]);
c.style.left = thischild[2]+'px';
c.style.top = thischild[3]+'px';
c.style.width = thischild[4]+'px';
c.style.height = thischild[5]+'px';
c.className = thischild[6];
if(thischild[8]!='undefined' && thischild[8]!='' && thischild[8]!=null){c.title = thischild[8];}
c.setAttribute('linkURL', thischild[7]);
if(thischild[7]!='' && thischild[7]!=null){c.onmousedown = function(){goto(this.getAttribute("linkURL"),this)}}
if(c.scrollHeight > thischild[5] || thischild[1].indexOf("forceScroller=\"true\"") > -1){makeScrollers(c)}
}
// ======== Distributors ===
if(thischild[0]=='distributor'){
c = document.createElement('div');
c.setAttribute('id',viewports[i][0]+'_text_'+u);
n.appendChild(c);
c.innerHTML = unescape(thischild[1]);
c.style.left = thischild[2]+'px';
c.style.top = thischild[3]+'px';
c.style.width = '20px';//thischild[4]+'px';
c.style.height = '16px';//thischild[5]+'px';
c.className = thischild[6];
c.style.background = 'url(assets/pushpin.png)';
c.style.backgroundRepeat = 'no-repeat';
c.title = 'distributor';
if(thischild[8]!='undefined' && thischild[8]!='' && thischild[8]!=null){c.title = thischild[8];}
c.setAttribute('linkURL', thischild[7]);
if(thischild[7]!='' && thischild[7]!=null){c.onmousedown = function(){goto(this.getAttribute("linkURL"),this)}}
if(c.scrollHeight > thischild[5] || thischild[1].indexOf("forceScroller=\"true\"") > -1){makeScrollers(c)}
}
// ======== IMG ===========
else if(thischild[0]=='img'){
c = document.createElement('img');
n.appendChild(c);
c.src = thischild[1];
//c.title = c.src.replace('jpg', '');
$setPos(c,thischild[2],thischild[3],thischild[4],thischild[5])
c.setAttribute('linkURL', thischild[6]);
if(thischild[6]!='' && thischild[6]!=null){c.onmousedown = function(){goto(this.getAttribute("linkURL"),this)}}
}//e
// ======== OVERLAY ===========
else if(thischild[0]=='overlay'){
c = document.createElement('div');
n.appendChild(c);
c.style.background ='url('+thischild[1]+')';
c.style.left = thischild[2]+'px';
c.style.top = thischild[3]+'px';
c.style.width = 500+'px';
c.style.height = 500+'px';
}//e child type
}//o kids
}//o vports
}//f

function makeScrollers(i){
c = document.createElement('div');
i.parentNode.appendChild(c);
$setPos(c,int(i.style.left) + int(i.style.width),int(i.style.top) + int(i.style.height)-22,10,12)
c.style.background ='url(assets/arrow_up.png)';
c.setAttribute('id','scroller_'+i.id);
c.setAttribute('title','Scroll Up');
c.onclick = function(){scrollText(this.id, true);}

c = document.createElement('div');
i.parentNode.appendChild(c);
$setPos(c,int(i.style.left) + int(i.style.width),int(i.style.top) + int(i.style.height)-10,10,12)
c.style.background ='url(assets/arrow_down.png)';
c.setAttribute('id','scroller_'+i.id);
c.setAttribute('title','Scroll Down');
c.onclick = function(){scrollText(this.id, false);}
}//f

$log = '';
function scrollText(id, d, e){//id of scrolling obj, direction, destination
i = $(id.replace('scroller_',''));
ScrollDistance = 200; //(int(i.style.height)/2);

maxScroll = i.scrollHeight - int(i.style.height);//calc max scroll
$log +='max = '+maxScroll + ' [] ';
$log += 'sDistance = '+ScrollDistance + ' [] ';
if(d){e = i.scrollTop - ScrollDistance; $log+=' upwards [] ';}//direction == true
else {e = i.scrollTop + ScrollDistance;}
if(e>maxScroll){e = maxScroll;}//limit max
if(e<0){e=0}//limit min
i.scrollTop=e;

}//f




function oldScrollers(){
i = $(id.replace('scroller_',''));
ScrollSpeed = 3;

if(!e){
ScrollDistance = (int(i.style.height)/2);
if(d){e = i.scrollTop - ScrollDistance;}//direction == true
else {e = i.scrollTop + ScrollDistance;}
maxScroll = i.scrollHeight - int(i.style.height) ;//calc max scroll
if(e>maxScroll){e = maxScroll}//limit max
if(e<0){e=0;}//limit min
}//i e isnt set

if(i.scrollTop>e){i.scrollTop-=ScrollSpeed; $log+=' going up';}
else             {i.scrollTop+=ScrollSpeed;}
if(i.scrollTop > e+ScrollSpeed || i.scrollTop < e-ScrollSpeed){setTimeout(function(){scrollText(id,d,e)}, 1)}//within scrolldistance of goal
}//f

// ===========================================

window.onresize = function(event) {setTable();}//f

var p;

window.onload = function(){
$('body').innerHTML = '';
addMenu()
renderViewports()
setTable();
p = getValue('#');     if(p==null || p==''){p=viewports[0][0]}
goto(p)

// === set hotswaps ======
if(ReviewsBlogHandbag.length>0){openBlog(0, 'Reviews')}
if(NewsBlogHandbag.length>0){openBlog(0, 'News')}
if(BlairBlogHandbag.length>0){openBlog(0, 'Blair')}
if(NigelBlogHandbag.length>0){openBlog(0, 'Nigel')}
if(OthersBlogHandbag.length>0){openBlog(0, 'Others')}

if(pinot_noirHandbag.length>0){openWine(0, 'pinot_noir')}
if(chardonnayHandbag.length>0){openWine(0, 'chardonnay')}
if(rieslingHandbag.length>0){openWine(0, 'riesling')}
if(othersHandbag.length>0){openWine(0, 'others')}
}//f

function screenSize(){
if(window.innerWidth){Awx = window.innerWidth; Awy = window.innerHeight;}
else{Awx = document.documentElement.clientWidth; Awy = document.documentElement.clientHeight;}
return{x:Awx, y:Awy}
}

var timmy = null;
var $log = '';

function setTable(){
clearTimeout(timmy)
Aw = screenSize();
x = Math.round((viewportWidth - Aw.x)/2)+endScrollx;
y = Math.round((viewportHeight - Aw.y)/2)+endScrolly;
window.scroll(x,y)
vo = $('viewportOverlay');
vo.style.position = 'absolute';
vo.style.left = x + 'px';
vo.style.top = y + 'px';
vo.style.width = Aw.x + 'px';
vo.style.height = Aw.y + 'px';
alignMenu();
timmy = setTimeout(setTable, 10);
pollHash();
}

var recentHash = window.location.hash;

function pollHash() {
if (window.location.hash==recentHash) {return;}
recentHash = window.location.hash; 
//if(recentHash==''){alert('its a keeper.'); }
goto(desk + '</>'+ window.location.hash.replace("#=","")); 

}

function matchViewportOverlay(x,y){
vo = $('viewportOverlay');
vo.style.left = x + 'px';
vo.style.top = y + 'px';
}//f

function alignMenu(){
x = Math.round((viewportWidth - Aw.x)/2)+endScrollx;
y = Math.round((viewportHeight - Aw.y)/2)+endScrolly;
m = $('menu');
m.style.width = Aw.x+'px';
m.style.left = x + 'px';
m.style.top = (y + Aw.y) - 27 + 'px';
}//f

function $(i){return document.getElementById(i);}
function int(i){return parseInt(i.replace('px',''));}//f

function getValue(varname)
{
url = window.location.href;
qparts = url.split("?");

if (qparts.length <=1){return null;}

query = qparts[1];
vars = query.split("&");
value = "";

for (i=0;i<vars.length;i++){
parts = vars[i].split("=");
if (parts[0] == varname){value = parts[1];break;}
}

value = unescape(value);
value.replace(/\+/g," ");

return value;
}//f

function returnRoot(){
var file_name = document.location.href;
return file_name.substring(0,file_name.lastIndexOf("/"));
}//f

// ========== navigation =========

function goto(i,e){
closeImg()
srcStr = i;
clearTimeout(timmy)
d=null;
iArray=i.split("</>"); 
if(iArray.length>1){d = iArray[0]; i = iArray[1];} else(i=iArray[0])

if(d!=null){d = d.toLowerCase();} desk = desk.toLowerCase(); if(d==desk){d=null}

if(d!=null){
if(d=='popup'){openPop(srcStr,e)}
else if(d=='distributors'){openDis(srcStr,e)}
else if(d=='external'){openLink(i)}
else if(d=='cellar_year'){cellar_open_year(i)}
else if(d=='cellar_type'){cellar_open_type(i)}
// ====== different desktop ========
else{
i = i.toLowerCase();
window.location.href = '?d='+d+'&#=' + i;
}//e
}//i
// ====== this desktop ========
else{
if(i!=''){
i = i.toLowerCase();
docc = returnRoot();
if(window.location != docc + '/?d='+desk+'&#=' + i){window.location.href = '?d='+desk+'&#=' + i;}
curFocus = i;
ready_x = false; 
ready_y = false;

if(typeof(i)=="string"){i = $(i);}
p = $getPos(i);
endScrollx = p.x;
endScrolly = p.y;
scrollingWithTheBigDogs()
}//i i isnt empty
}//e
}//f

function openLink(i){
window.open(i);
}//f

function scrollingWithTheBigDogs(){
s = getScroll();
x=s.x; y = s.y;

if(!ready_x){
endScrollx_adjusted = Math.round((viewportWidth - Aw.x)/2)+endScrollx;
if(s.x>endScrollx_adjusted)       {dis = Math.round((s.x-endScrollx_adjusted)/ratio); if(dis<1){dis=1};     x = s.x - dis;}
else if(s.x<endScrollx_adjusted)  {dis = Math.round((endScrollx_adjusted-s.x)/ratio); if(dis<1){dis=1};     x = s.x + dis;}
else{s.x=endScrollx_adjusted}
}//i
if(!ready_y){
endScrolly_adjusted = Math.round((viewportHeight - Aw.y)/2)+endScrolly;
if(s.y>endScrolly_adjusted)       {dis = Math.round((s.y-endScrolly_adjusted)/ratio); if(dis<1){dis=1};     y = s.y - dis;}
else if(s.y<endScrolly_adjusted)  {dis = Math.round((endScrolly_adjusted-s.y)/ratio); if(dis<1){dis=1};      y = s.y + dis;}
else{s.y=endScrolly_adjusted}
}//i
matchViewportOverlay(x,y);
window.scroll(x,y);
if(x!= endScrollx_adjusted){ready_x=false;}else{ready_x=true}
if(y!= endScrolly_adjusted){ready_y=false;}else{ready_y=true}
if(ready_x==true && ready_y==true){ready_x = false; ready_y = false; setTable();}
else{setTimeout(scrollingWithTheBigDogs, 5)}
}//f

function getScroll(){
var ScrollTop = document.body.scrollTop;
if (ScrollTop == 0){
 if (window.pageYOffset){ScrollTop = window.pageYOffset;}
 else{ScrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;}
}
var ScrollLeft = document.body.scrollLeft;
if (ScrollLeft == 0){
 if (window.pageXOffset){ScrollLeft = window.pageXOffset;}
 else{ScrollLeft = (document.body.parentElement) ? document.body.parentElement.scrollLeft : 0;}
}

return{x:ScrollLeft, y:ScrollTop}
}//f

function $getPos(ob){
iTop = 0; iLeft = 0; tCi = ob;
width = int(ob.style.width); height = int(ob.style.height);
while(tCi.offsetParent){iLeft += tCi.offsetLeft; iTop  += tCi.offsetTop; tCi   = tCi.offsetParent;}//w
return{x:iLeft, y:iTop, w:width, h:height}
}//f

function addMenu(){
$('body').innerHTML = '<img width="1px" height="1px" src="assets/viewport_overlay.png" id="viewportOverlay"><div id="menu"><div class="paper"><div class="m0" onclick="goto(\'Home</>Home\')">Home</div><div class="m1" onclick="goto(\'Home</>Team\')">The Team</div><div class="m2" onclick="goto(\'Gareths_Desk</>Home\')">Our Land &amp; Vines</div><div class="m3" onclick="goto(\'wines</>Wines_home\')">Our Wines</div><div class="m4"onclick="goto(\'shop</>shop_home\')">Buy Wine</div><div class="m5" onclick="goto(\'distribution</>Distributors_home\')">Distribution</div><div class="m6" onclick="goto(\'Home</>Gallery\')">Gallery</div><div class="m7" onclick="goto(\'Home</>Blairs_Blog\')">Reviews, Blogs, etc</div><div class="m8" onclick="goto(\'Home</>Contact\')">Contact Us</div></div></div><div id="matte"></div>';
}//f

function $setPos(obj,l,t,w,h){
if(typeof(obj)=="string"){obj = $(obj)}
if(l!='' && l!='NaN'){obj.style.left = l + 'px';}
if(t!='' && t!='NaN'){obj.style.top = t + 'px';}
if(w!='' && w!='NaN'){obj.style.width = w + 'px';}
if(h!='' && h!='NaN'){obj.style.height = h + 'px';}
}//f

//======== Hot Swapping =====

function openBlog(i,c){
if(c=='Reviews'){$('reviewTitle').innerHTML = '<h2><i>'+reviewsTitles[i]+'</i></h2>'}
eval('t = '+c+'BlogHandbag[i]');
t = str_replace("\\'", "'",t);
$(c+'BlogDisplay').innerHTML = t;
}//f

function openWine(i,w){
eval('t = '+w+'Handbag[i]');
t[1] = str_replace("\\'", "'",t[1]);
$(w+'Display').innerHTML = t[1];
$(w).getElementsByTagName('img')[0].src = 'labels/'+t[2];
}//f

// ====== img Popup ========

function openPop(str, obj){
setTable();
content = str.split('</>');
vpPos = $getPos($('viewportOverlay'));
m = $('matte');
$setPos(m,vpPos.x,vpPos.y,vpPos.w,vpPos.h);
m.style.display = 'block';
m.onmousedown = closeImg;

// ====== place holder ========
hPos = $getPos(obj);
h = document.createElement('div');
$('body').appendChild(h);
h.id = 'tempPopDiv';
$setPos(h,hPos.x,hPos.y,hPos.w-20,hPos.h-20);

// ===== start img load ======
i = document.createElement('img');
i.title = content[2];
i.id = 'tempPopImage';
i.style.padding = '10px';
//i.innerHTML = '';
i.src = content[1];
i.onmousedown = closeImg;

// === add caption =======
if(content.length<2){content[2] = ' ';}
p = document.createElement('p');
p.innerHTML = content[2];
p.id = 'caption';
placeImage(i,p);
}//f


function placeImage(i,p){
if(i.width>0){
tx = Math.round((viewportWidth - Aw.x)/2)+endScrollx+(Math.round((Aw.x-i.width)/2));    
ty = Math.round((viewportHeight - Aw.y)/2)+endScrolly+(Math.round((Aw.y-i.height)/2));
tw = i.width + 10; th = i.height + 50;

hol = $('tempPopDiv');
hpos = $getPos(hol);
ratio = 4;


if(hpos.x<tx){diffx = Math.round((tx-hpos.x)/ratio);        if(diffx<1){diffx=1};   x = hpos.x+diffx;}  
else if(hpos.x>tx){diffx = Math.round((hpos.x-tx)/ratio);   if(diffx<1){diffx=1};   x = hpos.x-diffx;} 
else{x=0;}

if(hpos.y<ty){diffy = Math.round((ty-hpos.y)/ratio);        if(diffy<1){diffy=1};   y = hpos.y+diffy;}
else if(hpos.y>ty){diffy = Math.round((hpos.y-ty)/ratio);   if(diffy<1){diffy=1};   y = hpos.y-diffy;}
else{y=0;}
if(hpos.w<tw){diffw = Math.round((tw-hpos.w)/ratio); if(diffw<1){diffw=1}; w = hpos.w+diffw;}  if(hpos.w>tw){diffw = Math.round((hpos.w-tw)/ratio); if(diffw<1){diffw=1}; w = hpos.w-diffw;}   
if(hpos.h<th){diffh = Math.round((th-hpos.h)/ratio); if(diffh<1){diffh=1}; h = hpos.h+diffh;}  if(hpos.h>th){diffh = Math.round((hpos.h-th)/ratio); if(diffh<1){diffh=1}; h = hpos.h-diffh;} 


$setPos(hol,x,y,w,h);
if(hpos.x==tx && hpos.y==ty && hpos.w==tw && hpos.h==th){settleImg(i,p);}
else{setTimeout(function(){placeImage(i,p)},1)}
}
else{setTimeout(function(){placeImage(i,p)},1)}
}//f

function settleImg(i,p){
hol = $('tempPopDiv');
hol.appendChild(i);
hol.appendChild(p);

c = document.createElement('div');
hol.appendChild(c);
c.style.position = 'absolute';
c.style.display = 'block';

hPos = $getPos(hol);
$setPos(c,hPos.w,-15,30,30);
c.style.background = 'URL(assets/close_pop.png)'; 
c.onclick = closeImg;

}//f

function closeImg(){
if($('matte').style.display == 'block'){
$('tempPopDiv').parentNode.removeChild($('tempPopDiv'));
$('matte').style.display = 'none';
loaded = true;
}
}//f

// ====== Distributors =====

function openDis(str, obj){
content = str.split('</>');
vpPos = $getPos($('viewportOverlay'));
m = $('matte');
$setPos(m,vpPos.x,vpPos.y,vpPos.w,vpPos.h);
m.style.display = 'block';
m.onmousedown = closeImg;

// ====== place holder ========
hPos = $getPos(obj);
h = document.createElement('div');
$('body').appendChild(h);
h.id = 'tempPopDiv';
h.style.padding = '0px';
h.innerHTML = '';
$setPos(h,hPos.x,hPos.y,hPos.w,hPos.h);
placeDis(content[1]);
}//f

function placeDis(p){
tx = Math.round((viewportWidth - Aw.x)/2)+endScrollx+(Math.round((Aw.x-500)/2));    
ty = Math.round((viewportHeight - Aw.y)/2)+endScrolly+(Math.round((Aw.y-350)/2));
tw = 500; th = 350;

hol = $('tempPopDiv');
hpos = $getPos(hol);
ratio = 4;

if(hpos.x<tx){diff = Math.round((tx-hpos.x)/ratio); if(diff<1){diff=1}; x = hpos.x+diff;}  if(hpos.x>tx){diff = Math.round((hpos.x-tx)/ratio); if(diff<1){diff=1}; x = hpos.x-diff;} 
if(hpos.y<ty){diff = Math.round((ty-hpos.y)/ratio); if(diff<1){diff=1}; y = hpos.y+diff;}  if(hpos.y>ty){diff = Math.round((hpos.y-ty)/ratio); if(diff<1){diff=1}; y = hpos.y-diff;}
if(hpos.w<tw){diff = Math.round((tw-hpos.w)/ratio); if(diff<1){diff=1}; w = hpos.w+diff;}  if(hpos.w>tw){diff = Math.round((hpos.w-tw)/ratio); if(diff<1){diff=1}; w = hpos.w-diff;}   
if(hpos.h<th){diff = Math.round((th-hpos.h)/ratio); if(diff<1){diff=1}; h = hpos.h+diff;}  if(hpos.h>th){diff = Math.round((hpos.h-th)/ratio); if(diff<1){diff=1}; h = hpos.h-diff;} 

$setPos(hol,x,y,w,h);
if(hpos.x==tx && hpos.y==ty && hpos.w==tw && hpos.h==th){settleDis(p)}
else{setTimeout(function(){placeDis(p)},25)}
}//f

function settleDis(p){
hol = $('tempPopDiv');
hol.style.background = 'URL(assets/dis_card.jpg)'; 
hol.innerHTML = p;

c = document.createElement('div');
hol.appendChild(c);
c.style.position = 'absolute';
c.style.display = 'block';

hPos = $getPos(hol);
$setPos(c,hPos.w-15,-15,30,30);
c.style.background = 'URL(assets/close_pop.png)'; 
c.onclick = closeImg;
}//f

function str_replace(needle, newNeedle, haystack){
while(haystack.indexOf(needle)>-1){
haystack = haystack.replace(needle, newNeedle);
}//w
return haystack;
}//f

var cellar_year = 2008;
var cellar_type = 'pinot_noir';
var cellar_wine = '';



function cellar_open_type(i){
cellar_type = i;
cellar_wine = '';
req_cellar()
}

function cellar_open_year(i){
cellar_year = i;
cellar_wine = '';
req_cellar()
}

function cellar_open_wine(i){
cellar_wine = i;
req_cellar()
}

function req_cellar(){
contactServer('cellar.php?gimme=content&gyear='+cellar_year+'&type='+cellar_type+'&wine='+cellar_wine,'cellar_print');
}

function cellar_print(){
pArray = ajaxResponse.split('<qqq>');
$('cellar_year_display').innerHTML = pArray[0];
if(pArray[2]!=''){$('cellar_content_display').innerHTML = '<h3>'+pArray[1]+'</h3>'+pArray[2];}
else{$('cellar_content_display').innerHTML = 'No information available for '+cellar_type;}


if(pArray[3]!=''){$('cellaring-vintage').getElementsByTagName('img')[0].src = 'labels/'+pArray[3];}
else{$('cellaring-vintage').getElementsByTagName('img')[0].src = 'labels/safe_label.jpg';}
contactServer('cellar.php?gimme=list&gyear='+cellar_year+'&type='+cellar_type,'cellar_print_list');
}

function cellar_print_list(){
if(ajaxResponse!=''){$('cellar_list').innerHTML = ajaxResponse;}
else{$('cellar_list').innerHTML = 'No '+cellar_type+' for this year';}
}






function contactServer(url, output){
	var ajaxRequest;
	try{ajaxRequest = new XMLHttpRequest();}// Opera 8.0+, Firefox, Safari
 catch (e){
		try{	ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");}// Internet Explorer Browsers
  catch (e) {
	  try{				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");} 
   catch (e){alert("Your browser is not currently Supported");	return false;}
		}
	}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
ajaxResponse = ajaxRequest.responseText;
eval(output+"()")
}
}
ajaxRequest.open("GET", url, true);
ajaxRequest.send(null); 

}//f

var ajaxResponse;
