﻿// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Legacy functionality for Wholesale Search page
function initCatalog(args) { catalog.initCatalog(args); }
function initSearch() { catalog.initSearch(); }
function saveSearch() { catalog.saveSearch(); }
function search(force) { catalog.search(force); }
function next() { catalog._nav(1); }
function prev() { catalog._nav(+1); }
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
var ColorSet = new Array();
function SortNumber(a, b) { return a > b; }
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
//
// ColorValues
//
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
function ColorValues(values) { this.items = values; }
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
ColorValues.prototype._render = function (box, i) {
  return " <div class='miniColorBox" + box +
    (this.items[i].charAt(0) == '#'
    ? "' style='background-color:" + this.items[i] + "'></div>"
    : "' style='background-image:url(" + this.items[i] + ")'></div>"
    );
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
ColorValues.prototype.render = function (view) {
  var html = '';
  if (this.items) {
    if (view == 1) {
      for (var i = 0; i < this.items.length; i++) {
        html += " <div class='slice b" + this.items.length + i.toString() +
            (this.items[i].charAt(0) == '#'
            ? "' style='background-color:" + this.items[i] + "'></div>"
            : "' style='background-image:url(" + this.items[i] + ")'></div>"
            );
      }
    }
    else {
      switch (this.items.length) {
        case 1:
          html = this._render(9, 0);
          break;
        case 2:
          html = this._render(6, 0)
                + this._render(3, 1);
          break;
        case 3:
          html = this._render(3, 0)
                + this._render(3, 1)
                + this._render(3, 2);
          break;
      }
    }
  }
  return html;
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
//
// Size
//
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
function Size(x) {
  this.ID = x.V;
  this.English = x.E;
  this.Name = x.L;
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
Size.prototype.render = function (ID, i) {
  return '<div id="size' + ID + '_' + i + '" class="option" onclick="catalog.ChangeProductSize(this, \'' + ID + '\', \'' + this.English + '\', \'' + this.Name + '\')">' + this.Name + '</div>';
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
//
// color
//
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
function Color(c) {
  this.English = c.E;
  this.Name = c.L;
  this.Values = new ColorValues(c.V);
  if (this.English) {
    this.Src = this.English;
    this.Src = this.Src.replace(/ /g, '');
    this.Src = this.Src.replace(/\//g, '_');
    this.Src = this.Src.replace(/è/g, 'e');
    this.Src = this.Src.replace(/é/g, 'e');
  }
  else {
    this.Src = 'none';
  }
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
Color.prototype.render = function (ID, i, subCat, view) {
  return '<div id="' + ID + '_' + i + '" class="' + (view == 1 ? 'option' : 'miniColorBox') + '" title="'
  + this.Name
  + '" onmouseover="catalog.changeProductColor(this, \'' 
  + ID + '\', \'' 
  + subCat + '\', \''
  + this.English + '\', \''
  + this.Name + '\', ' 
  + view + ');">'
  + (view == 1 ? '<div class="box">' : '')
  + this.Values.render(view)
  + (view == 1 ? '</div>' : '')
  + '</div>';
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
//
// Product
//
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
function Product(s) {
  this.ID = s.ID;
  this.GenericCode = s.GC;
  if (s.DC) {
    this.DefaultColor = s.DC;
    this.DefaultColor = this.DefaultColor.replace(/ /g, '');
    this.DefaultColor = this.DefaultColor.replace(/\//g, '_');
    this.DefaultColor = this.DefaultColor.replace(/è/g, 'e');
    this.DefaultColor = this.DefaultColor.replace(/é/g, 'e');
  }
  else {
    this.DefaultColor = 'none';
  }
  this.UrlDefaultColor = (!!s.UD);
  this.CategoryID = s.CT;
  this.SubCategoryID = s.SU;
  this.CID = (s.CT ? s.CT + (s.SU ? '-' + s.SU : '') : '');
  this.Name = s.NM;
  this.Price = s.PR;
  this.SalePrice = s.SL;
  this.BarPack = s.sPK;
  this.BarSale = s.sSE;
  this.FiveStar = s.RT;
  this.IsNew = (s.oNW && (new Date(Date.parse(s.oNW))) > new Date());
  this.IsSale = s.oSL;
  this.Bars = s.BR;
  this.Overlays = s.OV;
  this.SizeChart = s.SC;
  if (s.sNC && ((new Date(Date.parse(s.sNC.date))) > new Date())) {
    this.BarNewColors = s.sNC.text;
  }
  if (s.CL) {
    this.Colors = new Array();
    var e;
    for (var i = 0; i < s.CL.length; i++) {
      e = s.CL[i].E;
      if (!ColorSet[e]) {
        ColorSet[e] = new Color(s.CL[i]);
      }
      this.Colors[i] = ColorSet[e];
    }
  }
  if (s.SZ) {
    this.Sizes = new Array();
    for (var i = 0; i < s.SZ.length; i++) {
      this.Sizes[i] = new Size(s.SZ[i]);
    }
  }

  this.Culture = "US";
  switch(_onlineStoreID){
    case 2: this.Culture = "EU"; break
    case 3: this.Culture = "GB"; break
    case 4: this.Culture = "CA"; break
    case 5: this.Culture = "JP"; break
    case 6: this.Culture = "CH"; break
    case 7: this.Culture = "KR"; break
    case 10: this.Culture = "MX"; break
    case 12: this.Culture = "AU"; break
    case 15: this.Culture = "BR"; break
  }
}
Product.prototype.IsLiveStore = false;
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
Product.prototype.render = function (isRetail, lang, c, cid, subCat, pathPrefix, utm) {
  var color = (this._c && this.Colors && this.Colors[this._c[0]] ? this.Colors[this._c[0]] : '');

  var link = '';
  if (isRetail) {
    link = this.ID + '.html' + (cid && cid != this.CID ? '?cid=' + cid : '');
    if (color || this.UrlDefaultColor) {
      link += (link.indexOf('.html?') < 0 ? '?c=' : '&c=')
      + escape(color ? color.English : (this.DefaultColor ? this.DefaultColor : ''));
    }
    if (link && link.length > 0 && utm) {
      if (link.indexOf('.html?') < 0) link += '?';
      link += utm;
    }
  }
  else {
    link = ('product.aspx?s=' + this.GenericCode + (cid > 0 ? '&cid=' + cid : '') + '&w='
          + (this.ID.toLowerCase() == this.GenericCode.toLowerCase() ? 0 : 1)
          + (color ? '&c=' + escape(color.English) : ''))
          ;
  }

  var bars = '';
  if (this.Bars && this.Bars.length > 0 /*&& isRetail*/) {
    for (var i = 0; i < this.Bars.length; i++) {
      bars = '<div class="bar" style="'
                + (this.Bars[0].f ? 'color:' + this.Bars[0].f + ';' : '')
                + (this.Bars[0].b ? 'background-color:' + this.Bars[0].b + ';' : '')
                + '" >' + this.Bars[0].t + '</div>'
    }
  }

  subCat = subCat.replace(' ', '-');
  var sfx = this.ID + '_' + subCat;

  return '<td class="product"><div class="cell" >'
  // Render Picture
  + '<div id="dv_'
  + sfx + '" class="image"><a id="Img_'
  + sfx + '" onclick="catalog.saveSearch();"'
  + (pathPrefix ? ' target="_blank"' : '')
  + ' href="'
  + (pathPrefix ? pathPrefix : '')
  + link + '"><img id="im_'
  + sfx + '" src="http://i.americanapparel.net/storefront/photos/grid/colorserve.asp?media='
  + this.ID + '_' + (color ? color.Src : this.DefaultColor) + '.jpg' + (isRetail ? '' : '&r=us1') + '" class="image" />'
  + (this.Overlays && this.Overlays.length > 0 //&& isRetail
    ? '<img class="slashes" src="http://i.americanapparel.net/storefront/overlays/' + this.Overlays[0] + '"/></a></div>'
    : (this.IsNew
      ? '<img class="slashes" src="http://i.americanapparel.net/storefront/images/overlays/' + lang + '/slashNew.gif"/></a></div>'
      : (this.IsSale && isRetail
        ? '<img class="slashes" src="http://i.americanapparel.net/storefront/images/overlays/' + lang + '/slashOnSale.gif"/></a></div>'
        : '</a></div>')))

  // Render colors
  + this.RenderColors(subCat)

  // Render Labels
  + '<div class="text" style="clear:both;" ><a id="Txt_'
  + sfx + '" onclick="catalog.saveSearch();" href="'
  + link + '">'
  + (this.IsLiveStore ? '' : this.GenericCode + '<br/>')
  + '<b>' + this.Name + '</b></a>'
  + bars
	+ (this.BarNewColors ? '<div class="newColorsSmall"> ' + this.BarNewColors + '</div>' : '')
	+ (this.BarPack ? '<div class="pacSmall"> ' + this.BarPack + '</div>' : '')
	+ (this.BarSale ? '<div class="seSmall"> ' + this.BarSale + '</div>' : '')
	+ (isRetail
	  ? '<div class="pricing">'
	  + (this.SalePrice
	    ? '<span class="priceSaleListing">' + this.Price + '</span>'
	    + '<span class="salePrice">' + this.SalePrice + '</span>'
	    : '<span>' + this.Price + '</span>')
	    + '</div>'
      + (this.IsLiveStore
        ? ''
        : '<img class="ratings" src="'
        + (this.FiveStar
	        ? 'http://i.americanapparel.net/storefront/ratings/images/rating_' + this.FiveStar + '.gif" />'
	        : 'http://i.americanapparel.net/storefront/ratings/images/' + lang + '/rating_notrated.gif" />'
	        )
        )
      + '</div>'
	  : '')
  // End	      
  + (c < 0 ? '</div></td>'
    : (c < 4
      ? '</div></td><td><div class="cellGap">&nbsp;</div></td>'
      : '</div></td></tr><tr><td colspan="7" style="height:8px;"></td></tr><tr>'));
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
Product.prototype.RenderColors = function (subCat, view) {
  if (this.Colors) {
    var html = '<div class="colors">';
    if (view == 1) {
      html += '<div class="label">Color: <span id="lblColor' + this.ID + '" class="assist">Please Select</span></div>';
    }
    if (this._c) {
      for (var i = 1; i < this._c.length; i++) {
        if (this._c[i] > -1) {
          html += this.Colors[this._c[i]].render(this.ID, i - 1, subCat, view);
        }
      }
    }
    else {
      for (var i = 0; i < this.Colors.length; i++) {
        html += this.Colors[i].render(this.ID, i, subCat, view);
      }
    }
    return html + '</div>';
  }
  else {
    return '';
  }
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
Product.prototype.RenderSizes = function () {
  if (this.Sizes) {
    var html = '<div class="sizes">';

    html += '<div class="label">Size: <span id="lblSize' + this.ID + '" class="assist">Please Select</span></div>'

    for (var i = 0; i < this.Sizes.length; i++) {
      html += this.Sizes[i].render(this.ID, i);
    }
    if (this.SizeChart) {
      html += '<div class="chart"><a href=\'javascript:popUpSize("http://www.americanapparel.net/sizing/size.asp?chart=' + this.SizeChart + '&region=' + this.Culture + '&lang=en");\'><img src="http://i.americanapparel.net/storefront/images/icon_ruler.gif" alt="">Size Chart</a></div>'
    }
    return html + '</div>';
    return '<div class="sizes"></div>';
  }
  else {
    return '';
  }
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
Product.prototype.RenderSpecial = function (isRetail, lang, c, cid, subCat, pathPrefix, utm) {
  var color = (this._c && this.Colors && this.Colors[this._c[0]] ? this.Colors[this._c[0]] : '');
  var link =
        (isRetail
        ? this.ID + '.html?view=1'
          + (cid > 0 ? '&cid=' + cid : '')
          + (color ? '&c=' + escape(color.English) : '')
          + (utm ? '&' + utm : '')
        : ('product.aspx?s=' + this.GenericCode + (cid > 0 ? '&cid=' + cid : '') + '&w='
          + (this.ID.toLowerCase() == this.GenericCode.toLowerCase() ? 0 : 1)
          + (color ? '&c=' + escape(color.English) : '')))
        ;

  subCat = subCat.replace(' ', '-');
  var sfx = this.ID + '_' + subCat;

  return '<td><div class="topbar"><div class="code">'
  + this.GenericCode + '</div><div class="name">'
  + this.Name + '</div></div>'
  // Render Picture
  + '<div class="sideLeft"><div id="dv_'
  + sfx + '" class="mainImage"><a id="Img_'
  + sfx + '" onclick="catalog.saveSearch();"'
  + (pathPrefix ? ' target="_blank"' : '')
  + ' href="'
  + (pathPrefix ? pathPrefix : '')
  + link + '"><img id="im_'
  + sfx + '" src="http://i.americanapparel.net/storefront/photos/detail/serve.asp?media='
  + this.ID + '_' + (color ? color.Src : this.DefaultColor) + '.jpg' + (isRetail ? '' : '&r=us1') + '" class="image" />'
  + '</a></div></div>'

  + '<div class="sideRight"><div class="details">'
  + this.RenderColors(subCat, 1)
  + this.RenderSizes()

  // Render More Views
  + '<div id="divMoreViewScroll' + this.ID + '" class="moreviews">'
    + '<a class="prevPage browse left"></a>'
    + '<div class="scrollable" id="infinite' + this.ID + '"><div class="items" id="divMoreViewScrollImages' + this.ID + '"></div></div>'
    + '<a class="nextPage browse right"></a>'
  + '</div>'
  + '<div id="divMoreViewStatic' + this.ID + '" class="moreviews">'
    + '<a class="browseOff left"></a>'
    + '<div class="scrollable"><div class="items" id="divMoreViewStaticImages' + this.ID + '"></div></div>'
    + '<a class="browseOff right"></a>'
  + '</div>'

  // End
  +'</div></div></td></tr><tr><td colspan="7" style="height:8px;"></td></tr><tr>';
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
//
// Navigation Functions
//
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
function Navigation() {
  this.Lang = 'en';
  this.ResultsSingular = '';
  this.ResultsMultiple = '';
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
Navigation.prototype._setInnerHtml = function (suffix, value) {
  var e;
  e = document.getElementById('divNaviHead' + suffix); if (e) e.innerHTML = value;
  e = document.getElementById('divNaviFoot' + suffix); if (e) e.innerHTML = value;
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
Navigation.prototype._setStyleVisibility = function (suffix, value) {
  var e;
  e = document.getElementById('divNaviHead' + suffix); if (e) e.style.visibility = value;
  e = document.getElementById('divNaviFoot' + suffix); if (e) e.style.visibility = value;
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
Navigation.prototype._setClassName = function (suffix, value) {
  var e;
  e = document.getElementById('lblNaviHead' + suffix); if (e) e.className = value;
  e = document.getElementById('lblNaviFoot' + suffix); if (e) e.className = value;
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
Navigation.prototype.update = function (index, step, total, showAll) {
  
  if (total > 0) {
    this._setInnerHtml("Count", (total > 1
    ? this.ResultsMultiple.replace('{0}', this._formatNumber(total, this.Lang)) 
    : this.ResultsSingular));

    if (total > step) {
      this._setStyleVisibility("Views", "visible");

      if (showAll) {
        this._setStyleVisibility("Pages", "hidden");
        this._setClassName("Paging", "views");
        this._setClassName("SeeAll", "");

      } else {
        this._setStyleVisibility("Pages", "visible");
        this._setClassName("Paging", "");
        this._setClassName("SeeAll", "views");


        var html = "";
        var maxPageIndex = Math.ceil(total / step) - 1;
        if (maxPageIndex > 0) {

          var numSequence = 4;
          var pageIndex = (index / step);
          html += (pageIndex == 0
                  ? '</div><div class="arrow prevOff"></div></div><div class="numb">'
                  : '</div><div class="arrow prev" onclick="catalog._nav(-1)";></div></div><div class="numb">');

          if (maxPageIndex > numSequence) {
            var min = pageIndex;
            var max = pageIndex + numSequence;
            if (max > maxPageIndex) {
              max = maxPageIndex + 1;
              min = max - numSequence;
              html += '<div class="pg" onclick="catalog.gotoPage(1);" >1</div><div class="dots">...</div>';
            }
            for (var i = min; i < max; i++) {
              html += (i == pageIndex ? '<div class="on">' : '<div class="pg" onclick="catalog.gotoPage(' + i + ');" >') + (i + 1) + '</div>';
            }
            if (max != maxPageIndex + 1) {
              html += '<div class="dots">...</div><div class="pg" onclick="catalog.gotoPage(' + maxPageIndex + ');" >' + (maxPageIndex + 1) + '</div>';
            }
          }
          else {
            for (var i = 0; i <= maxPageIndex; i++) {
              html += (i == pageIndex ? '<div class="on">' : '<div class="pg" onclick="catalog.gotoPage(' + i + ');" >') + (i + 1) + '</div>';
            }
          }

          html += (pageIndex == maxPageIndex
                  ? '</div><div class="arrow nextOff"></div>'
                  : '</div><div class="arrow next" onclick="catalog._nav(1)";></div>');
          this._setInnerHtml('Pages', html);
        }
      }

    } else {
      this._setStyleVisibility("Views", "hidden");
      this._setStyleVisibility("Pages", "hidden");
    }
  }
  scrollTo(0, 0);
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
Navigation.prototype._formatNumber = function (n, lang) {
  if (n < 1000) {
    return '' + n;
  }
  else {
    var delim = ',';
    switch (lang) {
      case 'fr': delim = '.'; break;
    }
    var text = '' + n;
    var i = text.length;
    var output = "";
    var k = 0;
    var j = -1;
    while (i > -1) {
      output += text.charAt(i);
      j++;
      if (j == 3 && i != 0) {
        output += delim;
        j = 0;
      }
      i--;
    }
    output = output.split("").reverse().join("");
    return output
  }
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
//
// Catalog
//
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
function Catalog(args) {
  this.index = 0;
  this.isRetail = true;
  this.showAll = false;
  this.showFilters = true;
  this.showSorting = true;

  this.KEY_CATEGORY = "Category";
  this.KEY_COLOR = "Color";
  this.lang = 'en';
  this.orderings = [];
  this.maps = [];
  this.defaults = [];
  this.colors = [];
  this.filter = [];
  this.attribute = [];
  this.user = { "sort": 0, "filt": [] };
  Product.prototype.IsLiveStore = (document.domain.toString().indexOf("store.americanapparel") == 0);
  var lid = 1;
  try
  {
    lid = GetCookieLanguageID();
  }
  catch(err)
  {
    lid = 1;
  }
  switch (lid) {
    case 1: this.lang = 'en'; break;
    case 2: this.lang = 'fr'; break;
    case 10: this.lang = 'es'; break;
    default: this.lang = 'en'; break;
  }
  this.nav = null;
  this.data = [];
  this.orderings = [];
  this.maps = [];
  this.categorySize = [];
  this.defaults = [];
  this.max = 0;
  this.IS_STATIC = true;
  if (args) {
    this.IS_STATIC = !args.Data;
    if (args.isRetail != undefined) this.isRetail = args.isRetail;
    if (args.lang != undefined) this.lang = args.lang;
    if (args.Max) this.max = args.Max;
    if (args.KEY_COLOR) this.KEY_COLOR = args.KEY_COLOR;
    if (args.KEY_CATEGORY) this.KEY_CATEGORY = args.KEY_CATEGORY;
    if (args.ResultsSingular && args.ResultsMultiple) {
      this.nav = new Navigation();
      this.nav.Lang = this.lang;
      this.nav.ResultsSingular = args.ResultsSingular;
      this.nav.ResultsMultiple = args.ResultsMultiple;
    }
    // Depricating Lower case - Kept for backwards compatability
    else {
      if (args.resultsSingular != undefined && args.resultsMultiple != undefined) {
        this.nav = new Navigation();
        this.nav.Lang = this.lang;
        this.nav.ResultsSingular = args.resultsSingular;
        this.nav.ResultsMultiple = args.resultsMultiple;
      }
    }
    if (args.Data && args.Data.length) {
      for (var i = 0; i < args.Data.length; i++) {
        this.data[i] = new Product(args.Data[i]);
      }
    }
    if (args.Attribute && args.Attribute.length) {
      this.attribute = args.Attribute;
    }
    if (args.Orderings && args.Orderings.length) {
      this.orderings = args.Orderings;
    }
    if (args.DefaultColors && args.DefaultColors.length) {
      this.defaults["Color"] = args.DefaultColors;
    }
    this.categoryID = args.CategoryID;
    this.showFilters = args.ShowFilters;
    this.showSorting = args.ShowSorting;
    this.categorySize = args.CategorySize;
    if (args.Maps && args.Maps.length) {
      var a, b;
      var maps;
      var type;
      var data;
      this.maps = [];
      for (var i = 0; i < args.Maps.length; i++) {
        maps = args.Maps[i];
        if (maps && maps.length > 1) {
          a = maps[0]
          type = maps[1];
          this.maps[a] = [];
          if (type && type.length) {
            for (var j = 0; j < type.length; j++) {
              if (type[j] && type[j].length > 1) {
                b = type[j][0];
                data = type[j][1];
                this.maps[a][b] = data;
              }
            }
          }
        }
      }
    }
  }
  this.utm = '';
  var domain = (document && document.domain ? document.domain.toString() : "");
  if (domain.indexOf(".com.mx") > 0
  || domain.indexOf(".com.br") > 0
  || domain.indexOf("mxn.dev.") > -1
  || domain.indexOf("brl.dev.") > -1
  || domain.indexOf("localhost") > -1
  ) {
    var hasCampaign = false;
    var utmz = getCookie("__utmz");
    if (utmz) {
      var x = utmz.split('=');
      hasCampaign = (x && x.length > 3 && x[3] != "(none)");
    }
    if (!hasCampaign) {
      var category;
      var t = document.location.toString();
      var i = t.indexOf('/', 10) + 1;
      if (i > 0) {
        t = t.substr(i);
        i = t.indexOf('.html');
        if (i > 0) {
          category = t.substr(0, i);
        }
      }
      this.utm = (category ? '&utm_source=onlinestore&utm_medium=' + category + '&utm_campaign=' + category : '');
    }
  }
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
Catalog.prototype.renderStyleGridCell = function (index) {
  var e = document.getElementById("divStyleGridCell");
  if (e) {
    var i = parseInt(index);
    e.innerHTML = (-1 < i && i < this.data.length
    ? '<div class="catalog"><div class="styles"style="width:132px;"><table cellspacing="0" cellpadding="0" border="0" class="section" style="margin:0;"><tbody><tr>'
    + this.data[i].render(this.isRetail, this.lang, 0, this.categoryID, "", null, this.utm)
    + '</tr></tbody></table></div></div>'
    : '')
    ;
  }
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
Catalog.prototype.initStyleGrid = function () {
  if (this.data && this.data.length) {
    var e;
    e = document.getElementById('pnContent');
    if (e) {
      var p;
      var hide = '<div class="catalog"><div class="styles">';
      var html = '<div class="styleGrid" style=""><ul class="grid">';
      for (var i = 0; i < this.data.length; i++) {
        p = this.data[i];
        html += '<li order="' + i + '" class="bt_grid"><a href="' + p.ID + '.html"><img src="http://i.americanapparel.net/storefront/photos/thumbnail/colorserve.asp?media=' + p.ID + '_' + p.DefaultColor + '.jpg" /></a></li>';
      }
      html += '</ul></div><div id="divStyleGridCell" style="display:none;"></div>';
      e.innerHTML = html;
    }
    e = document.getElementById('pnShowSome'); if (e) e.style.display = '';
    e = document.getElementById('pnShowNone'); if (e) e.style.display = 'none';
    e = document.getElementById('pnShowSomeSort'); if (e) e.style.display = 'none';
    this.addCriteo();

    (function () {
      if (jQuery && jQuery.bt && jQuery.bt.defaults) {
        jQuery.bt.defaults.contentSelector = function () {
          var temp = $(this);
          var index = temp.attr('order');
          catalog.renderStyleGridCell(index);
          return $('#divStyleGridCell').html();
        };
        jQuery.bt.defaults.ajaxPath = null;
      }
    })(jQuery);
    $('.bt_grid').bt();
  }
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
Catalog.prototype.CheckMoreViews = function (attempts) {
  attempts = (attempts > 0 ? attempts : 0);
  var done = true;
  if (this.MoreViews) {
    var mv;
    for (var ID in this.MoreViews) {
      eval('mv=catalog.mv' + ID);
      if (mv && mv.length > 0) {
        if (!this.MoreViews[ID]) {
          var end, src, html = '';
          for (var i = 0; i < mv.length; i++) {
            src = mv[i];
            end = src.length - 5;
            html += '<img'
                  + (src.substr(end) == 'v.jpg'
                    ? ' class="fancy" href="http://i.americanapparel.net/storefront/photos/morephotos/' + src.substr(0, end) + 'v.html"'
                    : ' onclick="javascript:return catalog.ShowMoreImages(this,\'' + ID + '\');"'
                    )
                  + ' src="http://i.americanapparel.net/storefront/photos/morephotos/' + src + '" />'
                  ;
          }
          if (mv.length < 5) {
            e = document.getElementById("divMoreViewStaticImages" + ID); if (e) e.innerHTML = html;
            e = document.getElementById("divMoreViewStatic" + ID); if (e) e.style.display = 'block';
          }
          else {
            e = document.getElementById("divMoreViewScrollImages" + ID); if (e) e.innerHTML = html;
            e = document.getElementById("divMoreViewScroll" + ID); if (e) e.style.display = 'block';
            $("#infinite" + ID).scrollable().circular();
          }
          this.MoreViews[ID] = true;
        }
      }
      else {
        done = false;
      }
    }
  }
  if (!done && attempts < 5) {
    setTimeout('catalog.CheckMoreViews(' + (attempts + 1) + ')', 500);
  }
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
Catalog.prototype.ShowMoreImages = function (img, StyleID) {
  var e = document.getElementById("im_" + StyleID + '_x');
  if (e && img.src) {
    var prefix = img.src.substr(0, img.src.length - 5);
    e.src = prefix + "d.jpg";
    //this.setFullScreen(prefix + ".jpg");
  }
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
Catalog.prototype.renderMatrix = function (products, i, max, subCat) {
  var view = parseInt(getQueryStringValue('view'));
  if (max < 0) { i = 0; max = products.length; } // Show All
  var ID, p;
  var c = 0;
  var t = 0;
  var html = '<table cellspacing="0" cellpadding="0" border="0" class="' + (view == 1 ? 'special' : 'section') + '"><tr>';
  if (!subCat) subCat = { "id": 0, "name": 'x' };
  var temp = new Array(); // Array used to stop duplicates
  var color, colorIndex = 0;
  while (i < products.length && t < max) {
    if (!temp[products[i].ID]) {
      if (!(i + 1 < products.length && t + 1 < max)) {
        c = -1;
      }
      p = products[i];
      if (view == 1) {
        this.MoreViews[p.ID] = false;
        color = null;
        colorIndex = -1;
        if (p._c && p._c[0] && p._c[0] > -1) {
          colorIndex = p._c[0];
        }
        else {
          for (var cc = 0; cc < p.Colors.length; cc++) {
            if (p.Colors[cc].Src == p.DefaultColor) {
              colorIndex = cc;
              break;
            }
          }
        }
        if (colorIndex > -1) {
          color = p.Colors[colorIndex];
          setTimeout('catalog.changeProductColor(' + colorIndex + ', "' + p.ID + '", "' + subCat.name + '", "' + color.Src + '", "' + color.Name + '", ' + view + ')', 631);
        }
        setTimeout('LoadScript("http://i.americanapparel.net/storefront/photos/morephotos/index.aspx?v=catalog.mv' + p.ID + "&s=" + p.ID + '", "utf-8");', 500);
        html += p.RenderSpecial(this.isRetail, this.lang, c
        , (this.categoryID ? this.categoryID + (subCat.id > 0 ? '-' + subCat.id : '') : '')
        , subCat.name, null, this.utm);
      }
      else {
        html += p.render(this.isRetail, this.lang, c
        , (this.categoryID ? this.categoryID + (subCat.id > 0 ? '-' + subCat.id : '') : '')
        , subCat.name, null, this.utm);
      }
      c = (c < 4 ? c + 1 : 0);
      temp[products[i].ID] = 1;
    }
    t++;
    i++;
  }
  return html + '</tr></table>';
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
Catalog.prototype.renderSections = function () {
  var html = '';
  var s, r = /[ -]/gm;
  for (var i = 0; i < this.section.length; i++) {
    s = this.section[i];
    html += '<div class="header"><span>'
        + (s.name ? s.name : '&nbsp;') + '</span>'
        + (s.name ? '<a name="' + s.name.replace(r, '') + '">&nbsp;</a>' : '')
        + '</div>'
        ;
    html += this.renderMatrix(s.items, 0, s.items.length, s);
  }
  return html;
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
//
// Filter Function
//
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
//  Pre-condition: filter[1+].length == data.length
//  data = Array of Products
/// filter[0] = Sorting Map         Ex: [[,2,4,1]] ::=show data[2],data[4],data[1]
/// filter[1] = Color Index Arrays  Ex: [,,,[2,2,4],[0,0],,]
/// filter[2+]= Boolean Filters     Ex: [,,,1,,1,11,,1,,1]
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
Catalog.prototype.mergeColors = function (array, extra) {
  var combo = 0;
  var i, j;
  if (array && array.length) {
    combo = [];
    for (i = 0; i < array.length; i++) {
      combo[i] = array[i];
    }
  }

  if (extra && extra.length) {
    if (!combo) {
      combo = [];
    }
    combo[0] = extra[0];
    var x, found;
    for (i = 1; i < extra.length; i++) {
      x = extra[i];
      found = false;
      for (j = 1; j < combo.length; j++) {
        if (combo[j] == x) {
          found = true;
          j = combo.length;
        }
      }
      if (!found) {
        combo[combo.length] = x;
      }
    }

  }
  return combo;
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
Catalog.prototype._removeColor = function (value) {
  if (this.colors) {
    var index = -1;
    for (var c = 0; c < this.colors.length; c++) {
      if (this.colors[c].id == value) {
        index = c;
        c = this.colors.length;
      }
    }
    if (index > -1) this.colors.splice(index, 1);
  }
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
Catalog.prototype.runFilters = function () {

  // Combine Filters
  var combo = new Array();
  var temp, count;

  // Sorting Map
  if (!this.order) {
    // If sorting map does not exist create one
    temp = [''];
    for (var i = 0; i < this.data.length; i++) {
      temp[i + 1] = i;
    }
    this.order = [temp];
  }

  var index = 0;
  var keys = [];
  // Combine Color Filters
  if (this.colors) {
    for (var x = 0; x < this.colors.length; x++) {
      temp = this.colors[x].value;
      if (temp) {
        keys[keys.length] = this.colors[x].id;
        for (var i = 0; i < temp.length; i++) {
          combo[i] = this.mergeColors(combo[i], temp[i]);
        }
      }
    }
    var pick;
    for (var i = 0; i < combo.length; i++) {
      if (combo[i] && combo[i].length > 2) {
        pick = combo[i][0];
        combo[i][0] = -999;
        combo[i].sort(SortNumber);
        combo[i][0] = pick;
      }
    }
  }
  this.user.filt[this.KEY_COLOR] = (keys.length > 0 ? keys : null);

  // If no Color Filter, then allow all products
  if (keys.length < 1) for (var i = 0; i < this.data.length; i++) combo[i] = 1;

  // Combine Boolean Filters
  var bools;
  var type;
  if (this.filter) {
    for (var x in this.filter) {
      type = this.filter[x];
      if (type) {

        keys = [];

        // "OR" Combine Boolean Filters by Type
        bools = [];
        for (var y in type) {
          temp = type[y];
          if (temp) {

            keys[keys.length] = y;
            for (var i = 0; i < temp.length; i++) {
              bools[i] = (bools[i] == 1 ? 1 : (temp[i] == 1 ? 1 : 0));
            }
          }
        }

        this.user.filt[x] = (keys.length > 0 ? keys : null);

        // Apply Type's Boolean Filters
        if (bools.length == combo.length) {
          for (var i = 0; i < bools.length; i++) {
            if (bools[i] != 1) {
              combo[i] = null;
            }
          }
        }

      }
    }
  }


  // Apply Combination Filter
  var s, ix, ic;
  var section = new Array();
  for (var x = 0; x < this.order.length; x++) {
    temp = [];
    for (var i = 1; i < this.order[x].length; i++) {
      ix = this.order[x][i];
      if (ic = combo[ix]) {
        s = this.data[ix];
        s._c = (ic == 1 ? '' : ic);
        temp[temp.length] = s;
      }
    }
    if (temp.length > 0) {
      s = this.order[x][0];
      section[section.length] = { "id": (s ? s.i : 1), "name": (s ? s.n : ""), items: temp }
    }
  }
  return section;

}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
Catalog.prototype.render = function (update) {
  this.MoreViews = [];

  if (update) this.section = this.runFilters();

  var total = (this.section[0] && this.section[0].items ? this.section[0].items.length : 0);
  if (this.nav) {
    if (this.showAll) {
      this.index = 0;
    }
    setCookie('aaPage', this.index, 1);
    this.nav.update(this.index, this.max, total, this.showAll);
  }

  if (this.header && this.section.length == 1) {
    this.section[0].name = this.header;
  }

  var e;
  var dvShowID = 'pnShowNone';
  var dvHideID = 'pnShowSome';
  if (this.section.length > 0) {
    e = document.getElementById('pnContent');
    if (e) {
      e.innerHTML =
            (this.section.length > 1 || this.section[0].name
            ? this.renderSections()
            : this.renderMatrix(this.section[0].items, this.index, (this.showAll ? -1 : this.max))
            );
    }
    dvShowID = 'pnShowSome';
    dvHideID = 'pnShowNone';

    this.CheckMoreViews(0);
  }
  else {
    // No results from search
    var dvNoneShowID = 'divShowNoneFromSearch';
    var dvNoneHideID = 'divShowNoneFromFilter';
    if (this.data && this.data.length > 0) {
      // No results from maps
      dvNoneShowID = 'divShowNoneFromFilter';
      dvNoneHideID = 'divShowNoneFromSearch';
    }
    e = document.getElementById(dvNoneShowID); if (e) e.style.display = '';
    e = document.getElementById(dvNoneHideID); if (e) e.style.display = 'none';
  }
  e = document.getElementById(dvShowID); if (e) e.style.display = '';
  e = document.getElementById(dvHideID); if (e) e.style.display = 'none';
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
Catalog.prototype.sort = function (x) {
  this.user.sort = (-1 < x && x < this.orderings.length ? x : 0);
  for (var i = 0; i < this.orderings.length; i++) {
    x = document.getElementById('divSort' + i); if (x) x.className = 'option';
  }
  x = document.getElementById('divSort' + this.user.sort); if (x) x.className = 'option selected';
  document.innerSearch.a.value = this.user.sort;
  this.order = this.orderings[this.user.sort];
  this.render(true);
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
Catalog.prototype.setFilter = function (e, key, value) {
  if (e) {
    if (e.options) {

      // Category + Landing pages
      value = e.options[e.selectedIndex].value;
      if (key == this.KEY_COLOR) {
        this.colors = [];
        //this.colors[value] = this.maps[key][value];
        this.colors[0] = { 'id': value, 'value': this.maps[key][value] };
      }
      else {
        this.filter[key] = [];
        this.filter[key][value] = this.maps[key][value];
      }

    }
    else {

      // Search page
      this.setFilterSearch(e, key, value);

    }
    this.index = 0;
    this.render(true);
  }
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
Catalog.prototype.setFilterSearch = function (e, key, value) {
  if (e) {
    var p = e.parentNode;
    var reset = false;
    if (e.className == "option" || e.className == "option unselected") {
      e.className = "option selected"

      for (var i = 0; i < p.children.length; i++) {
        if (p.children[i].className == "option") {
          p.children[i].className = "option unselected";
        }
      }

      if (key == this.KEY_COLOR) {
        //this.colors[value] = this.maps[key][value];
        this.colors[this.colors.length] = { 'id': value, 'value': this.maps[key][value] };
      }
      else {
        if (!this.filter[key]) this.filter[key] = [];
        this.filter[key][value] = this.maps[key][value];
      }

      e = document.getElementById("divFilter" + key + "Reset");
      if (e) e.style.display = "block";

    }
    else {
      e.className = "option unselected";

      reset = true;
      for (var i = 0; i < p.children.length; i++) {
        if (p.children[i].className == "option selected") {
          reset = false;
          break;
        }
      }

      if (reset) this.resetFilter(key);
      else {
        if (key == this.KEY_COLOR) {
          // this.colors[value] = null;
          this._removeColor(value);
        }
        else {
          this.filter[key][value] = null;
        }
      }
    }

    if (key == this.KEY_CATEGORY && this.categorySize && this.categorySize.length == p.children.length) {
      var size = [];
      for (var i = 0; i < p.children.length; i++) {
        if (p.children[i].className == "option selected") {

          for (var s = 0; s < this.categorySize[i].length; s++) {
            size[s] = (size[s] ? size[s] : this.categorySize[i][s]);
          }
        }
      }
      p = document.getElementById("divFilterSizeOptions");
      if (p && p.children) {
        if (p.children.length == size.length) {
          for (var i = 0; i < p.children.length; i++) {
            if (p.children[i].children.length > 0) {
              p.children[i].children[0].className = (size[i] ? "" : "disabled");
            }
          }
        } else {
          this.enableOptions(p);
        }
      }
    }
  }
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
Catalog.prototype.enableOptions = function (e) {
  if (e && e.children) {
    for (var i = 0; i < e.children.length; i++) {
      if (e.children[i].children.length > 0) {
        e.children[i].children[0].className = "";
      }
    }
  }
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
Catalog.prototype.resetFilter = function (key, skipUpdate) {
  var e = document.getElementById("divFilter" + key + "Reset");
  this.user.filt[key] = null;

  if (e && e.style.display != "none") {
    if (e) e.style.display = "none";
  }

  e = document.getElementById("divFilter" + key + "Options");
  for (var i = 0; i < e.children.length; i++) {
    if (e.children[i]) {
      e.children[i].className = "option";
    }
  }
  if (key == this.KEY_COLOR) {
    for (var value in this.maps[key]) {
      // this.colors[value] = null;
      this._removeColor(value);
    }
  } else {
    this.filter[key] = null;
    if (key == this.KEY_CATEGORY) this.enableOptions(document.getElementById("divFilterSizeOptions"));
  }
  if (!skipUpdate) {
    this.index = 0;
    this.render(true);
  }
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
Catalog.prototype.resetAllFilters = function () {
  for (var key in this.maps) {
    this.resetFilter(key, true);
  }
  this.index = 0;
  this.render(true);
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
Catalog.prototype.hideFilter = function (key) {
  var e = document.getElementById("divFilter" + key + "Label");
  if (e) {
    e.className = "label close";
    e = document.getElementById("divFilter" + key + "Options");
    if (e) e.style.display = "none";
  }
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
Catalog.prototype.showFilter = function (key) {
  var e = document.getElementById("divFilter" + key + "Label");
  if (e) {
    e.className = "label";
    e = document.getElementById("divFilter" + key + "Options");
    if (e) e.style.display = "";
  }
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
Catalog.prototype.showHideFilter = function (key) {
  var e = document.getElementById("divFilter" + key + "Label");
  if (e) {
    if (e.className == "label") {
      this.hideFilter(key);
    }
    else {
      e.className = "label";
      e = document.getElementById("divFilter" + key + "Options");
      if (e) e.style.display = "";
    }
  }
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
Catalog.prototype.showAllFilters = function () {
  for (var key in this.maps) {
    this.showHideFilter(key);
  }
  var e;
  e = document.getElementById("divHideAll"); if (e) e.style.display = "";
  e = document.getElementById("divShowAll"); if (e) e.style.display = "none";
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
Catalog.prototype.hideAllFilters = function () {
  for (var key in this.maps) {
    this.hideFilter(key);
  }
  var e;
  e = document.getElementById("divShowAll"); if (e) e.style.display = "";
  e = document.getElementById("divHideAll"); if (e) e.style.display = "none";
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
Catalog.prototype.ChangeProductSize = function (option, style, value, name) {
  var e;
  e = document.getElementById("lblSize" + style);
  if (e) {
    e.className = "output";
    e.innerHTML = name;
    var i = 0;
    while (e = document.getElementById("size" + style + '_' + (i++))) {
      e.className = "option";
    }
    option.className = "option picked";
  }
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
Catalog.prototype.changeProductColor = function (swatch, style, subCat, color, name, view) {
  if (swatch > -1) {
    swatch = document.getElementById(style + '_' + swatch)
  }
  var e;
  e = document.getElementById("lblColor" + style);
  if (e) {
    e.className = "output";
    e.innerHTML = name;
    var i = 0;
    while (e = document.getElementById(style + '_' + (i++))) {
      e.className = "option";
    }
    swatch.className = "option picked";
  }
  /* / Highlight Picked Color Box
  var s, i = 0;
  while (s = document.getElementById(style + '_' + (i++))) {
  s.className = "miniColorBox";
  }
  swatch.className = "miniColorBoxPicked";
  */

  // Add Color Parameter
  var ecolor = escape(color);
  ecolor = ecolor.replace(/è/g, 'e');
  ecolor = ecolor.replace(/é/g, 'e');
  var obj, ids;

  var sfx = style + '_' + subCat;

  var ids = ['Img', 'Txt'];
  for (var x = 0; x < ids.length; x++) {
    obj = document.getElementById(ids[x] + '_' + sfx);
    if (obj) {
      i = obj.href.indexOf('&c=');
      if (i > 0) {
        obj.href = obj.href.substring(0, i + 3) + ecolor;
      }
      else {
        i = obj.href.indexOf('?c=');
        if (i > 0) {
          obj.href = obj.href.substring(0, i + 3) + ecolor;
        }
        else {
          if (obj.href.indexOf('.html?') > 0 || obj.href.indexOf('.aspx?') > 0) {
            obj.href = obj.href + '&c=' + ecolor;
          }
          else {
            obj.href = obj.href + '?c=' + ecolor;
          }
        }
      }
    }
  }

  // Change Image
  color = color.replace(/ /g, '');
  color = color.replace(/\//g, '_');
  color = color.replace(/è/g, 'e');
  color = color.replace(/é/g, 'e');

  var iurl = "http://i.americanapparel.net/storefront/photos/" + (view == 1 ? "detail/" : "grid/color") + "serve.asp?media=" + style + "_" + color + ".jpg" + (this.isRetail ? '' : '&r=us1');
  if (view > 0) {
    obj = document.getElementById('im_' + sfx); if (obj) obj.src = iurl;
    obj = document.getElementById('dv_' + sfx); if (obj) obj.backgroundImage = 'url(' + iurl + ')';
  }
  else {
    ImageTransition(sfx, iurl);
  }
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
Catalog.prototype.loadFilter = function (key, reset) {
  var value = (!reset ? this.load(key, false) : []);
  var active = false;
  var e = document.getElementById('ddl' + key);
  if (!e) { e = document.getElementById('menu' + key); }
  if (e) {
    if (e.selectedIndex) e.selectedIndex = 0;
    // catalog.aspx
    if (key == this.KEY_CATEGORY) {
      var temp = this.orderings[0];
      if (temp.length > 1) {
        active = true;
        var cats = [];
        var x, scat, name;
        for (var i = 0; i < temp.length; i++) {
          name = temp[i][0];
          if (name.n != undefined) name = name.n;
          x = document.createElement("option")
          x.innerHTML = name;
          x.value = name;
          e.appendChild(x);

          scat = new Array(this.data.length);
          for (var p = 1; p < temp[i].length; p++) scat[(temp[i][p].n == undefined ? temp[i][p] : temp[i][p].n)] = 1;
          cats[name] = scat;
        }
        catalog.maps[this.KEY_CATEGORY] = cats;
      }
    }
    //else {
    if (e.options.length > 2) {
      active = true;

      // Initialise filter
      if (value && value.length > 0) {
        this.filter[key] = this.maps[key][value[0]];
        for (var i = 0; i < e.options.length; i++) {
          if (e.options[i].value == value[0]) {
            e.selectedIndex = i;
            break;
          }
        }
        this.setFilter(e, key);
      }
      else {
        this.filter[key] = null;
      }
    }
    //}
    e = document.getElementById("div" + key);
    if (e) e.style.display = (active ? "block" : "none");
    //[DEPRICATED-START]
    else e = document.getElementById("divFilter" + key);
    if (e) e.style.display = (active ? "block" : "none");
    //[DEPRICATED-FINAL]
  }
  else {
    // search.aspx
    e = document.getElementById("divFilter" + key + "Options");
    if (e && e.children.length > 0) {
      active = true;

      // Initialise filter
      if (value && value.length > 0) {
        var option;
        var temp;
        for (var v = 0; v < value.length; v++) {
          temp = value[v];
          if (temp) {
            option = null;

            // Find Option
            if (key == this.KEY_COLOR) {
              for (var i = 0; i < e.children.length; i++) {
                if (e.children[i].children
                && e.children[i].children.length > 1
                && e.children[i].children[1].innerHTML == temp) {
                  option = e.children[i];
                  break;
                }
              }
            }
            else {
              if (key == "Rating") {
                temp = 'http://i.americanapparel.net/storefront/ratings/images/rating_' + value[v] + (value[v].length > 1 ? '' : '0') + '.gif';
              }
              else {
                temp = '>' + value[v] + '<';
              }
              for (var i = 0; i < e.children.length; i++) {
                if (e.children[i].innerHTML.indexOf(temp) > 0) {
                  option = e.children[i];
                  break;
                }
              }
            }

            if (option) {
              this.setFilterSearch(option, key, value[v]);
            }
          }
        }

      }
    }
  }
  return active;
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
Catalog.prototype._checkSearchTermColor = function () {
  if (this.data && this.data.length && this.searchTerm) {
    var colorName = "";
    e = this.data[0].Colors;
    if (e && e.length) {
      for (var i = 0; i < e.length; i++) {
        if (e[i].Name && e[i].Name.toLowerCase() == this.searchTerm) {
          colorName = e[i].Name;
          i = e.length;
          break;
        }
      }
    }
    if (colorName) {
      for (var i = 0; i < this.data.length; i++) {
        e = this.data[i].Colors;
        if (e && e.length) {
          for (var c = 0; c < e.length; c++) {
            if (e[c].Name == colorName) {
              if (this.data[i].DefaultColor != e[c].Src) {
                this.changeProductColor(null, this.data[i].ID, 'x', e[c].English, e[c].Name);
              }
              c = e.length;
              break;
            }
          }
        }
      }
    }
  }
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
Catalog.prototype.init = function () {
  if (this.IS_STATIC) {
    return;
  }
  this.filter = [];
  var e = document.getElementById('tbxQuery');
  if (e) {
    // search.aspx
    this.searchTerm = getQueryStringValue('s');
    this.searchTerm =
    (this.searchTerm
    ? decodeURI(this.searchTerm).replace(/\+/g, ' ').replace(/%2F/g, '/')
    : "");
    e.value = this.searchTerm;
    if (_useAutoSuggest) {
      var data = [];
      data['elem'] = e;
      data['seeMore'] = _seeMore;
      new AutoSuggest(data);
    }
    if (this.data && this.data.length) {
      var term = this.searchTerm.split(' ');
      if (term && term.length) {
        var e, s, x;
        for (var i = 0; i < term.length; i++) {
          s = term[i].charAt(0).toUpperCase() + term[i].substr(1);
          if (this.maps["Color"][s]) {
            e = document.getElementById("divOptionColor" + s);
            if (e) this.setFilter(e, "Color", s);
          }
          else if (this.maps["Category"][s]) {
            e = document.getElementById("divOptionCategory" + s);
            if (e) this.setFilter(e, "Category", s);
          }
          else {
            x = s.charAt(s.length - 1).toLowerCase();
            s = (x == "s"//|| x == "y"
          ? s.substr(0, s.length - 1)// + (x == "y" ? "ies" : "")
          : null
          );
            if (s) {
              if (this.maps["Category"][s]) {
                e = document.getElementById("divOptionCategory" + s);
                if (e) this.setFilter(e, "Category", s);
              }
            }
          }
        }
      }
      this.index = this.load('Page', true);
      e = document.getElementById("hlkResetSearch");
      if (e) e.href = window.location;
    }
    if (this.showFilters == undefined) {
      this.showFilters = true;
    }
    if (this.showFilters) {
      var count = 0;
      var temp;
      var countOptions;
      for (var type in this.maps) {
        temp = this.maps[type];
        countOptions = 0;
        if (temp) {
          for (var x in temp) {
            if (temp[x] && temp[x].length > 0) {
              countOptions++;
            }
          }
        }
        if (countOptions > 0) {
          count++;
        } else {
          e = document.getElementById("divFilter" + type + "Label"); if (e) e.onclick = "";
          e = document.getElementById("divFilter" + type); if (e) e.className = "filter disabled";
        }
      }
      if (count > 0) {
        this.loadFilter(this.KEY_CATEGORY);
        this.loadFilter("Size");
        this.loadFilter(this.KEY_COLOR);
        this.loadFilter("Fabric");
        this.loadFilter("Price");
        this.loadFilter("Rating");
      }
      else {
        e = document.getElementById("divSearchHelpers"); if (e) e.className = "helpers disabled";
        e = document.getElementById("divHideAll"); if (e) e.onclick = "";
      }
    }
  }
  else {
    // catalog.aspx
    if (this.data && this.data.length) {
      if (this.attribute) {
        for (var i = 0; i < this.attribute.length; i++) {
          if (this.attribute[i]) {
            e = document.getElementById("lblFilter" + i);
            if (e) e.innerHTML = this.attribute[i].n;
            e = document.getElementById("ddlAnyOption" + i);
            if (e) e.innerHTML = this.attribute[i].a;
          }
        }
      }
      this.max = this.data.length;
      if (this.showFilters) {
        var loaded = false;
        for (var i = 0; i < 4; i++) {
          if (this.loadFilter("Filter" + i)) {
            loaded = true;
          }
        }
        e = document.getElementById("divFilter0");
        if (e) {
          e.style.display = "none";
          e = document.getElementById("divFilter4");
          if (e) {
            e.style.display = "block";
            this.showSorting = false;
          }
        }
        if (loaded) {
          e = document.getElementById("innerSearch");
          if (e) e.style.display = '';
        }
      }
    }
  }

  e = document.getElementById("pnShowSomeSort");
  if (e) e.style.display = (this.showSorting ? "block" : "none");

  this.sort(this.load('Sort', true));
  this.addCriteo();

  if (this.searchTerm) {
    this._checkSearchTermColor();
  }
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
Catalog.prototype.saveSearch = function () {
  setCookie('aaSort', this.user.sort, 1);

  this.save(this.KEY_CATEGORY);
  this.save(this.KEY_COLOR);
  this.save("Fabric");
  this.save("Size");
  this.save("Price");
  this.save("Rating");
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
Catalog.prototype.save = function (key) {
  var s = ""
  var data = this.user.filt[key];
  if (data) {
    if (data.length > 0) {
      s = data[0];
      for (var i = 1; i < data.length; i++) {
        s += "||" + data[i];
      }
    }
  }
  setCookie("aa" + key, s, 1);
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
Catalog.prototype.load = function (key, isInt, defValue) {
  var qsKeyID = '';
  switch (key) {
    case this.KEY_CATEGORY: qsKeyID = "r"; break; // Root category
    case "Fabric": qsKeyID = "f"; break; // Fabric
    case "Rating": qsKeyID = "u"; break; // User rating
    case this.KEY_COLOR: qsKeyID = "g"; break; // Generic color
    case "Price": qsKeyID = "p"; break; // Price
    case "Size": qsKeyID = "z"; break; // siZe
    case "Sort": qsKeyID = "a"; break; // sort (ex: A to Z)
    case "Fit": qsKeyID = "t"; break; // fiT
  }
  var data;
  var serverData = (this.defaults ? this.defaults[key] : null);
  if (serverData) {
    data = serverData;
  }
  else {
    value = getQueryStringValue(qsKeyID);
    value = value.replace(/%2526/g, '&');
    value = value.replace(/%%/g, '%25%');
    try {
      value = decodeURIComponent(value);
    }
    catch (err) {
      value = unescape(value);
    }
    value = value.replace(/\+/g, ' ');

    if (!value && qsKeyID != "r") {
      value = getCookie("aa" + key);
    }
    if (isInt) {
      data = (value ? parseInt(value) : (defValue ? defValue : 0));
    } else {
      data = (value ? value.split("||") : []);
    }
  }
  return data;
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
Catalog.prototype.search = function (force) {
  var txt = document.innerSearch.s.value || document.getElementById("tbxQuery");
  if (txt && txt.length > 0 && (force || txt.toLowerCase() != this.searchTerm.toLowerCase())) {
    document.innerSearch.submit();
  }
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
Catalog.prototype._nav = function (delta) {
  this.index += (delta * this.max);
  this.render(false);
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
Catalog.prototype.gotoPage = function (pageIndex) {
  this.index = (pageIndex * this.max);
  this.render(false);
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
Catalog.prototype.toggleShowAll = function (show) {
  this.showAll = show;
  this.render(false);
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
Catalog.prototype.addCriteo = function () {
  if (document.domain == 'store.americanapparel.net'
  || document.domain == 'origin-store.americanapparel.net'
  || document.domain == 'usd.dev.web.americanapparel.net'
  ) {
    var criteo = "";
    var max = (this.data.length > 3 ? 3 : this.data.length);
    for (var i = 0; i < max; i++) {
      criteo += "&i" + (i + 1) + "=" + this.data[i].ID;
    }
    var e = document.getElementById("cto_mg_div");
    if (e) {
      e.innerHTML = '<iframe width="1px" height="1px" style="display:none;" src="'
                    + "http://dis.us.criteo.com/dis/dis.aspx?p1=" + escape("v=2&wi=7712575&pt1=3" + criteo) + "&t1=sendEvent&p=2514&c=2&cb=" + Math.floor(Math.random() * 99999999999)
                    + '"></iframe>';
    }
  }
}
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
