var startTimer = new Date();
var category;
var categories;
var messages = new Array();
var flickr;
var folder = '/';
function setResolution(res) {
   var cres = readCookie('res');
   if (res) {
      //if (cres >- 1) eraseCookie('res');
      createCookie('res',res,60*24*265);
      if (res == 0) removeBackground();
      else {
         removeBackground();
         loadFlickrImage(res);
      }
   } else if (!cres) {
      var loadtime = (new Date()-startTimer)/1000;
      if (loadtime>10) res = 1;
      else res = 2;
   } else res = cres;
   document.getElementById('res').selectedIndex = res;
   return (res==0)?'none':(res==1)?'med':'high';
}
function removeBackground() {
   if (document.body.firstChild.nodeName == 'IMG') 
      document.body.removeChild(document.body.firstChild);
   return true;
}
function textSize(direction) {
   var size = (document.body.style.fontSize)?parseFloat(document.body.style.fontSize):100;
   var newsize;
   if (direction == 'increase') newsize = (size+12.5) + '%';
   else newsize = (size-12.5) + '%';
   document.body.style.fontSize = newsize;
}
function bodyheight() {
   var D = document;
   return Math.max(
      Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
      Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
      Math.max(D.body.clientHeight, D.documentElement.clientHeight)
   );
}

function loadFlickrLinkImages(section) {
   //var flickr = new FlickrAPI('760306ba991e4bcb125e9887e2400e76', '');
   var links = document.getElementsByTagName('A');
   var t,tn,img,params,linknum,link,linkname,photo,parent,insection,category;
   for (linknum=0;linknum<links.length;linknum++) {
      link = links[linknum];
      parent = link.parentNode;
      if (parent) {
         insection = false;
         while (parent.nodeName.toUpperCase() != 'BODY') {
            if (parent.id == section) { 
               insection = true;
               break;
            }
            parent = parent.parentNode;
         }
      }
      if (insection) {
         linkname = link.firstChild.nodeValue;        
         params = new Array();
         params['api_key'] = '760306ba991e4bcb125e9887e2400e76';
         params['group_id'] = '1016935@N23';
         if (linkname) {
            category = linkname.toLowerCase();
            category = category.replace(/\s+.*$/,"");
            category = category.replace(/s$/, "");
            if (category) params['tags'] = category;
         }
         params['extras'] = 'date_taken,owner_name';
         var json = flickr.callMethodJSON('flickr.groups.pools.getPhotos', params);
         var obj = eval('('+json+')');
         var photos = obj.photos.photo;
         var img;
         if (photos.length) {
            var randomnumber=Math.floor(Math.random()*photos.length);
            photo = photos[randomnumber];
            url = flickr.getPhotoURL(photos[randomnumber],'square');
            img = document.createElement('IMG');
            //img.alt = photo.title;
            img.alt = linkname;
            img.src = url;
            img.className = 'sectionlinkimage';
            t = document.createElement('P');
            t.style.padding = 0;
            t.style.margin = 0;
            t.style.backgroundColor = '#fff';
            t.appendChild(document.createTextNode(linkname));
            //link.removeChild(link.firstChild);
            link.replaceChild(t,link.firstChild);
            link.appendChild(img);
         } //else alert('No ' + category.toLowerCase() + ' photos available');
      }
   }   
   return true;
}
function asyncFlickrLinkImages(section) {
   var links = document.getElementsByTagName('A');
   var t,tn,img,params,linknum,link,linkname,photo,parent,insection,category;
   for (linknum=0;linknum<links.length;linknum++) {
      link = links[linknum];
      parent = link.parentNode;
      if (parent) {
         insection = false;
         while (parent.nodeName.toUpperCase() != 'BODY') {
            if (parent.id == section) { 
               insection = true;
               break;
            }
            parent = parent.parentNode;
         }
      }
      if (insection) {
         linkname = link.firstChild.nodeValue;
         // insert cookie code to stop constant server requests.
         if (readCookie('li_'+linkname)!=false) {
            loadCookieLinkImages(link,linkname);
         } else {
            params = new Array();
            params['api_key'] = '760306ba991e4bcb125e9887e2400e76';
            params['group_id'] = '1016935@N23';
            if (linkname) {
               category = linkname.toLowerCase();
               category = category.replace(/\s+.*$/,"");
               category = category.replace(/s$/, "");
               if (category) params['tags'] = category;
            }
            params['extras'] = 'date_taken,owner_name';
            flickr.asyncMethodJSON('flickr.groups.pools.getPhotos', params, 'loadAsyncLinkImages', link);
         }
      }
   }
}
function loadAsyncLinkImages() {
   var c;
   for (c in reqs) {
      request = reqs[c];
      if (!request.processed && request.xhr.readyState == 4) {
         reqs[c].processed = true;
         var link,linkname;
         link = request.target;
         linkname = link.firstChild.nodeValue;
         var JSONtext = request.xhr.responseText;
         var obj = JSON.parse(JSONtext);
         var t,tn,img,params,linknum,link,linkname,photo,parent,insection,category;
         //var obj = eval('('+json+')');
         var photos = obj.photos.photo;
         var litem;
         var img;
         if (photos.length) {
            var randomnumber=Math.floor(Math.random()*photos.length);
            photo = photos[randomnumber];
            url = flickr.getPhotoURL(photos[randomnumber],'square');
            createCookie('li_'+linkname,url);
            t = document.createElement('P');
            t.style.padding = 0;
            t.style.margin = 0;
            t.style.backgroundColor = '#fff';
            t.appendChild(document.createTextNode(linkname));
            //link.removeChild(link.firstChild);
            litem = link.parentNode;
            link.replaceChild(t,link.firstChild);
            litem.style.backgroundImage = 'url('+url+')';
            litem.className = 'imlink';
            //link.appendChild(img);
         } //else alert('No ' + category.toLowerCase() + ' photos available');
         else {litem.style.textAlign = 'center';}
      }
      if (request.processed) request = null;
   }
   return true;
}
function loadCookieLinkImages(link,section) {
   var t,litem,url;
   linkname = link.firstChild.nodeValue;
   url = readCookie('li_'+section);
   t = document.createElement('P');
   t.style.padding = 0;
   t.style.margin = 0;
   t.style.backgroundColor = '#fff';
   t.appendChild(document.createTextNode(linkname));
   //link.removeChild(link.firstChild);
   litem = link.parentNode;
   link.replaceChild(t,link.firstChild);
   litem.style.backgroundImage = 'url('+url+')';
   litem.className = 'imlink';
   return true;
}
function createBackdropImage(photo,res) {
   var myWidth = 0, myHeight = 0;
   if( typeof( window.innerWidth ) == 'number' ) {
   //Non-IE
      myWidth = window.innerWidth;
      myHeight = window.innerHeight;
      // on mozilla the space used by the vertical scroll bar is included so 
      // you have to test for it and remove it.
      if (window.scrollMaxY > 0) 
         myWidth -= 17;
   } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
   //IE 6+ in 'standards compliant mode'
      myWidth = document.documentElement.clientWidth;
      myHeight = document.documentElement.clientHeight;
   } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
   //IE 4 compatible
      myWidth = document.body.clientWidth;
      myHeight = document.body.clientHeight;
   }
   var img;
   url = flickr.getPhotoURL(photo,res);
   img = document.createElement('IMG');
   img.id = 'backgroundimage';
   img.src = url;
   img.style.width = myWidth + 'px';
   img.style.height = myHeight + 'px';
   img.style.border = 'none';
   img.style.padding = 0;
   img.style.margin = 0;
   img.style.position = 'absolute';
   img.style.top = 0;
   img.style.left = 0;
   img.style.zIndex = -1;
   img.className = 'bn20';
   var node = document.body.firstChild;
   document.body.insertBefore(img,node);
   node = document.body.firstChild;
   while (node = node.nextSibling) {
      if (node.style) node.style.zIndex = 3;
   }
   return true;
}
function loadFlickrImage(res,category) {
   var myWidth = 0, myHeight = 0;
   if( typeof( window.innerWidth ) == 'number' ) {
   //Non-IE
      myWidth = window.innerWidth;
      myHeight = window.innerHeight;
      // on mozilla the space used by the vertical scroll bar is included so 
      // you have to test for it and remove it.
      if (document.documentElement.clientHeight > myHeight) myWidth -= 17;
   } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
   //IE 6+ in 'standards compliant mode'
      myWidth = document.documentElement.clientWidth;
      myHeight = document.documentElement.clientHeight;
   } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
   //IE 4 compatible
      myWidth = document.body.clientWidth;
      myHeight = document.body.clientHeight;
   }
   //var flickr = new FlickrAPI('760306ba991e4bcb125e9887e2400e76', '');
   var params = new Array();
   params['api_key'] = '760306ba991e4bcb125e9887e2400e76';
   //params['group_id'] = '977762@N24';
   params['group_id'] = '1016935@N23';
   if (category) params['tags'] = category;
   params['extras'] = 'date_taken,owner_name';
   var json = flickr.callMethodJSON('flickr.groups.pools.getPhotos', params);
   var obj = eval('('+json+')');
   var photos = obj.photos.photo;
   var img;
   if (category && ! photos.length) load();
   else {
      var randomnumber=Math.floor(Math.random()*photos.length)
      url = flickr.getPhotoURL(photos[randomnumber],res);
      img = document.createElement('IMG');
      img.id = 'backgroundimage';
      img.src = url;
      img.style.width = myWidth + 'px';
      img.style.height = myHeight + 'px';
      img.style.border = 'none';
      img.style.padding = 0;
      img.style.margin = 0;
      img.style.position = 'absolute';
      img.style.top = 0;
      img.style.left = 0;
      img.style.zIndex = -1;
      var node = document.body.firstChild;
      document.body.insertBefore(img,node);
      node = document.body.firstChild;
      while (node = node.nextSibling) {
         if (node.style) node.style.zIndex = 3;
      }
   }
   return true;
}
function loadFlickrThumb(category) {
   var res = 'square';
   //var flickr = new FlickrAPI('760306ba991e4bcb125e9887e2400e76', '');
   var params = new Array();
   params['api_key'] = '760306ba991e4bcb125e9887e2400e76';
   //params['group_id'] = '977762@N24';
   params['group_id'] = '1016935@N23';
   if (category) params['tags'] = category;
   params['extras'] = 'date_taken,owner_name';
   json = flickr.callMethodJSON('flickr.groups.pools.getPhotos', params);
   var obj = eval('(' + json + ')');
   var photos = obj.photos.photo;
   var photo,img,div,lnk;
   if (category && category != 'none' && ! photos.length) loadFlickrThumb();
   else {
      var randomnumber=Math.floor(Math.random()*photos.length);
      photo = photos[randomnumber];
      createCookie('im_page',photo);
      url = flickr.getPhotoURL(photo,res);
      img = document.createElement('IMG');
      img.id = 'thumbimage';
      img.alt = photo.title;
      img.src = url;
      img.style.border = 'none';
      img.style.padding = 0;
      img.style.margin = 0;
      img.className = 'banner';
      img.onload = function() {repeatThumb(this.id);}
      var node = document.getElementById('bannerplc');
      if (!node) node = document.getElementById('content');
      var width = (node.style.width)?node.style.width:node.offsetWidth;
      if( typeof( window.innerWidth ) == 'number' ) width -= 2;
      div = document.createElement('DIV');
      div.id = 'bannerdiv';
      div.style.width = width + 'px';
      div.style.backgroundColor = 'transparent';
      div.className = 'banner';
      lnk = document.createElement('A');
      lnk.href = 'http://www.flickr.com/photos/'+photo.owner+'/'+photo.id;
      lnk.target = 'flickr';
      lnk.className = 'banner';
      lnk.appendChild(img);
      div.appendChild(lnk);
      if (node.id == 'bannerplc') node.parentNode.replaceChild(div,node);
      else node.parentNode.insertBefore(div,node);
      getColorsForPhoto(url);
   }
   return true;
}
function asyncFlickrThumb() {
   var cat;
   //var flickr = new FlickrAPI('760306ba991e4bcb125e9887e2400e76', '');
   var params = new Array();
   params['api_key'] = '760306ba991e4bcb125e9887e2400e76';
   //params['group_id'] = '977762@N24';
   params['group_id'] = '1016935@N23';
   if (categories.length) {
      cat = categories.pop();
      cat = cat.replace(/s$/,"");
      cat = cat.replace(/ie$/,"y");
      params['tags'] = cat;
      category = cat;
   }
   params['extras'] = 'date_taken,owner_name';
   flickr.asyncMethodJSON('flickr.groups.pools.getPhotos', params, 'loadAsyncThumb');
}
function loadAsyncThumb() {
   var res = 'low';
   var c,p,tn,br,m;
   for (c in reqs) {
      request = reqs[c];
      if (!request.processed && request.xhr.readyState == 4) {
         reqs[c].processed = true;
         var JSONtext = request.xhr.responseText;
         var obj = JSON.parse(JSONtext);
         var photos = obj.photos.photo;
         var photo,img,div,lnk;
         //if (category && category != 'none' && ! photos.length) asyncFlickrThumb();
         if (!photos.length) {
            messages.push('No photos tagged with '+category+'.'); 
            asyncFlickrThumb();
         } else {
            var randomnumber=Math.floor(Math.random()*photos.length);
            photo = photos[randomnumber];
            url = flickr.getPhotoURL(photo,res);
            img = document.createElement('IMG');
            img.id = 'thumbimage';
            img.alt = photo.title;
            img.src = url;
            img.style.border = '1px solid black';
            img.style.padding = '5px';
            img.style.backgroundColor = 'white';
            img.style.margin = '10px';
            img.className = 'banner';
            var node = document.getElementById('bannerplc');
            if (!node) node = document.getElementById('bannerdiv');
            var width = (node.style.width)?node.style.width:node.offsetWidth;
            if( typeof( window.innerWidth ) == 'number' ) width -= 2;
            div = document.createElement('DIV');
            div.id = 'bannerdiv';
            div.style.width = (width-2) + 'px';
            div.style.backgroundColor = 'transparent';
            bimg = folder+"callout/imagecolorswatch.php?url="+escape(url)
            div.style.backgroundImage = "url('"+bimg+"')";  
            div.style.backgroundRepeat = 'no-repeat';
            div.style.backgroundPosition = 'center';
            div.style.border = '1px solid black';
            div.style.overflow = 'hidden';
            div.className = 'banner';
            lnk = document.createElement('A');
            lnk.href = 'http://www.flickr.com/photos/'+photo.owner+'/'+photo.id;
            lnk.target = 'flickr';
            lnk.className = 'banner';
            lnk.appendChild(img);
            div.appendChild(lnk);
            /*
            if (messages.length) {
               p = document.createElement('P');
               p.className = 'bannermessage';
               while (m = messages.pop()) {
                  p.appendChild(document.createTextNode(m));
                  if (messages.length>0) p.appendChild(document.createElement('BR'));  
               }
               div.appendChild(p);     
            }
            */
            if (node.id == 'bannerplc') node.parentNode.replaceChild(div,node);
            else node.parentNode.replaceChild(div,node);
            //document.body.style.backgroundImage = "url('"+bimg+"')";
            //document.body.style.backgroundRepeat = "repeat";
            getColorsForPhoto(url);
            //createBackdropImage(photo,'square');
         }
      }
      if (request && request.processed) request = null;
   }
   return true;
}
function repeatThumbRevert(id) {
   var img1 = document.getElementById(id);
   var img2;
   var lnk = img1.parentNode;
   var myHeight = 0;
   var divwidth,copies,rcopies,rem,remsize,gaps,gap,c,trans;
   if (lnk.childNodes.length==1) {
      divwidth = lnk.parentNode.offsetWidth;
      // work around for IE 5.5 which creates a second row for some reason.
      /*
      if ( document.body && 
         ( document.body.clientWidth || document.body.clientHeight ) ) {
         divwidth -= 6;
      }
      */
      // get max number of images that fit across the screen
      copies = Math.floor(divwidth/img1.width); 
      // find out how many pixels are left over
      rem = divwidth%img1.width;
      
      img1.style.width = (img1.width + rem) + 'px';
      img1.style.height = (img1.width) + 'px';
      rem = 0;
      // the size of the gaps is then the left over pixels divided by the number
      // of gaps = copies -1
      gaps = Math.floor((rem)/(copies-1));
      //if( typeof( window.innerWidth ) != 'number' ) gaps -= 1;
      rem = (rem % (copies-1))-2;
      //remsize = Math.floor((rem)/(copies-1));
      remsize = 1;
      // the new remainder is what is left after removing the gaps
      // this gets used up by the images in the middle having 1px wider gaps
      trans = 10;
      var rcopies = Math.floor(copies/3);
      copies -= rcopies;
      for (c=1;c<copies;c++) {
         img2 = img1.cloneNode(true);
         img2.id = 'thumbimage_l'+c
         gap = (rem>0)?gaps+remsize:gaps;
         img2.style.marginRight = gap+'px';
         img2.style.marginLeft = 0;
         img2.style.height = null;
         img2.style.width = null;
         img2.className = 'bn'+trans;
         lnk.appendChild(img2);
         rem-=remsize;
         trans+=10;
      } 
      trans = 90;
      for (c=1;c<=rcopies;c++) {
         if (c==1) img1.style.marginRight = gap+'px';
         img2 = img1.cloneNode(true);
         img2.id = 'thumbimage_r'+c
         gap = (rem>0)?gaps+remsize:gaps;
         if (c!=rcopies) img2.style.marginRight = gap+'px';
         else img2.style.marginRight = 0;
         img2.style.marginLeft = 0;
         img2.style.height = null;
         img2.style.width = null;
         img2.className = 'bn'+trans;
         lnk.insertBefore(img2,lnk.firstChild);
         rem-=remsize;
         trans-=10;
      }
   }
}
function repeatThumb(id) {
   var img1 = document.getElementById(id);
   var img2;
   var lnk = img1.parentNode;
   var myHeight = 0;
   var divwidth,copies,rcopies,rem,remsize,gaps,gap,c,trans,squize,squ1ze;
   if (lnk.childNodes.length==1) {
      divwidth = lnk.parentNode.offsetWidth;
      // work around for IE 5.5 which creates a second row for some reason.
      // get max number of images that fit across the screen
      copies = Math.floor(divwidth/img1.width); 
      // find out how many pixels are left over
      rem = divwidth%img1.width;
      gap = 8;
      remsize = rem - ((copies-1) * gap);
      if (remsize < 0) {
         while (remsize < 0) {
            copies-=1;
            remsize = divwidth - (copies * img1.width) - ((copies-1)*gap);
         }
         rem = remsize;
      } else rem = remsize;
      gap = 7;
      squize = img1.width + Math.floor(rem/copies);
      lnk.parentNode.style.height = squize + 'px';
      rem = rem%copies;
      squ1ze = squize + rem;
      img1.style.width = squ1ze + 'px';
      img1.style.height = squize + 'px';
      rem = 0;
      trans = 10;
      //var rcopies = Math.floor(copies/3);
      //copies -= rcopies;
      for (c=1;c<copies;c++) {
         img2 = img1.cloneNode(true);
         //gap = gaps;
         img2.style.marginRight = gap+'px';
         img2.style.marginLeft = 0;
         img2.style.height = squize + 'px';
         img2.style.width = squize + 'px';
         img2.className = 'bn'+trans;
         lnk.appendChild(img2);
         trans+=10;
      } 
      /* 
      trans = 90;
      for (c=1;c<=rcopies;c++) {
         if (c==1) img1.style.marginRight = gap+'px';
         img2 = img1.cloneNode(true);
         //gap = gaps;
         if (c!=rcopies) img2.style.marginRight = gap+'px';
         else img2.style.marginRight = 0;
         img2.style.marginLeft = 0;
         img2.style.height = squize + 'px';
         img2.style.width = squize + 'px';
         img2.className = 'bn'+trans;
         lnk.insertBefore(img2,lnk.firstChild);
         trans-=10;
      }
      */
   }
}
function rebanner() {
   var backdrop = document.getElementById('backgroundimage');
   if(backdrop) backdrop.parentNode.removeChild(backdrop);
   var bannerdiv = document.getElementById('bannerdiv');
   if (bannerdiv) {
      var parent = bannerdiv.parentNode;
      var div = document.createElement('DIV');
      div.id = 'bannerplc';
      parent.replaceChild(div,bannerdiv)
      asyncFlickrThumb(category);
   }
   setScreenLayout();
}
function loadgallery(container,per_page,page,category) {
   //var flickr = new FlickrAPI('760306ba991e4bcb125e9887e2400e76', '');
   var divwidth = container.offsetWidth;
   var el_per_page = document.getElementById(container.id+'_per_page');
   if (el_per_page && el_per_page.value != per_page) per_page = el_per_page.value;
   var el_category = document.getElementById(container.id+'_category')
   if (el_category && el_category.value != category) category = el_category.value;
   if (category) {
      category = category.replace(/ies$/, "y");
      category = category.replace(/s$/, "");
   } 
   var per_row = 3;
   var photosurround = 38;// total of borders from square frame to margin around each photo box
   var photosize = Math.floor((divwidth/per_row)-photosurround);
   var params = new Array();
   page = parseInt(page);
   per_page = parseInt(per_page);
   params['api_key'] = '760306ba991e4bcb125e9887e2400e76';
   params['group_id'] = '1016935@N23';
   if (category) params['tags'] = category;
   if (per_page) params['per_page'] = per_page;
   if (page) params['page'] = page;
   params['extras'] = 'date_taken,owner_name';
   var json = flickr.callMethodJSON('flickr.groups.pools.getPhotos', params);
   var obj = JSON.parse(json);
   var photos = obj.photos.photo;
   var img,url,div,el,frame;
   var table,tbody,tr,th,td;
   var photo,li,prop,ul2,li2,name;
   node = container;
   while (node = container.firstChild) {
      container.removeChild(node);
   }
   div = document.createElement('div');
   div.className='gallerypages';
   if (page > 1) {
      el = document.createElement('BUTTON');
      el.style.cursor = 'hand';
      el.className = 'gallerypagedown';
      el.onclick=function () {
         loadgallery(container,per_page,page-1,category);
         //scroll(0,0);
      };
      el.appendChild(document.createTextNode('< Page ' + (page-1)));
      div.appendChild(el);
   }
   if (obj.photos.pages > page) {
      el = document.createElement('BUTTON');
      el.style.cursor = 'hand';
      el.className = 'gallerypageup';
      el.onclick=function () {
         loadgallery(container,per_page,page+1,category);
         //scroll(0,0);
      };
      el.appendChild(document.createTextNode('Page ' + (page+1) + '>'));
      div.appendChild(el);
   }
   
   // add a bit to choose images per page.
   el = document.createElement('LABEL');
   el.appendChild(document.createTextNode('Page'));
   div.appendChild(el);
   
   el = document.createElement('INPUT');
   el.type = 'text';
   el.className = 'text';
   el.style.width = '20px';
   el.id = container.id + '_pagenumber';
   el.value = page;
   el.onchange = function() {loadgallery(container,per_page,this.value,category);};
   div.appendChild(el);
   
   el = document.createElement('LABEL');
   el.appendChild(document.createTextNode('Photos'));
   div.appendChild(el);
   
   el = document.createElement('INPUT');
   el.type = 'text';
   el.className = 'text';
   el.style.width = '20px';
   el.id = container.id + '_per_page';
   el.value = per_page;
   el.onchange = function() {loadgallery(container,this.value,page,category);};
   div.appendChild(el);
   
   el = document.createElement('LABEL');
   el.appendChild(document.createTextNode('Filter'));
   div.appendChild(el);
   
   el = document.createElement('INPUT');
   el.type = 'text';
   el.className = 'text';
   el.style.width = '100px';
   el.id = container.id + '_category';
   if (category) el.value = category;
   el.onchange = function() {loadgallery(container,per_page,1,this.value);};
   div.appendChild(el);
   
   el = document.createElement('A');
   el.className = 'updatebutton';
   el.appendChild(document.createTextNode('Update'));
   div.appendChild(el);
   
   container.appendChild(div);
   
   for (i = 0; i < photos.length; i++){
      div = document.createElement('div');
      div.className = 'galleryphotoframe';
      div.style.width = (photosize+10)+'px';
      
      photo = photos[i];
      url = flickr.getPhotoURL(photo);
      url = url.replace(/.jpg/,'_m.jpg');
      img = document.createElement('IMG');
      img.src = url;
      img.alt = photo.title;
      img.onload=function () {centerImgInFrame(this);};
      
      img.className = 'gallery';
      el = document.createElement('A');
      el.href = 'http://www.flickr.com/photos/'+photo.owner+'/'+photo.id;
      el.target = 'flickr';
      el.appendChild(img);
      
      // add frame to deal with portrait / landscape images 
      frame = document.createElement('DIV');
      frame.className = 'galleryframe';
      frame.style.width = photosize+'px';
      frame.style.height = photosize+'px';
      frame.appendChild(el);
      div.appendChild(frame);
      
      node = document.createElement('P');
      node.className = 'footnote';
      el = document.createElement('A');
      el.appendChild(document.createTextNode(photo.title));
      node.appendChild(el);
      div.appendChild(node);
      
      table = document.createElement('TABLE');
      table.className = 'photoattributes';
      tbody = document.createElement('TBODY');
      
      tr = document.createElement('TR');
      th = document.createElement('TH');
      th.appendChild(document.createTextNode('Photographer'));
      tr.appendChild(th);
      td = document.createElement('TD');
      el = document.createElement('A');
      el.href = 'http://www.flickr.com/photos/'+photo.owner;
      el.target = 'flickr';
      name = getPhotographer(photo.owner);
      el.appendChild(document.createTextNode(name));
      td.appendChild(el);
      tr.appendChild(td);
      tbody.appendChild(tr);
      
      tr = document.createElement('TR');
      th = document.createElement('TH');
      th.appendChild(document.createTextNode('Taken on'));
      tr.appendChild(th);
      td = document.createElement('TD');
      td.appendChild(document.createTextNode(convertDate(photo.datetaken)));
      tr.appendChild(td);
      tbody.appendChild(tr);
      
      table.appendChild(tbody);
      div.appendChild(table);
      container.appendChild(div);
   }
   div = document.createElement('div');
   div.className='gallerypages';
   
   container.appendChild(div);
   return true;
}
function centerImgInFrame(img) {
   // portrait or landscape
   var fsize = img.parentNode.parentNode.style.width;
   var gap = Math.floor(Math.abs(img.width - img.height)/2);
   if (img.width > img.height) {
      img.style.width = fsize;
      img.style.height = 'auto';
      img.style.marginTop = gap+'px';
   } else {
      img.style.height = fsize;
      img.style.width = 'auto';
      //img.style.marginLeft = gap+'px';
   }
}
function ordinalDate(day) {
   var daystring;
   switch (Math.floor(day/10)) {
   case 1: daystring = (day*1) + 'th';break;
   default: {
      switch (day%10) {
      case 1: daystring = (day*1) + 'st';break;
      case 2: daystring = (day*1) + 'nd';break;
      case 3: daystring = (day*1) + 'rd';break;
      default: daystring = (day*1) + 'th';break;
      }
   }break;
   }
   return daystring;
}
function convertDate(dstring) {
   var monarray = new Array('Jan','Feb','Mar','Apr','May','Jun',
                              'Jul','Aug','Sep','Oct','Nov','Dec');
   var datearray = dstring.split(/\s/);
   var dstring = datearray[0];
   datearray = dstring.split(/\-/);
   dstring = ordinalDate(datearray[2]) + ' ' + monarray[datearray[1]-1] + ' ' + datearray[0];
   /*
   var date = new Date();
   date.setFullYear(datearray[0],datearray[1]-1,datearray[2]);
   dstring = date.toDateString();
   */
   return dstring;
}
function getPhotographer(user_id) {
   //var flickr = new FlickrAPI('760306ba991e4bcb125e9887e2400e76', '');
   var params = new Array();
   params['api_key'] = '760306ba991e4bcb125e9887e2400e76';
   params['user_id'] = user_id;
   var json = flickr.callMethodJSON('flickr.people.getInfo', params);
   var obj = eval('(' + json + ')');
   obj = obj.person.realname;
   return obj._content;
}
function loadBackdropImage() {
   var myWidth = 0, myHeight = 0;
   if( typeof( window.innerWidth ) == 'number' ) {
   //Non-IE
      myWidth = window.innerWidth;
      myHeight = window.innerHeight;
      // on mozilla the space used by the vertical scroll bar is included so 
      // you have to test for it and remove it.
      if (document.documentElement.clientHeight > myHeight) myWidth -= 17;
   } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
   //IE 6+ in 'standards compliant mode'
      myWidth = document.documentElement.clientWidth;
      myHeight = document.documentElement.clientHeight;
   } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
   //IE 4 compatible
      myWidth = document.body.clientWidth;
      myHeight = document.body.clientHeight;
   }
   
   //window.alert( 'Width = ' + myWidth );
   //window.alert( 'Height = ' + myHeight );
   var imagesource = './images/YorkshireDalesWinter.jpg';
   imagesource = './images/Yorkshire_Dales_beck_with_hawthorne.jpg';
  
   var banner_dir = './images/backgrounds/';
   var banner_images = new Array('A_Friendly_Bee.jpg',
                                 'Bee_Orchid.JPG',
                                 'DSCF1121.JPG',
                                 'DSCF1130.JPG',
                                 'NYMoors1.jpg',
                                 'swaledale_valley_yorkshire_dales.jpg',
                                 'Yorkshire_Dales_beck_with_hawthorne.jpg',
                                 'YorkshireDalesWinter.jpg',
                                 'Clare/Near Arncliffe.jpg',
                                 'Clare/2005 Red Admiral, Norfolk.jpg',
                                 'Clare/2008-08-07 Meadow Brown, Humber.JPG',
                                 'Clare/Horton in Ribblesdale 02.JPG',
                                 'Clare/Paull Holme Strays 017.jpg',
                                 'Clare/Paull Holme Strays 015.jpg',
                                 'Clare/Paull Holme Strays 023.jpg',
                                 'Clare/Potamogeton.JPG');
   var now = new Date();
   var rand = now % banner_images.length;
   //var el_banner = document.getElementById('banner');
   //var src_image = 'url(' + banner_dir + banner_images[rand] + ')';
   imagesource = banner_dir + banner_images[rand];
  
   var img = document.createElement('IMG');
   img.id = 'backgroundimage';
   img.src = imagesource;
   img.style.width = myWidth + 'px';
   img.style.height = myHeight + 'px';
   img.style.border = 'none';
   img.style.padding = 0;
   img.style.margin = 0;
   img.style.position = 'absolute';
   img.style.top = 0;
   img.style.left = 0;
   img.style.zIndex = -1;
   var node = document.body.firstChild;
   document.body.insertBefore(img,node);
   node = document.body.firstChild;
   while (node = node.nextSibling) {
      if (node.style) node.style.zIndex = 3;
   }
   return true;
}
function switchTransparency(obj) {
   var op = (obj.style.opacity == 0.85)?0.6:0.85;
   var txt = (op == 1)?'[transparent]':'[non-transparent]';
   var tn = document.createTextNode(txt);
   obj.replaceChild(tn,obj.firstChild);
   var node = document.getElementById('content');
   obj.style.opacity = op;
   node.style.opacity = op;
   if (navigator.appName.indexOf("Netscape")!=-1
         &&parseInt(navigator.appVersion)>=5) {
      obj.style.MozOpacity = op;
      node.style.MozOpacity = op;
   } else if (navigator.appName.indexOf("Microsoft")!= -1 
         &&parseInt(navigator.appVersion)>=4) {
      obj.style.filter = "alpha(opacity = " + op * 100 + ")";
      node.style.filter = "alpha(opacity = " + op * 100 + ")";
   }
   obj.blur();
   return true;
}
function hoverTransparency(node,action) {
   var op;
   if (parseFloat(action)>0) op = parseFloat(action);
   else op = (action == 'out')?0.6:0.9;
   node.style.opacity = op;
   if (navigator.appName.indexOf("Netscape")!=-1
         &&parseInt(navigator.appVersion)>=5) {
      node.style.MozOpacity = op;
   } else if (navigator.appName.indexOf("Microsoft")!= -1 
         &&parseInt(navigator.appVersion)>=4) {
      node.style.filter = "alpha(opacity = " + op * 100 + ")";
   }
   return true;
}
function nameSection(name) {
   name=(name)?"- "+name:"";
   var node = document.getElementById('sectionname'); 
   if (node.childNodes.length>0) node.replaceChild(document.createTextNode(name),node.firstChild);
   else node.appendChild(document.createTextNode(name));
   return true;
}
function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}
document.onmouseup = followScrollBar;
document.onmouseover = followScrollBar;
window.onresize = rebanner;
function followScrollBar() {
   var dims = getScrollXY();
   var im = document.getElementById('backgroundimage');
   if (im) {
      im.style.top = dims[1] + 'px';
   }
   var mn;
   /*
   mn = document.getElementById('sidebar-left');
   if (mn) {
      //im.style.top = dims[1] + 'px';
      mn.style.marginTop = (10 + dims[1]) + 'px';
   }
   */
   /*
   mn = document.getElementById('sidebar-right');
   if (mn) {
      //im.style.top = dims[1] + 'px';
      mn.style.marginTop = (5 + dims[1]) + 'px';
   }
   */
   return true;
}
var onshow = null;
function showhidemenu(menuname,forced) {
   /*
      if a menu is opened and another menu is already open you want the old menu
      to close. the old menu name is stored in onshow. 
      but if the open menu is being closed you don't want to force an update to 
      onshow because you're already doing it.
   */
   var updateonshow = (onshow && !forced && (menuname != onshow));
   if (updateonshow) showhidemenu(onshow,true);  
   var menuid = 'submenu_'+menuname;
   var menu = document.getElementById(menuid);
   var show = (menu.style.display != 'block');
   var button = document.getElementById('button_'+menuname);
   button.src = (show)?'images/arrow_left.gif':'images/arrow_right.gif';
   menu.style.display = (show)?'block':'none';
   //if (onshow) hidemenu(onshow);
   if (show) {
      var menucontainer = button;
      while(menucontainer.className != 'menu') menucontainer = menucontainer.parentNode;
      var top =  menucontainer.style.marginTop;
      top = (top)?parseInt(top) + 170:170;
      var left = menucontainer.offsetWidth;
      left = (left)?parseInt(left) + 5:5;
      menu.style.top = top + 'px';
      menu.style.left = left + 'px';
      menu.style.zIndex = 5;
      onshow = menuname;
   } else onshow = null;
   return true;
}

function getHTTPObject() {
	var xhr = false;
	if (window.XMLHttpRequest) {
		xhr = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		try {
			xhr = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e) {
			try {
				xhr = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(e) {
				xhr = false;
			}
		}
	}
	return xhr;
}
var ocreq;

function getColorsForPhoto(url) {
	ocreq = getHTTPObject();
	ocreq.onreadystatechange = setColorScheme;
	ocreq.open("GET", folder+"callout/imagecolors.php?url="+escape(url), true);
	ocreq.send(null);
}

// function is executed when var request state changes
function setColorScheme() {
   var node;
   var JSONtext,JSONobject;
   if ((ocreq.readyState == 4) && (ocreq.responseText != null)) {
      JSONtext = ocreq.responseText;
      JSONobject = JSON.parse(JSONtext);
      //var light = unifyColor(JSONobject.boldcolor,225);
      //var medium = unifyColor(JSONobject.boldcolor,128);
      document.body.style.backgroundColor = getHexColor(JSONobject.palecolor);
      document.body.style.color = getHexColor(JSONobject.darkcolor);
      /*
      node = document.getElementById('headerbox');
      node.style.backgroundColor = getHexColor(JSONobject.darkcolor); 
      node = document.getElementById('main').firstChild;
      while (node && node.className != 'contentborder') node = node.nextSibling;
      node.style.backgroundColor = getHexColor(light);
      node.style.borderColor = getHexColor(JSONobject.darkcolor);
      node = document.getElementById('sidebar-left').firstChild;
      while (node && node.className != 'liner') node = node.nextSibling;
      node.style.backgroundColor = getHexColor(JSONobject.boldcolor);
      node.style.borderColor = getHexColor(JSONobject.darkcolor);
      node = document.getElementById('sidebar-right').firstChild;
      while (node && node.className != 'liner') node = node.nextSibling;
      node.style.backgroundColor = getHexColor(JSONobject.boldcolor);
      node.style.borderColor = getHexColor(JSONobject.darkcolor);
      */
   }
}

function unifyColor(color,target) {
   var tcolor = new Object();
   var multiplier = (Math.floor((color.red + color.green + color.blue)/3)/target);
   tcolor.red = ((color.red/multiplier)>255)?255:Math.floor(color.red/multiplier);
   tcolor.green = ((color.green/multiplier)>255)?255:Math.floor(color.green/multiplier);
   tcolor.blue = ((color.blue/multiplier)>255)?255:Math.floor(color.blue/multiplier);
   var avg = Math.floor((tcolor.red + tcolor.green + tcolor.blue)/3);
   var dif = Math.floor((target - avg)/2);
   if (tcolor.red < target) tcolor.red += dif;
   if (tcolor.green < target) tcolor.green += dif;
   if (tcolor.blue < target) tcolor.blue += dif;
//alert('r'+color.red+'g'+color.green+'b'+color.blue+'\nr'+tcolor.red+'g'+tcolor.green+'b'+tcolor.blue);
   return tcolor;
}
function getHexColor(color) {
   var r = d2h(color.red);
   while (r.length < 2) r = new String('0' + r); 
   var g = d2h(color.green);
   while (g.length < 2) g = new String('0' + g); 
   var b = d2h(color.blue);
   while (b.length < 2) b = new String('0' + b); 	
   return '#'+r+g+b;
}
function d2h(d) {return d.toString(16);}
function h2d(h) {return parseInt(h,16);}


function pausecomp(millis) {
   var date = new Date();
   var curDate = null;
   do { curDate = new Date(); }
   while(curDate-date < millis);
}

function createCookie(name,value,mins) {
   var date;
   var expires;
	if (mins) {
		date = new Date();
		date.setTime(date.getTime()+(mins*60000));
		expires = "; expires="+date.toGMTString();
	}
	else expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
	return true;
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return false;
}

function eraseCookie(name) {
	createCookie(name,0,-1);
}
