window.popupWindowOffset = 248;
window.isIE6 = false /*@cc_on || @_jscript_version <= 5.7 @*/;

function getColorTable() {
  var ret = Array();
  var main_image = document.getElementById('products_main_image');
  if (!main_image) return ret;
  var possible_image_tables = main_image.getElementsByTagName('table');
  for (var i=0; i < possible_image_tables.length; i++) {
    if (possible_image_tables[i].getElementsByTagName('td').length > 1)
      return possible_image_tables[i].getElementsByTagName('td');
  }
  return ret;
}

window.availableDressColors = Array();
window.colorDefinitions = Array();
function buildColorTable(found_colors) {
  for (var i=0; i < found_colors.length; i++) {
   var attribs = {};
   var td = found_colors[i];
   var img = td.getElementsByTagName('img')[0];
   if (img && img.alt && !img.title) img.title = img.alt;
   if (!( img && img.title )) {
     continue;
   }
   attribs['color_name'] = searchColor(img.title);
   attribs['human_color_name'] = img.title;
   if (!( img.onclick && img.onclick.toString() )) {
     continue;
   }
   if (window.isIE6) attribs['img'] = img.onclick.toString().split("'")[1];
   else attribs['img'] = img.onclick.toString().split('\"')[1];
   var primary_color_field = document.getElementById('available_colors_Colors');
   if (!primary_color_field) primary_color_field = document.getElementById('available_colors_Bodice_Colors');
   if (primary_color_field) img.onclick = mkColorChangeFun(attribs['color_name'], primary_color_field);

   preloadImage(attribs['img']);
   attribs['color_hex'] = td.getAttribute('bgcolor');
   window.availableDressColors.push(attribs);
  }
  return true;
}

function setBackground(elem, bg) {
  if (!bg) return;
  if (bg.substr(0,1) == '#') {
    elem.style.backgroundColor = bg;
    elem.style.backgroundImage =  '';
  } else {
    elem.style.backgroundImage =  "url('../../../../colors/" + bg + "')";
    elem.style.backgroundPosition = '0 0';
    elem.style.backgroundColor = 'transparent';
  }
}

function getColorTableFromDiv() {
  var color_defs = document.getElementById('color_definitions');
  if (!color_defs) return;
  color_defs = color_defs.getElementsByTagName('div');
  for (var i=color_defs.length-1 ; i >= 0; i--) {
    var colors = color_defs[i].getElementsByTagName('input');
    var p = Array();
    for (var j=colors.length-1; j >= 0; j--) p.push({'color_name' : colors[j].name,
                                                     'color_hex' : colors[j].value
						   });
    window.colorDefinitions.push({'fabric' : (color_defs[i].className ? color_defs[i].className : 'default'),
                                  'colors' : p});
  }
}

function getCurrentFabric() {
  var cf = document.getElementById('currentFabric');
  if (cf) return cf.value;
  var fs = document.getElementById('fabric_selector');
  if (fs) {
    var sel = fs.parentNode.getElementsByTagName('select');
    if (sel && sel[0]) return sel[0].options[sel[0].selectedIndex].innerHTML;
  }
  return 'default';
}

function searchColor(color) {
  return color.toLowerCase().replace(/gray/g, 'grey').replace(/ /g, '');
}

function getColorInfo(c) {
  var search = searchColor(c);
  if (search == 'solid/sameasskirt') return {
    'color_name' : 'solid/sameasskirt',
    'color_hex' : '#fff'
  };
  for (var i= window.availableDressColors.length-1; i>= 0; i--) {
    if (search == window.availableDressColors[i]['color_name']) return window.availableDressColors[i];
  }
  for (var i=window.colorDefinitions.length-1; i >= 0; i--) {
    if (window.colorDefinitions[i].fabric == getCurrentFabric()) {
      for (var j = window.colorDefinitions[i].colors.length-1; j >= 0; j--) {
        if (searchColor(window.colorDefinitions[i].colors[j].color_name) == search) {
	  return window.colorDefinitions[i].colors[j];
	}
      }
    }
  } 
  for (var i=window.colorDefinitions.length-1; i >= 0; i--) {
    if (window.colorDefinitions[i].fabric == 'default') {
      for (var j = window.colorDefinitions[i].colors.length-1; j >= 0; j--) {
        if (searchColor(window.colorDefinitions[i].colors[j].color_name) == search) {
	  return window.colorDefinitions[i].colors[j];
	}
      }
    }
  } 
  return false;
}

function toggleSelects(hide) {
  if (!window.isIE6) return;
  var newState = hide ? 'hidden' : '';
  var productOptions = document.getElementById('productsOptions');
  var selectsToHide = productOptions ? productOptions.getElementsByTagName('select') : Array();
  for ( var i=selectsToHide.length-1; i >= 0; i--) {
    selectsToHide[i].style.visibility=newState;
  }
}

function mkFloatingDiv(template) {
  var cover = document.createElement('div');
  cover.id = "windowCover";
  var mask = document.createElement('div');
  if (!window.isIE6) mask.id = "windowMask";
  mask.style.height=document.getElementById('wrapper').offsetHeight + 'px';
  cover.style.top = windowScroll().y + 'px';

  document.body.appendChild(mask);
  var w = document.createElement('div');
  w.id = "innerWindow";
  cover.appendChild(w);
  var wh = pi(windowSize().height);
  w.style.height = (wh - 100) + 'px';
  w.style.width="575px";
  document.getElementById('popupTemplates').removeChild(template);
  w.appendChild(template);
  var pe = getElementsByClassName('primary_element', '', w);
  pe = pe.length ? pe[0] : false;
  if (pe) {
    pe.style.height = (wh - window.popupWindowOffset) + 'px';
  }
  document.body.appendChild(cover);
  toggleSelects(true); 
  return false;
}

function hideFloatingDiv() {
  var cover = document.getElementById('windowCover');
  if (!cover) return;
  document.body.removeChild(cover);
  var mask = document.getElementById('windowMask');
  if (mask) document.body.removeChild(mask); 
  var template = cover.firstChild.firstChild;
  cover.firstChild.removeChild(template);
  document.getElementById('popupTemplates').appendChild(template);
  cover.innerHTML = '';
  toggleSelects(false); 
  return false;
}

function mkColorChangeFun(color_name, ac) {
  if (color_name) return function() {
    selectColor(color_name, ac);
    colorSelectorChanged(ac); 
    hideFloatingDiv(); 
    var hc;
    while(hc = document.getElementById('hover_color')) {
      document.body.removeChild(hc);
    }
  };
  return function() {
    var hc;
    while(hc = document.getElementById('hover_color')) {
      document.body.removeChild(hc);
    }
    colorSelectorChanged(ac); 
  };
}

function mkUnhoverColor(t, color) {
  return function() {
    var hc;
    while(hc = document.getElementById('hover_color')) {
      document.body.removeChild(hc);
    }
  }
}

function getOffset(o) {
 if (!o) return {'top' : 0, 'left' : 0};
 var py = o.scrollTop ? o.scrollTop : 0;
 var px = o.scrollLeft ? o.scrollLeft : 0;

 var l = o.offsetLeft - px;
 var t = o.offsetTop - py;
 var p = getOffset(o.offsetParent);
 return { 'top' : t+p.top,
          'left' : l+p.left
	};
}

function mkHoverColor(t, color) {
  if (!document.getElementById('hover_color')) {  
  return function() {
    var offset = getOffset(t);
    var hoverColor = document.createElement('div');
    hoverColor.id = 'hover_color';
    hoverColor.className = 'hoverColor';
    var cf = document.getElementById('color_list_filler');
    var py = (cf && cf.scrollTop) ? cf.scrollTop : 0;
    var px = (cf && cf.scrollLeft) ? cf.scrollLeft : 0;
    hoverColor.style.left= offset.left + 30 - px + 'px';
    hoverColor.style.top= offset.top + 30 - py + 'px';
    setBackground(hoverColor, color);
    document.body.appendChild(hoverColor);
  };
  }
}

function mkColorTemplate(colorTemplate, c, ac) {
  var ct = colorTemplate.cloneNode(true);
  var info = getColorInfo(c);
  if (info === false) {
    //alert('could not find color info for ' + c);
    return false;
  }
  ct.className = 'colorThumbnailTemplate';
  var thumb = getElementsByClassName('color_thumbnail', '', ct)[0];
  if (info['color_hex'].substr(0,1) != '#') thumb.style.width="50px";
  setBackground(thumb, info['color_hex']);
  thumb.onclick = mkColorChangeFun(info['color_name'], ac);
  thumb.onmouseover = mkHoverColor(thumb, info['color_hex']);
  thumb.onmouseout = mkUnhoverColor(thumb, info['color_hex']);
  var l = getElementsByClassName('color_name', '', ct)[0];
  l.innerHTML = c;
  if (info['color_hex'].substr(0,1) != '#') l.style.width="110px";
  return ct;
}

function selectColor(colorName, ac) {
  var cs = ac.parentNode.getElementsByTagName('select')[0];
  colorName = searchColor(colorName); 
  for (var i=cs.options.length-1; i > 0; i--) {
    if (searchColor(cs.options[i].innerHTML) == colorName) break;
  }
  if (i == 0 && colorName.replace('/', '' != colorName)) return selectColor(colorName.substring(0, colorName.indexOf('/')), ac);
  cs.selectedIndex = i;
}

function colorSelectorChanged(ac) {
  var cs = ac.parentNode.getElementsByTagName('select')[0];
  var sel = cs.options[cs.selectedIndex].innerHTML;
  var info = getColorInfo(sel);
  if (info === false) return; 
  if (info.img) document.main.src = info['img'];
  setBackground(getElementsByClassName('color_preview', '', cs.parentNode.parentNode)[0], info['color_hex']);
  getElementsByClassName('color_preview', '', cs.parentNode.parentNode)[0].style.borderColor='black';
  getElementsByClassName('color_preview', '', cs.parentNode.parentNode)[0].style.width = (info['color_hex'].substr(0,1) != '#') ? "50px" : "25px";
}

function mkColorPalette(colorTemplate, colors, color_names_field) {
  var maxCols = parseInt(document.getElementById('colorPaletteCols').value);
  var color_list = document.getElementById('color_list');
  color_list.innerHTML = '';
  var color_row;
  offset = 0;
  for (var i=0; i < colors.length; i++) {
    var c = colors[i];
    var colorCol = mkColorTemplate(colorTemplate, c, color_names_field);
    if (colorCol === false) {
      offset++;
      continue;
    }
    if ((i - offset) % maxCols == 0) {
      if (color_row) {
        var br = document.createElement('br');
        br.className = "clearBoth";
        color_row.appendChild(br);
      }
      color_row = document.createElement('li');
      color_list.appendChild(color_row);
    }
    color_row.appendChild(colorCol);
  }
}

function popupDiv(l) {
  var template;
  var customOffset = 0;
  switch(l.toLowerCase()) {
    case 'colors':
    case 'sash_colors':
    case 'top_colors':
    case 'bodice_colors':
    case 'trim_colors':
    case 'underlay_colors':
    case 'lace_colors':
    case 'lining_colors':
    case 'top_trim_colors':
    case 'jacket_colors':
    case 'shawl_colors':
    case 'skirt_colors':
    case 'net_colors':
    case 'satin_colors':
    case 'french_satin_colors':
    case 'chiffon_colors':
    case 'ribbon_colors':
    case 'flower_colors':	
    case 'overlay_colors':	
    case 'bow_colors':	
    case 'tulle_colors':	
      var ac = document.getElementById('available_colors_' + l);
      if (ac) generateColorPopup(ac);
      template = document.getElementById('colorPopupTemplate');
    break;
    
    case 'sizes':
    case 'top_sizes':
    case 'skirt_sizes':
    case 'jacket_sizes':
    case 'pants_sizes':
    case 'all_sizes':
      setupSizes(l);
      template = document.getElementById('sizePopupTemplate');
      customOffset = 57; 
    break; 
  }
  window.popupWindowOffset += customOffset;
  if (template) mkFloatingDiv(template);
  window.popupWindowOffset -= customOffset;
}
function setupColors() {
  var color_table = getColorTable();
  if (color_table.length) buildColorTable(color_table);
  getColorTableFromDiv();
}

function generateColorPopup(available_colors) {
  var colors = available_colors.value.split(',');
  var colorTemplate = document.getElementById('colorThumbnailTemplate');
  if (colorTemplate) mkColorPalette(colorTemplate, colors, available_colors);
}

function mkHighlight(row) {
  return function() {
    var cells = cellsForRow(row);
    for (var i=cells.length-1; i >= 0; i--) cells[i].style.backgroundColor="#d3e3fd";
  }
}
function mkUndoHighlight(row) {
  return function() {
    var cells = cellsForRow(row);
    for (var i=cells.length-1; i >= 0; i--) cells[i].style.backgroundColor="";
  }
}
function mkSizeClicker(sizeName, index, undoHighlight) {
return function() {
	  if (typeof(window.sizeSelector)=='function') window.sizeSelector(index);
	  else window.sizeSelector.selectedIndex = index;
	  undoHighlight();
	  hideFloatingDiv();
	};
}

function cellsForRow(tr) {
  var out = Array();
  for (var i=0; i < tr.childNodes.length; i++) if ((tr.childNodes[i].nodeType == 1) && (tr.childNodes[i].tagName == 'TD' || tr.childNodes[i].tagName == 'TH'))
    out.push(tr.childNodes[i]);
  return out;
}

function splitHeaderIfExists(table) {
  var rows = table.getElementsByTagName('tr');
  var headings = cellsForRow(rows[0]);
  var headingText = Array();
  if (headings.length - 1 == cellsForRow(rows[1]).length) {
    for (var i=headings.length-1; i >= 0; i--) if (headings[i].rowSpan != 1) {
      rows[0].removeChild(headings[i]);
      return headings[i].innerHTML;
    }
  }
  if (headings.length != cellsForRow(rows[1]).length) {
    for (var i=0; i < headings.length; i++) if (trim(innerText(headings[i]))) headingText.push(innerText(headings[i]));
    table.getElementsByTagName('tbody')[0].removeChild(rows[0]);
    return headingText.join(' &amp; ');
  }
}

function getSizeIndex(indices, sizeName) {
  sizeName = trim(sizeName).toLowerCase();
  if (typeof(indices[sizeName]) != 'undefined') return indices[sizeName];
  sizeName = sizeName.split('/');
  for ( var i=sizeName.length-1; i >= 0; i--) {
    var sn = trim(sizeName[i]).toLowerCase();
    if (typeof(indices[sn]) != 'undefined') return indices[sn];
  }
}

function removeRow(table, row) {
  if (!table) return;
  var tb = table.getElementsByTagName('tbody')[0];
  if (tb) tb.removeChild(row);
}

function setupSizes(l) {
  var sizeSelectorIndexForSize = {};
  if (l != 'all_sizes') {
    var as = document.getElementById('available_sizes_' + l);
    window.sizeSelector = as ? as.parentNode.getElementsByTagName('select')[0] : false;
    var sizes = as.value.split('|');
    for (var i=sizes.length-1; i >= 0; i--) {
      sizeSelectorIndexForSize[trim(sizes[i].split(' ')[0]).toLowerCase()] = i;
    }
  } else {
    var ass = getElementsByClassName('available_sizes');
    for (var l=0; l < ass.length; l++) {
      var sizes = ass[l].value.split('|');
      var sizeName;
      for (var i=sizes.length-1; i >= 0; i--) {
        sizeName = trim(sizes[i].split(' ')[0]).toLowerCase();
        if (typeof(sizeSelectorIndexForSize[sizeName]) == 'undefined') {
	   sizeSelectorIndexForSize[sizeName] = Array();
           sizeSelectorIndexForSize[sizeName].push(i);
	}
      }
    }
    window.sizeSelectorIndeces = sizeSelectorIndexForSize;
    window.sizeSelector = function(indeces) {
      var ss = getElementsByClassName('available_sizes');
      for (var i=0; i < ss.length; i++) ss[i].parentNode.getElementsByTagName('select')[0].selectedIndex = indeces[i];
    };
  }
  var st = document.getElementById('size_chart_meterics');
  if (!st || !window.sizeSelector) return;
  var tables = st.getElementsByTagName('table');
  for (var i=tables.length-1; i >= 0; i--) {
    var oldHeading = splitHeaderIfExists(tables[i]);
    if (oldHeading) getElementsByClassName('size_table_heading')[0].innerHTML = oldHeading;
    var rows = tables[i].getElementsByTagName('tr');
    for (var j=rows.length-1; j > 0; j--) {
      cols = cellsForRow(rows[j]);
      if (!cols.length) continue;
      var sizeName = cols[0].innerHTML;
      if (typeof(getSizeIndex(sizeSelectorIndexForSize, sizeName)) == 'undefined') {
        removeRow(tables[i], rows[j]);
        continue;
      }
      for (var k=cols.length-1; k >= 0; k--) {
        cols[k].onmouseover = mkHighlight(rows[j]);
        cols[k].onmouseout = mkUndoHighlight(rows[j]);
	cols[k].onclick = mkSizeClicker(sizeName, getSizeIndex(sizeSelectorIndexForSize, sizeName), mkUndoHighlight(rows[j]));
	if (k > 0) {
          var impData = document.createElement('input');
	  impData.type="hidden";
	  impData.name="hidv";
          impData.value=cols[k].innerHTML;
	  cols[k].appendChild(impData);
	}
      }
    }
  }
}
function entitiesToNum(d) {
  d = d.replace('&frac12;', '.5');
  d = d.replace('&frac14;', '.25');
  d = d.replace('&frac34;', '.75');
  return trim(d);
}

function numToEntities(d) {
  d = '' + d;
  d = d.replace('.5', '&frac12;');
  d = d.replace('.25', '&frac14;');
  d = d.replace('.75', '&frac34;');
  return d;
}

function dataConvert(data, factor) {
  data = parseFloat(entitiesToNum(data));
  data = Math.round(data * factor * 4) / 4;
  if (factor < 1) return numToEntities(data);
  return data;
}
function unitConvert(metric) {
  var st = document.getElementById('size_chart_meterics');
  if (!st || !window.sizeSelector) return;
  var tables = st.getElementsByTagName('table');
  for (var i=tables.length-1; i >= 0; i--) {
    var rows = tables[i].getElementsByTagName('tr');
    for (var j = rows.length-1; j > 0; j--) {
      var cells = cellsForRow(rows[j]);
      for (var k=cells.length-1; k > 0; k--) {
        var cells_k_data = cells[k].getElementsByTagName('input');
	var impData = cells_k_data[0];
	cells[k].removeChild(impData);
	cells_k_data = metric ? dataConvert(impData.value, 2.54) : impData.value;
	cells[k].innerHTML = cells_k_data;
	cells[k].appendChild(impData);
      }
    }
  }
}

function setupSelectors() {
  var ac = getElementsByClassName('available_colors');
  for (var i=ac.length-1; i >= 0; i--) {
    var cs = ac[i] ? ac[i].parentNode.getElementsByTagName('select')[0] : false;
    if (cs) {
      cs.onchange = mkColorChangeFun('', ac[i]);
      //cs.onchange();
    }
  }
}
function mkColorNameClick(c) {
  var colorType = c.parentNode.childNodes[0].innerHTML.split(':')[0].replace(/ /g, '_');
  var ac = document.getElementById('available_colors_' + colorType);
  if (!ac) return function() {
    alert('I cannot find this color type (' + colorType + ')');
  }
  return mkColorChangeFun(c.innerHTML, ac);
}

function mkColorNameHover(c) {
  var d = document.getElementById('colorPreviewSquare');
  var offset = getOffset(c);
  var info = getColorInfo(c.innerHTML);
  return function() {
    setBackground(d, info.color_hex);
    d.style.top = offset.top + 25 + 'px';
    d.style.left = offset.left + 15 + 'px';
    d.style.display = "";
  };
}

function mkColorNameUnHover() {
  var d= document.getElementById('colorPreviewSquare');
  if (d)
    d.style.display="none";
}

function setupColorNameHovers() {
  var colorNames = getElementsByClassName('colorName');
  for (var i=colorNames.length-1; i >= 0; i--) {
    var c = colorNames[i];
    c.onclick = mkColorNameClick(c);
    c.onmouseover = mkColorNameHover(c);
    c.onmouseout = mkColorNameUnHover;
  }
}
function setActiveTab(id) {
  var tabBars = getElementsByClassName('popupTabs')[0];
  var tabs = tabBars.getElementsByTagName('li');
  for (var i = tabs.length-1; i >= 0; i--) {
    if (i == id) tabs[i].className='active';
    else tabs[i].className = '';
  }
}

function doMetric() {
  document.getElementById('size_guide').style.display="none";
  document.getElementById('size_chart_meterics').style.display="";
  if (!window.metric) unitConvert(1);
  window.metric = true;
  setActiveTab(1);
}
function doSAE() {
  document.getElementById('size_guide').style.display="none";
  document.getElementById('size_chart_meterics').style.display="";
  if (window.metric) unitConvert();
  window.metric = false;
  setActiveTab(0);
}
function doSizeGuide() {
  document.getElementById('size_guide').style.display="";
  document.getElementById('size_chart_meterics').style.display="none";
  setActiveTab(2);
}
window.metric = false;
runQueue.push(setupColors);
runQueue.push(setupSelectors);
runQueue.push(setupColorNameHovers);
