var gogoCatalog = {
  product_stock: [ ],
  product_options: [ ],
  
  update_stock_info: function (PrID,SuID,PrLink)
  {
    var stockUnits = gogoCatalog.product_stock[PrID];
    var SU = null;
    for(var x = 0; x < stockUnits.length; x++)
    {
      if(SuID == stockUnits[x].SuID)
      {
        // Found 
        var price = document.getElementById('suprice' + PrID);
        var normalprice = document.getElementById('sunormalprice' + PrID);
        var saleflag    = document.getElementById('susaleflag'+PrID);
        var avail = document.getElementById('suavailability' + PrID);
        var link  = document.getElementById('sulink' + PrID);
        var qty   = document.getElementById('suqty' + PrID);
        var sunotify   = document.getElementById('sunotify' + PrID);
        var subuybutton = document.getElementById('subuybutton' + PrID);
        var subackorderbutton = document.getElementById('subackorderbutton' + PrID);
        
        if(price) price.innerHTML = '$' + stockUnits[x].SuCurrentPrice.toFixed(2);
        if(avail) avail.innerHTML = (stockUnits[x].SuQuantityInStock == null || stockUnits[x].SuQuantityInStock > 0) ? 'IN STOCK' : 'SOLD OUT';
        
        gogoCatalog.show_sale_flag(stockUnits[x].SuSalePrice, stockUnits[x].SuNormalPrice, PrID, stockUnits[x].SuSaleEnds);        
        
        if(stockUnits[x].SuQuantityInStock == null || stockUnits[x].SuQuantityInStock > 0)
        {
          if(link)     link.innerHTML = '<a href="' + PrLink + '?SelectSuID=' + SuID + '">Order Now</a>';
          if(qty)      qty.style.display = '';
          if(sunotify) sunotify.style.display = 'none';
          if(subackorderbutton) subackorderbutton.style.display = 'none';
          if(subuybutton)       subuybutton.style.display = '';
        }
        else if(!stockUnits[x].SuStrictQuantity)
        {
          if(link)     link.innerHTML = '<a href="' + PrLink + '?SelectSuID=' + SuID + '">Backorder Now</a>';
          if(qty)      qty.style.display = '';
          if(sunotify) sunotify.style.display = 'none';
          if(subackorderbutton) subackorderbutton.style.display = '';
          if(subuybutton)       subuybutton.style.display = 'none';
        }
        else
        {
          if(link)     link.innerHTML = '<a href="' + PrLink + '?SelectSuID=' + SuID + '">Notify when available</a>';
          if(qty)      qty.style.display = 'none';
          if(sunotify) sunotify.style.display = '';
          if(subackorderbutton) subackorderbutton.style.display = '';
          if(subuybutton)       subuybutton.style.display = 'none';
        }                
        return;
      }
    }
  },
  
  update_choices: function(option_pos,field_pfx,under_form,options,sales_units,on_change_callback)
  {
    var Chosen = [ ];
    var selects = under_form.getElementsByTagName('select');
              
    selects.getByOptionPos = 
      function(pos) 
      { 
        for(var i = 0; i < this.length; i++) 
        { 
          if(this[i].name == field_pfx + '[SuName][' + pos + ']') return this[i]; 
        }
        
        return false;
      }
    
    // Grab the choices for those up to this point
    for(var i = 0; i <= option_pos; i++)
    {             
      var choice = selects.getByOptionPos(i);
      
      if(!choice)
      {
        choice = '';
      }
      else
      {
        choice = choice.options[choice.selectedIndex].value;
      }
      Chosen[i] = choice;
    }
    
    // reconstruct the choices from here on
    for(var i = option_pos+1; i < options.length; i++)
    {
      var optField = selects.getByOptionPos(i);
      var choices  = options[i].choices;
      
      if(!optField)
      {
        // Hmm, what now?
      }
      else if(optField.tagName.toLowerCase() == 'select')
      {
        var currentChoice = optField.selectedIndex == -1 ? null : optField.options[optField.selectedIndex].value;
         
        // Nuke currents
        for(var j = optField.options.length-1;j >= 0; j--)
        {
          optField.options[j] = null;
        }
        
        for(var j = 0; j < choices.length; j++)
        {                    
          // ennsure there is a SU with this option
          var has_one    = false;
          var nameStarts = Chosen.concat([ choices[j] ]).join('|');  
          for(var x = 0; x < sales_units.length; x++)
          {
            if(sales_units[x].SuName.substr(0,nameStarts.length) == nameStarts) 
            {
              has_one = true;
              break;
            }
          }
          
          if(has_one)
          {
            optField.options[optField.options.length] = new Option(choices[j], choices[j]);
            if(choices[j] == currentChoice) optField.selectedIndex = optField.options.length-1;
          }
        }
      
        if(optField.selectedIndex >= 0)
        {
          Chosen[Chosen.length] = optField.options[optField.selectedIndex].value;
        }
        else
        {
          Chosen[Chosen.length] = '';
        }
      }
    }
  
    // Update the selected sales unit
    var SelectedName = Chosen.join('|');
    for(var i = 0; i < sales_units.length; i++)
    {        
      if(sales_units[i].SuName == SelectedName)
      {
        var inputs = under_form.getElementsByTagName('input');
        for(var j = 0; j < inputs.length; j++)
        {          
          if(inputs[j].name == field_pfx + '[SuID]')
          {
            inputs[j].value = sales_units[i].SuID;     
                        
            if(on_change_callback) on_change_callback(sales_units[i]);
                      
            return;
          }
        }
      }
    }
    
  },

  show_sale_flag: function(saleprice,normalprice,productid,saleends)
  {
    var saleholder = document.getElementById('susaleflag'+productid);
    if(!saleholder) return;
    saleholder.innerHTML = '';
    if(saleprice)
    {                      
      var span = document.createElement('span');
      span.appendChild(document.createTextNode('ON SALE'));
      span.className = 'css-catalog-sale-flag';
      saleholder.appendChild(span);
      
      var span = document.createElement('span');
      span.appendChild(document.createTextNode(' Normally: '));
      
      var span2 = document.createElement('span');
      span2.className = 'css-catalog-normal-price';
      span2.innerHTML = '$'+normalprice.toFixed(2);
      span.appendChild(span2);
      saleholder.appendChild(span);
               
      if(saleends && typeof Date.prototype.format != 'undefined')
      {
        var d = new Date(saleends * 1000);
        
        var span3 = document.createElement('span');
        span3.className = 'css-catalog-sale-ends';
        span3.innerHTML = ' Sale Ends ' + d.format('%e %h %I:%M %p');
        
        saleholder.appendChild(span3);
      }
      
      saleholder.style.display = '';
    }
    else
    {
      saleholder.style.display = 'none';
    }
  }
 

}

  /**
   * Date.format()
   * string format ( string format )
   * Formatting rules according to http://php.net/strftime
   *
   * Copyright (C) 2006  Dao Gottwald
   *
   * This library is free software; you can redistribute it and/or
   * modify it under the terms of the GNU Lesser General Public
   * License as published by the Free Software Foundation; either
   * version 2.1 of the License, or (at your option) any later version.
   *
   * This library is distributed in the hope that it will be useful,
   * but WITHOUT ANY WARRANTY; without even the implied warranty of
   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   * Lesser General Public License for more details.
   *
   * You should have received a copy of the GNU Lesser General Public
   * License along with this library; if not, write to the Free Software
   * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
   *
   * Contact information:
   *   Dao Gottwald  <dao at design-noir.de>
   *
   * @version  0.7
   * @todo     %g, %G, %U, %V, %W, %z, more/better localization
   * @url      http://design-noir.de/webdev/JS/Date.format/
   */
  
  var _lang = (navigator.systemLanguage || navigator.userLanguage || navigator.language || navigator.browserLanguage || '').replace(/-.*/,'');
  switch (_lang) {
    case 'de':
      Date._l10n = {
        days: ['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag'],
        months: ['Januar','Februar','M\u00E4rz','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember'],
        date: '%e.%m.%Y',
        time: '%H:%M:%S'};
      break;
    case 'es':
      Date._l10n = {
        days: ['Domingo','Lunes','Martes','Mi�rcoles','Jueves','Viernes','S\u00E1bado'],
        months: ['enero','febrero','marcha','abril','puede','junio','julio','agosto','septiembre','octubre','noviembre','diciembre'],
        date: '%e.%m.%Y',
        time: '%H:%M:%S'};
      break;
    case 'fr':
      Date._l10n = {
        days: ['dimanche','lundi','mardi','mercredi','jeudi','vendredi','samedi'],
        months: ['janvier','f\u00E9vrier','mars','avril','mai','juin','juillet','ao\u00FBt','septembre','octobre','novembre','decembre'],
        date: '%e/%m/%Y',
        time: '%H:%M:%S'};
      break;
    case 'it':
      Date._l10n = {
        days: ['domenica','luned\u00EC','marted\u00EC','mercoled\u00EC','gioved\u00EC','venerd\u00EC','sabato'],
        months: ['gennaio','febbraio','marzo','aprile','maggio','giugno','luglio','agosto','settembre','ottobre','novembre','dicembre'],
        date: '%e/%m/%y',
        time: '%H.%M.%S'};
      break;
    case 'pt':
      Date._l10n = {
        days: ['Domingo','Segunda-feira','Ter\u00E7a-feira','Quarta-feira','Quinta-feira','Sexta-feira','S\u00E1bado'],
        months: ['Janeiro','Fevereiro','Mar\u00E7o','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
        date: '%e/%m/%y',
        time: '%H.%M.%S'};
      break;
    case 'en':
    default:
      Date._l10n = {
        days: ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],
        months: ['January','February','March','April','May','June','July','August','September','October','November','December'],
        date: '%Y-%m-%e',
        time: '%H:%M:%S'};
      break;
  }
  Date._pad = function(num, len) {
    for (var i = 1; i <= len; i++)
      if (num < Math.pow(10, i))
        return new Array(len-i+1).join(0) + num;
    return num;
  };
  Date.prototype.format = function(format) {
    if (format.indexOf('%%') > -1) { // a literal `%' character
      format = format.split('%%');
      for (var i = 0; i < format.length; i++)
        format[i] = this.format(format[i]);
      return format.join('%');
    }
    format = format.replace(/%D/g, '%m/%d/%y'); // same as %m/%d/%y
    format = format.replace(/%r/g, '%I:%M:%S %p'); // time in a.m. and p.m. notation
    format = format.replace(/%R/g, '%H:%M:%S'); // time in 24 hour notation
    format = format.replace(/%T/g, '%H:%M:%S'); // current time, equal to %H:%M:%S
    format = format.replace(/%x/g, Date._l10n.date); // preferred date representation for the current locale without the time
    format = format.replace(/%X/g, Date._l10n.time); // preferred time representation for the current locale without the date
    var dateObj = this;
    return format.replace(/%([aAbhBcCdegGHIjmMnpStuUVWwyYzZ])/g, function(match0, match1) {
      return dateObj.format_callback(match0, match1);
    });
  }
  Date.prototype.format_callback = function(match0, match1) {
    switch (match1) {
      case 'a': // abbreviated weekday name according to the current locale
        return Date._l10n.days[this.getDay()].substr(0,3);
      case 'A': // full weekday name according to the current locale
        return Date._l10n.days[this.getDay()];
      case 'b':
      case 'h': // abbreviated month name according to the current locale
        return Date._l10n.months[this.getMonth()].substr(0,3);
      case 'B': // full month name according to the current locale
        return Date._l10n.months[this.getMonth()];
      case 'c': // preferred date and time representation for the current locale
        return this.toLocaleString();
      case 'C': // century number (the year divided by 100 and truncated to an integer, range 00 to 99)
        return Math.floor(this.getFullYear() / 100);
      case 'd': // day of the month as a decimal number (range 01 to 31)
        return Date._pad(this.getDate(), 2);
      case 'e': // day of the month as a decimal number, a single digit is preceded by a space (range ' 1' to '31')
        return Date._pad(this.getDate(), 2);

      case 'H': // hour as a decimal number using a 24-hour clock (range 00 to 23)
        return Date._pad(this.getHours(), 2);
      case 'I': // hour as a decimal number using a 12-hour clock (range 01 to 12)
        return Date._pad(this.getHours() % 12, 2);
      case 'j': // day of the year as a decimal number (range 001 to 366)
        return Date._pad(this.getMonth() * 30 + Math.ceil(this.getMonth() / 2) + this.getDay() - 2 * (this.getMonth() > 1) + (!(this.getFullYear() % 400) || (!(this.getFullYear() % 4) && this.getFullYear() % 100)), 3);
      case 'm': // month as a decimal number (range 01 to 12)
        return Date._pad(this.getMonth() + 1, 2);
      case 'M': // minute as a decimal number
        return Date._pad(this.getMinutes(), 2);
      case 'n': // newline character
        return '\n';
      case 'p': // either `am' or `pm' according to the given time value, or the corresponding strings for the current locale
        return this.getHours() < 12 ? 'am' : 'pm';
      case 'S': // second as a decimal number
        return Date._pad(this.getSeconds(), 2);
      case 't': // tab character
        return '\t';
      case 'u': // weekday as a decimal number [1,7], with 1 representing Monday
        return this.getDay() || 7;

      case 'w': // day of the week as a decimal, Sunday being 0
        return this.getDay();
      case 'y': // year as a decimal number without a century (range 00 to 99)
        return this.getFullYear().toString().substr(2);
      case 'Y': // year as a decimal number including the century
        return this.getFullYear();
      
      default:
        return match0;
    }
  }

  // These remain for legacy compatability reasons only
  var product_stock = gogoCatalog.product_stock;  
  var product_options = gogoCatalog.product_options;  
  var update_stock_info = gogoCatalog.update_stock_info;
  var update_choices = gogoCatalog.update_choices;
  
