var coloursel='';

function switchTab(div_id) { // detail page tabs
  var tabs = new Array ('r','i','s','d');
  for (var i=0; i < tabs.length; i++) {
  	 document.getElementById('tabbox'+tabs[i]).style.display = 'none';
  	 if (document.getElementById('tab'+tabs[i]).className != 'dead') { document.getElementById('tab'+tabs[i]).className = 'off'; }
  }
 	document.getElementById('tabbox'+div_id).style.display = 'block';
	 document.getElementById('tab'+div_id).className = 'on';
}

function goToDetail(id,link) {
  var el = document.getElementById(id);
  var col = el.getAttribute('data-colour')
  if (col) { col = '&coloursel='+col; }
  window.location=link+col;
}

// stock + matrix functions
var stockBoxCount=0;
var stockBoxArray = new Array;
function showStock(boxidx, id, name) {

  if (stockBoxArray[boxidx].selected) {
    var el = document.getElementById('bb_'+boxidx+'_'+stockBoxArray[boxidx].selected);
    if (el) {
      stockBoxArray[boxidx].selected = '';
      el.src = thisUrl+'assets/images/storefinder/stock.jpg';
    }
  }

  stockBoxArray[boxidx].selected = id;
  var el = document.getElementById('bb_'+boxidx+'_'+id);
  if (el) {
    el.src = thisUrl+'assets/images/storefinder/stocksel.jpg';
  }
// sitecodes is embeded in storefinder_summary.tmp and set by the asp
  var sites = sitecodes.split(';');
  var idx = stockBoxArray[boxidx].dataidx;
  for (var i=0; i<sites.length-1; i++) {
    var els = document.getElementById('shosto_'+sites[i]+'_'+boxidx);
    if (els) {
      var srec = mx_stock[idx].array[id.toUpperCase()+'|'+sites[i].toUpperCase()];
      if (srec != undefined) {
        if (srec <= 0) { els.innerHTML = 'Out of Stock'; }
        else if (srec > 5) { els.innerHTML = 'In Stock'; }
        else { els.innerHTML = 'Only '+srec+' left'; }
      } else {
        els.innerHTML = 'Out of Stock';
      }
    }
  }
}
function createShopList(boxidx, idx, matrix) {

  stockBoxArray[boxidx] = {};
  stockBoxArray[boxidx].dataidx = idx; // save link between box on screen and mx_data array
  stockBoxArray[boxidx].selected = '';  // used to remember which colour/size is selected on screen

  var el = document.getElementById('stockShops');
  if (el) {
// sitecodes is embeded in storefinder_summary.tmp and set by the asp
    var citys = citycodes.split(';');
    var sites = sitecodes.split(';');

    var s = '';
    for (i=0; i<citys.length-1; i++) {
      s += '<div class="stockCity">'+citys[i]+'&nbsp;</div>';
      s += '<div class="stockLevel" id="shosto_'+sites[i]+'_'+boxidx+'">-</div>';
    }
    el.innerHTML = s;
  }

  if (!matrix) {
    showStock(boxidx,mx_stock[idx].part,'');
  }
}

// matrix functions
function selectIt(bodyid, part, btn_id) {
// current selected style is saved on the bodyid div so that more than one can exist on the same page (maybe a quick order popup)
  var elb = document.getElementById(bodyid);
  if (elb) {
    buyCode = elb.getAttribute('data-buyCode');

    if (buyCode) {  // restore last selected
      var el = document.getElementById('bb_'+bodyid+'_'+buyCode);
      if (el) {
        el.src = el.getAttribute('data-osrc');
      }
      elb.setAttribute('data-buyCode','');
    }

    var el = document.getElementById('bb_'+bodyid+'_'+part);
    if (el) {
      elb.setAttribute('data-buyCode',part);
//      elb.setAttribute('data-buyImg',imgname);
      el.setAttribute('data-osrc',el.src);
      el.src = thisUrl+'assets/images/mtx/sizeChosen.jpg';
    }
  }

  if (btn_id) {
    var btn = document.getElementById(btn_id);
    if (btn) {
      btn.className = 'buyBtn-on';
    }
  }
}
// matrix and ddl buy button onclick handler
function buyIt(qtyid, bodyid, event, special) {
// bodyid = the id of the div holding the matrix --> that is where selectIt() saves the currently selected style
// or it is the id of the colour DDL container which holds data-idx value
  var elb = document.getElementById(bodyid);
  if (elb) {
    buyCode = elb.getAttribute('data-buyCode');
//    buyImg = elb.getAttribute('data-buyImg');
    buyStock = elb.getAttribute('data-buyStock');
    mx_data_idx = elb.getAttribute('data-idx');
    buyImg = mx_data[mx_data_idx].imagename;
    if (buyCode) {
       special = (special == undefined ? 'NOPRESEL' : special);
      
       var count = document.getElementById('matrix_buy_count');
       if (count) {
          mbc = count.value;
          if (mbc!='<elucid_mtx_count>') {
             matrix_buy_count = parseInt(mbc);
             if (matrix_buy_count>0) {
                ajaxRefresh = '';
                buySomeAjax(qtyid,buyCode, event, special, buyImg);
                matrix_buy_count--;
                document.getElementById('matrix_buy_count').value = matrix_buy_count;
             }
             updateFreeCount();
//alert(count);
             if (matrix_buy_count==0) {
                lbError = 'close now';  // force it to close, not transition
                lightBoxClose()
                closeAlertX(matrixPopupId, null);
//alert('hgere');
                location.reload (true);
             }
          }
       } else {
          ajaxRefresh = matrixAjaxRefresh; 
          buySomeAjax(qtyid,buyCode, event, special, buyImg,count);
          closeAlertX(matrixPopupId, null);
       }       	

//      if (ajaxRefresh) { closeAlertX(matrixPopupId, null); }
//      closeAlertX(matrixPopupId, null);

//      alertX('buying '+qty+' of '+buyId);
    } else {
      var kind = elb.getAttribute('data-type');
      if (kind == 'MATRIX')
        { alertX('Please select the Size and Colour you wish to buy<br />by clicking the relevent icon in the grid'); }
      else
        {
          if (buyStock-0 > 0) { alertX('Please select the Size and Colour you wish to buy<br />using the selectors'); }
           else { alertX('Please select an Item that is in stock'); }
        }
    }
  }
}

var matrix_tip_override = '';  // used for stock matrix which always says 'click to show stock'
function setTips(cs_rec,mx_data_idx, colour, size) {
  if (matrix_tip_override) {
    cs_rec.stock_btn = "inStock"
    cs_rec.stock_text = ""
    cs_rec.tooltip = matrix_tip_override+'  ('+mx_data[mx_data_idx].colours[colour].descr + ' ' +mx_data[mx_data_idx].sizes[size].descr+')';
    cs_rec.canbuy = true;
    return;
  }

  cs_rec.stock_btn = "inStock"
  cs_rec.tooltip = "Click to add this item to your basket"  // for the matrix tooltip
  cs_rec.stock_text = ""                                    // for the drop down text
  cs_rec.canbuy = false;

  if (cs_rec.stock == '-99999' || cs_rec.status == 0) {  // status of 0 logically = discontinued
    cs_rec.stock_btn = "discontinued";
    cs_rec.tooltip = "Discontinued";
    cs_rec.stock_text = "Discontinued";
  }
  else if (cs_rec.stock == '-999') {
    cs_rec.stock_btn = "noStock";
    cs_rec.tooltip = "Out of Stock";
    cs_rec.stock_text = "out of stock";
  }
  else if (cs_rec.stock-0 <= 0) {
    cs_rec.stock_btn = "noStock";
    cs_rec.tooltip = "Out of Stock";
    cs_rec.stock_text = "out of stock";
  }
  else if (cs_rec.stock_weeks-0 > 0) {
    if (cs_rec.stock_weeks > 16) { cs_rec.stock_weeks = 16; }  // max image is 16
    cs_rec.stock_btn = "soon"+cs_rec.stock_weeks;
    cs_rec.tooltip = cs_rec.stock_weeks + " weeks wait";
    cs_rec.stock_text = cs_rec.stock_weeks + " weeks wait";
    cs_rec.canbuy = true;
  }
  else if ((cs_rec.stock-0 > 0) && (cs_rec.stock-0 >= mx_data[mx_data_idx].lowstocklimit-0)) {
    cs_rec.stock_btn = "inStock";
    cs_rec.tooltip = "Click to add this item to your basket";
    cs_rec.stock_text = "in stock";
    cs_rec.canbuy = true;
  }
  else if ((cs_rec.stock-0 > 0) && (cs_rec.stock-0 < mx_data[mx_data_idx].lowstocklimit-0)) {
    cs_rec.stock_btn = "loStock";
    cs_rec.tooltip = "Stock low - click to add to your basket";
    cs_rec.stock_text = "low stock";
    cs_rec.canbuy = true;
  }
  cs_rec.tooltip += '  ('+mx_data[mx_data_idx].colours[colour].descr + ' ' +mx_data[mx_data_idx].sizes[size].descr+')';
/*
  if stock > 0 and e_status>0  then
     stock_mess = "buy"
  else
     if UCase(def_out_of_stock) = "DATE" and len(avail_date) > 0 then
       stock_mess = "available on "&avail_date
     elseif Len(def_out_of_stock)>0 then
        if stock = -99999 then
           stock_mess = def_discontinued_item
        else
           stock_mess = def_out_of_stock
        end if
     end if
  end if
*/
}
// swatch mouse functions
function showColour(ele, part, colour) {
  var el = document.getElementById('pimage');
  if (el) {
    var s = thisUrl+'products/images/large/'+part+colour+'.jpg';
    el.src = s;
    var s = thisUrl+'products/images/zoom/'+part+colour+'.jpg';
    makeZoomable('pimage', '', 'productZoomImage',s,false,'Click for Zoom Image','0,0,0,-1');
  }
}
function showColourOver(ele, part, colour) {
  var el = document.getElementById('pimage');
  if (el) {
    el.setAttribute('origname',el.src);
    var s = thisUrl+'products/images/large/'+part+colour+'.jpg';
    el.src = s;
  }
}
function showColourOut(ele) {
  var el = document.getElementById('pimage');
  if (el) {
    el.src = el.getAttribute('origname');
  }
}
// alternamte image mouse functions
function showAlt(ele, imgname) {
  var el = document.getElementById('pimage');
  if (el) {
    var s = thisUrl+'products/images/large/'+imgname;
    el.src = s;
    el.setAttribute('origname',el.src);
    var s = thisUrl+'products/images/zoom/'+imgname;
    makeZoomable('pimage', '', 'productZoomImage',s,false,'Click for Zoom Image','0,0,0,-1');
  }
}
function showAltOver(ele, imgname) {
  var el = document.getElementById('pimage');
  if (el) {
    el.setAttribute('origname',el.src);
    var s = thisUrl+'products/images/large/'+imgname;
    el.src = s;
  }
}
function showAltOut(ele) {
  var el = document.getElementById('pimage');
  if (el) {
    el.src = el.getAttribute('origname');
  }
}
function noslash(s) {
  s = s.replace('/','');
//  s = s.replace('&','');  if & is in partcode web site will crash in buyajax to stop it getting to xml
  return s;
}
/*  Matrix display functions notes
All the vars used to generate the matrix data are in showpart_mtx_main.asp and are called json_xxxxxxx
The data needed for the functions is in the following form
-- the main array -- note: it uses an array of arrays so that stock finder can use many of them on the same page
var mx_data = new Array();
mx_data[0] = {};
-- the current part and other globals
mx_data[0].template = 'LIST';
mx_data[0].part = 'B2997';
mx_data[0].swatchcount = '0';
mx_data[0].lowstocklimit = '3';
-- the features found - not used but I thought it might be useful
mx_data[0].feat = new Array();
mx_data[0].feat[0] = { 'feature':'COLOUR', 'descr':'' };
mx_data[0].feat[1] = { 'feature':'SIZE', 'descr':'' };
-- colour array
mx_data[0].colours = new Array();
mx_data[0].colours[0] = { 'sel':'BCK', 'descr':'Blue Check' };
-- sizes array
mx_data[0].sizes = new Array();
mx_data[0].sizes[0] = { 'sel':'03', 'descr':'0-3 mths' };
mx_data[0].sizes[1] = { 'sel':'12', 'descr':'1-2 yrs' };
mx_data[0].sizes[2] = { 'sel':'36', 'descr':'3-6 mths' };
mx_data[0].sizes[3] = { 'sel':'612', 'descr':'6-12 mths' };
-- the actual data for each colour/size possibility
-- the index is [colour][size] and should really match the mx_feat array unless the asp frigs it
mx_data[0].array = new Array();
mx_data[0].array[0] = new Array();
mx_data[0].array[0][0]= {  'status':'3',  'incl':'10.00',  'excl':'10.00',  'stock':'19',  'stock_weeks':'0',  'stock_date':'' };
mx_data[0].array[0][1]= {  'status':'3',  'incl':'10.00',  'excl':'10.00',  'stock':'101',  'stock_weeks':'0',  'stock_date':'' };
mx_data[0].array[0][2]= {  'status':'3',  'incl':'10.00',  'excl':'10.00',  'stock':'121',  'stock_weeks':'0',  'stock_date':'' };
mx_data[0].array[0][3]= {  'status':'3',  'incl':'10.00',  'excl':'10.00',  'stock':'98',  'stock_weeks':'0',  'stock_date':'' };
*/
function createMatrixNormal(idx, headid, bodyid, btn_id, header, special) {
  // HEADING
  //             1  2  3 ...
  // white |---| X  X  X ...
  // black [---] X  X  X ...
  // if special = 'STOCK' then the matrix cells are set to call a showstock() function as well as
  //   displaying a selection tick. -- used for the stock check page

  // add the header
  if (header && headid) {
    var el = document.getElementById(headid);
    if (el) { el.innerHTML = header; }
  }

  // create the size row with blanks in the colour name and swatch column
  var row1 = '<div class="matrixBoxSizes">';
    row1 += '<div class="colourname">&nbsp;</div><div class="colourimg">&nbsp;</div>';
    row1 += '<ul>';
      for (var i=0; i<mx_data[idx].sizes.length; i++) {
        row1 += '<li class="size">'+mx_data[idx].sizes[i].sel+'</li>';
      }
    row1 += '</ul>';
  row1 += '</div>';
  // end of size row

  // add each of the colour rows
  var row2='';
  for (var colour=0; colour<mx_data[idx].colours.length; colour++) {

    row2 += '<div class="variation" >';
      row2 += '<div class="colourname">'+mx_data[idx].colours[colour].descr+'</div>';
// swatch onclick code
      row2 += '<img class="colourimg" onclick="showColour(this,\''+mx_data[idx].part+'\', \''+noslash(mx_data[idx].colours[colour].sel)+'\');" src="'+thisUrl+'products/images/swatches/'+mx_data[idx].part+noslash(mx_data[idx].colours[colour].sel)+'.jpg" alt="'+mx_data[idx].colours[colour].descr+'" onerror="imageErr(this,\''+thisUrl+'products/images/no-swatch.jpg\');" />';
// swatch onmouseover code
//      row2 += '<img class="colourimg" onmouseover="showColourOver(this,\''+mx_data[idx].part+'\', \''+mx_data[idx].colours[colour].sel+'\');" onmouseout="showColourOut(this);" src="'+thisUrl+'products/images/swatches/'+mx_data[idx].part+mx_data[idx].colours[colour].sel+'.jpg" alt="" />';
      row2 += '<div class="buttons">';
        row2 += '<ul>';

          // note img id (bb_... is so I can identify the one selected when the customer clicks the buy button
          for (var size=0; size<mx_data[idx].sizes.length; size++) {
            setTips(mx_data[idx].array[colour][size], idx, colour, size);

            row2 += '<li class="sizebutton">';
            if (special == 'STOCK') {
              row2 += '<img src="'+thisUrl+'assets/images/storefinder/stock.jpg" id="bb_'+stockBoxCount+'_'+mx_data[idx].part+mx_data[idx].colours[colour].sel+mx_data[idx].sizes[size].sel+'" alt="'+mx_data[idx].array[colour][size].tooltip+'" title="'+mx_data[idx].array[colour][size].tooltip+'" ';
              row2 += 'onClick="showStock(\''+stockBoxCount+'\',\''+mx_data[idx].part+mx_data[idx].colours[colour].sel+mx_data[idx].sizes[size].sel+'\',\''+mx_data[idx].part+'\',event);"';
              row2 += '/>';
            } else {
//              if (mx_data[idx].array[colour][size] && mx_data[idx].array[colour][size].status > '0') {
                row2 += '<img src="'+thisUrl+'assets/images/mtx/'+mx_data[idx].array[colour][size].stock_btn+'.jpg" id="bb_'+bodyid+'_'+mx_data[idx].part+mx_data[idx].colours[colour].sel+mx_data[idx].sizes[size].sel+'" alt="'+mx_data[idx].array[colour][size].tooltip+'" title="'+mx_data[idx].array[colour][size].tooltip+'" ';
                // add the onclick handler if is is in stock
                if (mx_data[idx].array[colour][size].canbuy ) {
                  row2 += 'onClick="selectIt(\''+bodyid+'\',\''+mx_data[idx].part+mx_data[idx].colours[colour].sel+mx_data[idx].sizes[size].sel+'\',\''+btn_id+'\' ,event);" style="cursor:pointer;" ';
                }
                row2 += '/>';
//              }
            }
            row2 += '</li>';
          }
        row2 += '</ul>';
      row2 += '</div>';
    row2 += '</div>';
  }

  // add it to the page
  var el = document.getElementById(bodyid);
  if (el) {
//alert(row1+row2);
    el.innerHTML = row1+row2;
    el.setAttribute('data-type','MATRIX');
    el.setAttribute('data-idx',idx); // leave behind the idx in case the buy button needs it
  }
}

function createMatrixTable(idx, headid, bodyid, btn_id, header, special) {
  // exactly the same as createMatrixNormal but uses a table with very little styling
  // HEADING
  //             1  2  3 ...
  // white |---| X  X  X ...
  // black [---] X  X  X ...
  // if special = 'STOCK' then the matrix cells are set to call a showstock() function as well as
  //   displaying a selection tick. -- used for the stock check page

  // add the header
  if (header && headid) {
    var el = document.getElementById(headid);
    if (el) { el.innerHTML = header; }
  }

  // create the size row with blanks in the colour name and swatch column
  var row1 = '<tr class="t_matrixBoxSizes">';
    row1 += '<td class="t_colourname">&nbsp;</td><td class="t_colourimg">&nbsp;</td>';
      for (var i=0; i<mx_data[idx].sizes.length; i++) {
        row1 += '<td class="t_size" align="center" style="padding:0 5px;">'+mx_data[idx].sizes[i].descr+'</td>';
      }
  row1 += '</tr>';
  // end of size row

  // add each of the colour rows
  var row2='';
  for (var colour=0; colour<mx_data[idx].colours.length; colour++) {

    row2 += '<tr class="t_variation" >';
      row2 += '<td class="t_colourname" ><a href="" onclick="showColour(this,\''+mx_data[idx].part+'\', \''+noslash(mx_data[idx].colours[colour].sel)+'\'); return false;">'+mx_data[idx].colours[colour].descr+'</a></td>';
//      row2 += '<td class="t_colourname" >'+mx_data[idx].colours[colour].descr+'</td>';
// swatch onclick code
      row2 += '<td class="t_colourimg"><img class="t_colourimg" onclick="showColour(this,\''+mx_data[idx].part+'\', \''+noslash(mx_data[idx].colours[colour].sel)+'\');" src="'+thisUrl+'products/images/swatches/'+mx_data[idx].part+noslash(mx_data[idx].colours[colour].sel)+'.jpg" alt="'+mx_data[idx].colours[colour].descr+'" onerror="imageErr(this,\''+thisUrl+'products/images/no-swatch.jpg\');" /></td>';
// swatch onmouseover code
//      row2 += '<img class="colourimg" onmouseover="showColourOver(this,\''+mx_data[idx].part+'\', \''+mx_data[idx].colours[colour].sel+'\');" onmouseout="showColourOut(this);" src="'+thisUrl+'products/images/swatches/'+mx_data[idx].part+mx_data[idx].colours[colour].sel+'.jpg" alt="" />';

          // note img id (bb_... is so I can identify the one selected when the customer clicks the buy button
          for (var size=0; size<mx_data[idx].sizes.length; size++) {
            setTips(mx_data[idx].array[colour][size], idx, colour, size);
            row2 += '<td class="t_sizebutton" align="center"><center>';
            if (special == 'STOCK') {
              row2 += '<img src="'+thisUrl+'assets/images/storefinder/stock.jpg" id="bb_'+stockBoxCount+'_'+mx_data[idx].part+mx_data[idx].colours[colour].sel+mx_data[idx].sizes[size].sel+'" alt="'+mx_data[idx].array[colour][size].tooltip+'" title="'+mx_data[idx].array[colour][size].tooltip+'" ';
              row2 += 'onClick="showStock(\''+stockBoxCount+'\',\''+mx_data[idx].part+mx_data[idx].colours[colour].sel+mx_data[idx].sizes[size].sel+'\',\''+mx_data[idx].part+'\',event);"';
              row2 += '/>';
            } else {
              row2 += '<img src="'+thisUrl+'assets/images/mtx/'+mx_data[idx].array[colour][size].stock_btn+'.jpg" id="bb_'+bodyid+'_'+mx_data[idx].part+mx_data[idx].colours[colour].sel+mx_data[idx].sizes[size].sel+'" alt="'+mx_data[idx].array[colour][size].tooltip+'" title="'+mx_data[idx].array[colour][size].tooltip+'" ';
              // add the onclick handler if is is in stock
                if (mx_data[idx].array[colour][size].canbuy ) {
                row2 += 'onClick="selectIt(\''+bodyid+'\',\''+mx_data[idx].part+mx_data[idx].colours[colour].sel+mx_data[idx].sizes[size].sel+'\',\''+btn_id+'\' ,event);" style="cursor:pointer;" ';
              }
              row2 += '/>';
            }
            row2 += '</center></td>';
          }
    row2 += '</tr>';
  }

  // add it to the page
  var el = document.getElementById(bodyid);
  if (el) {
//alert('<table>'+row1+row2+'</table>');
    el.innerHTML = '<table class="matrixTable" cellpadding="0" cellspacing="0" border="0">'+row1+row2+'</table>';
    el.setAttribute('data-type','MATRIX');
    el.setAttribute('data-idx',idx); // leave behind the idx in case the buy button needs it
  }
}

function createMatrixAlphabet(idx, headid, bodyid, btn_id, header, special) {
  // HEADER
  // A  B  C ... M
  // X  X  X ... X
  // N  O  P ... Z
  // X  X  X ... X

  // add the header
  if (header && headid) {
    var el = document.getElementById(headid);
    if (el) { el.innerHTML = header; }
  }

  // assume either 1 size, multi colour OR 1 colour, multi size
  // set letters = to the biggest of either the mx_colour array of the mx_sizes array
  // set c1, c2, s1 and s2 to the loop sizes to use
  if (mx_data[idx].colours.length > mx_data[idx].sizes.length)
    { letters = mx_data[idx].colours;  c1 = 0; c2 = mx_data[idx].colours.length-1;    s1 = 0; s2 = 0; }
  else
    { letters = mx_data[idx].sizes;    c1 = 0; c2 = 0;    s1 = 0; s2 = mx_data[idx].sizes.length-1;  }

  var rowlen = Math.round((c2+s2+1) / 2);  // item to wrap after
//alert(rowlen+' '+c2+' '+s2);

  var row2 = '<div class="matrixAlphaBox">';
  var count = 0;
  for (var colour=c1; colour<=c2; colour++) {
  for (var size=s1; size<=s2; size++) {

    if (count > 0 && (count % rowlen == 0)) {
      // add a full width div to force the next on to a new row
      row2 += '<div class="matrixAlphaBreak">&nbsp;</div>';
    }

    setTips(mx_data[idx].array[colour][size], idx, colour, size);
    row2 += '<div class="letter" >';
      row2 += '<div class="letterName">'+letters[count].sel+'</div>';

      if (special == 'STOCK') {
        row2 += '<img src="'+thisUrl+'assets/images/storefinder/stock.jpg" id="bb_'+stockBoxCount+'_'+mx_data[idx].part+mx_data[idx].colours[colour].sel+mx_data[idx].sizes[size].sel+'" alt="'+mx_data[idx].array[colour][size].tooltip+'" title="'+mx_data[idx].array[colour][size].tooltip+'" ';
        row2 += 'onClick="showStock(\''+stockBoxCount+'\',\''+mx_data[idx].part+mx_data[idx].colours[colour].sel+mx_data[idx].sizes[size].sel+'\',\''+mx_data[idx].part+'\',event);"';
        row2 += '/>';
      } else {
        row2 += '<img src="'+thisUrl+'assets/images/mtx/'+mx_data[idx].array[colour][size].stock_btn+'.jpg" id="bb_'+bodyid+'_'+mx_data[idx].part+mx_data[idx].colours[colour].sel+mx_data[idx].sizes[size].sel+'" alt="'+mx_data[idx].array[colour][size].tooltip+'" title="'+mx_data[idx].array[colour][size].tooltip+'" ';
        // add the onclick handler if is is in stock
        if (mx_data[idx].array[colour][size].canbuy ) {
          row2 += 'onClick="selectIt(\''+bodyid+'\',\''+mx_data[idx].part+mx_data[idx].colours[colour].sel+mx_data[idx].sizes[size].sel+'\',\''+btn_id+'\' ,event);" style="cursor:pointer;" ';
        }
        row2 += '/>';
      }
    row2 += '</div>';
    count++;
  }
  }
  row2 += '</div>';

  // add it to the page
  var el = document.getElementById(bodyid);
  if (el) {
    el.innerHTML = row2;
    el.setAttribute('data-type','MATRIX');
    el.setAttribute('data-idx',idx); // leave behind the idx in case the buy button needs it
  }
}
function createMatrixBra(idx, headid, bodyid, btn_id, header, special) {
  // HEADING
  // white |---|        black |---|
  //     B  C  D ...    //     B  C  D ...
  // 32  X  X  X ...    // 32  X  X  X ...
  // 34  X  X  X ...    // 34  X  X  X ...

  // add the header
  if (header && headid) {
    var el = document.getElementById(headid);
    if (el) { el.innerHTML = header; }
  }

//frig a suitable array for bras for testing
//var bras = new Array('32B','32C','32D','34B','34C','34D','36C','36D','36D','38D','38D','40E','40E','42B','42C','42D','44B','44C','44D','46C','46D','46D','48D','48D','50E','50E');
//var numb = mx_data[idx].sizes.length;
//mx_data[idx].sizes = new Array();
//for(var i=0; i< numb; i++) { mx_data[idx].sizes[i] = { 'sel':bras[i], 'descr':bras[i] }; }

  var chests = new Array();
  var cups = new Array();
  var refa = new Array();
  var cuplen = 0;

  // split the sizes up into cups and chests and create an index of sizes => size array
//alert(idx);
//alert(mx_data[idx]);
var dd = mx_data[idx].sizes[0].sel;
//dd = '4DD';
//alert('>'+dd+'< xxx '+dd.match(/([0-9][0-9][^0-9])/));
//alert('>'+dd+'< xxx '+dd.match(/([0-9]?2)+([^0-9]?)/));
// if you get an mx_data[..] doesnt exists error here you are probably passing the wrong idx to this function
   properBraSizes = mx_data[idx].sizes.length > 0 && mx_data[idx].sizes[0].sel.match(/([0-9][0-9][^0-9])/);  // is it Num Num Alpha eg 32B

  for (var i=0; i<mx_data[idx].sizes.length; i++) {
    if (properBraSizes) {
      var chest = mx_data[idx].sizes[i].sel.substr(0,2);
      var chestname = chest;
      var cup = mx_data[idx].sizes[i].sel.substr(2,4);
    } else {
      var chest = mx_data[idx].sizes[i].sel;
      var chestname = mx_data[idx].sizes[i].descr;
      var cup = '';
    }
    refa[mx_data[idx].sizes[i].sel] = i;
    chests[chest] = { descr:chestname };
    if (cups[cup] == undefined) { cuplen++; }
    cups[cup] = '';
  }

  var row1 = '';
  for (var colour=0; colour<mx_data[idx].colours.length; colour++) {
    row1 += '<div class="matrixBraColour">';

      // add the colour name and swatch
      row1 += '<div class="variation" >';
        row1 += '<div class="colourname">'+mx_data[idx].colours[colour].descr+'</div>';
//        row1 += '<img class="colourimg" src="'+thisUrl+'products/images/swatches/'+mx_data[idx].part+mx_data[idx].colours[colour].sel+'.jpg" alt="'+mx_data[idx].colours[colour].descr+'" onerror="imageErr(this,\''+thisUrl+'products/images/no-swatch.jpg\');" />';
        row1 += '<img class="colourimg" onclick="showColour(this,\''+mx_data[idx].part+'\', \''+noslash(mx_data[idx].colours[colour].sel)+'\');" src="'+thisUrl+'products/images/swatches/'+mx_data[idx].part+noslash(mx_data[idx].colours[colour].sel)+'.jpg" alt="'+mx_data[idx].colours[colour].descr+'" onerror="imageErr(this,\''+thisUrl+'products/images/no-swatch.jpg\');" />';

      row1 += '</div>';

      row1 += '<table class="matrixBraTable" cellspacing="0" cellpadding="0">';
        // add the cup sizes line
        row1 += '<tr class="t_matrixBraLine">';
          row1 += '<td class="t_brasize">&nbsp;</td>';
          for (var cup in cups) {
            row1 += '<td class="t_bracup">'+cup+'</td>';
          }
        row1 += '</tr>';

        for (var chest in chests) {
          row1 += '<tr class="t_matrixBraLine">';
            row1 += '<td class="t_brasize">'+chests[chest].descr+'</td>';
            for (var cup in cups) {
              var size = refa[chest+cup];
              if (size == undefined) { // chest/cup combo isnt in the size array
                row1 += '<td clas="t_bracup">&nbsp;</td>';
              } else {
                setTips(mx_data[idx].array[colour][size], idx, colour, size);

                row1 += '<td class="t_bracup">';
                if (special == 'STOCK') {
                  row1 += '<img src="'+thisUrl+'assets/images/storefinder/stock.jpg" id="bb_'+stockBoxCount+'_'+mx_data[idx].part+mx_data[idx].colours[colour].sel+mx_data[idx].sizes[size].sel+'" alt="'+mx_data[idx].array[colour][size].tooltip+'" title="'+mx_data[idx].array[colour][size].tooltip+'" ';
                  row1 += 'onClick="showStock(\''+stockBoxCount+'\',\''+mx_data[idx].part+mx_data[idx].colours[colour].sel+mx_data[idx].sizes[size].sel+'\',\''+mx_data[idx].part+'\',event);"';
                  row1 += '/>';
                } else {
                  row1 += '<img src="'+thisUrl+'assets/images/mtx/'+mx_data[idx].array[colour][size].stock_btn+'.jpg" id="bb_'+bodyid+'_'+mx_data[idx].part+mx_data[idx].colours[colour].sel+mx_data[idx].sizes[size].sel+'" alt="'+mx_data[idx].array[colour][size].tooltip+'" title="'+mx_data[idx].array[colour][size].tooltip+'" ';
                  // add the onclick handler if is is in stock
                  if (mx_data[idx].array[colour][size].canbuy ) {
                    row1 += 'onClick="selectIt(\''+bodyid+'\',\''+mx_data[idx].part+mx_data[idx].colours[colour].sel+mx_data[idx].sizes[size].sel+'\',\''+btn_id+'\' ,event);" style="cursor:pointer;" ';
                  }
                  row1 += '/>';
                }
                row1 += '</td>';
              }
            }
          row1 += '</tr>';
        }

      row1 += '</table>';
    row1 += '</div>';
  }

  // add it to the page
  var el = document.getElementById(bodyid);
  if (el) {
    el.innerHTML = row1;
    el.setAttribute('data-type','MATRIX');
    el.setAttribute('data-idx',idx); // leave behind the idx in case the buy button needs it
  }
}

function createMatrixDDL(idx, ddl_1_id, ddl_2_id, btn_id, header, special) {
  // fills ddl_1_id with the colour selector and ddl_2_id with the size selector
  // eg template would be
  // <div>Colour</div> <div id="DDl1"><div>
  // <div>Size</div> <div id="DDl12><div>

  // create the colour selector or div
  if (mx_data[idx].colours.length == 1) {
    row1 = '<div class="selOneChoice">'+mx_data[idx].colours[0].descr+'</div><input type="hidden" id="'+ddl_1_id+'_choice1" name="choice1_'+idx+'" value="'+mx_data[idx].colours[0].sel+'" />';
  } else {
    row1 = '<select class="std" id="'+ddl_1_id+'_choice1" name="'+ddl_1_id+'_choice1" size="1" onChange="DDLColourChanged(this, \''+ddl_1_id+'\', \''+idx+'\', \''+btn_id+'\');">';
    row1+= '<option SELECTED value="">Choose a '+mx_data[idx].feat[0].feature+'</option>';
    for (var i=0; i < mx_data[idx].colours.length; i++) {
      var cccdd = mx_data[idx].colours[i].sel
      row1+= '<option value="'+cccdd+'">'+mx_data[idx].colours[i].descr+'</option>';
    }
    row1+= '</select>';
  }
//alert(row1);
  // add the selector ready for the sizes
  row2 = '<select class="std"" id="'+ddl_1_id+'_choice2" name="'+ddl_1_id+'_choice2" onChange="DDLSizeChanged(this, \''+ddl_1_id+'\', \''+idx+'\', \''+btn_id+'\');">';
  row2+= '</select>';

  // add it to the page
  var el = document.getElementById(ddl_1_id);
  if (el) {
    el.innerHTML = row1;
    el.setAttribute('data-type','DDL');
    el.setAttribute('data-idx',idx); // leave behind the idx in case the buy button needs it
  }
  var el = document.getElementById(ddl_2_id);
  if (el) { el.innerHTML = row2; }

  var el = document.getElementById(ddl_1_id+'_choice1');
  if (el) {

    // was a colour code was passed to the page ?
    if (coloursel && coloursel !='<elucid_coloursel>' && el.options) {
      for (var i=0; i < el.options.length; i++) {
        if (el.options[i].value.match(coloursel)) { el.value = el.options[i].value;  break; }
      }
    }

    DDLColourChanged(el, ddl_1_id, idx, btn_id);
  }
}

function DDLColourChanged(sel1, bodyid, idx, btn_id) {  // bodyid is the id of the div containing sel1
  if (!sel1) { sel1 = document.getElementById(bodyid+'_choice1'); } // sel1 is colour selector
  var sel2 = document.getElementById(bodyid+'_choice2');  // sel2 is size selector
  if (sel1 && sel1.tagName == 'SELECT') { var opt1 = sel1.selectedIndex - 1; } else { var opt1 = 0; }
  // opt1 is now the index to mx_data[idx].array[?]

  var sval = sel2.value;

  sel2.options.length = 0;
  sel2.options[0]=new Option("Choose a SIZE",'');
  
  var sopt = -1;
  if (opt1 > -1) {
    for (var i=0; i<mx_data[idx].sizes.length; i++) {
//      if (mx_data[idx].array[opt1][i] && mx_data[idx].array[opt1][i].status > '0') {
        if (sval == mx_data[idx].sizes[i].sel) { sopt = i; }
        setTips(mx_data[idx].array[opt1][i], idx, opt1, i);

        var txt = mx_data[idx].sizes[i].descr + '    (' + mx_data[idx].array[opt1][i].stock_text+')';
        sel2.options[sel2.options.length]=new Option(txt, mx_data[idx].sizes[i].sel);
//      }
    }
  }
  
  if (sopt > -1) { sel2.selectedIndex = sopt+1; sel2.value = sval; } else { sel2.selectedIndex = 0 }
  if (sel1.value && sel2.options.length == 1) { sel2.options[0].text = 'No sizes in Stock'; }

  DDLSizeChanged(sel2, bodyid, idx, btn_id);
}

function DDLSizeChanged(sel2, bodyid, idx, btn_id) { // sel2 is size selector, bodyid is the id of the div containing the colour selector
  var sel1 = document.getElementById(bodyid+'_choice1');  // sel1 is colour selector
  var opt1 = (sel1.tagName == 'SELECT' ? sel1.selectedIndex-1 : 0);
  var val1 = sel1.value;

  var opt2 = sel2.selectedIndex-1;  // this makes 'choose a size' = -1
  var val2 = sel2.value;

  var stock = (opt1 > -1 && opt2 > -1 ? mx_data[idx].array[opt1][opt2].stock : 0);
  var buyCode = (val2 && stock > 0 ? mx_data[idx].part + val1 + val2 : '');
  var elb = document.getElementById(bodyid);
  if (elb) {
    elb.setAttribute('data-buyCode',buyCode);
    elb.setAttribute('data-buyStock',stock);
  }

//  alert(buyCode+'zz'+opt+'yy'+val+'xx');
  if (btn_id) {
    var btn = document.getElementById(btn_id);
    if (btn) {
      btn.className = (opt2 > -1 && stock > 0 ? 'buyBtn-on' : 'buyBtn');
    }
  }
}
var winno = 0;
function emailfriend(what,wd,ht) {
   if (wd=="") {wd=600};
   if (ht=="") {ht=500};
  	var a = thisUrl+"email_a_friend.asp?part="+what
  	var b = "emailwin";
  	var c = "width="+wd+",height="+ht+",resizable,scrollbars=yes"
   var w = window.open(a,b,c);
   try {
     w.focus();
//     w.moveTo(10, 10)
   }
   catch(err)
   {}
}

function imageView(what,wd,ht) {
   if (wd=="") {wd=400};
   if (ht=="") {ht=500};
  	var a = thisUrl+"imageview.asp?what="+what
   winno++;
  	var b = "picwin"+winno;
  	var c = "width="+wd+",height="+ht+",resizable,scrollbars=yes"
   var w = window.open(a,b,c);
   try {
     w.focus();
     w.moveTo(50, 50)
   }
   catch(err)
   {}
}

function orderpopup(what,w,h) {
  if (what!="") {
     var x = "width="+w+",height="+h+",resizable,scrollbars=yes";
     var win = window.open("order_details.asp?order="+what,"Details",x);
     try {
       win.moveTo(100, 100);
       win.focus();
     }
     catch(err)
     {}
  }
}

function Querystring(qs) { // optionally pass a querystring to parse
	this.params = {};

	if (qs == null) qs = location.search.substring(1, location.search.length);
	if (qs.length == 0) return;

// Turn <plus> back to <space>
// See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
	qs = qs.replace(/\+/g, ' ');
	var args = qs.split('&'); // parse out name/value pairs separated via &

// split out each name=value pair
	for (var i = 0; i < args.length; i++) {
		var pair = args[i].split('=');
		var name = decodeURIComponent(pair[0]);

		var value = (pair.length==2)
			? decodeURIComponent(pair[1])
			: name;

		this.params[name] = value;
	}
}
Querystring.prototype.get = function(key, default_) {
	var value = this.params[key];
	return (value != null) ? value : default_;
}
Querystring.prototype.contains = function(key) {
 	var value = this.params[key];
 	return (value != null);
}

function gotoPage(el,sub,link) {
  var e = el.name;
  if (el.options) {
    for (var i = 0; i < el.options.length; i++) {
       if (el.options[i].selected) var val = el.options[i].value;
    }
  } else {
    val = '1000';
  }
  if (e == 'page') {
     var j = link.indexOf('page=');
     var n = 5;
  }
  if (e == 'perpage') {
     var j = link.indexOf('perpage=');
     var n = 8;
  }
  if (j==-1) {
     var urlx = link+'&'+e+'='+val;
  } else {
     var k = link.indexOf('&',j+1);
     if (k < 0) { k = link.length; }
     var l = link.length;
     var urlx = link.substr(0,j+n)+val+link.substr(k,l-k);
  }
  el.style.display = 'none';
  location = urlx;
}

function sortByPrice(el, url) {
  var sort;
  var pp = el.length;
  if (pp>0) {
     for (i = 0; i < pp; i++) {
        if (el.options[i].selected) sort = el.options[i].value;
     }
  }
  if (!sort) { return }
  var qs2 = new Querystring(url)
  var v1 = qs2.get("sortby")
  if (v1 == null)
    { url = url+'&sortby='+sort; }
  else
    { url=url.replace('sortby='+v1,'sortby='+sort); }
  el.style.display = 'none';
  location=url;
}
