﻿// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Grid Page Functions
//
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function initGrid() {
  page.userFilter = [0, 0, 0, 0];
  page.max = page.data.length;
  page.filter = new Array();

  page.filter[0] = page.filters[0][page.userFilter[0]]

  var f3 = page.initFilter(3, 'Fits', 't');
  var f2 = page.initFilter(2, 'Fabr', 'f');
  var f1 = page.initFilter(1, 'GCol', 'g');

  if (f1 || f2 || f3) {
    document.innerSearch.style["display"] = '';
  }

  page.userFilter[0] = page.getInitValue('aaSort', 'a', true, 3);

  page.sort(page.userFilter[0]);

}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Legacy functionality for Wholesale Search page
function initSearch() { page.initSearch(); }
function saveSearch() { page.saveSearch(); }
function search(force) { page.search(force); }
function next() { page._nav(1); }
function prev() { page._nav(+1); }
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
var ColorSet = new Array();
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// 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]
///
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function applyFilters(data, filter) {
    // Combine Filters
    var filterCombo = new Array();

    // filter[0] : Sorting Mapping
    if (!filter[0]) {
        var smap = new Array();
        smap[0] = '';
        for (var i = 0; i < data.length; i++) {
            smap[i + 1] = i;
        }
        filter[0] = new Array();
        filter[0][0] = smap;
    }

    // filter[1] : Color Index Arrays
    if (filter[1]) {
        for (var i = 0; i < filter[1].length; i++) {
            filterCombo[i] = filter[1][i];
        }
    }
    else {
        for (var i = 0; i < data.length; i++) {
            filterCombo[i] = 1;
        }
    }

    var debug = '\nfilterCombo.length=' + filterCombo.length;
    // filter[2+]: Boolean Filters
    for (var f = 2; f < filter.length; f++) {
        if (filter[f]) {
            debug += '\nfilter[' + f + '].length=' + filter[f].length;
            for (var i = 0; i < filter[f].length; i++) {
                if (filter[f][i] != 1) {
                    filterCombo[i] = null;
                }
            }
        }
    }
    
    //alert(debug);
    
    
    
    if (filterCombo.length == 0) {
        for (var i = 0; i < data.length; i++) filterCombo[i] = 1;
    }
    
    // Apply Combination Filter
    var s, ix, ic, temp;
    var section = new Array();
    for (var x = 0; x < filter[0].length; x++) {
        temp = new Array();
        for (var i = 1; i < filter[0][x].length; i++) {
            ix = filter[0][x][i];
            if (ic = filterCombo[ix]) {
                s = data[ix];
                s._c = (ic == 1 ? '' : ic);
                temp[temp.length] = s;
            }
        }
        if(temp.length > 0)
        {
          section[section.length] = {title: filter[0][x][0], items: temp}
        }
    }
    return section;
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Color
//
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function Color(c) {
    this.English = c.E;
    this.Name = c.L;
    this.Values =
    { items: c.V
    , render: function(id) {
        var html = '';
        if (this.items) {
            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;
    }
    , _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>"
        );
    }
    }
    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';
    }
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    this.render = function(ID, i, subCat) {
        var html = '<div id="' + ID + '_' + i + '" class="miniColorBox" title="'
        + this.Name
        + '" onclick="page.changeProductColor(this, \'' + ID + '\', \'' + subCat + '\', \''
        + this.English + '\');">'
        + this.Values.render();
        return html + '</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.CategoryID = s.CT;
    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;
    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];
        }
    }
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    this.render = function(isRetail, lang, c, cid, subCat) {

      var color = (this._c && this.Colors && this.Colors[this._c[0]] ? this.Colors[this._c[0]] : '');
      var link =
        (isRetail
        ? (this.ID + '.html'
          + (cid > 0 ? '?cid=' + cid
          + (color ? '&c=' + escape(color.English) : '')
          : (color ? '?c=' + escape(color.English) : '')))
        : ('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) {
        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="gridProduct"><div style="padding:5px;" >'
      // Render Picture
      + '<div id="dv_'
      + sfx + '" style="width:120px;height:155px;"><a id="Img_'
      + sfx + '" onclick="saveSearch();" href="'
      + link + '"><img id="im_'
      + sfx + '" src="http://i.americanapparel.net/storefront/images/grid' + (isRetail ? '' : '') + '/colorserve.asp?media='
      + this.ID + '_' + (color ? color.Src : this.DefaultColor) + '.jpg"/>'
      + (this.Overlays && this.Overlays.length > 0
        ? '<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="saveSearch();" href="'
      + link + '">' + 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><img class="ratings" src="' +
	        (this.FiveStar
	        ? 'http://i.americanapparel.net/storefront/ratings/images/rating_' + this.FiveStar + 'stars.gif" /></div>'
	        : 'http://i.americanapparel.net/storefront/ratings/images/' + lang + '/rating_notrated.gif" /></div>'
	        )
	      : '')
      // End	      
      + (c < 0 ? '</div></td>'
        : (c < 3
          ? '</div></td><td><div class="cellGap">&nbsp;</div></td>'
          : '</div></td></tr><tr><td colspan="7" style="height:8px;"></td></tr><tr>'));
    }
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    this.renderColors = function(subCat) {
        if (this.Colors) {
          var html = '<div class="colors">';
            if (this._c) {
                for (var i = 1; i < this._c.length; i++) {
                    html += this.Colors[this._c[i]].render(this.ID, i - 1, subCat);
                }
            }
            else {
                for (var i = 0; i < this.Colors.length; i++) {
                    html += this.Colors[i].render(this.ID, i, subCat);
                }
            }
            return html + '</div>';
        }
        else {
            return '';
        }
    }
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Render Functions
//
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function Render(isRetail, products, i, max, lang, cid, subCat) {
  if (max < 0) {
    // Show All
    i = 0;
    max = products.length;
  }
  var c = 0;
  var t = 0;
  var html = '<table cellspacing="0" cellpadding="0" border="0" class="gridTable"><tr>';
  if (!subCat) {
    subCat = 'x';
  }

  var temp = new Array(); // Array used to stop duplicates

  while (i < products.length && t < max) {
    if (!temp[products[i].ID]) {
      if (!(i + 1 < products.length && t + 1 < max)) {
        c = -1;
      }
      html += products[i].render(isRetail, lang, c, cid, subCat);
      c = (c < 3 ? c + 1 : 0);
      temp[products[i].ID] = 1;
    }
    t++;
    i++;
  }
  return html + '</tr></table>';
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function RenderSections(isRetail, section, lang, cid) {
    var html = '';
    var s;
    for (var i = 0; i < section.length; i++) {
        s = section[i];
        html += '<div class="grouping" '
        + (i == 0 ? ' style="margin-top:2px;" >' : '>') 
        + (s.title ? s.title : '&nbsp;') + '</div>';
        html += Render(isRetail, s.items, 0, s.items.length, lang, cid, s.title);
    }
    return html;
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Navigation Functions
//
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function Navigation(args) {
  this.ShowAll = false;
  this.Lang = 'en';
  this.msg = { DefaultHeader: ''
  , HitSingular: ''
  , HitPlural: ''
  , CurrentPage: { Live: '', Dead: '' }
  , SeeAllItems: { Live: '', Dead: '' }
  , OldMsg: ''
  };
  this.src =
    { prev: { dead: 'http://i.americanapparel.net/storefront/images/arrows/triangle_left_False.gif'
             , live: 'http://i.americanapparel.net/storefront/images/arrows/triangle_left_True.gif'
    }
    , next: { dead: 'http://i.americanapparel.net/storefront/images/arrows/triangle_right_False.gif'
             , live: 'http://i.americanapparel.net/storefront/images/arrows/triangle_right_True.gif'
    }
    };
  if (args) {
    if (args['src.prev.dead']) this.src.prev.dead = args['src.prev.dead'];
    if (args['src.prev.live']) this.src.prev.live = args['src.prev.live'];
    if (args['src.next.dead']) this.src.next.dead = args['src.next.dead'];
    if (args['src.next.live']) this.src.next.live = args['src.next.live'];
    if (args['DefaultHeader']) this.msg.DefaultHeader = args['DefaultHeader'];
    if (args['HitSingular']) this.msg.HitSingular = args['HitSingular'];
    if (args['HitPlural']) this.msg.HitPlural = args['HitPlural'];
    if (args['CurrentPage.Live']) this.msg.CurrentPage.Live = args['CurrentPage.Live'];
    if (args['CurrentPage.Dead']) this.msg.CurrentPage.Dead = args['CurrentPage.Dead'];
    if (args['SeeAllItems.Live']) this.msg.SeeAllItems.Live = args['SeeAllItems.Live'];
    if (args['SeeAllItems.Dead']) this.msg.SeeAllItems.Dead = args['SeeAllItems.Dead'];
    if (args['OldMsg']) this.msg.OldMsg = args['OldMsg']; // Legacy
    if (args['Lang']) this.Lang = args['Lang'];
  }
  /** ************************************************************************/
  this._innerHtml = function(prefix, suffix, html) {
    var e;
    e = document.getElementById(prefix + 'Head' + suffix); if (e) e.innerHTML = html;
    e = document.getElementById(prefix + 'Foot' + suffix); if (e) e.innerHTML = html;
  }
  /** ************************************************************************/
  this._styleDisplay = function(prefix, suffix, display, option) {
    var e;
    if (!option || option == 0) e = document.getElementById(prefix + 'Head' + suffix); if (e) e.style.display = display;
    if (!option || option == 1) e = document.getElementById(prefix + 'Foot' + suffix); if (e) e.style.display = display;
  }
  /** ***********************************************************************
  */
  this.update = function(index, step, total, lang, showAll) {
    var e;
    var m;
    var nStart = index + 1;
    var nFinal = index + step;
    var strStart = this._formatNumber(nStart, lang);
    var strFinal = this._formatNumber((nFinal > total ? total : nFinal), lang);
    var strTotal = this._formatNumber(total, lang);

    m =
      (total < 1
      ? this.msg.DefaultHeader
      : (total > 1
      ? this.msg.HitPlural.replace('##', strTotal)
      : this.msg.HitSingular));
    e = document.getElementById('pnSearchHeader'); if (e) e.innerHTML = m;

    if (total > 0) {
      m = this.msg.OldMsg;
      if (m) {
        // Legacy code for Wholesale store
        m = m.replace('{0}', strStart);
        m = m.replace('{1}', strFinal);
        m = m.replace('{2}', strTotal);
        this._innerHtml('lb', 'Result', m);
      }

      var currentPage = { text: '', click: '', show: '' };
      var seeAllItems = { text: '', click: '', show: '' };
      var display = { buttons: '', paging: '' };
      if (total > step) {
        if (showAll) {
          currentPage.text = this.msg.CurrentPage.Live;
          seeAllItems.text = this.msg.SeeAllItems.Dead;
          currentPage.click = 'page.toggleShowAll(false)';
          display.buttons = 'none';
        } else {
          currentPage.text = this.msg.CurrentPage.Dead;
          seeAllItems.text = this.msg.SeeAllItems.Live;
          seeAllItems.click = 'page.toggleShowAll(true)';

          var prev = 'page._nav(-1);';
          var next = 'page._nav(1);';
          if (index > 0) {
            if (nFinal >= total) next = '';
          }
          else {
            prev = '';
            if (nFinal > total) next = '';
          }
          this._navLink('Prev', prev);
          this._navLink('Next', next);
        }
        m = currentPage.text;
        if (m) {
          m = m.replace('{0}', strStart);
          m = m.replace('{1}', strFinal);
          this._innerHtml('lb', 'CurrentPage', m);
        }
        this._navLink('CurrentPage', currentPage.click);
      }
      else {
        // Only 1 page
        display.buttons = 'none';
        display.paging = 'none';
        currentPage.show = '';
        seeAllItems.text = this.msg.SeeAllItems.Dead;
      }
      this._navLink('SeeAllItems', seeAllItems.click);
      this._innerHtml('lb', 'SeeAllItems', seeAllItems.text);

      this._styleDisplay('lb', "Delim", display.paging);
      this._styleDisplay('lb', "CurrentPage", display.paging);
      this._styleDisplay('pn', "NaviButtons", display.buttons);
      this._styleDisplay('pn', "Navi", display.paging, 1);
    }
    this._innerHtml('lb', 'Total', '(' + this._formatNumber(total, this.Lang) + ')');
    scrollTo(0, 0);
  }
  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  this._navLink_Helper = function(suffix, onclick) {
    var link = document.getElementById('lb' + suffix);
    var icon = document.getElementById('im' + suffix);
    if (link) {
      if (onclick) {
        link.onclick = new Function(onclick);
        link.style.cursor = 'pointer';
        link.className = 'livelink';
      }
      else {
        link.onclick = '';
        link.style.cursor = '';
        link.className = 'deadlink';
      }
    }
    if (icon) {
      var arrow = (suffix.charAt(4) == 'N' ? this.src.next : this.src.prev);
      icon.src = (onclick ? arrow.live : arrow.dead);
    }
  }
  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  this._navLink = function(suffix, onclick) {
    this._navLink_Helper('Head' + suffix, onclick);
    this._navLink_Helper('Foot' + suffix, onclick);
  }
  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  this._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
    }
  }
  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Page
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function PageLayout(isRetail, args) {
  this.index = 0;
  this.isRetail = isRetail;
  this.showAll = false;
  this.args = args;
  this.lang = 'en';
  switch (getCookie("aalang")) {
    case '1': this.lang = 'en'; break;
    case '2': this.lang = 'fr'; break;
    case '10': this.lang = 'es'; break;
    default: this.lang = 'en'; break;
  }
  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  this.render = function(update) {
    if (update) this.section = applyFilters(this.data, this.filter);

    var total = (this.section[0] && this.section[0].items ? this.section[0].items.length : 0);
    if (!this.nav && (this.defHeader || (this.args && this.args["DefaultHeader"]))) {
      if (this.args) {
        this.args['Lang'] = this.lang;
        this.args['Total'] = total;
        if (this.defHeader) this.args['DefaultHeader'] = this.defHeader;
        if (this.hitCount1) this.args['HitSingular'] = this.hitCount1;
        if (this.hitPlural) this.args['HitPlural'] = this.hitPlural;
        if (this.msgHeader) this.args['OldMsg'] = this.msgHeader;
      }
      this.nav = new Navigation(this.args);
      if (this.index > total) {
        this.index = 0;
      }
    }
    if (this.nav) {
      if (this.showAll) {
        this.index = 0;
      }
      setCookie('aaPage', this.index, 1);
      this.nav.update(this.index, this.max, total, this.lang, this.showAll);
    }

    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].title
            ? RenderSections(this.isRetail, this.section, this.lang, this.cid)
            : Render(this.isRetail, this.section[0].items, this.index, (this.showAll ? -1 : this.max), this.lang, this.cid)
            );
      }
      dvShowID = 'pnShowSome';
      dvHideID = 'pnShowNone';
    }
    e = document.getElementById(dvShowID); if (e) e.style.display = '';
    e = document.getElementById(dvHideID); if (e) e.style.display = 'none';


  }
  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  this.sort = function(opt) {
    var max = this.filters[0].length;
    if (-1 < opt && opt < max) {
      var e;
      document.innerSearch.a.value = opt;
      this.userFilter[0] = opt;
      for (var i = 0; i < max; i++) {
        e = document.getElementById('dv_Sort' + i); if(e) e.className = 'button';
      }
      e = document.getElementById('dv_Sort' + opt); if(e) e.className = 'picked';

      this.filter[0] = this.filters[0][opt];
    } else {
      this.filter[0] = this.filters[0][0];
    }
    this.filter[0] = this.filters[0][opt];

    this.render(true);
  }
  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  this.setFilter = function(iFilter, menu) {
    var value = menu.options[menu.selectedIndex].value;
    this.userFilter[iFilter] = value;
    this.filter[iFilter] = this.filters[iFilter][value];
    this.index = 0;
    this.render(true);
  }
  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  this.getInitValue = function(cookieID, qsKeyID, isInt, defValue) {
    var value = getCookie(cookieID);
    if (value) {
      setCookie(cookieID, '', 1);
    }
    else {
      value = getQueryStringValue(qsKeyID);
      value = decodeURIComponent(value);
      value = value.replace(/\+/g, ' ');
    }
    if (isInt) {
      value = (value ? parseInt(value) : (defValue ? defValue : 0));
    }
    return value;
  }
  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  this.initFilter = function(iFilter, id, qsKeyID) {
    var value = this.getInitValue('aa' + id, qsKeyID, false);
    var menu = document.getElementById('menu' + id);
    if (value) {
      this.filter[iFilter] = this.filters[iFilter][value];
      if (menu) {
        for (var i = 0; i < menu.length; i++) {
          if (menu.options[i].value == value) {
            menu.selectedIndex = i;
            break;
          }
        }
      }
    }
    else {
      if (menu) menu.selectedIndex = 0;
      this.filter[iFilter] = null;
    }
    this.userFilter[iFilter] = value;

    var active = false;
    if (menu && menu.length > 2) {
      active = true;
      var pn = document.getElementById("pnFilter" + id);
      if (pn) {
        pn.style["display"] = '';
      }
    }
    return active;

  }
  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  this.changeProductColor = function(swatch, style, subCat, color) {

    /* / 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/images/grid"+(this.isRetail?'':'2')+"/colorserve.asp?media=" + style + "_" + color + ".jpg"
    ImageTransition(sfx, iurl);
  }
  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  this.initSearch = function() {
    this.userFilter = [0, 0, 0];
    this.max = 16;
    this.filter = new Array();
    this.section = null;
    this.searchTerm = decodeURI(getQueryStringValue('s')).replace(/\+/g, ' ')

    document.innerSearch.s.value = this.searchTerm;

    this.initFilter(2, 'Root', 'r');
    this.initFilter(1, 'GCol', 'g');

    this.userFilter[0] = this.getInitValue('aaSort', 'a', true);
    this.index = this.getInitValue('aaPage', 'p', true);

    this.sort(this.userFilter[0]);
  }
  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  this.saveSearch = function() {
    setCookie('aaSort', this.userFilter[0], 1);
    setCookie('aaGCol', this.userFilter[1], 1);
    setCookie('aaFabr', this.userFilter[2], 1);
    setCookie('aaFits', this.userFilter[3], 1);

    setCookie('aaSort', this.userFilter[0], 1);
    setCookie('aaGCol', this.userFilter[1], 1);
    setCookie('aaRoot', this.userFilter[2], 1);
  }
  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  this.search = function(force) {
    var txt = document.innerSearch.s.value;
    if (txt.length > 0 && (force || txt.toLowerCase() != this.searchTerm.toLowerCase())) {
      document.innerSearch.submit();
    }
  }
  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  this._nav = function(delta) {
    this.index += (delta * this.max);
    this.render(false);
  }
  this.toggleShowAll = function(show) {
    this.showAll = show;
    this.render(false);
  }
  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
