// these can be overridden in custom.js or homehtml or templates
var co_name = 'Dev Site';
var showPagerArrows = true;
var backmode="normal";
var thisUrl = "";
var delim404 = "/"
var pp_id = 'pp';
var sp_id = 'sp';
var pu_id = 'pu';
var focusTo = '';
var pageIsLoaded = false;
var animate = true;
var customSelectDoAll = false; // override in custom.js if needed - false = only do selects with data-custom="" attribute
//
function isIE6() {
  var av = navigator.appVersion.toLowerCase();
  var i = av.indexOf('msie 6');
  return (i < 50 && i > -1);
}
function isIE() {
  var av = navigator.appVersion.toLowerCase();
  var i = av.indexOf('msie');
  return (i < 50 && i > -1);
}
function hide(el,swapto) {
  if (typeof(el) == 'string') { el = document.getElementById(el); }
  if (el && el.style) { el.style.display = 'none'; }
  if (swapto) {
    if (typeof(swapto) == 'string') { var elto = document.getElementById(swapto); } else { var elto = swapto; }
    if (elto) {elto.style.display = 'block'; }
  }
}
//
function hideSelects(ele) {
  if (isIE6()) {
    var eles = document.all.tags("SELECT");
    for(var m = 0; m < eles.length; ++m) {
      if (eles[m] != ele) {  eles[m].style.visibility='hidden'; }
    }
  }
}
//
function showSelects() {
  if (isIE6()) {
    for(var s = 0; s < document.all.tags("SELECT").length; ++s) {
        document.all.tags("SELECT")[s].style.visibility='visible';
    }
  }
}
//
function setFocusTo() {
  if (window.focusTo) {
    var el = document.getElementById(focusTo);
    if (el) { el.focus(); try { el.select(); } catch(err) {}; }
  }
}
//
function mouseX(evt) {
if (evt.pageX) return evt.pageX;
else if (evt.clientX)
   return evt.clientX + (document.documentElement.scrollLeft ?
   document.documentElement.scrollLeft :
   document.body.scrollLeft);
else return null;
}
//
function mouseY(evt) {
if (evt.pageY) return evt.pageY;
else if (evt.clientY)
   return evt.clientY + (document.documentElement.scrollTop ?
   document.documentElement.scrollTop :
   document.body.scrollTop);
else return null;
}
//--------------------------------------
function getBounds(ele) {
  var res = { x:0, y:0, w:0, h:0 }
  if (typeof(ele) == 'string') { var el = document.getElementById(ele); } else { var el = ele; }
  if (el) {
    res.x = el.offsetLeft; res.y = el.offsetTop;  res.h = el.offsetHeight;  res.w = el.offsetWidth;
    while((el=el.offsetParent) != null) {
      res.x += el.offsetLeft+(el.clientLeft ? el.clientLeft : 0);
      res.y += el.offsetTop+(el.clientTop ? el.clientTop : 0);
    }
  }
  return res;
}
//--------------------------------------
function xOnPage(x,w,centerIt,ele,fixed) {
  var sw = -1;
  if (self.innerWidth){sw = self.innerWidth;}
  else if (document.documentElement && document.documentElement.clientWidth){sw = document.documentElement.clientWidth;}
  else if (document.body){sw = document.body.clientWidth;}
  var wmin = (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : (window.pageXOffset ? window.pageXOffset : 0));
  if (typeof(wmin) != 'number' || wmin < 0) { wmin = 0; }

  if (isIE6()) { fixed = false; }
  if (fixed) { wmin = 0; }

  var sw = sw + wmin;
  if (centerIt) { x = (Math.round((sw - wmin - w) / 2)) + wmin; }
  if ((sw > -1)) {	if (x<0) { x=0; }		if ((x + w) > sw - 10) {	x = sw - w - 10;	} }
		if (x < wmin) { x = wmin; }
  if (ele && w > sw) { ele.style.width = sw-10+'px'; }

		return x;
}
function yOnPage(y,h,centerIt,ele,fixed) { // pass ele to make sure max height is not exceeded
  var sh = -1;
  if (self.innerHeight){sh = self.innerHeight;}
  else if (document.documentElement && document.documentElement.clientHeight){sh = document.documentElement.clientHeight;}
  else if (document.body){sh = document.body.clientHeight;}
  var hmin = (document.documentElement.scrollTop ? document.documentElement.scrollTop : (window.pageYOffset ? window.pageYOffset : 0));
  if (typeof(hmin) != 'number' || hmin < 0) { hmin = 0; }
//alert(hmin+'|'+sh);
  if (isIE6()) { fixed = false; }
  if (fixed) { hmin = 0; }

  var sh = sh + hmin;
  if (centerIt) { y = (Math.round((sh - hmin - h) / 2)) + hmin; }
//document.title = y+' '+h+' '+sh;
  if ((sh > -1)) {	if (y<0) { y=0; }		if ((y + h) > sh - 10) {	y = sh - h - 10 ; } }
		if (y < hmin) { y = hmin; }
//alert(ele.offsetHeight+' '+h+' '+sh);
  if (ele && h > sh) { ele.style.height = sh-6+'px'; }
 	return y;
}
//--------------------------------------
// popup.... are routines to use if you want a mouse listener and optional hotspot.
// use: call popupInit(closefunc, hotid) at the start of your popup show function and pass it your hide/close function.
// hotId is the id of the click-to-close area - pass '' for anywhere on the page or !divid to close anywhere EXCEPT divid.
// If you want to manually close the popup, call popupClose('','myresult') NOT your hide/close function
// 'myresult' will be put in global var popupResult so you can control what to do in the hide/close function
var popupSafeToClose = false;
var popupOMD = null;
var popupDiv = '';
var popupCloseFunc = null;
var popupResult = '';
var popupClosing = false;
var popupPending = null;
var popupClosedTime = 0;
//
function popupInit(closeFunc, hotId) {
  if (popupClosing) { return false;  }
  popupPending = null;
  // tidy up any open popup
  if (popupSafeToClose) { popupRemoveListener(); if (popupCloseFunc) { popupCloseFunc();} popupCloseFunc = null;  popupSafeToClose = false; }
  // prep the listener for the new popup
  popupCloseFunc = closeFunc;  popupDiv = hotId;  popupAttachListener();  hideSelects();  popupSafeToClose = true;
  return true;
}
//
function popupClose(e,closeResult) {
  if (popupSafeToClose) {
    if (e == undefined) var e = window.event; // make sure IE has the event in e
    if (e && e.button && e.button == 2) return;
    if (popupDiv.match('!')) { var pd = popupDiv.substring(1,100); var inpd = false; } else { var pd = popupDiv; var inpd = true; }
//document.title = document.title + 'z'+(e=='')+'z';
//alert(e+' '+pd+' '+popupInDiv(e,pd,inpd));
    if (pd == '' || (pd != '' && (e == '' || e == 'timer' || (popupInDiv(e,pd,inpd))))) {
      popupClosing = true;
      popupResult = (closeResult==undefined ? null : closeResult);
//      popupResult = ((closeResult == '') || (closeResult==null) || (closeResult==undefined) ? '' : closeResult);
      popupRemoveListener();
      popupSafeToClose = false;
//alert(popupCloseFunc);
//document.title = document.title + 'i';
      if (popupCloseFunc) {
//document.title = document.title + 'q';
      popupCloseFunc();
      }
      popupCloseFunc = null;
      showSelects();
      popupClosing = false;
      popupClosedTime = Date.parse(new Date());

      if (popupPending) { popupPending(); popupPending = null; }
    }
  }
}
function popupJustClosed() {
  var now = Date.parse(new Date());
//  alert(now+' '+popupClosedTime);
  var i = Math.abs(now - popupClosedTime);
//  alert(i);
  popupClosedTime = 0;
  return (i < 100);
}
//
function popupAttachListener() {
   	if (document.layers) {	document.captureEvents(Event.MOUSEDOWN);	}
   	popupOMD = document.onmousedown;
   	if (popupOMD != null) {	document.onmousedown = function(event) { popupOMD(event); popupClose(event); } }
    else { document.onmousedown = function(event) { popupClose(event); } }
}
//
function popupRemoveListener() {
   	if (popupOMD != null) {	document.onmousedown = popupOMD; } else { document.onmousedown = null; }
}
//
function popupInDiv(e, divID, testbool) {
  if (!e) var e = window.event; // make sure IE has the event in e
  if (!divID) { divID = popupDiv; }
  if (document.layers) {
			var clickX = e.pageX;
			var clickY = e.pageY;
			var t = document.layers[divID];
			if ((clickX > t.left) && (clickX < t.left+t.clip.width) && (clickY > t.top) && (clickY < t.top+t.clip.height)) {
				return testbool;
			}
		}
		else if (e && e.srcElement) {
			var t = e.srcElement;
			while (t && t.parentElement != null) {
//alert(t.ID+' '+divID+' '+testbool);
				if (t.id==divID) {	return testbool; }
				t = t.parentElement;
			}
		}
		else if (e && e.target) {
			var t = e.target;

//   try { if (t.id) {} } // will get error here if firefox and input box is clicked on - mar 2010
//   catch(errr) { alert('err: '+errr); return !testbool;}

   try {
   		while (t && (t.parentNode != null) && (t.parentNode != undefined) && (t.attributes)) {
   				if (t.id==divID) { return testbool; }
 	  			t = t.parentNode;
 	  	}
  	}
   catch(err)
   { alert('error: '+err.description);}
		}
		return !testbool;
}
// end popup listener
//--------------------------------------
function getCookie( check_name ) {
   var a_all_cookies = document.cookie.split( ';' );
   var a_temp_cookie = '';
   var cookie_name = '';
   var cookie_value = '';
   var b_cookie_found = false; // set boolean t/f default f

   for ( i = 0; i < a_all_cookies.length; i++ )
   {
      a_temp_cookie = a_all_cookies[i].split( '=' );
      cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');  // trim
      if ( cookie_name == check_name )
      {
         b_cookie_found = true;
         if ( a_temp_cookie.length > 1 ) { cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') ); }
//alert(document.cookie);
         return cookie_value;
         break;
      }
      a_temp_cookie = null;
      cookie_name = '';
   }
   if ( !b_cookie_found ) { return ''; }
}
//--------------------------------------
// expires is in days
function setCookie( name, value, expires, path, domain, secure ) {
  var today = new Date();
  today.setTime( today.getTime() );
  if ( expires ) { expires = expires * 1000 * 60 * 60 * 24; }
  var expires_date = new Date( today.getTime() + (expires) );

  var s = name + "=" +escape( value ) +
    ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + //expires.toGMTString()
    ( ( path ) ? ";path=" + path : "" ) +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ( ( secure ) ? ";secure" : "" );
  document.cookie = s;
}
//--------------------------------------
function deleteCookie( name, path, domain ) {
  if ( getCookie( name ) ) document.cookie = name + "=" +
     ( ( path ) ? ";path=" + path : "") +
     ( ( domain ) ? ";domain=" + domain : "" ) +
     ";expires=Thu, 01-Jan-1990 00:00:01 GMT";
}
//----
function cssStyle(el, property) {
  var elo = el;
  if (typeof(el) == 'string') { el = document.getElementById(el); }
  if (!el) { alert('cssStyle error: element '+elo+' property '+property+' does not exist'); return null; }
  var res = el.style[property];
  if (!res) {
    if (el.currentStyle && el.currentStyle[property]) {
      res = el.currentStyle[property];
    } else {
      // this method uses 'background-image' not the passed format of 'backgroundImage'
      prop = "";
      for (var i=0; i < property.length; i++) {
        if (property.charAt(i) == property.charAt(i).toUpperCase()) {
          prop += '-' + property.charAt(i).toLowerCase(); }
        else {
          prop += property.charAt(i); }
      }
      try {
      res = getComputedStyle(el,'').getPropertyValue(prop);
      } catch(err) {}
    }
  }
  if (!res) { res = ''; }
  if (typeof(res) == 'string') { res = res.replace('px',''); }
  return res;
}
//------------
var isModal = true;
var shadowOffset = 8;
var shadowBox = null;

function showShadowBox( id, mode ) {
  var offs = { 't':shadowOffset, 'l':shadowOffset, 'w':0, 'h':0 }
  if (mode == 'center') { offs = { 't':-3, 'l':-3, 'w':6, 'h':6 } }

  var div = createDynamicPopup('shadowBox');  div.style.zIndex = '0';
  if (div) {
    if (typeof(id) == 'string') { var el = document.getElementById(id); } else {var el = id; }
    var i = cssStyle(el,'zIndex');
    if (i-0 > 0) { div.style.zIndex = (i-1) + ''; }
    var fixed = cssStyle(el,'position');
    if (fixed = 'fixed') {
      hmin = 0; wmin = 0;
    } else {
      var hmin = (document.documentElement.scrollTop ? document.documentElement.scrollTop : (window.pageYOffset ? window.pageYOffset : 0));
      if (typeof(hmin) != 'number' || hmin < 0) { hmin = 0; }
      var wmin = (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : (window.pageXOffset ? window.pageXOffset : 0));
      if (typeof(wmin) != 'number' || wmin < 0) { wmin = 0; }
    }
    div.style.top = (el.offsetTop+offs.t+hmin) + 'px';
    div.style.left = (el.offsetLeft+offs.l+wmin) + 'px';
    div.style.height = (el.offsetHeight + offs.h) + 'px';
    div.style.width = (el.offsetWidth + offs.w) + 'px';
    div.style.display = 'block';
    shadowBox = div;      // keep a global reference to it
    el.shadow = shadowBox;  // so drag can find the div
  }
}
function hideShadowBox( ) {
  var div = document.getElementById('shadowBox');
  if (div) {
    div.style.display = 'none';
  }
}

function screenSize() {
  var sw = -1;
  if (self.innerWidth){sw = self.innerWidth;}
  else if (document.documentElement && document.documentElement.clientWidth){sw = document.documentElement.clientWidth;}
  else if (document.body){sw = document.body.clientWidth;}
  var wmin = (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : (window.pageXOffset ? window.pageXOffset : 0));
  if (typeof(wmin) != 'number' || wmin < 0) { wmin = 0; }
  var sh = -1;
  if (self.innerHeight){sh = self.innerHeight;}
  else if (document.documentElement && document.documentElement.clientHeight){sh = document.documentElement.clientHeight;}
  else if (document.body){sh = document.body.clientHeight;}
  var hmin = (document.documentElement.scrollTop ? document.documentElement.scrollTop : (window.pageYOffset ? window.pageYOffset : 0));
  if (typeof(hmin) != 'number' || hmin < 0) { hmin = 0; }
  return { 'x':wmin, 'y':hmin, 'w':sw, 'h':sh };
}

function documentSize() {
//alert(window.innerHeight+'|'+window.scrollMaxY+'|'+document.body.scrollHeight+'|'+document.body.offsetHeight);
  if (window.innerHeight != undefined && window.scrollMaxY != undefined) {// Firefox
    var y = window.innerHeight + window.scrollMaxY;
    var x = window.innerWidth + window.scrollMaxX;
  } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
    var y = document.body.scrollHeight;
    var x = document.body.scrollWidth;
  } else { // works in Explorer 6 Strict, Mozilla (not FF) and Safari
    var y = document.body.offsetHeight;
    var x = document.body.offsetWidth;
  }
  if (y == 0) {
    var y = document.body.scrollHeight || document.documentElement.scrollHeight;
    var x = document.body.scrollWidth || document.documentElement.scrollWidth;
  }
  if (y == 0)  y = 5000;
  return { 'width':x, 'height':y };
}

function autoSetFrameSize(el) {  // el should be 'this' in the onload of the iframe
  var c=(el.contentWindow || el.contentDocument);
  if (c.document)c=c.document;
  var h = c.body.scrollHeight || c.documentElement.scrollHeight;
  el.style.height = h + 'px';
}

var coverCount = 0;
var coverZIndex = new Array();
var lastCoverZindex = 0;
function showModalCover( ) {
  var div = document.getElementById('modalCover');
  if (!div) { div = createDynamicPopup('modalCover');  setZIndex(div);  lastCoverZindex = globZindex;}
  if (div) {
    div.style.left = '0px';
    div.style.width = '100%';
    div.style.top = '0px';

    var sh = -1;
    if (self.innerHeight){sh = self.innerHeight;}
    else if (document.documentElement && document.documentElement.clientHeight){sh = document.documentElement.clientHeight;}
    else if (document.body){sh = document.body.clientHeight;}

    var size = documentSize();
    var h = size.height;
    if (h < sh) { h = sh; }
    div.style.height = h+'px';
    div.style.display = 'block';
    coverCount++;
    coverZIndex[coverCount] = lastCoverZindex;
  }
}

function hideModalCover( ) {
  var div = document.getElementById('modalCover');
  if (div) {
    coverCount--;
    if (coverCount == 0)
      { div.style.display = 'none'; }
    else
      { div.style.zIndex = coverZIndex[coverCount]}
  }
}
var globZindex = 7000;
function setZIndex(el) {
  globZindex++;
  el.style.zIndex = globZindex;
}

function createDynamicPopup(id, modal, style, parent ) {
  if (modal) { var cover = createDynamicPopup('modalCover');  setZIndex(cover); lastCoverZindex = globZindex; }

//  var div = document.getElementById(id);
// 	if (div) { div.parentNode.removeChild(div);

  var div = document.getElementById(id);
  if (!div) {
    var div = document.createElement('div');
    div.setAttribute('id', id);
    div.setAttribute('name', id);
    if (style) { div.setAttribute('className',style); }
    if (style) { div.setAttribute('class',style); }
    if (typeof(parent) == 'string' && parent) { parent = document.getElementById(parent); }
    if (!parent || parent == undefined) { parent = document.body }
    parent.appendChild(div);
  }
  div.style.display = 'none';
  setZIndex(div)
  return div;
}
function integerOnly(event) {  // onkeydown event
  event = event || window.event;
  var key = (event.keyCode ? event.keyCode : event.which);
  var shift = (event.shiftKey ? event.shiftKey : event.shiftKey);
// 0..9 with no shift, 0-9 keypad, return-13, tab-9, del-46, backspace-8, left-37, right-39, home-36, end-35
//document.title = key+'x'+shift;
  if ((((key >= 48) && (key <= 57)) && shift!=1) || ((key >= 96) && (key <= 105)) || (key == 13) || (key == 8) || (key == 9) || (key == 46) || (key == 39) || (key == 37) || (key == 35) || (key == 36))
    { return true; }
  else
    { event.returnValue = false; return false; }
}
/*function myunload() {
  document.getElementById('unloading').style.display = 'block';
//  document.body.className = 'unloading';
  window.scrollTo(0,1);
  window.scrollTo(0,0);
}*/
function wborder(el) {
// returns the padding and border width for el's style
  return (cssStyle(el,'borderLeftWidth')-0) + (cssStyle(el,'borderRightWidth')-0) +
         (cssStyle(el,'paddingLeft')-0) + (cssStyle(el,'paddingRight')-0);
}
function hborder(el) {
// returns the padding and border width for el's style
  return (cssStyle(el,'borderTopWidth')-0) + (cssStyle(el,'borderBottomWidth')-0) +
         (cssStyle(el,'paddingTop')-0) + (cssStyle(el,'paddingBottom')-0);
}
function fullPath(path) {
  return (path.match('://') ? path : thisUrl+path);
}
function transitionStop(el) {
  if (el && el.trans) { el.trans.finish(); }
}
function transition(from, tooo, param) {
  var i_trans = new c_trans(from, tooo, param);
}
//var ctc = 0;
function c_trans(from, tooo, param) {
//from:  { id:id, el:element, x:left, y:top, w:width, h:height }
//tooo:  { id:id, el:element, x:left, y:top, w:width, h:height }
//param  { classname:'abc', speed:##, movediv:'Y', grow:'Y', vanish:'Y', hide:'Y', onend:funcname } NOTE ALL FIELD NAMES ARE LOWERCASE
// speed is approx time the transition should take in millisecs, note IE is a bit slow
// vanish:'Y' overrides the tooo size/position so it ends up as 10x10 box in the center of tooo.id
// grow='Y' auto calculates the from position to be a 10x10 box in the center of tooo.id
//     - specify x,y,w,h in from to override the 10x10 centred start position
// movediv:'Y' will move the actual div passed as 'from'
// hide:'Y' will hide the div at the end and move it back to its original position and size Only works if movediv is used
// onend : pass it a function to call when the transition is complete - format: function(div) where div will be the 'from' div
// focus : will set focus to the passed id after the onend has been called
// note, pass a div or el as from if you need to access the div in the onend function

   c_trans.prototype.die = function() {
     clearTimeout(this.timer);
     if (this.from.el && this.from.el.trans) { this.from.el.trans = null; }

     if (!this.param.movediv) {
       this.div.style.display = 'none';
       var elp = this.div.parentNode;
       if (elp) { elp.removeChild(this.div); }
     }
     else if (this.param.hide) {
       this.div.style.display = 'none';
//       ctc++;
//document.title = 'xxposf'+ctc+' '+this.posf.x+' '+this.posf.y+' '+this.posf.w+' '+this.posf.h
       if (this.inited && this.posf.w > 0) {
         // put it back in its original position
         this.div.style.top = this.posf.y + 'px';
         this.div.style.left = this.posf.x + 'px';
         this.div.style.width = this.posf.w + 'px';
         this.div.style.height = this.posf.h + 'px';
       }
     }
   }

   c_trans.prototype.finish = function() {
     if (this.from.el && this.from.el.offsetLeft < -1500) { this.from.el.style.left = this.post.x + 'px'; }
     this.die();
     if (this.param.onend) { this.param.onend(this.from.el); }
     if (this.param.focus) { var el = document.getElementById(this.param.focus); if (el) { el.focus(); } }
     this.destroy;
   }

   c_trans.prototype.onTimer = function() {
     try {
       this.count++;
       if (this.count <= this.maxCount) {
         if (this.loops[this.loop] == 'wh' || this.loops[this.loop] == 'w') {
           this.pos.x = this.pos.x + this.xstep;
           this.pos.w = this.pos.w - this.wstep;
         }
         // padding can make this go -ive -  bail if it does
         if (this.pos.w < 0) { this.pos.w = 0; this.count = this.maxCount+2; }

         if (this.loops[this.loop] == 'wh' || this.loops[this.loop] == 'h') {
           this.pos.y = this.pos.y + this.ystep;
           this.pos.h = this.pos.h - this.hstep;
         }
         if (this.pos.h < 0) { this.pos.h = 0; this.count = this.maxCount+2; }

         if (this.loops[this.loop] == 'fi') {
           this.opacity += this.ostep;
           this.div.style.opacity = this.opacity / 100;
           this.div.style.filter = "alpha(opacity=" + Math.round(this.opacity) + ")";
         }

         this.div.style.top = Math.round(this.pos.y) + 'px';
         this.div.style.left= Math.round(this.pos.x) + 'px';
         this.div.style.width = Math.round(this.pos.w) + 'px';
         this.div.style.height = Math.round(this.pos.h) + 'px';
       }
//document.title = 'pos '+this.pos.x+' '+this.pos.y+' '+this.pos.w+' '+this.pos.h
       if (this.count <= this.maxCount+1) {
         if (this.count > this.maxCount && this.loop < this.loops.length-1)
         {
           this.loop++;  this.count = 0;
         }
         this.timer = setTimeout( ( function ( obj ) { return function () { obj.onTimer( ); }; } )( this ), tinc );
       } else {
  //     this.div.style.zIndex = 100;
  //alert('trans width='+this.div.offsetWidth+' '+this.div.pos.w+' '+this.div.opos.w+' '+this.wstep);
         this.finish();
       }
     }
     catch(err)
     {}
   }

   var copyof = function(x) { var ret = {}; for (var i in x) { ret[i] = x[i]; } return ret; }
   var exists = function(val) { return val != undefined; }

   c_trans.prototype.init = function() {
     this.posf = { x:0, y:0, w:10, h:10 }
     this.post = { x:100, y:100, w:10, h:10 }

     if (exists(this.from.el)) { this.elf = this.from.el; this.posf = getBounds(this.elf); }
     if (exists(this.from.id)) { this.elf = document.getElementById(this.from.id); this.posf = getBounds(this.elf); this.from.el = this.elf; }
     if (exists(this.from.x)) { this.posf.x = this.from.x; }
     if (exists(this.from.y)) { this.posf.y = this.from.y; }
     if (exists(this.from.w)) { this.posf.w = this.from.w; }
     if (exists(this.from.h)) { this.posf.h = this.from.h; }
     if (this.from.el) { this.from.el.trans = this; }
//for (var xxx in posf) { alert(xxx + ' = ' + posf[xxx]) }

     if (exists(this.to.el)) { this.elt = this.to.el; this.post = getBounds(this.elt); }
     if (exists(this.to.id)) { this.elt = document.getElementById(this.to.id); this.post = getBounds(this.elt); this.to.el = this.elt; }
     if (exists(this.to.x)) { this.post.x = this.to.x; }
     if (exists(this.to.y)) { this.post.y = this.to.y; }
     if (exists(this.to.w)) { this.post.w = this.to.w; }
     if (exists(this.to.h)) { this.post.h = this.to.h; }
     if (this.to.el) { this.to.el.trans = this; }
//for (var xxx in post) { alert(xxx + ' = ' + post[xxx]) }

     var hmin = (document.documentElement.scrollTop ? document.documentElement.scrollTop : (window.pageYOffset ? window.pageYOffset : 0));
     if (typeof(hmin) != 'number' || hmin < 0) { hmin = 0; }
     var fixed = (cssStyle(this.from.el,'position') == 'fixed' && !isIE6());
//alert(fixed);
     if (fixed) { this.post.y += hmin;  this.posf.y += hmin; }

     if (this.posf && this.post) {
       if (this.param.movediv) {
         this.div = this.elf;
       } else {
         this.div = createDynamicPopup('trans_div'+c_trans.divno);
         c_trans.divno++;
         if (this.from.el) { this.from.el.style.left = '-10000px'; }
       }
// line below commented to make lolo faq popOpen work with rolldown()
//       this.div.style.position = 'absolute';
       if (!this.param.movediv) {
         if (this.param.classname)
           { this.div.className = this.param.classname; }
         else
           { this.div.style.background = 'white'; this.div.style.border = '1px solid red'; }
       }

       if (this.loops[0] == 'fi') {
         this.div.style.opacity = this.opacity / 100;
         this.div.style.filter = "alpha(opacity=" + this.opacity + ")";
       }

       var wfix = wborder(this.div);
       this.posf.w -= (wfix);
       this.post.w -= (wfix);

       var hfix = hborder(this.div);
       this.posf.h -= (hfix);
       this.post.h -= (hfix);

       if (this.posf.w < 0) { this.posf.w = 0; }
       if (this.posf.h < 0) { this.posf.h = 0; }

       if (this.param.grow) {
         // default is grow from 10x10 centered on 'to' but can be overridden by setting the 'from' x,y,w,h
         if (this.from.w == undefined) { this.posf.w = 10; }
         if (this.from.x == undefined) { this.posf.x = Math.round(this.post.x + (this.post.w/2)-(this.posf.w/2)); }
         if (this.from.h == undefined) { this.posf.h = 10; }
         if (this.from.y == undefined) { this.posf.y = Math.round(this.post.y + (this.post.h/2)-(this.posf.h/2)); }
       }
//for (var xxx in posf) { alert(xxx + ' = ' + posf[xxx]) }

       if (this.param.vanish) {  // shrink to 10x10 centered on 'to'
         this.post.x = Math.round(this.post.x + (this.post.w/2)-5); this.post.w = 10;
         this.post.y = Math.round(this.post.y + (this.post.h/2)-5); this.post.h = 10;
       }

//ctc++;
//document.title = 'posf'+ctc+' '+this.posf.x+' '+this.posf.y+' '+this.posf.w+' '+this.posf.h+' post '+this.post.x+' '+this.post.y+' '+this.post.w+' '+this.post.h+' '+this.div.style.display;
       // something was causing a call with posf bits = 0 when the minibasket and lightbox were showing which screws up future calls
       if (this.posf.x == 0 && this.posf.y == 0 && this.posf.w == 0 && this.posf.h == 0) {
         this.finish();
         return;
       }

       this.div.style.top = this.posf.y + 'px';
       this.div.style.left = this.posf.x + 'px';
       this.div.style.width = this.posf.w + 'px';
       this.div.style.height = this.posf.h + 'px';
       this.pos = copyof(this.posf);
       this.div.style.display = 'block';
       this.xdiff = (this.posf.x - this.post.x);
       this.ydiff = (this.posf.y - this.post.y);
       this.wdiff = (this.posf.w - this.post.w);
       this.hdiff = (this.posf.h - this.post.h);

       this.maxCount = Math.round(this.param.speed / ((tinc + 100) * this.loops.length)) + 1;
       this.xstep = -this.xdiff / this.maxCount;
       this.ystep = -this.ydiff / this.maxCount;
       this.wstep = this.wdiff / this.maxCount;
       this.hstep = this.hdiff / this.maxCount;

       if (this.loops[0] == 'fi') {
         tinc = 50;
         this.maxCount = this.param.speed / (tinc + 20);
         this.ostep = 80 / this.maxCount;
       }
//alert('posf '+posf.x+' '+posf.y+' '+posf.w+' '+posf.h+' post '+post.x+' '+post.y+' '+post.w+' '+post.h+' '+this.div.style.display);
//document.title = 'posf '+this.posf.x+' '+this.posf.y+' '+this.posf.w+' '+this.posf.h+' post '+this.post.x+' '+this.post.y+' '+this.post.w+' '+this.post.h+' '+this.div.style.display;

       this.count = 0;
       this.inited = true;
       this.timer = setTimeout( ( function ( obj ) { return function () { obj.onTimer( ); }; } )( this ), 1 );
     }
   }

  var tinc = 33;
  this.inited = false;
  this.from = from;
  this.to = tooo;
  this.param = param;
//for (var xxx in param) { alert(xxx + ' = ' + param[xxx]) }

  this.loops = new Array;
  this.loop = 0;
  if (this.param.action == undefined)
    { this.loops[0] = 'wh'; }
  else
    { this.loops = this.param.action.split(',');
  }
  this.opacity = 20;
  if (this.param.speed == undefined) { this.param.speed = 20; }
  if (this.param.movediv == undefined) { this.param.movediv = ''; }
  if (this.param.classname == undefined) { this.param.classname = ''; }
  if (this.param.onend == undefined) { this.param.onend = ''; }
  if (this.param.hide == undefined) { this.param.hide = ''; }
  if (this.param.focus == undefined) { this.param.focus = ''; }
  this.init();
}
c_trans.divno = 0;
// ---------
function rolldown(div) {
  if (typeof(div) == 'string') { div = document.getElementById(div); }
  if (div) {
    var left = div.trueleft ? div.trueleft-0 : div.offsetLeft-0;
    var from = { el:div, x:left, y:div.offsetTop, w:div.offsetWidth, h:1 };
    var too = { x:left, y:div.offsetTop, w:div.offsetWidth, h:div.offsetHeight };
    div.style.display = 'none';
    div.style.overflow = 'hidden';
    transition( from, too, { speed:500, action:'h', movediv:'Y' } );
  }
}
function rollup(div, endfunc) {
  // div must be fixed size, set in css
  if (typeof(div) == 'string') { div = document.getElementById(div); }
  if (div) {
    var from = { el:div, x:div.offsetLeft, y:div.offsetTop, w:div.offsetWidth, h:div.offsetHeight };
    var too = { x:div.offsetLeft, y:div.offsetTop, w:div.offsetWidth, h:0 };
    transition( from, too, { speed:500, action:'h', movediv:'Y', hide:'Y', onend:endfunc } );
  }
}
// -----------
function createImg(id, owner) {
  var img = document.createElement('img');
  img.setAttribute('id', id);
  img.setAttribute('name', id);
  img.style.display = 'none';
  img.style.zIndex = 1;
  owner.appendChild(img);
  return img;
}
function c_imageTrans(div_id,imgclass,path,imagedefs,options) {

  c_imageTrans.prototype.transTimer = function() {
    try {
      var done = false;
      if (this.images[this.image].width > 0) { //ie the image has loaded
        this.imgs[1].setAttribute('imgno',this.image);
        this.imgs[1].alt = this.imagealts[this.image];
        this.imgs[1].title = this.imagealts[this.image];
        this.imgs[1].style.cursor = (this.imagelinks[this.image] ? 'pointer' : 'default');


        if (this.effect == 'swap') {
          this.imgs[0].style.display = 'none';
          this.imgs[0].src = fullPath(this.path)+this.imagenames[this.image];
          this.imgs[0].style.display = 'block';
          done = true;
        }
        else if (this.effect == 'fadein') {
          if (this.step == 0) {
            this.imgs[1].src = fullPath(this.path)+this.imagenames[this.image];
            this.limit = 100;
            this.pos = 0;
            this.jumpInc = this.imgs[0].offsetWidth * (1000 / this.speed) * (this.timerInc / 1000) / 25;
            if (this.jumpInc < 2) { this.jumpInc = 2; }
            this.imgs[1].style.marginTop = '-'+this.imgs[0].offsetHeight+'px';
            this.imgs[1].style.marginLeft = '0px';
            this.imgs[1].style.opacity = this.pos / 100;
            this.imgs[1].style.filter = "alpha(opacity=" + Math.round(this.pos) + ")";
            this.imgs[1].style.display = 'block';
            this.imgs[0].style.opacity = this.limit - (this.pos / this.limit);
            this.imgs[0].style.filter = "alpha(opacity=" + (this.limit- Math.round(this.pos)) + ")";
          }
          this.step++;
          this.pos = this.pos + this.jumpInc;
          if (this.pos > this.limit) { this.pos = this.limit; }
          this.imgs[1].style.opacity = this.pos / this.limit;
          this.imgs[1].style.filter = "alpha(opacity=" + Math.round(this.pos) + ")";
          this.imgs[0].style.opacity = this.limit - (this.pos / this.limit);
          this.imgs[0].style.filter = "alpha(opacity=" + (this.limit- Math.round(this.pos)) + ")";
          if (this.pos >= this.limit) {
            done = true;
          }
        }
        else if (this.effect == 'slideleft') {
          if (this.step == 0) {
            this.imgs[1].src = fullPath(this.path)+this.imagenames[this.image];
            this.limit = 0;
            this.pos = this.imgs[0].offsetWidth;
            this.imgs[0].offsetWidth * this.timerInc / this.speed;
            this.jumpInc = this.imgs[0].offsetWidth * (1000 / this.speed) * (this.timerInc / 1000);
            if (this.jumpInc < 1) { this.jumpInc = 1; }
            this.imgs[1].style.marginTop = '-'+this.imgs[0].offsetHeight+'px';
            this.imgs[1].style.marginLeft = this.pos+'px';
            this.imgs[1].style.display = 'block';
          }
          this.step++;
          this.pos = this.pos - this.jumpInc;
          if (this.pos < this.limit) { this.pos = this.limit; }
          this.imgs[1].style.marginLeft = this.pos+'px';
          if (this.pos <= this.limit) {
            done = true;
          }
        }
        else if (this.effect == 'slideright') {
          if (this.step == 0) {
            this.imgs[1].src = fullPath(this.path)+this.imagenames[this.image];
            this.limit = 0;
            this.pos = -this.imgs[0].offsetWidth;
            this.jumpInc = this.imgs[0].offsetWidth * (1000 / this.speed) * (this.timerInc / 1000);
            if (this.jumpInc < 1) { this.jumpInc = 1; }
            this.imgs[1].style.marginTop = '-'+this.imgs[0].offsetHeight+'px';
            this.imgs[1].style.marginLeft = this.pos+'px';
            this.imgs[1].style.display = 'block';
          }
          this.step++;
          this.pos = this.pos + this.jumpInc;
          if (this.pos > this.limit) { this.pos = this.limit; }
          this.imgs[1].style.marginLeft = this.pos+'px';
          if (this.pos >= this.limit) {
            done = true;
          }
        }
        else if (this.effect == 'stretchleft') {
          if (this.step == 0) {
            this.imgs[1].src = fullPath(this.path)+this.imagenames[this.image];
            this.limit = this.imgs[0].offsetWidth;;
            this.pos = 0;
            this.jumpInc = this.imgs[0].offsetWidth * (1000 / this.speed) * (this.timerInc / 1000);
            if (this.jumpInc < 1) { this.jumpInc = 1; }
            this.imgs[1].style.marginTop = '-'+this.imgs[0].offsetHeight+'px';
            this.imgs[1].style.marginLeft = this.limit+'px';
            this.imgs[1].style.width = this.pos+'px';
            this.imgs[1].style.display = 'block';
          }
          this.step++;
          this.pos = this.pos + this.jumpInc;
          if (this.pos > this.limit) { this.pos = this.limit; }
          this.imgs[1].style.width = this.pos+'px';
          this.imgs[1].style.marginLeft = this.limit-this.pos+'px';

          if (this.imgs[1].offsetWidth >= this.limit) {
            done = true;
          }
        }
        else if (this.effect == 'stretchright') {
          if (this.step == 0) {
            this.imgs[1].src = fullPath(this.path)+this.imagenames[this.image];
            this.limit = this.imgs[0].offsetWidth;;
            this.pos = 0;
            this.jumpInc = this.imgs[0].offsetWidth * (1000 / this.speed) * (this.timerInc / 1000);
            if (this.jumpInc < 1) { this.jumpInc = 1; }
            this.imgs[1].style.marginTop = '-'+this.imgs[0].offsetHeight+'px';
            this.imgs[1].style.marginLeft = '0px';
            this.imgs[1].style.width = this.pos+'px';
            this.imgs[1].style.display = 'block';
          }
          this.step++;
          this.pos = this.pos + this.jumpInc;
          if (this.pos > this.limit) { this.pos = this.limit; }
          this.imgs[1].style.width = this.pos+'px';

          if (this.imgs[1].offsetWidth >= this.limit) {
            done = true;
          }
        }
        if (done) {
            this.imgs[0].src = fullPath(this.path)+this.imagenames[this.image];
            this.imgs[1].style.width = cssStyle(this.imgs[0],'width')+'px';
            this.imgs[0].setAttribute('imgno',this.image);
            this.imgs[0].alt = this.imagealts[this.image];
            this.imgs[0].title = this.imagealts[this.image];
            this.imgs[0].style.cursor = (this.imagelinks[this.image] ? 'pointer' : 'default');
            this.imgs[0].style.display = 'block';
            this.imgs[0].style.opacity = 100;
            this.imgs[0].style.filter = "alpha(opacity=100)";
        }
      }
      else
      {
        done = true;  // image not ready so start timer for next transition
      }
    }
    catch(err)
    { alert(err.description); return;}

    if (this.aborted) { return; }

    if (done) {
      this.timer = setTimeout( ( function ( obj ) { return function () { if (obj) { obj.endTrans( ); } }; } )( this ), 10 );
    } else {
      this.timer = setTimeout( ( function ( obj ) { return function () { if (obj) { obj.transTimer( ); } }; } )( this ), 1000 / this.timerInc );
    }
  }

  c_imageTrans.prototype.endTrans = function() {
    this.imgs[1].style.display = 'none';
    if (this.autoscroll) {
      this.timer = setTimeout( ( function ( obj ) { return function () { obj.onTimer( ); }; } )( this ), this.interval );
    }
  }

  c_imageTrans.prototype.trans = function() {
    this.timer = setTimeout( ( function ( obj ) { return function () { obj.transTimer( ); }; } )( this ), 10 );
  }

  c_imageTrans.prototype.onTimer = function() {
    try {
      if (this.aborted) { return; }

      if (pageIsLoaded) {
        if (!this.loaded) { // time to load all the images
          for (var i=0; i < this.imagenames.length; i++ ) {
            this.images[i] = new Image();
            this.images[i].src = fullPath(this.path)+this.imagenames[i];
          }
          this.loaded = true;
          this.timer = setTimeout( ( function ( obj ) { return function () { obj.onTimer( ); }; } )( this ), this.interval );
        }
        else
        {
          this.image++; if (this.image >= this.images.length) { this.image = 0; }
          this.effectno++; if (this.effectno >= this.effects.length) { this.effectno = 0; }
          this.effect = this.effects[this.effectno];
          this.step = 0;
          if (this.aborted) { return; }
          this.trans();
        }
      }
      else if (this.autoscroll)
      {
        this.timer = setTimeout( ( function ( obj ) { return function () { obj.onTimer( ); }; } )( this ), this.initinterval );
      }
    }
    catch(err)
    { alert(err.description); return;}
  }

  c_imageTrans.prototype.doPrev = function() {
    clearTimeout(this.timer);
    this.imgs[0].src = fullPath(this.path)+this.imagenames[this.image];
    // move back two and then call onTimer that moves to the next one
    this.autoscroll = false;
    this.image -= 2; if (this.image < 0) { this.image += this.images.length; }
    if (this.effects.length == 1) {
      if (this.effects[0].indexOf('slide') > -1) { this.effects[0] = 'slideright'; }
      if (this.effects[0].indexOf('stretch') > -1) { this.effects[0] = 'stretchright'; }
    } else {
      this.effectno -= 2; if (this.effectno < 0) { this.effectno += this.effects.length; }
    }
    this.onTimer();
  }
  c_imageTrans.prototype.doNext = function() {
    clearTimeout(this.timer);
    this.imgs[0].src = fullPath(this.path)+this.imagenames[this.image];
    this.autoscroll = false;
    if (this.effects.length == 1) {
      if (this.effects[0].indexOf('slide') > -1) { this.effects[0] = 'slideleft'; }
      if (this.effects[0].indexOf('stretch') > -1) { this.effects[0] = 'stretchleft'; }
    }
    this.onTimer();
  }

  c_imageTrans.prototype.abort0 = function() {
    var i = this.imgs[0].getAttribute('imgno');
    if (this.imagelinks[i]) {
      this.aborted = true;
      this.imgs[1].style.display = 'none';
      this.imgs[0].style.opacity = 100;
      this.imgs[0].style.filter = "alpha(opacity=100)";
      if (this.imageclicks[i]) { eval(this.imageclicks[i]); }
      window.location = this.imagelinks[i];
    }
//    alert(this.imagelinks[i]+'xxx0');
  }

  c_imageTrans.prototype.abort1 = function() {
    var i = this.imgs[1].getAttribute('imgno');
    if (this.imagelinks[i]) {
      this.aborted = true;
      this.imgs[1].style.display = 'none';
      this.imgs[0].style.opacity = 100;
      this.imgs[0].style.filter = "alpha(opacity=100)";
      if (this.imageclicks[i]) { eval(this.imageclicks[i]); }
//      if (this.imageclicks[i]) { new Function (this.imageclicks[i]); }
      window.location = this.imagelinks[i];
    }
//    alert(this.imagelinks[i]+'xxx1');
  }

  c_imageTrans.prototype.stop = function() {
    this.aborted = true;
    clearTimeout(this.timer);
    this.step = 0;
    this.imgs[0].style.opacity = 100;
    this.imgs[0].style.filter = "alpha(opacity=100)";
    this.imgs[1].style.display = 'none';
  }

  c_imageTrans.prototype.restart = function() {
    clearTimeout(this.timer);
    this.step = 0;
    this.autoscroll = true;
    this.timer = setTimeout( ( function ( obj ) { return function () { obj.onTimer( ); }; } )( this ), this.interval );
    this.aborted = false;
  }

  c_imageTrans.prototype.init = function() {
    var div = document.getElementById(div_id);
    if (div) {
      div.style.overflow = 'hidden';
      this.imgs[0] = createImg(div_id+'img1',div);
      this.imgs[1] = createImg(div_id+'img2',div);
      this.imgs[0].className = this.imgclass;
      this.imgs[1].className = this.imgclass;
      this.imgs[0].src = fullPath(this.path)+this.imagenames[0];
      this.imgs[0].style.display = 'block';
      this.imgs[0].onclick = ( function ( obj ) { return function () { obj.abort0( ); }; } )( this )
      this.imgs[1].onclick = ( function ( obj ) { return function () { obj.abort1( ); }; } )( this )
      this.imgs[0].oncontextmenu = ( function ( obj ) { return function () { obj.stop( ); }; } )( this )
      this.imgs[1].oncontextmenu = ( function ( obj ) { return function () { obj.stop( ); }; } )( this )
      this.imgs[0].alt = this.imagealts[0];
      this.imgs[0].title = this.imagealts[0];
      this.imgs[0].setAttribute('imgno','0');
      this.imgs[0].style.cursor = (this.imagelinks[0] ? 'pointer' : 'default');
    }
  }

  checkAnimate();
  var def_effects = new Array ( 'fadein', 'swap', 'slideleft', 'slideright', 'stretchleft', 'stretchright' );
  this.aborted = false;
  this.autoscroll = true;
  this.imgs = new Array;  // two html img elements for the switch
  this.div_id = div_id;
  this.images = new Array;  // actual images
  this.imagenames = new Array;
  this.imagealts = new Array;
  this.imagelinks = new Array;
  this.imageclicks = new Array;
  if (typeof(imagedefs) == 'string') {
    var defs = imagedefs.split(',');  // image name|link|alt comma sep list
    for (var i =0; i < defs.length; i++) {
      var defsa = defs[i].split('|');
      this.imagenames[this.imagenames.length] = defsa[0];
      this.imagelinks[this.imagelinks.length] = defsa[1];
      this.imagealts[this.imagealts.length] = defsa[2];
    }
  } else { // its an array of json arrays
    for (var i =0; i < imagedefs.length; i++) {
      this.imagenames[this.imagenames.length] = imagedefs[i].img;
      this.imagelinks[this.imagelinks.length] = imagedefs[i].link;
      this.imagealts[this.imagealts.length] = imagedefs[i].alt;
      this.imageclicks[this.imageclicks.length] = imagedefs[i].click;
    }
  }
  this.imgclass = imgclass;
  this.path = path;
  this.effectno = -1;
  this.init();
  this.loaded = false;
  this.img = 0;
  this.image = 0;
  this.initinterval = 100; // timer interval for loaded check

  this.timerInc = 35;  // frames per sec
  this.jumpInc = 1; // default movement per timer call
  this.speed = 100;  // timer interval for transition
  this.interval = 1000; // timer interval between transitions
  this.effects = def_effects;

  if (typeof(options) == 'string') {
    if (options != 'random') { this.effects = options.split(','); }
  } else {
    if (options.effect) { if (options.effect != 'random') { this.effects = options.effect.split(','); } }
    if (options.speed) { this.speed = options.speed-0; }
    if (options.interval) { this.interval = options.interval-0; }
    if (options.leftbtn) {
      var el = document.getElementById(options.leftbtn);
      if (el) {
        el.onclick = ( function ( obj ) { return function () { obj.doPrev( ); }; } )( this );
      }
    }
    if (options.rightbtn) {
      var el = document.getElementById(options.rightbtn);
      if (el) {
        el.onclick = ( function ( obj ) { return function () { obj.doNext( ); }; } )( this );
      }
    }
  }
  if (!animate) { return; }
  this.timer = setTimeout( ( function ( obj ) { return function () { obj.onTimer( ); }; } )( this ), this.initinterval );
}
function imageTrans(div_id,path,imagenames,imgclass,alt,effect) {
// imagenames can be a string with 'jpg|link|alt,jpg|link|alt' or a json array [ { 'img':'', 'link':'', 'alt':'' },... ]
  var it = new c_imageTrans(div_id,path,imagenames,imgclass,alt,effect);
  return it;
}
//
function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
	chars = chars || "\\s";
 try {
  	var res = str.replace(new RegExp("^[" + chars + "]+", "g"), "");
 } catch(err) {};
	return res;
}

function rtrim(str, chars) {
	chars = chars || "\\s";
 try {
  	var res = str.replace(new RegExp("[" + chars + "]+$", "g"), "");
 } catch(err) {};
	return res;
}
//
var preLoadImages = '';  // comma seperated list of file names
function preLoad() {
// image path must be relative to root. Comma seperate multiple values
  if (document.images) {
    var imga = preLoadImages.split(',');
    for (var i=0; i < imga.length; i++) {
      if (imga[i] != '') {
        var rslt = new Image();
        rslt.src = fullPath(imga[i]);
      }
    }
  preLoadImages = '';
  }
}
// load most of the images after the main body has loaded.
// to use just change img src="??" to img data-src="??"
function postLoadImages() {
  var Coll = document.getElementsByTagName("IMG");
  for (var m = 0; m < Coll.length; ++m) {
    if (Coll[m].getAttribute('data-src')) {
      Coll[m].src = Coll[m].getAttribute('data-src');
      Coll[m].setAttribute('data-src','');
//      Coll[m].oncontextmenu= function() { return false; }  // stop right click on images
    }
    // data-currency-src means there are currency dependent versions of this image
    else if (Coll[m].getAttribute('data-currency-src')) {
      var s = Coll[m].getAttribute('data-currency-src');
      s = s.replace('.jpg',currency_code+'.jpg');
      s = s.replace('.gif',currency_code+'.gif');
      s = s.replace('.png',currency_code+'.png');
      Coll[m].src = s;
      Coll[m].setAttribute('data-currency-src','');
    }
    else if (Coll[m].getAttribute('data-gbponly-src')) {
      var s = Coll[m].getAttribute('data-gbponly-src');
      if (window.currency_code && currency_code != 'GBP') {
        Coll[m].style.display = 'none'; // not gbp = hide it
      } else {
        s = s.replace('.jpg',currency_code+'.jpg');
        s = s.replace('.gif',currency_code+'.gif');
        s = s.replace('.png',currency_code+'.png');
        Coll[m].src = s;
        Coll[m].setAttribute('data-gbponly-src','');
      }
    }
  }
  if (window.resetMenuHeight) { resetMenuHeight(); }
}
/*function addLoadEvent(func, first) {  // set first to true to add this event at the front of the queue
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  }
  else {
  window.onload = function() {
      if (first) { func(); }
      if (oldonload) { oldonload(); }
      if (!first) { func(); } // an error here usually means you have passed the func with ()
    }
  }
}
function pageLoaded() { pageIsLoaded = true; }
addLoadEvent(pageLoaded);
*/
var loadEvents = new Array;
function addLoadEvent(func, seq) {
// seq should be a numeric sequence number but can be null or true or 'last' for backward compatibility
// the events will be run in sequence order - true = 100 null = 101 last = 102
// important < 100, facebook, google > 5000
// document.title = document.title + seq+', ';
  switch(seq) {
    case true : seq = 100; break;
    case undefined : seq = 101; break;
    case 'last' : seq = 102; break;
  }
  loadEvents.push( { 'func':func, 'seq':seq } );
}
function loadSort(a,b) {
  return b.seq - a.seq;
}
function doLoad() {
  pageIsLoaded = true;
  backController();
  checkAnimate();
  initHeaderDivs();

  // uncomment the alert to see the sequence and function name
  loadEvents = loadEvents.sort(loadSort);
  for (var i=loadEvents.length-1; i >= 0; i--) {
//document.title = document.title + loadEvents[i].seq+', ';
//alert(loadEvents[i].seq+'\r\n'+loadEvents[i].func);
    loadEvents[i].func();
  }
}
function doUnLoad() {
// just here so ff onload fires when back button is clicked
}
//
function backController() {
//alert(backmode);
  var el = document.getElementById('backctrl');
  if (el) {
    if (el.value=='LOADED') {
      if (backmode == 'normal') {
        refreshMiniBasket();
//alert('reload mini');
      }
      if ((backmode == 'basket') || (backmode == 'lock')){
        document.body.innerHTML = '';
//alert('reload');
        location.reload(true);
      }
      if (window.backFunction) { window.backFunction(); }
    }
    else { var xx = window.setTimeout('backController2()',100); }
  }
}
function backController2() {
  var el = document.getElementById('backctrl');
  if (el) {
    if (el.value=='OK') { el.value = 'LOADED'; }
    else {
      if (backmode == 'normal') {
//alert('reload mini 2');
        refreshMiniBasket();
      }
      if ((backmode == 'basket') || (backmode == 'lock')) {
        document.body.innerHTML = '';
//alert('reload2');
        location.reload(true);
      }
      if (window.backFunction) { window.backFunction(); }
    }
  }
}
function checkAnimate() {
// add ani=false to the querystring to stop animations
  var s = window.location.href.toLowerCase();
  if (s.indexOf('ani=') > -1) {
    var ani = (s.indexOf('ani=false') > -1 ? 'F' : 'T');
    setCookie('animate',ani);
    animate = (ani != 'F');
  } else {
    var ani = getCookie('anmimate');
    if (ani == 'F') { animate = false; }
  }
}
function setHeight() {
var y = -1;
if (self.innerHeight){y = self.innerHeight;}
else if (document.documentElement && document.documentElement.clientHeight){y = document.documentElement.clientHeight;}
else if (document.body){y = document.body.clientHeight;}
if ((y > 100) && (document.body.offsetHeight) && (y > document.body.offsetHeight))
  { document.body.style.height = y + 'px'; }
}
//--------------------------------------
function noBack(path) {
// call this rather than loction= to stop the current page being added to the browser history
// not tested but the logic needs to be replace the url rather than locate to another
  window.URL.replace(path);
}
//
function imageErr(el, id, hideel, stopclick, restart) {
// usage = <img onerror="imageErr(this, 'imagesize', 'hide1;hide2', 'id1;id2;over|id1;out|id1');" >
// id can be 'large','medium' etc of a full img file path
// hideel is a ; delim list of ids to hide eg. the id of a box with a zoom prompt in it
// stopclick is a ; delim list of ids to remove the onclcik handler from.
// stopclick can be used to switch off mouseover and mouseout by adding 'over|' of out| before the id
// restart = true will re-install the onerror handler - use this if the image src may be changed again
// original image 'src' will be saved into data-origsrc so that the original image path and name can be found
  var safe = el.onerror;
  el.onerror = null;  // stop stack overflow if err image doesnt exist
  if (id == 'large' || id == 'zoom' || id == 'medium' || id == 'thumb' || id == 'small' || id == 'smallhero') {
    id = thisUrl+'products/images/coming_soon_'+id+'.jpg';
  }
  if (id == 'swatch' ) { id = thisUrl+'products/images/no-swatch.jpg'; }
//alert(id);
// save the original 'src' attribute
  var os = el.getAttribute('data-origsrc');
  if (!os) {
    el.setAttribute('data-origsrc',el.src);
  }
  el.src=id;
//hideel = '';
  if (hideel) {
    var ar = hideel.split(';');
    for (var i=0; i<ar.length; i++) {
      if (ar[i]) {
        ely = document.getElementById(ar[i].replace(' ',''));
        if (ely) {ely.style.display='none'; }
      }
    }
  }
  if (stopclick) {
    var ar = stopclick.split(';');
    for (var i=0; i<ar.length; i++) {
      if (ar[i]) {
        var typ = '';
        var nam = ar[i].replace(' ','');
        if (nam.match(/over\|/i)) { typ = 'min'; nam = nam.substr(5); }
        if (nam.match(/out\|/i)) { typ = 'mout'; nam = nam.substr(4); }
        ely = document.getElementById(nam);
        if (ely) {
          if (typ == '') { ely.onclick = null; ely.style.cursor = 'default'; }
          if (typ == 'min') { ely.onmouseover = null; }
          if (typ == 'mout') { ely.onmouseout = null; }
        }
      }
    }
  }
  if (restart) {
    el.onerror = safe;
  }
}
function pluralise(id, stext, count) {
  var el = document.getElementById(id);
  if (el) { if (count != 1) { el.innerHTML = el.innerHTML.replace(stext,stext+'s'); } }
}
//
function noNull(s) {
  if (s == null) { s = ''; }
  return s;
}

function searchFocus(el,val) {
  var div = document.getElementById(el.id);
  if (div) {
    if (div.value == val) { div.value = ''; }
  }
}

var videoCount = 0;
function showVideo(name, title, wid, ht) {
  name = (name.indexOf(':') > -1 ? name : thisUrl+'products/video/'+name+'.wmv');
  wid = (wid ? wid : 320);
  ht = (ht ? ht : 290);
  var s = '';
  videoCount++;
  s+= '<object id="MediaPlayer'+videoCount+'" CLASSID="CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95" codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701" standby="Loading..." width='+wid+' height='+ht+' type="application/x-oleobject" >';
  s+= '<param name="FileName" value="'+name+'">';
  s+= '<param name="AnimationatStart" value="true">';
  s+= '<param name="TransparentatStart" value="true">';
  s+= '<param name="AutoStart" value="true">';
  s+= '<param name="AutoSize" value="false">';
//  s+= '<param name="ShowTracker" value="true">';
//  s+= '<param name="ShowGotoBar" value="false">';
//  s+= '<param name="ShowDisplay" value="false">';
//  s+= '<param name="ShowStatusBar" value="false">';
  s+= '<param name="UIMode" value="mini">';
//  s+= '<param name="ShowControls" value="true">';
  s+= '<param name="Volume" value="-450">';
  s+= '<embed type="application/x-mplayer2" pluginspage="http://www.microsoft.com/Windows/MediaPlayer/" src="'+name+'" name="MediaPlayer'+videoCount+'"  width='+wid+' height='+ht+'  autostart=1 showcontrols=1 volume=-450>';
  s+= '</object>';
  showX(s,'',wid+80,title);
}

function printDiv(divID, ovWid, ovHt) {
// note the div passed must have a width and height set in css to use auto setting
  diva = divID.split(';');
  var w = 0;
  var h = 0;
  for (var i=0; i < diva.length; i++) {
    if (diva[i]) {
      var el = document.getElementById(diva[i]);
      w += el.clientWidth-0;
      h += el.clientHeight-0;
    }
  }
  if (w < 200) { w = 600; }
  if (h < 200) { h = 400; }
  if (ovWid != undefined) { w = ovWid; }
  if (ovHt != undefined)  { h = ovHt; }
  var w1 = w+20;
  var h1 = h;
  h1 = h1+100;
  if (h1 > self.innerHeight)  { h1 = self.innerHeight; }
  var x = "width="+w1+",height="+h1+",resizable,scrollbars=yes,menubar=yes";
  var win = window.open(thisUrl+'printdiv.html?divid='+divID+'&wid='+w+'&hei='+h,'printdiv',x);
  try {
    win.focus();
    win.moveTo(50, 50)
  }
  catch(err)
  {}
}

function stopRightClick() {
  function clickIE() {if (document.all) {return false;}}
  function clickNS(e) {if (document.layers||(document.getElementById&&!document.all)) { if (e.which==2||e.which==3) {(message);return false;}}}
  if (document.layers) {document.captureEvents(Event.MOUSEDOWN);document.onmousedown=clickNS;}
  else{document.onmouseup=clickNS;document.oncontextmenu=clickIE;}
  document.oncontextmenu=new Function("return false")
}

function setMessage(s) {
// use for top of the page messages
  var el = document.getElementById('headMessage');
  if (el) { el.innerHTML = s; }
}

function initHeaderDivs() {
  // header divs are empty so that google doesnt pick up google index text from them at the top of the page
  // copy text from the holder divs lower down the page
  var el = document.getElementById('headerContainerPrint');
  var el1 = document.getElementById('headerContainerPrint_Holder');
  if (el && el1 ) { el.innerHTML = el1.innerHTML; }

  var el = document.getElementById('headMessages');
  var el1 = document.getElementById('headMessages_Holder');
  if (el && el1 && (trim(el1.innerHTML) != '')) { el.innerHTML = el1.innerHTML; }
}

function nonPHPImageName(imgname) {
// removes the showpartf_image.php stuff from an image name and returns just the raw path
  var res = imgname;
  if (imgname.indexOf('showpartf_image.php') > -1) {
    res = imgname.split('showpartf_image.php')[0] + imgname.split('large=')[1];
  }
  return res;
}

function makeWorkArea(s) {
  // temp off screen work area. First used as a place to process the ajax matrix html
  // done so that the matrix height is known before passing it to showAlertX
  var div = createDynamicPopup('workArea');
  if (div) {
    div.style.left = '-3000px';
    div.style.display = 'block';
    div.innerHTML = s;
  }
}
function getWorkArea() {
  var div = document.getElementById('workArea');
  var res = 'workArea doesnt exist';
  if (div) {
    res = div.innerHTML;
    div.innerHTML = '';
  }
  return res;
}

// override alertConfig in custom.js if needed
var alertConfig = { defaultHeaders : true, cssButtons : true, buttonExt : 'jpg', buttonAlt : true, buttonAlign: 'center', buttonWidth: '100px', useIcons : true, leftFillHeader : false, printButton : false }
// next vars are set by alertXHeader so that drag handler and popupInit can get the ids used in the header
var alertCount = 0;
var alertXId = '';
var alertXCloseId = '';
var alertXDragId = '';
function doAlertXButtons(id, buttons) {
  var s = '';
  var c = 0;
  for (var key in buttons) {
    var val = buttons[key];
    c++;
    if (c==1) { s+='<table id="'+id+'PromptTable" align="'+alertConfig.buttonAlign+'" cellspacing="0" cellpadding="0" style="width:auto; margin:0 auto; padding:0;" ><tr>'; }
    if (alertConfig.cssButtons) {
      s+='<td align="center" style="padding:4px 5px 0 5px;"><a class="BMBtn" onclick="closeAlertX(\''+id+'\',\''+val+'\');" style="width:'+alertConfig.buttonWidth+'; margin:0px 0;" alt="'+(alertConfig.buttonAlt ? key : '')+'" >'+key+'</a></div></td>';
    } else {
      s+='<td align="center" style="padding:4px 5px 0 5px;"><img onclick="closeAlertX(\''+id+'\',\''+val+'\');" src="'+thisUrl+'assets/images/alert_'+key+'.'+alertConfig.buttonExt+'" alt="'+(alertConfig.buttonAlt ? key : '')+'" /></td>';
    }
  }
  if (c > 0) { s+='</tr></table>'; }
  return s;
}

// header is in a function so I can use if for all popups to get the same look for all of them
// id should only be passed by initalertX
function alertXHeader(header, id) {
  var s = '';
  s+='<table id="alertXHead'+alertCount+'" class="alertXHead" cellspacing="0" cellpadding="0" border="0" ><tr>';
  if (alertConfig.useIcons) {
    if (header.match(/alert/i)) { s+='<td id="alertXIconI"></td>'; }
    if (header.match(/confirm/i)) { s+='<td id="alertXIconQ"></td>'; }
  }
  header = trim(header);
  header = header.replace(/alert:/i,'');
  header = header.replace(/confirm:/i,'');
  headerStyle = '';
  if (alertConfig.printButton) {
    s+='<td id="alertXPrint" class="alertXPrint"><img src="'+thisUrl+'assets/images/alertprint.'+alertConfig.buttonExt+'" onclick="printDiv(\'alertXMessage'+alertCount+'\');" alt="print" title="print" /></td>';
    headerStyle = ' style="text-align:center;"';
  }
  if (!alertConfig.useIcons && !alertConfig.printButton && alertConfig.leftFillHeader) {
    s+='<td id="alertXLeftFill" class="alertXLeftFill">&nbsp;</td>';
  }
  s+='<td id="alertXHeadText'+alertCount+'" class="alertXHeadText" '+headerStyle+'>'+header+'</td>';
  var clicky = (id ? 'onclick="closeAlertX(\''+id+'\');"' : 'onclick="popupClose(\'\',\'\');"');
  s+='<td id="alertXClose'+alertCount+'" class="alertXClose" align="right" valign="top"><img src="'+thisUrl+'assets/images/alertclose.'+alertConfig.buttonExt+'" '+clicky+' alt="close" title="close" /></td>';
  s+='</tr></table>';
  alertXId = 'alertX'+alertCount;
  alertXCloseId = 'alertXClose'+alertCount;
  alertXDragId = 'alertXHeadText'+alertCount;
//alert(s);
  return s;
}
function initAlertX(header, buttons, justify, modal) {
  alertCount++;
  var id = 'alertX'+alertCount;
//  var alertClass = (alertPrettyHead ? 'alertXPretty' : 'alertX');
  var alertClass = 'alertX';
//alert(header);
  el = createDynamicPopup(id, modal, alertClass);

  var s = alertXHeader(header, id);
  
  s+='<div class="alertXMessage" id="alertXMessage'+alertCount+'" class="alertXMessage" style="text-align:'+justify+'"></div>';

  var c = 0; for (var key in buttons) { c++; }
  if (c) {
    s+='<div class="alertXPrompt" id="'+id+'Prompt"><div id="'+id+'PromptContainer">';
    s+= doAlertXButtons(id, buttons);
    s+='</div></div>';
  }

  if (el) {
    el.innerHTML = s;
    var el1 = document.getElementById('alertXHeadText'+alertCount);
    var AlertX = DragHandler.attach(el1,el); // make it draggable
  }
  // resets for next call
  alertConfig.printButton = false;
  return el;
}

function closeThisAlertX(thisel, val) {
  // will find the AlertX holding the thisel element and close it with 'val' as the closeresult
  var el = thisel;
  while((el=el.offsetParent) != null) {
    if (el.id.substr(0,6) == 'alertX' && el.id.substr(0,13) != 'alertXMessage') {
      closeAlertX(el.id,val);
      return true;
    }
  }
  return false;
}

function closeAlertX(id, val) {
  var el = document.getElementById(id);
  if (el) {
    var res = true;
    if (el.closer && el.closer != undefined) { res = el.closer(val); }
    if (res || res == undefined) {
      el.style.display = 'none';
//      hideShadowBox();
      hideModalCover();
      document.body.removeChild(el);
    }
  }
}
var alertData = new Array();
var alertPreProcess = null;  // point this to a function xyz(s) to process the string just before it is put in innerHTML
var alertPostProcess = null;  // point this to a function xyz(el) to process the popup element once it is part of the HTML
function showAlertX(s, header, buttons, width, justify, closer, modal ) {
// returns the ID of the Alert box in case it is needed for manual close of button changing
  if (!header) { header = ''; }
  el = initAlertX(header, buttons, justify, modal);
  if (el) {
    el.closer = closer;
    var elm = document.getElementById('alertXMessage'+alertCount);

    // was it a div id passed rather than text
    if (s.length < 30 && s.indexOf(' ') == -1) {
      var eldata = document.getElementById(s);
      if (eldata) {
        // the first call will put contents into alertData array and kill the original
        // all future calls will use the alertData data
        // this makes sure that if the passed div id contains an input form, there arent duplicates of all the field ids.
        if (alertData[s]) {
          s = alertData[s];
        } else {
          alertData[s] = eldata.innerHTML;
          s = alertData[s];
          eldata.innerHTML = '';
        }
      }
    }

    if (alertPreProcess) { s = alertPreProcess(s); } // used in showpartf.js
    alertPreProcess = null;

    showModalCover();
    var twid = 0;
    if (!width) {
      temp = createDynamicPopup('alertXT');
      if (temp) {
        s = s.replace(/#39/g,'\'');  // restore #39's to quotes before browser sees it
        temp.innerHTML = s;
        temp.style.display = 'block';
        twid = temp.offsetWidth-0;  // this is the width the text wants to try to be
        temp.innerHTML = '';
        try { document.body.removeChild(temp); } catch(err) { }
      }
    }
    var ss  = screenSize();
    el.style.display = 'block';

    var hel = document.getElementById('alertXHead'+alertCount);
    hel.style.width = 'auto';
    var hwid = hel.offsetWidth;
    hel.style.width = '100%';
//    alert(twid+' '+hwid);
    if (hwid > twid) { twid = hwid; }

    var elpt = document.getElementById('alertX'+alertCount+'PromptTable');
    if (elpt && elpt.offsetWidth > twid) { twid = elpt.offsetWidth; }
    if (twid == 0) { twid = 400; }
    if (twid < 200) { twid = 200; }
    if (width) { twid = width; }
    elm.innerHTML = s;

    var elp = document.getElementById('alertX'+alertCount+'Prompt');
    if (twid > ss.w-wborder(el)-16) { twid = ss.w-wborder(el)-16; }
    elm.style.width = twid + 'px';
    el.style.width = twid + wborder(elm) + 'px';
    if (el.offsetHeight > ss.h) {
      var elh = document.getElementById('alertXHead'+alertCount);
      var maxmh = ss.h-(elp ? elp.offsetHeight : 0)-elh.offsetHeight-hborder(el)-hborder(elm);
      if (elm.offsetHeight > maxmh) { elm.style.height = maxmh+'px'; }
    }
    var x = el.offsetLeft;
    var y = el.offsetTop;
    var w = el.offsetWidth;
    var h = el.offsetHeight;
    x = xOnPage(x,w,true);
    y = yOnPage(y,h,true);

    el.style.left = x + 'px';
    el.style.top  = y + 'px';
    if (!modal) { showShadowBox(el); }
  }
  el.focus();
  if (alertPostProcess) { alertPostProcess(el); }
  alertPostProcess = null;
  return 'alertX'+alertCount;
}

// close func must have a single param which will contain the value of the button clicked or undefined if the X is clicked
// width will force the width of the box if set. '' or 0 will auto set the width
// header will override the default box header
// buttons is a json array like { 'visible text':'return value', 'Cancel':'cancel', 'Ok':'ok' }
// all alert boxes are independent so to close one manually you will need to save alertX_Id() after creating one
// OR call closeThisAlertX(thisel, val) from an element in the box

// an example alertX closing function
function alertCloseTest(val) {
  if (val == 'ok') { alert('ok clicked - return is false so it wont close'); return false; }
  if (val == 'cancel') { alert('cancel clicked - will close');  }
  if (val == undefined) { alert('you clicked the close icon');  }
}
function alertX_SetButtons(id, buttons) {
// allows the buttons to be changed dynamically  eg { 'Close':'close' }
// save the result of alertX() so it can be passed here as id
  var el = document.getElementById(id+'PromptContainer');
  if (el) {
    var s = doAlertXButtons(id, buttons);
    el.innerHTML = s;
  }
}
function alertX(s,closeFunc, width, header, align, buttons) {
  if (!s || s == undefined) { s = ''; }
  s = s + '';
//  s = s.replace(/\n/g,'<br>');
//  s = s.replace(/#39/g,'\'');
  if (!header && alertConfig.defaultHeaders) { header = co_name+' Alert'; }
  if (!align) { align = 'center'; }
  if (!buttons) { buttons = { 'OK':'ok' }; }
  return showAlertX(s,header, buttons, width, align, closeFunc, isModal);
}
function alertX_BR(s,closeFunc, width, header, align, buttons) {
  if (!s || s == undefined) { s = ''; }
  s = s + ''; // make sure its a string
  s = s.replace(/\</g,'&lt;');
  s = s.replace(/\>/g,'&gt;');
  s = s.replace(/\n/g,'<br>');
  if (!header && alertConfig.defaultHeaders) { header = 'Alert'; }
  if (!align) { align = 'left'; }
  if (!buttons) { buttons = { 'OK':'ok' }; }
  return showAlertX(s,header, buttons, width, align, closeFunc, isModal);
}
function showX(s,closeFunc, width, header) {
  if (!s || s == undefined) { s = ''; }
  s = s + '';
  if (!header && alertConfig.defaultHeaders) { header = co_name+' Alert'; }
  return showAlertX(s,header,{}, width, 'center', closeFunc, isModal);
}
function confirmX(s, closeFunc, width, header) {
//  s = s.replace(/\n/g,'<br>');
//  s = s.replace(/#39/g,'''');
  if (!header && alertConfig.defaultHeaders) { header = co_name+' Confirm'; }
  return showAlertX(s,header,{ 'OK':'ok', 'Cancel':'cancel' }, width, 'left', closeFunc, isModal);
}
function promptX(s, closeFunc, width, buttons, header) {
//  s = s.replace(/\n/g,'<br>');
//  s = s.replace(/#39/g,"'");
  return showAlertX(s,header,buttons, width, 'left', closeFunc, isModal);
}

function makeTable(fmt, s, tclass) {
// fmt is an array of columns defined as ['width','th justify','td justify','head text']
// justify is C, L or R
  var justy = new Array; justy['L']='Left'; justy['C'] = 'center'; justy['R'] = 'right';
//  if (tclass) { tclass = ' class="'+tclass+'"'; } else { tclass='';}
  if (tclass) {} else {tclass='';}

  var dohead = false;  // set to true if text supplied in the fmt array
  var totw = 0;
  var cols = fmt.length;
  for (var i=0; i<cols; i++) {
    var col = fmt[i];
    if (col[3]) { dohead = true; }
    totw += col[0]-0;
  }

  res = '<table cellspacing="0" cellpadding="4" border="0" width="'+totw+'" '+tclass+'>';
  if (dohead) {
    res += '<tr>';
    for (var i=0; i<fmt.length; i++) {
      var col = fmt[i];
      var val = (col[3] ? col[3] : '&nbsp;');
      res += '<th width="'+col[0]+'" align="'+justy[col[1]]+'">'+val+'</th>';
    }
    res += '</tr>';
  }

  var a = s.split('|');
  var col = 0;
  for (var i=0; i<a.length-1; i++) {
    col++;
    if (col == 1) { res += '<tr>'; }
    var val = (a[i] ? a[i] : '&nbsp;');
    res += '<td width="'+fmt[col-1][0]+'" align="'+justy[fmt[col-1][2]]+'">'+val+'</td>';
    if (col == cols) { res += '</tr>'; col = 0; }
  }

  res += '</table>';
  return res;
}

function seoName(s) {
   var res = trim(s);
   res = res.replace(/ /g,'-')
   res = res.replace(/&amp;/g,'')
   res = res.replace(/&/g,'')
   res = res.replace(/\//g,'-')
   res = res.replace(/\+/,'-')
   res = res.replace(/--/g,'-')
   res = res.replace(/---/g,'-')
   res = res.replace(/--/g,'-')
   res = res.replace(/\(/g,'')
   res = res.replace(/\)/g,'')
   res = res.replace(/\./g,'')
   res = res.replace(/\,/g,'')
   res = res.replace(/\:/g,'')
   res = res.replace(/\'/g,'')
   res = res.replace(/"/g,'')
   res = res.replace(/%/g,'')
   res = res.replace(/#/g,'')
   res = res.replace(/\*/g,'')
   res = res.replace(/’/g,'')
   res = res.replace(/‘/g,'')
   res = res.replace(/%2D/g,'-')
   return res;
}

//--------------------------------------

function addBasketPopupContents() {
  var s = '';
  if (window.vouc_data && vouc_data.length > 0) {
    var el = document.getElementById('basketPopupLines_holder');
    if (el) {
      var tmpo = el.innerHTML;
      tmpo = tmpo.replace(/xx_table/ig,'table');
      var el = document.getElementById('basketPopupLine_holder');
      if (el) {
        var tmp = el.innerHTML;
        tmp = tmp.replace(/xx_tr/ig,'tr');
        tmp = tmp.replace(/xx_td/ig,'td');
        tmp = tmp.replace(/xx_img/ig,'img');
        for (var i=0; i<vouc_data.length; i++) {
          var tmp1 = '';
          tmp1+=tmp;
          tmp1 = tmp1.replace(/[\<\[]xx_part\]/g, vouc_data[i].part);

          var major = (vouc_data[i].template2 ? vouc_data[i].template2 : vouc_data[i].major);
          tmp1 = tmp1.replace(/\[xx[_ ]partcolour\]/ig, vouc_data[i].partcolour ? vouc_data[i].partcolour  : major);
          tmp1 = tmp1.replace(/\[xx[_ ]major\]/g, major);

          tmp1 = tmp1.replace(/\[xx[_ ]part_link\]/g, (vouc_data[i].major ? vouc_data[i].major : vouc_data[i].part));
          tmp1 = tmp1.replace(/\[xx[_ ]descr\]/g, vouc_data[i].descr);
          tmp1 = tmp1.replace(/\[xx[_ ]descr_link\]/g, seoName(vouc_data[i].descr));
          tmp1 = tmp1.replace(/\[xx[_ ]qty\]/g, vouc_data[i].qty);
          tmp1 = tmp1.replace(/\[xx[_ ]price\]/g, vouc_data_curr+vouc_data[i].total);
          s+= tmp1;
        }
      }
      tmpo = tmpo.replace('\[xx_lines\]',s);
      tmpo = tmpo.replace(/xx_onerror/ig,'onerror');
      var el = document.getElementById('basketPopupScroll');
      if (el) { el.innerHTML = tmpo; }
    }
    var el = document.getElementById('basketPopupCount');
    if (el) { el.innerHTML = vouc_data_qty; }
    var el = document.getElementById('basketPopupTotal');
    if (el) { el.innerHTML = vouc_data_curr+roundDP(vouc_data_tot,2); }
  }
}

function initBasketPopup(modal) {
  var id = 'basketPopup';
  var div = document.getElementById(id);
  if (!div || !window.vouc_data) { return false; }

  if (div.style.display != 'block') { var div = createDynamicPopup(id,modal); }
  
  addBasketPopupContents();

  return div;
}
var c = 0;
//--------------------------------------
function onOpenBasketPopupTimer() {
  showBasketPopupReal(null, openBasketEle)
}
function showBasketPopup(event, ele, time) {
  clearTimeout(openBasketPopupTimer);
  clearTimeout(closeBasketPopupTimer);
  openBasketEle = ele;
  basketPopupInterval = (time == undefined ? 0 : time);
  openBasketPopupTimer = setTimeout( 'onOpenBasketPopupTimer()', 300 );
}
function showBasketPopupReal(event, ele) {
  clearTimeout(openBasketPopupTimer);
  clearTimeout(closeBasketPopupTimer);
  if (basketPopupAborted) { return }

  var div = document.getElementById('basketPopup');
  var wasVisible = div && div.style.display == 'block';
  var calledFromBuy = basketPopupInterval > 0;

//  if (wasVisible && ) {
    // its a call from an ajax return and the dropdown is dropped so refresh and start the timer
//    calledFromBuy = true;
//    addBasketPopupContents();
//    refreshBasketPopup();
//    closeBasketPopupTimer = setTimeout( 'onCloseBasketPopupTimer()', basketPopupInterval );
//    basketPopupInterval = 0;
//    return;
//  }
  if (wasVisible && !calledFromBuy) { return } // stop repeated firing of mouseover being a problem

  var div = initBasketPopup();
  if (div) {
    c++;
    if (!wasVisible) popupInit(hideBasketPopupReal,'xxxx');

    var els = document.getElementById('basketPopupScroll');
    els.style.height = 'auto';
    els.style.overflow = 'visible';

    if (!wasVisible) div.style.left = '-10000px';  // create it off screen so i can make it visible to find its size
//div.style.left = '0px';
    div.style.overflow = 'visible';
    div.style.height = 'auto';
    div.style.display='block';
    var xy = getBounds(ele);
    y = yOnPage(xy.y+xy.h,0);
    x = xOnPage(xy.x+xy.w-div.offsetWidth,div.offsetWidth)+10;

    var dxy = getBounds(div);
    var exy = getBounds(els);
    var sxy = screenSize();
    if (y + dxy.h > sxy.y + sxy.h) {
      els.style.overflow = 'hidden';
      els.style.overflowY = 'scroll';
      var h = sxy.y + sxy.h - y + exy.h - dxy.h;
      if (h < 20) { h = 20; }
      els.style.height = h + 'px';
    }

    div.style.top = y + 'px';
    div.style.left = x + 'px';
    div.trueleft = x;
    hideSelects();
//document.title = div.offsetHeight+ ' | '+h+' | '+exy.h+' | '+sxy.h;
    div.onmouseover = new Function("keepBasketPopup();");
    div.onmouseout = new Function("hideBasketPopup();");

    if (!wasVisible) {
      rolldown(div);
    }
    
    if (calledFromBuy) { closeBasketPopupTimer = setTimeout( 'onCloseBasketPopupTimer()', basketPopupInterval ); }
    basketPopupInterval = 0;
  }
}
//--------------------------------------
var openBasketPopupTimer = null;
var openBasketEle = null;
var closeBasketPopupTimer = null;
var basketPopupAborted = false;
var basketPopupInterval = 0;
function hideBasketPopupReal(ss) {
  var id = document.getElementById('basketPopup');
//  if (id) { id.style.display='none'; showSelects(); }
  if (id) { rollup(id, showSelects); }

}
function onCloseBasketPopupTimer() {
  clearTimeout(closeBasketPopupTimer);
  closeBasketPopupTimer = null;
  popupClose('','');
}
function hideBasketPopup(e) {
//  e = e || window.event; // make sure IE has the event in e
//alert(popupInDiv(e,'miniBasketMain',true)+'xx'+popupInDiv(e,'basketPopup',true)+'yy'+(!popupInDiv(e,'miniBasketMain',true) && !popupInDiv(e,'basketPopup',true)));
//  if (!popupInDiv(e,'miniBasketMain',true) && !popupInDiv(e,'basketPopup',true)) {
    clearTimeout(openBasketPopupTimer);
    closeBasketPopupTimer = setTimeout( 'onCloseBasketPopupTimer()', 500 );
//  }
}
function keepBasketPopup() {
  clearTimeout(closeBasketPopupTimer);
}
function hideBasketPopup_CO(event,miniBasketEle) {
  // called when mini basket is clicked to go to checkout
  basketPopupAborted = true;
  popupClose('','');
  if (miniBasketEle) {
    miniBasketEle.className = miniBasketEle.className + ' clicked';
  }
}

// call stopTypeAhead() / starttypeAhead() to switch this function off and on

// local vars
var searchBox = null;  // pointer to the searchbox element
var searchhttp=null;
var searchedValue = '';
var badValue = '';
var typeAheadLive=true;

function stopTypeAhead() {
  typeAheadLive = false;
  if (window.typeAheadPopup) { typeAheadPopup.style.display = 'none'; }
}

function startTypeAhead() {
  typeAheadLive = true;
}

//--------------------------------------
function showSuggestions(a) {
//alert(a);
  var id = 'suggestionBox';
  var div = document.getElementById(id);
  if (!div) {
    div = createDynamicPopup(id,false);
 			div.innerHTML+='<div id="sresults" class="ta" name="suggestionresults"></div>';
  }
  popupInit(hideSuggestionsCore,'!suggestionBox');

  // put the shadow png around the box
//  a = '<div id="suggestionT"><!--xx--></div><div id="suggestionM">' + a + '</div><div id="suggestionB"><!--xx--></div>';
  a = '<table cellspacing="0" cellpadding="0" border="0"><tr><td class="tl" style="background-position: 0 0;">'+a;
  a+= '</td><td class="tr" style="background-position: right 0;">&nbsp;<!--x--></td></tr><tr><td class="bot" style=" background-position: left bottom;" ><!--x--></td><td class="bot" style=" background-position: right bottom;"><!--x--></td></tr></table>';

  el = document.getElementById('sresults');
  el.innerHTML = a;

  div.style.display='block';
  var xy = getBounds(searchBoxId);
  y = yOnPage(xy.y+xy.h+4,div.offsetHeight);
  x = xOnPage(xy.x,div.offsetWidth);

  div.style.top = y + 'px';
  div.style.left = x + 'px';
  hideSelects();
//  showShadowBox(div);
}
//--------------------------------------
var canSearchSugg = true;

function hideSuggestions() {
  popupClose('','');
}
function hideSuggestionsCore() {
  var id = document.getElementById('suggestionBox');
  if (id) { id.style.display='none'; showSelects(); }
  searchedValue = '';
//  hideShadowBox();
}

function getSearchRes() {
  if (!typeAheadLive) { return; }
  if(searchhttp.readyState==4 && searchhttp.status==200) {
    canSearchSugg = true;
    res = searchhttp.responseText;
//alert(res);
    if (res) {
      var aa ='';
      var pts = res.split('|');
      for (var i=0; i<pts.length; i++) {
        if (trim(pts[i])) {
          var pt = pts[i].split('\\');
          f=searchedValue;
          var s1 = (pt[2] ? pt[2] : 'products');
          var L_descr = pt[1].toLowerCase();
          var L_f = f.toLowerCase(f);
          var p = L_descr.indexOf(L_f);
          var s = pt[1].substr(p,searchedValue.length);
          var d='<span class="match">'+s+'</span>';
          pt[1]=pt[1].replace(new RegExp(searchedValue,"ig"),d)
          aa = aa+'<li><a id=item'+i+' href="'+thisUrl.replace('https:','http:')+'sp'+delim404+s1+delim404+pt[0]+'?tyah=y" onclick="popupClose(\'\',\'\');">'+pt[1]+'</a></li>';
        }
      }
    }
    if (!aa) {
      var dt = searchBox.getAttribute('data-none-found');
      if (dt) {
        a = dt;
      } else {
//        a='no suggestions - try again.';
        a='<br />&nbsp;&nbsp;no suggestions found<br /><br />press <b>Enter</b> for a <br /> &nbsp;more thorough search<br /><br />';
      }
      badValue = searchedValue;
    } else {
      a = '<ul>'+aa+'</ul>';
      badValue = '';
    }
    showSuggestions(a);
  }
}

function getSuggestions() {
  try {   // The following "try" blocks get the XMLHTTP object for various browsers…
     searchhttp = new ActiveXObject("Msxml2.XMLHTTP");
  } catch (e) {
    try {
      searchhttp = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (e2) {
      // This block handles Mozilla/Firefox browsers...
      try {
        searchhttp = new XMLHttpRequest();
      } catch (e3) {
        searchhttp = false;
      }
    }
  }
  if(searchhttp!=null) {
    var fixer = new Date();
    searchhttp.open("GET",thisUrl+"typeAhead.asp?searchwhat="+searchedValue+'&when='+fixer.getTime(),true);
    searchhttp.onreadystatechange=function(){ getSearchRes(); };
    searchhttp.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2005 00:00:00 GMT");
    searchhttp.send(null);
    canSearchSugg = false;  // stop it searching again until this one has replied
  }
}

function doSearch(c) {
  doSearchTimer();
}
function doSearchTimer() {
  if (!typeAheadLive) { return }
  if (canSearchSugg) {
    var dv = searchBox.getAttribute('data-def-value');
    if (dv && dv == searchBox.value) { searchBox.value = ''; return; }
    var a = trim(searchBox.value);
    if (!a) { hideSuggestions(); searchedValue = ''; return }
    if (searchedValue != a) {
      searchedValue = a;
  //    if (badValue == '' || searchedValue.indexOf(badValue) != 0) {
      badValue = '';
      getSuggestions();
  //    }
    }
  } else {
    setTimeout(doSearchTimer, 30 );
  }
}

function searchSuggKeyDown(c) {
  c = c || window.event;
  var a = (c.keyCode ? c.keyCode : c.which);
  if (a==191) { if (window.event) { event.returnValue = false; } return false; } // ?mark
  return true
}

function initSearchBox() {
  window.focus(); // make sure the search box isnt focused when the page loads
  searchBox = document.getElementById(searchBoxId);
  if (searchBox) {
//		searchBox.onkeypress = function(c) { return editKeyPress(c)};
    searchBox.onkeyup = function(c) { return doSearch(c) };
    searchBox.onfocus = function(c) { return doSearch(c) };
    searchBox.onkeydown = function(c) { return searchSuggKeyDown(c) };
  }
}

// *********** pre-post form data checking stuff
// to use this all you do is add ' onsubmit="return checkData(this);" ' to the form definition
// and add data-man="" to each input, select or textarea you want to be mandatory.
// data-man can have other values to add extra control to the pre-post checks
// multiple controls are separated by | eg "minl=5|maxl=20|blankok"
// "email" does a check for a valid email address
// "minl" and "maxl" control the min and max length
// "minv" and "maxv" control the min and max values
// "pwd" sets the min and max length to 6 and 20 and stops ' and " being entered
// "cc" does a basic credit card modulus check with min and max lengths of 13 and 19
// "confirm=xxx" will check that the value is the same as the value in the element with id="xxx"
// "novalue=nowt,none" will treat 'nowt' and 'none' as being the same as '' (comma delimited list)
//     -- use this if the default or blank value of a drop down is somthing other than ''
// "blankok" allows restrictions to be set but only checked if the value is not '' eg password change
// "noquote" prevents ' being entered
// "nodblquote" prevents " being entered
// "ukonly=country" country is the id of the country selector. Use this on a postcode field to insist
//    on a postcode, only, if the country code is in the 'postcodeCountries' array
// "oldpw" makes sure that the entered password matches the encrypted old password in:
//    <input type="hidden" name="sctot" id="sctot" value="<elucid_enc_pw>">
// "group=1" will only apply restrictions if a field with "group=1" has data in it
// "CIcheck=country" will force Channel islands in the 'country' field if a CI postcode is entered
//    or force UK if country = CI and postcode is not.
// "usca" will check for a 2 character State code if the country is US or CA.

function isEmail(s) {
  return s.match(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i) != null;
}
function ccCheck(number) {
  var number=number.replace(/ /g, '');  // Strip any spaces
  var number_length=number.length;
  var parity=number_length % 2;
  var total=0;
  for (i=0; i < number_length; i++) {
    var digit=number.charAt(i);
    if (i % 2 == parity) { digit=digit * 2;  if (digit > 9) { digit=digit - 9; } }
    total = total + parseInt(digit);
  }
  return ((total % 10 == 0) && (number_length >= 13) ? true : false);
}
var checkEleError = null;
var checkErrTimer = null;
var checkErrVal = '';
var checkErrEle = null;
var checkIDCounter = 0;
function showErr(el) {
  if (!checkEleError) {
    checkEleError = createDynamicPopup('errorPopup','','errorPopup');
    var s = '<table cellspacing="0" cellpadding="0" border="0"><tr>';
    s += '<td id="ceeMain" style="padding:14px 0 0 20px; font-weight:bold; background-position: 0 0;"></td>';
    s += '<td style="width:20px; height:20px; background-position: right 0;"><!--x--></td>';
    s += '</tr><tr>';
    s += '<td class="bot" style=" background-position: 0 bottom;"><!--x--></td>';
    s += '<td class="bot" style=" background-position: right bottom;"><!--x--></td>';
    s += '</tr></table>';
    checkEleError.innerHTML = s;
  } else {
    globZindex++;
    checkEleError.style.zIndex = globZindex;
  }

  var tmp = document.getElementById('ceeMain');
  tmp.innerHTML = el.stat;
  checkEleError.style.display = 'block';
  var exy = getBounds(el);
  var exe = getBounds(checkEleError);

  checkEleError.style.top = exy.y -exe.h+1 + 'px';
  checkEleError.style.left = exy.x + 15 + 'px';
  hideSelects(el);
}
function hideErr(el) {
  if (checkErrTimer) { clearTimeout(checkErrTimer); }
  if (checkEleError) { checkEleError.style.display = 'none'; }
  showSelects();
}
function checkErrOnTimer(tim) {
  var ele = checkErrEle;
//document.title = ele.tagName+' | '+ele.value+' | '+checkErrVal;
  if (ele.value != checkErrVal || ele.type == 'radio') {
    checkEle(ele, 1);
  } else {
    checkErrTimer = setTimeout( "checkErrOnTimer(this)", 1000 );
    checkErrTimer.ele = ele;
  }
}
function hasNoValue(val, novalue) {
  val = val.toLowerCase();
  if (val === '') { return true; }
  if (novalue) {
    for (var i=0; i<novalue.length; i++) {
      if (novalue[i].toLowerCase() == val.toLowerCase()) { return true; }
    }
  }
  return false;
}
function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}
var checkDataGroupData = new Array;
var checkDataGroup = new Array;
function groupIsEmpty(group,form) {
//  try { eval('var fields = checkDataGroup'+group); }
//  catch(err) { alert('data-man="group='+group+'" was used but checkDataGroup'+group+' variable was not set up'); };
//  if (!window.checkDataGroup[group]) {
//    alert('data-man="group='+group+'" was used but checkDataGroup'+group+' variable was not set up');
//    return false;

//  } else {
    if (!window.checkDataGroupData[group] || window.checkDataGroupData[group] == undefined) {
      if (!window.checkDataGroup[group]) {
        checkDataGroup[group] = '';
        var eles = form.elements;
        for (var i=0; i<eles.length; i++) {
          var man = eles[i].getAttribute('data-man');
          if (man && man.indexOf('group='+group) > -1) {
            checkDataGroup[group] += eles[i].id + ',';
          }
        }
      }
      checkDataGroupData[group] = '';
      var fields = checkDataGroup[group].split(',');
      for (var i=0; i<fields.length; i++) {
        if (fields[i]) {
          var ele = document.getElementById(fields[i]);
          if (ele) {
            checkDataGroupData[group] += trim(ele.value);
          } else {
            alert(fields[i]+' is in checkDataGroup['+group+'] but doesnt exist on the form');
          }
        }
      }
    }
    return checkDataGroupData[group] == '';
//  }
}
var postcodeCountries = 'UK,GB,JE,GY';  // override by copying to custom.js if needed
var CIcheck = { 'match':'(gy|je)[ ]*([0-9])', 'country':'CI', 'notCI':'UK' }; // override by copying to custom.js if needed
function checkEle(ele, from, form, src) {
  if (checkErrTimer) { clearTimeout(checkErrTimer); }
  var ok = true;
  var man = ele.getAttribute('data-man');
  var par = ele.getAttribute('data-man-par');
  if (par) {
    ele = document.getElementById(par);
    var man = ele.getAttribute('data-man');
  }
  var val = trim(ele.value);
  if (man != undefined && val != undefined) {
    var minl = 0; var maxl = 9999; var minv = -999999999; var maxv = 999999999;
    var noquote = false; nodblquote = false; countrySel = null;  CIcountrySel = null;  oldpw = false; uscaState = false;
    var confirm = '';  var novalue = ''; var isval = false; var blankok = false; group = ''; nospace = false;
    var customfunc = null;
    var mana = man.split('|');
    for (var j=0; j<mana.length; j++) {
      var manj = mana[j].split('=');
      if (manj[0] == 'cc') { minl = 13; maxl = 19; }
      if (manj[0] == 'pwd') { minl = 6; maxl = 20; noquote = true; nodblquote = true; nospace = true;}
      if (manj[0] == 'noquote') { noquote = true; }
      if (manj[0] == 'nodblquote') { nodblquote = true; }
      if (manj[0] == 'minl') { minl = manj[1]-0; }
      if (manj[0] == 'maxl') { maxl = manj[1]-0; }
      if (manj[0] == 'minv') { isval = true; minv = manj[1]-0; }
      if (manj[0] == 'maxv') { isval = true; maxv = manj[1]-0; }
      if (manj[0] == 'confirm') { confirm = document.getElementById(manj[1]); }
      if (manj[0] == 'novalue') { novalue = manj[1].split(','); }
      if (manj[0] == 'blankok') { blankok = true; }
      if (manj[0] == 'ukonly') { countrySel = document.getElementById(manj[1]); postcodeCountries += ','; }
      if (manj[0] == 'CIcheck') { CIcountrySel = document.getElementById(manj[1]);  }
      if (manj[0] == 'oldpw') { oldpw = true; }
      if (manj[0] == 'group') { group = manj[1]; }
      if (manj[0] == 'customfunc') { customfunc = manj[1]; }
      if (manj[0] == 'usca') { uscaState = true; }
    }
    var errstr = '';

    if (customfunc) {
      var ss = 'var res = '+customfunc+'(\''+ele.id+'\')';
      eval(ss);
      if (!res.ok) { ok = false; errstr += res.errstr }
    }
    
    if (from == 0 && group && groupIsEmpty(group,form)) {  // from = 0 = batch check
    }
    else if (blankok && hasNoValue(val,novalue)) {
    }
    else if (confirm == undefined || (confirm && (confirm.value == undefined))) {
      // if the confirm element doesnt exist show a message to programmer
      ok = false; errstr += 'confirm id does not exist (programmer)';
    }
    else if (confirm) {
      if (confirm.value != val) { ok = false; errstr += 'Confirmation value does not match'; }
    }
    else if (oldpw) {
      if (val == '') { ok = false; errstr += 'Please enter your old password'; }
      else {
        var pwel = document.getElementById('sctot');
        if (pwel) {
          var scpw = val.toUpperCase();
          var pwht = 0;
          for (var xi=0; xi < scpw.length; xi++) { pwht += scpw.charCodeAt(xi) * (1+Math.pow(xi*256,2)); }
          if (pwht != pwel.value) { ok = false; errstr += 'The password you entered does not match your old password'; }
        } else {
          ok = false; errstr += 'sctot not found on page (programmer)';
        }
      }
    }
    else if (uscaState) {
       pcountry = document.getElementById('country').value;
       pcounty = document.getElementById('county').value;
//       if (pcountry=='US'||pcountry=='CA') {
       if (pcountry=='US') {
          if (pcounty.length!=2) {
          	  errstr+='Please enter a 2 character State code.';
             ok = false;
          }
       }
    }
    else {
      var eng = (ele.tagName == 'SELECT' ? 'selected' : 'entered');
      if (man == 'cc' && !ccCheck(val)) { ok = false; errstr += 'Credit Card number is invalid<br>'; }
      if (man == 'email' && !isEmail(val)) { ok = false; errstr += 'Email address is not a valid address<br>'; }
      if (man == 'phone' && !isPhone(val)) { ok = false; errstr += 'Phone number is not a valid, only numeric characters accepted (0-9).<br>'; }
      if (val.length < minl) { ok = false; errstr += 'Minimum length is '+minl+' characters ('+val.length+' Entered)<br>'; }
      if (val.length > maxl) { ok = false; errstr += 'Maximum length is '+maxl+' characters ('+val.length+' Entered)<br>'; }
      if (nospace && (val.indexOf("'") > -1)) { ok = false; errstr += "Spaces are not allowed<br>"; }
      if (noquote && (val.indexOf("'") > -1)) { ok = false; errstr += "The single quote character (') is not allowed<br>"; }
      if (nodblquote && (val.indexOf('"') > -1)) { ok = false; errstr += "The double quote character (\") is not allowed<br>"; }
      if (isval && (val-0 < minv || val-0 > maxv || !isNumeric(val))) { ok = false; errstr += 'Please enter a number between '+minv+' and '+maxv+'<br>'; }

      if (errstr == '' && hasNoValue(val, novalue)) {
        if (countrySel) {
         if (postcodeCountries.indexOf(countrySel.value+',') > -1 )
            { ok = false; errstr += 'A value needs to be '+eng+'<br>'; }
        } else {
          ok = false; errstr += 'A value needs to be '+eng+'<br>';
        }
      } else {
        // something entered
        if (CIcountrySel) {
          var matchit = new RegExp(CIcheck.match, "i")
          if (val.match(matchit) && CIcountrySel.value != CIcheck.country) {
            CIcountrySel.value = CIcheck.country;
//            alert('Channel Islands country has been auto selected to match your Channel Islands postcode');
            errstr+= 'Channel Islands has been auto selected to match your Channel Islands postcode';
            ok = false;
          } else if (!val.match(matchit) && CIcountrySel.value == CIcheck.country) {
            CIcountrySel.value = CIcheck.notCI;
            errstr+= 'UK has been auto selected to match your non-Channel Islands postcode';
            ok = false;
          }
        }
      }
    }

    var rex = new RegExp("((http://|https://|ftp://|file://)|(www\\.|ftp\\.))[-A-Z0-9+&@#/%=~_|$?!:,.]*[A-Z0-9+&@#/%=~_|$]", "i")
    var filt = val.match(rex);
    if (filt) { ok = false; errstr = 'Please remove the Web Site Address from the text.'; }
//    document.title = val + 'xx'+ filt;

    if (ele.tagName == 'INPUT' && ele.type.toUpperCase() == 'RADIO') {
      var radval = '';
      ok = true;
      var rads = ele.form.getElementsByTagName ('input');
      if (rads) {
        for (var i = 0; i < rads.length; ++i) {
          if (rads[i].type == 'radio' && rads[i].name == ele.name && rads[i].checked) {
            radval = rads[i].value;
          }
        }
      }
      if (radval == '') {
        ok = false; errstr = 'A value needs to be selected<br>';
      }
    }

    var bdrel = ele;
    var bckel = ele;
    // IE wont do select border so set the parents border instead
    if (ele.tagName == 'SELECT' || (ele.tagName == 'INPUT' && ele.type.toUpperCase() == 'RADIO')) {  bdrel = ele.parentNode; }
    if (ele.tagName == 'INPUT' && ele.type.toUpperCase() == 'RADIO') { bckel = ele.parentNode; }
//alert(ele.id+' '+ele.name+' '+ok+' '+errstr);

    if (!ok) {
      if (ele.done != true) {
        ele.done = true;
        ele.oldbwid = cssStyle(bdrel,'borderTopWidth');
        ele.oldbstyle = cssStyle(bdrel,'borderTopStyle');
        ele.oldbcolor = cssStyle(bdrel,'borderTopColor');
//alert(bel.tagName+' '+bel.className+' '+ele.oldbcolor);
        ele.oldbgcolor = cssStyle(bckel,'backgroundColor');
        ele.oldbgimage = cssStyle(bckel,'backgroundImage');
        ele.oldcolor = cssStyle(ele,'color');
        var pos = getBounds(ele);
        if (ele.tagName == 'INPUT' && ele.type == 'radio') {
//alert(ele+' '+ele.id+ ' '+ele.tagName);
          bdrel.onkeyup = new Function("checkEle(this,1,'','ku')");
          bdrel.onmouseup = new Function("checkEle(this,1,'','mu')");
          bdrel.onchange = new Function("checkEle(this,1,'','ch')");
          bdrel.onblur = new Function("hideErr(this); checkEle(this,0,'','bl')");
          bdrel.onfocus = new Function("checkEle(this,1,'','fo')");
          if (!ele.id) { checkIDCounter++; ele.id = 'AutoGenId'+checkIDCounter; }
          bdrel.setAttribute('data-man-par',ele.id);

          // set up all the radio buttons
/*          var rads = ele.form.getElementsByTagName ('input');
          if (rads) {
            for (var i = 0; i < rads.length; ++i) {
              if (rads[i].type == 'radio' && rads[i].name == ele.name) {
                ele.onkeyup = new Function("checkEle(this,1,'','ku')");
                ele.onmouseup = new Function("checkEle(this,1,'','mu')");
                ele.onchange = new Function("checkEle(this,1,'','ch')");
                ele.onblur = new Function("hideErr(this); checkEle(this,0,'','bl')");
                ele.onfocus = new Function("checkEle(this,1,'','fo')");
                ele.setAttribute('data-man-par',ele.id);
              }
            }
          }
*/
        } else {
          ele.onkeyup = new Function("checkEle(this,1,'','ku')");
          ele.onchange = new Function("checkEle(this,1,'','ch')");
          ele.onblur = new Function("hideErr(this); checkEle(this,0,'','bl')");
          ele.onfocus = new Function("checkEle(this,1,'','fo')");
        }
      }
      ele.stat = errstr;
      bdrel.style.border = '1px ridge #f00';
      bckel.style.background = 'url(assets/images/redcross2.gif) right 2px no-repeat #fff';
      if (from == 1) {
        showErr(ele);
        checkErrVal = val;
        checkErrTimer = setTimeout( "checkErrOnTimer(this)", 1000 );
        checkErrEle = ele;
      }
    }
    else if (ele.done == true) {
      bdrel.style.border = ele.oldbwid + 'px ' + ele.oldbstyle + ' ' + ele.oldbcolor;
//alert(bel.tagName+' '+bel.style.border);
      bckel.style.backgroundImage = ele.oldbgimage;
      bckel.style.backgroundColor = ele.oldbgcolor;
      hideErr(ele);
    }
  }
// document.title = ele.id+' | '+man+' | '+src+' | '+val+' | '+radval+' | '+ok+' | '+from+' | '+errstr;
  return ok;
}
function checkData(form) {
  var ok = true;
  var goto = false;
  if (form) {
    checkDataGroupData.length = 0;
    var eles = form.elements;
    for (var i=0; i<eles.length; i++) {
      var ele = eles[i];
      var res = checkEle(ele, 0, form);
      if (!res) { ok = false; if (!goto) { goto = ele; } }
    }
  }
  if (!ok) { try {  goto.focus(); } catch(err) {};  }
  return ok;
}

function checkID(el) {
  if (typeof(el) == 'string') { el = document.getElementById(el); }
  var ok = false;
  if (el) {
    ok = checkEle(el, 1, null);
    if (!ok) { try {  el.focus(); } catch(err) {};  }
  }
  return ok;
}

function checkChars(ele) {
   var str = ele.value;
   var max = ele.getAttribute('maxlength');
   var len = max -str.length;
   if (len>=0) {
      document.getElementById('noChars').innerHTML = len;
   } else {
      ele.value = str.substr(0, max)
   }
}

function roundDP(num, dp) {
  ans = num * Math.pow(10,dp)
  ans = Math.round(ans) + ""
  while (ans.length < dp+1) {ans = "0" + ans}
  len = ans.length
  ans = ans.substring(0,len-dp) + "." + ans.substring(len-dp,len)
  return ans
}

function ajaxFilter(s) {
  s = s.replace(/\n/g,'~');
  s = s.replace('#','');  // firefox and chrome will truncate the data at the point of a #
  s = s.replace('&','~and~');
  s = s.replace('£','~pnd~');
  return s;
}

function addScript(script) {
  var headID = document.getElementsByTagName("head")[0];
  var newScript = document.createElement('script');
  newScript.type = 'text/javascript';
  newScript.src = script;
  headID.appendChild(newScript);
}

var csel_id = 0;
var csel_last = '';

function cselDDClick(event, id, val) {
  var ele = document.getElementById(id);
  if (ele) {
    ele.value = val;
    selectRefresh(ele);
    if (ele.onchange) { ele.onchange(); }
  }
  popupClose('timer','');
//  document.title = document.title + 'x';
//  alert('x');

}
function selectRefresh(ele, focus) {
  // call this if selectedindex or value or the options are changed
  // ele should be the element or id of the original selector
  if (typeof(ele) == 'string') { ele = document.getElementById(ele); }
  if (ele) {
    var id = ele.id;
    var inp = document.getElementById(id+'inp');
    if (inp) {
      var txt = (ele.options.length > 0 && ele.selectedIndex > -1) ? ele.options[ele.selectedIndex].text : '';
      inp.value = txt;
      if (focus != 'draw') { selectRange(inp,0,0); }
    }
    if (ele.imgpath) {
      var img = document.getElementById(id+'img');
      if (img) {
        var bck = (ele.imgpath && txt) ? cselBackgroundUrl(ele,cselGetVal(ele.value)) : 'url()';
        img.style.backgroundImage = bck;
      }
    }
  }
  return inp;
}


function cselDDHide() {
  var ele = document.getElementById(csel_last);
  if (ele) {
    var dd = document.getElementById(csel_last+'dd');
    if (dd) {
      dd.style.display = 'none';
//document.title = document.title + ' '+dd.id+' ';
    }
    ele.dropped = false;
    ele.closedTime = Date.parse(new Date());
  }
//  document.title = document.title + 'y';
//  alert('y');
}

function cselKD(event,id) {
  event = event || window.event;
  var key = (event.keyCode ? event.keyCode : event.which);
  var shift = (event.shiftKey ? event.shiftKey : event.shiftKey);
// 0..9 with no shift, 0-9 keypad, return-13, tab-9, del-46, backspace-8, left-37, right-39, home-36, end-35
//document.title = key+'x'+shift;
//  if ((((key >= 48) && (key <= 57)) && shift!=1) || ((key >= 96) && (key <= 105)) || (key == 13) || (key == 8) || (key == 9) || (key == 46) || (key == 39) || (key == 37) || (key == 35) || (key == 36))
  res = false;
  newval = false;
  if (key == 13) { cselDDHide(); }
  if (key == 9) { res = true;  cselDDHide(); }
  if ((((key >= 48) && (key <= 57)) && shift!=1) || ((key >= 96) && (key <= 105)) || ((key >= 65) && (key <= 90))) {
//document.title = key+'x'+shift+'x'+String.fromCharCode(key);
    var ele = document.getElementById(id);
    if (ele) {
      var i = ele.selectedIndex+1; if (i >= ele.options.length) { i = 0; }
      while (i != ele.selectedIndex && i < ele.options.length) {
//document.title = document.title  + 'z'+i+' ';
        if (ele.options[i].value && ele.options[i].text.toUpperCase().charAt(0) == String.fromCharCode(key)) {
          ele.selectedIndex = i;
          newval = true;
          break;
        }
        i++; if (i >= ele.options.length) { i = 0; }
      }
    }
  }
  if (key == 40 || key == 38) {
    var ele = document.getElementById(id);
    if (ele) {
      if (key == 38) {
        ele.selectedIndex = (ele.selectedIndex > 0 ? ele.selectedIndex-1 : ele.selectedIndex);
      }
      if (key == 40) {
        ele.selectedIndex = (ele.selectedIndex < ele.options.length-1 ? ele.selectedIndex+1 : ele.selectedIndex);
      }
      newval = true;
    }
  }
  if (key == 27) { cselDDHide(); }

  if (newval) {
    if (ele.onchange) { ele.onchange(); }
    var inp = selectRefresh(ele);
    if (inp) { selectRange(inp,0,1); }
  }
  event.returnValue = res;
  return res;
}

function selectRange(ele, iStart, iLength) {
  if (typeof(ele) == 'string') { ele = document.getElementById(ele); }
  if (ele.createTextRange) {
      var oRange = ele.createTextRange();
      oRange.moveStart("character", iStart);
      oRange.moveEnd("character", iLength - ele.value.length);
      oRange.select();
  }
  else if (ele.setSelectionRange) {
      ele.setSelectionRange(iStart, iLength);
  }
}

function cselFocus(id) {
  var ele = document.getElementById(id+'inp');
  if (ele) { selectRange(ele,1,0);   ele.focus(); }
}

function selectHide(ele) {
  // call this to hide a selector which may have a customSelector covering it
  // ele should be the element or id of the original selector
  if (typeof(ele) == 'string') { ele = document.getElementById(ele); }
  if (ele) {
    if (ele.dropped == undefined) {  // ele has a cover up
      ele = document.getElementById(ele.id+'div');
      ele.style.display = 'none';
    } else {
      ele.style.display = 'none';
    }
  }
}

function selectShow(ele) {
  // call this to hide a selector which may have a customSelector covering it
  // ele should be the element or id of the original selector
  if (typeof(ele) == 'string') { ele = document.getElementById(ele); }
  if (ele) {
    if (ele.dropped == undefined) {  // ele has a cover up
      ele = document.getElementById(ele.id+'div');
      ele.style.display = 'block';
    } else {
      ele.style.display = 'block';
    }
  }
}

function cselBackgroundUrl(ele,val) {
  if (ele.imgfunc) {
    var value = eval(ele.imgfunc+'(ele,val,ele.imgvars)');
  } else {
    var value = ele.imgmask.replace(/\[xx_opt\]/ig,val);
  }
  return (val ? 'url('+ele.imgpath+value+ele.imgext+')' : 'url()');
}

function cselGetVal(val) {
  // values might have | or ~ delimiters - assume first element is the part number
  if (val.indexOf('|') > -1) { val = val.split('|')[0]; }
  if (val.indexOf('~') > -1) { val = val.split('~')[0]; }
  return val;
}

function cselDD(id, xx) {
  var ele = document.getElementById(id);
  if (ele) {
    var dd = createDynamicPopup(id+'dd', false, 'cSelDD_'+xx);//, document.getElementById(id+'div') )
    if (dd) {
      var now = Date.parse(new Date());
      var justClosed = (Math.abs(now - ele.closedTime) < 100);
//document.title = document.title + ' '+ele.dropped+' ';
      if (ele.dropped || justClosed) {
        ele.dropped = false;
        dd.style.display = 'none';
      } else {
        csel_last = id;
        popupInit(cselDDHide,'!'+id+'dd');
        ele.dropped = true;
        dd.style.left = '-10000px';
        dd.style.display = 'block';

        var blanksOk = (ele.getAttribute('data-noblank') == null ? true : false);
        var s = '';
        s += '<table cellspacing="0" cellpadding="0" border="0"><tr>';
        s += '<td class="tl" style="background-position: 0 0;">';
        s += '<div id="'+id+'scrl" class="cSelDDScrl_'+ele.getAttribute('data-custom')+'" style="float:left;" >';
        s += '<ul id="'+id+'ul" style="overflow:hidden;" >';
        for (var i=0; i<ele.options.length; i++) {
          var val = cselGetVal(ele.options[i].value);
          if (val != '' || blanksOk || ele.options.length == 1) {
            var bck = ele.imgpath ? ' style="background-image:'+cselBackgroundUrl(ele,val)+'" ' : '';
            s += '<li '+bck+' onclick="cselDDClick(event,\''+id+'\',\''+ele.options[i].value+'\');" onmousemove="cselFocus(\''+id+'\');" >'+ele.options[i].text+'</li>';
          }
        }
        s += '</ul>';
        s += '</div>';
        s += '</td><td class="tr" style="background-position: right 0;"><!--x--></td>';
        s += '</tr><tr>';
        s += '<td class="bot" style=" background-position: left bottom;" ><!--x--></td>';
        s += '<td class="bot" style=" background-position: right bottom;"><!--x--></td>';
        s += '</tr></table>';

        dd.innerHTML = s;

        var div = document.getElementById(id+'div');
        var d = getBounds(div);
        var dw = wborder(div);

        var bw = d.w;
        var ul = document.getElementById(id+'ul');
        var uw = wborder(ul);
        if (ul.offsetWidth - uw > bw) { bw = ul.offsetWidth - uw; }
        ul.style.width = (bw - dw - uw)+'px';

        var lis = ul.getElementsByTagName("LI");
        if (lis.length > 0) {
          var lw = wborder(lis[0]);
          for (var i=0; i<lis.length; i++) {
            lis[i].style.width = (bw - dw - uw - lw) + 'px';
          }
        }

        var ss  = screenSize();
        var spaceabove = d.y - ss.y;
        var spacebelow = ss.y + ss.h - d.y - d.h
        if (dd.offsetHeight <= spacebelow) {
          var dt = d.y + d.h;
        }
        else if (dd.offsetHeight <= spaceabove) {
          var dt = d.y - dd.offsetHeight;
        }
        else {
          var scrl = document.getElementById(id+'scrl');
          scrl.style.overflow = 'hidden';
          scrl.style.overflowY = 'scroll';
          scrl.style.width = (ul.offsetWidth+16-uw)+'px';
//          dd.style.width = scrl.offsetWidth;
          if (spaceabove > spacebelow) {
            scrl.style.height = (spaceabove-5-hborder(scrl))+'px';
            var dt = ss.y+1;
          } else {
            scrl.style.height = (spacebelow-5-hborder(scrl))+'px';
            var dt = d.y + d.h;
          }
        }

        setZIndex(dd);
        var xofs = ele.getAttribute('selectborder') == 'Y' ? 1 : 0;

        dd.style.left = xOnPage(d.x - xofs,dd.offsetWidth) + 'px';
        dd.style.top = dt + 'px';
      }

      selectRefresh(ele);
      var inp = document.getElementById(id+'inp');
      if (inp) { selectRange(inp,0,0);   inp.focus(); }
    }
  }
}

function doCustomSelects() {
// call a timer in case other things that create selects are also on a timer
  setTimeout(new Function("doCustomSelects_c()") ,1);
}

function doCustomSelects_c() {
  var sels = document.getElementsByTagName('select');
  if (sels) {
    for (var i = 0; i < sels.length; ++i) {
      var xx = sels[i].getAttribute('data-custom');
      if (customSelectDoAll && xx == null) { xx = ''; }
      if (xx !=  null) {
        var ele = sels[i];
        var yy = sels[i].getAttribute('data-img-path');
        sels[i].imgpath = (yy ? yy : '');
        var yy = sels[i].getAttribute('data-img-ext');
        sels[i].imgext = (yy ? yy : '.gif');
        var yy = sels[i].getAttribute('data-img-mask');
        sels[i].imgmask = (yy ? yy : '[xx_option]');
        var yy = sels[i].getAttribute('data-img-func');
        sels[i].imgfunc = (yy ? yy : null);
        var yy = sels[i].getAttribute('data-img-vars');
        sels[i].imgvars = (yy ? yy : '');
        // the code expects css to exist for cSelBack_xx and cSelInput_xx

        ele.style.display = 'none';

        if (!ele.id) { csel_id++; ele.id = 'csel_'+csel_id; }
        if (ele.id == 'title') { csel_id++; ele.id = ele.id + csel_id; }
        var id = ele.id;

        if (ele.dropped == undefined) {  // dont add another if this function is called a second time
        		var divn=document.createElement('div');
        		divn.id=id+'div';
        		divn.onclick = new Function('cselDD(\''+id+'\',\''+xx+'\'); return false;');
          divn.className = 'cSelBack_'+xx;

          var txt = (ele.options.length > 0 && ele.selectedIndex > -1) ? ele.options[ele.selectedIndex].text : '';
          var html = '';
          html += '<div class="cSelBtn_'+xx+'" id="'+id+'btn">&nbsp;</div>';
          html += '<div class="cSelImg_'+xx+'" id="'+id+'img" >';
          html += '<input type="text" class="cSelInput_'+xx+'" id="'+id+'inp" value="'+txt+'" readonly onkeydown="cselKD(event,\''+id+'\')" />';
          html += '</div>';
          html += '';
          divn.innerHTML = html;

          ele.dropped = false;
        		ele.parentNode.insertBefore(divn,ele);
        }

        var div = document.getElementById(id+'div');
        var d = getBounds(div);
        var dw = wborder(div);

        // if the original select is not visible d.w will be 0.
        // You may need to re-call this function if it is made visible later
        if (d.w > 0) {
          var btn = document.getElementById(id+'btn');
          var b = getBounds(btn);

          var img = document.getElementById(id+'img');
          var iw = wborder(img);
          // error here = style problem
          img.style.width = (d.w - dw - b.w - iw-1)+'px';

          var inp = document.getElementById(id+'inp');
          var ew = wborder(inp);
          inp.style.width = (d.w - dw - b.w - iw - ew- 1) + 'px';
          inp.onfocus = ele.onfocus;
          inp.onblur = ele.onblur;

          var hasBorder = false;
          var par = ele.parentNode;
          if (par && par.className.match(/selectborder/ig)) { hasBorder = true; }
          if (par && par.className.match(/ddlborder/ig)) { hasBorder = true; }
          if (par && par.className.match(/std50border/ig)) { hasBorder = true; }
          if (hasBorder) {
            bgi = cssStyle(div,'backgroundImage');
            if (bgi && bgi != 'none') { // it has a background image so remove the selectborder border
              par.style.border = '0px solid red'; par.style.width = '100%'
            } else {
              ele.setAttribute('selectborder','Y');
            }
          }
        }
        selectRefresh(ele,'draw');
      }
    }
  }
}

function initTabHeights(tabs_id) {
  var ons = new Array();
  var tab = document.getElementById(tabs_id);
  var ht = 0;
  if (tab) {
    var margin = cssStyle(tab,'marginLeft');
    tab.style.marginLeft = '-10000px';
    var c = -1;
    var tabs = document.getElementsByTagName("LI");
    for (var i=0; i<tabs.length; i++) {
      if (tabs[i].className == 'tab') {
        c++;
        ons[c] = cssStyle(tabs[i],'display');
        tabs[i].style.display = 'block';
        if (tabs[i].offsetHeight > ht) { ht = tabs[i].offsetHeight; }
      }
    }
    var c = -1;
    for (var i=0; i<tabs.length; i++) {
      if (tabs[i].className == 'tab') {
        tabs[i].style.height = ht + 2 - hborder(tabs[i]) + 'px';
        c++;
        tabs[i].style.display = ons[c];
      }
    }
    tab.style.marginLeft = margin+'px';
  }
}

// dynamic pagers
var dynPagers = new Array();
// add the push line below to the template which needs the scroller.
// pager is the id of a div you added to the template to contain the page number links
// pages is the id of a div you put around the area to be paged
// itemclass is the class of an item on a page
// itemtype is the tagname of the items eg 'DIV' or 'LI'
// pager_layout_js is a json array in custom.js defining the layout and css to use for the page click buttons
// onPageChange is function(idx) which will be called when a page is changed
// everything is called dynPage..... so it should be easy to find
//dynPagers.push( { pager:'dynPager_2', pages:'dynPages_1', items_per_row:4, rows_per_page:2,
//   itemclass:'pressitem', itemtype:'div', pager_layout_js:dyn_pager_type_2, removeRightBorder:true, onPageChange:null });


function dynPagerExampleOnPageChange(idx) {
  var loc = dynPagers[idx].pages;
  location = '#'+loc+'top';  // jump to the top of the list (assuming you put the <a label> there)
}

function dynPagerText(idx,r1,r2) {
  var dyn_pager = dynPagers[idx];
  var pageNo = dyn_pager.pageNo;
  var pageMax = dyn_pager.pageMax;
  var pager = dyn_pager.pager_layout_js;

  var sp = '';
  if (pageNo > 1 && pager.showPrevNextArrows) { sp += pager.prevButton; } else { sp += pager.noPrevButton; }
  sp = sp.replace(/\[xx[_ ]prev_page\]/ig,pageNo-1);

  var sb = '';
  if (r1 < r2) {
    for (var j=r1; j<=r2; j++) {
      if (j == pageNo) { sb += pager.thisPage; } else { sb += pager.linkPage; }
      sb = sb.replace(/\[xx[_ ]pageno\]/ig,j);
    }
  }

  var sn = '';
  if (pageNo < pageMax && pager.showPrevNextArrows) { sn += pager.nextButton; } else { sn += pager.noNextButton; }
  sn = sn.replace(/\[xx[_ ]next_page\]/ig,pageNo-0+1);

  var s = pager.layout;
  s = s.replace(/\[xx[_ ]prev\]/ig,sp);
  s = s.replace(/\[xx[_ ]pages\]/ig,sb);
  s = s.replace(/\[xx[_ ]next\]/ig,sn);
  s = s.replace(/\[xx[_ ]base\]/ig,pager.classBaseName);
  s = s.replace(/\[xx[_ ]idx\]/ig,idx);
  return s;
}

function dynShowPager(idx) {
  var tmp = dynPagerText(idx,1,dynPagers[idx].pageMax);

  var pagers = dynPagers[idx].pager.split(',');
  for (j = 0; j < pagers.length; j++) {
    var elp = document.getElementById(pagers[j]);
    if (elp) {
      elp.style.display = 'block';
      var flot = dynPagers[idx].pager_layout_js.position == 'right' ? 'right' : 'left';
      tmp = '<div id="'+pagers[j]+'Container" style="float:'+flot+'; display:inline;">'+tmp+'</div>';
      elp.innerHTML = tmp;
      var elc = document.getElementById(pagers[j]+'Container');
      if (elc) {
        if (dynPagers[idx].pager_layout_js.position == 'center') {
          var m = elp.offsetWidth - elc.offsetWidth;
          if (m > 2) { elc.style.marginLeft = (m / 2)+ 'px'; }
        }
      }
    }
  }

  var ps = (dynPagers[idx].pageNo-1) * dynPagers[idx].pageSize;
  var pe = ps + dynPagers[idx].pageSize-1;
  var el = document.getElementById(dynPagers[idx].pages)
  if (el) {
    var c = -1;
    var divs = el.getElementsByTagName(dynPagers[idx].itemtype);
    for (var j = 0; j < divs.length; j++) {
      if (divs[j].className == dynPagers[idx].itemclass) {
        c++;
        divs[j].style.display = (c >= ps && c <= pe ? 'block' : 'none');
      }
    }
  }
}

function dynPageTo(idx,p) {
  dynPagers[idx].pageNo = p;
  dynShowPager(idx);
  if (dynPagers[idx].onPageChange) {
    dynPagers[idx].onPageChange(idx);
  }
}

function initDynPagers() {
  for (var i = 0; i < dynPagers.length; i++) {
    var el = document.getElementById(dynPagers[i].pages)
    if (el) {
      var c = 0; var l = -1;
      var divs = el.getElementsByTagName(dynPagers[i].itemtype);
      for (var j = 0; j < divs.length; j++) {
        if (divs[j].className == dynPagers[i].itemclass) {
          c++;
          l = j;
          if (dynPagers[i].removeRightBorder && (c % dynPagers[i].items_per_row) == 0) { divs[j].style.borderRightWidth = 0; }
        }
      }
      if (dynPagers[i].removeRightBorder && (l > -1)) { divs[l].style.borderRightWidth = 0; }
      dynPagers[i].pageMax = Math.floor(c / (dynPagers[i].items_per_row * dynPagers[i].rows_per_page))+1;
      if ((dynPagers[i].pageMax-1)*dynPagers[i].items_per_row * dynPagers[i].rows_per_page == c) dynPagers[i].pageMax--;
      if (dynPagers[i].pageMax > 1) {
        dynPagers[i].pageNo = 1;
        dynPagers[i].itemCount = c;
        dynPagers[i].pageSize = dynPagers[i].items_per_row * dynPagers[i].rows_per_page;
        // hide all the divs after page 1
        for (var j = dynPagers[i].pageSize; j < divs.length; j++) { if (divs[j].className == dynPagers[i].itemclass) { divs[j].style.display = 'none'; } }
        dynShowPager(i);
      }
    }
  }
}

var popOpens = new Array();
// add the push line below to your template
// turns a list of divs or p's with one class for the title and another for the main text into
// a clickable open/close list  (lolo faq page)
// container is a div around the area to be controlled
// clickclass is the class of the titles or text to be clicked
// clickedclass is the class to use when the list is opened
// openclass is the class of the items to open when the 'clickclass' above them is clicked.
//popOpens.push( { container:'popOpen1', clickclass:'faqhi', clickedclass:'faqhio', openclass:'faq', exclusiveopen:false });

function popOpenClick(thisid,idx) {
  var popOpen = popOpens[idx];

    var el = document.getElementById(popOpens[idx].container)
    if (el) {
      var open = false;
      var close = popOpens[idx].exclusiveopen;
      var nodes = el.childNodes;
      for (var j = 0; j < nodes.length; j++) {
        if ((nodes[j].className == popOpens[idx].clickclass) || (nodes[j].className == popOpens[idx].clickedclass)) {
          if (nodes[j].id == thisid) {
            var state = nodes[j].getAttribute('data-opened');
            if (state == 'open') {
              open = false; close = true;
              nodes[j].setAttribute('data-opened','closed');
              nodes[j].className = popOpens[idx].clickclass;
            } else {
              open = true; close = false;
              nodes[j].setAttribute('data-opened','open');
              nodes[j].className = popOpens[idx].clickedclass;
            }
          } else {
            open = false;
            close = popOpens[idx].exclusiveopen;
          }
        }
        if (nodes[j].className == popOpens[idx].openclass) {
          if (open) {
            nodes[j].style.display = 'block';
            nodes[j].style.height = 'auto';
            rolldown(nodes[j]);
//            nodes[j].style.display = 'block';
          } else if (close) {
            rollup(nodes[j]);
//            nodes[j].style.display = 'none';
          }
        }
      }
    }

}

function initPopOpens() {
  for (var i = 0; i < popOpens.length; i++) {
    var el = document.getElementById(popOpens[i].container)
    if (el) {
      var c = 0;
      var nodes = el.childNodes;
      for (var j = 0; j < nodes.length; j++) {
        if (nodes[j].className == popOpens[i].clickclass) {
          c++;
          var nn = nodes[j].id ? nodes[j].id : 'popo'+c;
          nodes[j].id = nn;
          nodes[j].onclick = new Function('popOpenClick(\''+nn+'\',\''+i+'\'); return false;');
          nodes[j].setAttribute('data-opened','closed');
        }
        if (nodes[j].className == popOpens[i].openclass) {
          c++;
          nodes[j].style.display = 'none';
        }
      }
    }
  }
}

function showJson_c(data,ind,lev) {
  var s = '';
  for (var xx in data) {
    if (typeof(data[xx]) == 'object' && lev < 5) {
      s += ind + '[<b>'+xx+' object</b>]<br>';
      s += showJson_c(data[xx],ind+'&nbsp;&nbsp;',lev+1);
      s += ind + '[<b>/'+xx+' object</b>]<br>';
    } else {
      try { s += ind + '<b>'+ xx + '</b>='+data[xx]+'<br>'; } catch(err) { s += 'ERROR<br>'; return; }
    }
  }
  return s;
}
function showJson(data) {
  if (typeof(data) == 'object') {
    var s = '';
    s += showJson_c(data,'',0);
    alertX(s,'',0,'','left');
  } else {
    alertX('<b>not json data</b> <br>'+data,'',0,'','left');
  }
}


// Declaring required variables
var digits = "0123456789";
// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = "()- ";
// characters which are allowed in international phone numbers
// (a leading + is OK)
var validWorldPhoneChars = phoneNumberDelimiters + "+";
// Minimum no of digits in an international phone no.
var minDigitsInIPhoneNumber = 8;

function isInteger(s)
{   var i;
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}
function innerTrim(s)
{   var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not a whitespace, append to returnString.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (c != " ") returnString += c;
    }
    return returnString;
}
function stripCharsInBag(s, bag)
{   var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function isPhone(strPhone){
//alert(strPhone);
var bracket=3
strPhone=innerTrim(strPhone)
if(strPhone.indexOf('+')>1) return false
//alert('1');
if(strPhone.indexOf('-')!=-1) bracket=bracket+1
//alert('bracket='+bracket);
//alert('(='+strPhone.indexOf('('))
if(strPhone.indexOf('(')!=-1 && strPhone.indexOf('(')>bracket) return false
var brchr=strPhone.indexOf('(')
//alert('brchr='+brchr);
//alert(')='+strPhone.charAt(brchr+3))
if(strPhone.indexOf("(")!=-1 && strPhone.charAt(brchr+3)!=')') return false
//alert('2');
if(strPhone.indexOf("(")==-1 && strPhone.indexOf(')')!=-1) return false
//alert('3');
s=stripCharsInBag(strPhone,validWorldPhoneChars);
//alert('s='+s);
//alert(s.length >= minDigitsInIPhoneNumber);
return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
}


window.onload=doLoad;
window.onunload=doUnLoad;
addLoadEvent(initPopOpens,1);
addLoadEvent(setFocusTo,500);
addLoadEvent(postLoadImages,4001);
addLoadEvent(initDynPagers,4000);
