var PP_personalize = Class.create({
  initialize: function() {
    this.options = { 1: { error: false, text: '', font: '', color: '', type: '', graphic: 0},
                     5: { error: false, text: '', font: '', color: '', type: '', graphic: 0},
                     6: { error: false, text: '', font: '', color: '', type: '', graphic: 0}};

    this.setOptions();

    if (document.images) {
      ppprodpre = new Image(); ppprodpre.src = "http://images.lids.com/lab/prod-preview.gif";
      ppprevpre = new Image(); ppprevpre.src = "http://images.lids.com/lab/prod-delete.gif";
      ppadispre = new Image(); ppadispre.src = "http://images.lids.com/btns/add-to-cart_dis.gif";
    }

    if (this.graphics && $('emb_selection_T') && $('emb_selection_G')) { 
      this.emb_graphics_allowed = true; 
    }

    this.addObservers();
    this.setTab('l');  
  },

  addObservers: function() {
    $('tb-f').observe('click', this.setMainTab.bindAsEventListener(this)); 
    $('tb-p').observe('click', this.setMainTab.bindAsEventListener(this)); 
    $('ptb-l').observe('click', this.setTab.bindAsEventListener(this)); 
    $('ptb-r').observe('click', this.setTab.bindAsEventListener(this)); 
    $('ptb-b').observe('click', this.setTab.bindAsEventListener(this)); 
    $('emb_text').observe('change', this.validateInput.bindAsEventListener(this));
    $('emb_font').observe('change', this.validateInput.bindAsEventListener(this));
    $('emb_color').observe('change', this.validateInput.bindAsEventListener(this));

    if ($('emb_promo_banner')) { $('emb_promo_banner').observe('click', this.setPromoAction.bindAsEventListener(this)); }

    if (this.emb_graphics_allowed) { 
      $('emb_selection_T').observe('click', this.setType.bindAsEventListener(this)); 
      $('emb_selection_G').observe('click', this.setType.bindAsEventListener(this)); 

      $('G0').observe('click', this.setGraphic.bindAsEventListener(this)); 
      for(var i in this.graphics) {
        $('G' + i).observe('click', this.setGraphic.bindAsEventListener(this)); 
      }
    }
  },

  setMainTab: function(event) {
    if (Object.isString(event)) {
      mtab = event;
    } else {
      mtab = Event.element(event).id;
      if (mtab.length > 1) { mtab = mtab.substring(3,4); }
    }

    $('tb-f').removeClassName('selected');
    $('tb-p').removeClassName('selected');
    $('tb-' + mtab).addClassName('selected');

    $('feature').toggle(); 
    $('personalize').toggle(); 

    if (mtab == 'f') {
      this.personalize = false;
      $('pimg').src = "http://lf.hatworld.com/hwl?set=sku[" + this.sku + "],d[" + this.skud + "],c[2],w[345],h[259]&load=url[file:product]";
    } else {
      this.personalize = true;
      this.setTab(this.location);
    }
  },

  setTab: function(event) {
    if (Object.isString(event)) {
      this.location = event;
    } else {
      this.location = Event.element(event).id;
      if (this.location.length > 1) { this.location = this.location.substring(4,5); }
    }

    if (this.location == 'l')  {
      if (!this.ic && !this.etype[1].type) {
        if (this.etype[5].type) {
          this.location = 'r';
          this.ic = 5;
        } else {
          this.location = 'b';
          this.ic = 6;
        }
      } else {
        this.ic = 1;
      }
    } else if (this.location == 'r')  {
      this.ic = 5;
    } else if (this.location == 'b')  {
      this.ic = 6;
    } else {
      window.location = "http://www.lids.com/pid/" + this.sku;
    }

    $('ptb-l').removeClassName('selected');
    $('ptb-r').removeClassName('selected');
    $('ptb-b').removeClassName('selected');
    $('ptb-' + this.location).addClassName('selected');

    if (this.etype[this.ic].type)  {
      $('emb_text').disabled  = $('emb_font').disabled = $('emb_color').disabled = false;
      $('emb_text').maxLength = this.etype[this.ic].max_characters;
      $('emb_text').value     = this.options[this.ic].text;
      $('emb_font').value     = this.options[this.ic].font;
      $('emb_color').value    = this.options[this.ic].color;

      if (this.emb_graphics_allowed) {
        if (!this.options[this.ic].type) { 
          this.setType('G'); 
        } else {
          this.setType(this.options[this.ic].type); 
        } 
      } 
    } else {
      $('emb_text').disabled = $('emb_font').disabled = $('emb_color').disabled = true;
      $('emb_text').value = $('emb_font').value = $('emb_color').value = "";
    }

    this.validateInput();
  },

  setPromoAction: function(event) {
    this.setMainTab('p');
    if (this.etype[5].type && this.emb_graphics_allowed)  {
      this.setTab('r');
    } else {
      this.setTab('l');
    }
  },

  setType: function(event) {
    if (Object.isString(event)) {
      temp = event;
      validate = false;
    } else {
      temp = Event.element(event).id.substring(14,15);
      validate = true;
    }

    if (this.ic == 6) {
      $('emb_selection').hide();
      $('emb_option_G').hide();
      $('emb_option_T').show();
      $('emb_selection_T').checked = true;
      this.options[this.ic].type = 'T';
    } else {
      this.options[this.ic].type = temp; 
      $('emb_selection').show();
      $('emb_selection_' + this.options[this.ic].type).checked = true;
      $('emb_option_T').hide();
      $('emb_option_G').hide();
      $('emb_option_' + this.options[this.ic].type).show();
    }

    if (validate) { this.validateInput(); }
  },

  setGraphic: function(event) {
    if (Object.isString(event)) {
      graphic = event;
    } else {
      graphic = Event.element(event).id.substring(1,Event.element(event).id.length);
    }

    if (!this.graphics[graphic]) {
      graphic = 0;
    }

    this.options[this.ic].graphic = graphic;

    this.validateInput();
  },

  resetForm: function() {
    this.text = this.font = this.color = this.options[this.ic].text = this.options[this.ic].font = this.options[this.ic].color = this.options[this.ic].graphic = $('emb_text').value = $('emb_font').value = $('emb_color').value = '';
    this.options[this.ic].error = false;
    $('per-error').innerHTML = "";

    this.displayButtons();
    this.drawImage();
  },

  validateInput: function() {
    this.options[this.ic].error = false;
    $('per-error').innerHTML = "";

    if (!this.etype[this.ic].type)  {
      $('per-error').innerHTML = "Sorry, embroidery not allowed";

      if (this.emb_graphics_allowed) { 
        $('emb_selection').hide();
        $('emb_option_G').hide();
        $('emb_option_T').show();
        $('emb_selection_T').checked = true;
        this.options[this.ic].type = 'T';
      }
    }

    if (this.emb_graphics_allowed && this.options[this.ic].type == 'G') { 
      $('G0').setStyle({border: '1px solid #000000'}); 
      for(var i in this.graphics) {
        $('G' + i).setStyle({border: '1px solid #000000'}); 
      }
      $('G' + this.options[this.ic].graphic).setStyle({border: '1px solid #F8981D'}); 
    } else {
      $('emb_text').value = $('emb_text').value.replace(/[ ]+/g,' ');
      this.text  = this.options[this.ic].text = $('emb_text').value;
      this.font  = this.options[this.ic].font = $('emb_font').value;
      this.color = this.options[this.ic].color = $('emb_color').value;
  
      if (this.text.length > this.etype[this.ic].max_characters)  {
        this.text = this.options[this.ic].text = $('emb_text').value.substring(0,this.etype[this.ic].max_characters);
        $('emb_text').value = this.text;
      }
  
      if (this.font) {
        if (this.fonts[this.font].max_characters && this.text.length > this.fonts[this.font].max_characters) {
          this.text = this.options[this.ic].text = $('emb_text').value.substring(0,this.fonts[this.font].max_characters);
          $('emb_text').value = this.text;
        } else if (this.fonts[this.font].caps_only) {
          this.text = this.options[this.ic].text = $('emb_text').value.toUpperCase();
          $('emb_text').value = this.text;
        }
  
        var match = this.fonts[this.font].characters.exec(this.text);
        if (match) {
          this.options[this.ic].error = true;
          $('per-error').innerHTML = "Sorry, not all characters allowed";
        }
      }
    }

    this.displayButtons();
    this.drawImage();
  },

  displayButtons: function() {
    if (this.text || this.font || this.color) {
      $('preview').src = "http://images.lids.com/lab/prod-preview.gif";
      $('delete').src  = "http://images.lids.com/lab/prod-delete.gif";
      $('preview').alt = $('preview').title = "Preview";
      $('delete').alt  = $('delete').title  = "Delete";

      if (!this.oActions) {
        this.bPreview = this.validateInput.bindAsEventListener(this);
        this.bDelete  = this.resetForm.bindAsEventListener(this);
        $('preview').observe('click', this.bPreview);
        $('delete').observe('click', this.bDelete);
        this.oActions = true;
      }
    } else {
      if (this.oActions) {
        $('preview').stopObserving('click', this.bPreview);
        $('delete').stopObserving('click', this.bDelete);
        this.oActions = false;
      }

      $('preview').src = $('delete').src = "http://images.lids.com/spacer.gif";
      $('preview').alt = $('preview').title = $('delete').alt = $('delete').title = "";
    }

    if (this.options[this.ic].error) {
      $('perAction').src = "http://images.lids.com/btns/add-to-cart_dis.gif"; 
      $('perAction').onmouseover = $('perAction').onmouseout = null;
      $('perAction').setStyle({cursor: 'default'}); 

      if (this.oPurchase) {
        $('perAction').stopObserving('click', this.bAddCartP);
        this.oPurchase = false;
      }
    } else {
      $('perAction').src = "http://images.lids.com/btns/add-to-cart.gif"; 
      $('perAction').onmouseover = function() { $('perAction').src = "http://images.lids.com/btns/add-to-cart_on.gif"; } 
      $('perAction').onmouseout  = function() { $('perAction').src = "http://images.lids.com/btns/add-to-cart.gif"; }
      $('perAction').setStyle({cursor: 'pointer'}); 
      $('purAction').setStyle({cursor: 'pointer'}); 

      if (!this.oPurchase) {
        this.bAddCartP = this.addToCart.bindAsEventListener(this);
        $('perAction').observe('click', this.bAddCartP);
        this.oPurchase = true;
      }
    }

    if (!this.bAddCart) {
      this.bAddCart = this.addToCart.bindAsEventListener(this);
      $('purAction').observe('click', this.bAddCart);
    }
  },

  drawImage: function() {
    if (this.personalize) {
      if (!this.options[this.ic].error && this.emb_graphics_allowed && this.options[this.ic].type == 'G' && this.sku && this.skud && this.etype[this.ic].type) {
        if (this.options[this.ic].graphic > 0) {
          var colors = ''; var i = 0;
          for (var c in this.graphics[this.options[this.ic].graphic].colors) {
            colors = colors + ',imgclr' + (++i) + '[%23' + this.graphics[this.options[this.ic].graphic].colors[c] + ']';
          }

          $('pimg').src = "http://lf.hatworld.com/hwl?set=img[" + this.graphics[this.options[this.ic].graphic].img + "],imgw[" + this.graphics[this.options[this.ic].graphic].gw + "],imgh[" + this.graphics[this.options[this.ic].graphic].gh + "]" + colors + ",etype[" + this.etype[this.ic].type + "],sku[" + this.sku + "],skud[" + this.skud + "],rw[345],rh[259]&call=url[file:personalize-g]";
        } else {
          $('pimg').src = "http://lf.hatworld.com/hwl?set=sku[" + this.sku + "],d[" + this.skud + "],c[" + this.ic + "],w[345],h[259]&load=url[file:product]";
        }
      } else if (!this.options[this.ic].error && this.text && this.font && this.color && this.sku && this.skud && this.etype[this.ic].type) {
        var text = this.text.replace('.','U002E'); text = text.replace('?','U003F'); text = text.replace('!','U0021'); text = text.replace(',','U002C'); text = text.replace(':','U003A'); text = text.replace(';','U003B'); text = text.replace('\'','U0027'); text = text.replace('"','U0022'); text = text.replace('#','U0023'); text = text.replace('$','U0024'); text = text.replace('%','U0025'); text = text.replace('*','U002A'); text = text.replace('+','U002B'); text = text.replace('-','U002D'); text = text.replace('=','U003D'); text = text.replace('@','U0040'); text = text.replace('^','U005E'); text = text.replace('&','U0026amp;'); text = text.replace('|','U007C'); text = text.replace('/','U002F'); text = text.replace('\\','U005C'); text = text.replace('(','U0028'); text = text.replace(')','U0029'); text = text.replace('{','U007B'); text = text.replace('}','U007D'); text = text.replace('[','U005B'); text = text.replace(']','U005D'); text = text.replace('<','U0026lt;'); text = text.replace('>','U0026gt;'); text = text.replace('~','U007E'); text = text.replace('`','U0060'); text = text.replace('_','U005F'); 
        $('pimg').src = "http://lf.hatworld.com/hwl?set=txt[" + encodeURIComponent(text) + "],txtf[" + this.font + "],txtc[%23" + this.colors[this.color].color + "],etype[" + this.etype[this.ic].type + "],sku[" + this.sku + "],skud[" + this.skud + "],rw[345],rh[259]&call=url[file:personalize]";
      } else {
        $('pimg').src = "http://lf.hatworld.com/hwl?set=sku[" + this.sku + "],d[" + this.skud + "],c[" + this.ic + "],w[345],h[259]&load=url[file:product]";
      }
    }
  },

  addToCart: function() {
    if (this.options[1].error) {
      if (!this.personalize) { this.setMainTab('p'); }
      this.setTab('l');
    } else if (this.options[5].error) {
      if (!this.personalize) { this.setMainTab('p'); }
      this.setTab('r');
    } else if (this.options[6].error) {
      if (!this.personalize) { this.setMainTab('p'); }
      this.setTab('b');
    } else if ($('purQuantity').value <= 0) {
      if (this.personalize) { this.setMainTab('f'); }
      if ($('error')) { 
        $('error').innerHTML = "Please enter a quantity";
      } else {
        $('cc_content').insert({ top: "<div id='error'>Please enter a quantity</div>" });
      }
    } else if (!$('purUPC').value) {
      if (this.personalize) { this.setMainTab('f'); }
      if ($('error')) { 
        $('error').innerHTML = "Please select a product size";
      } else {
        $('cc_content').insert({ top: "<div id='error'>Please select a product size</div>" });
      }
    } else {
      if ($('error')) { $('error').remove(); }

      if (this.oPurchase) {
        $('perAction').stopObserving('click', this.bAddCartP);
        this.oPurchase = false;
      }

      if (this.bAddCart) {
        $('purAction').stopObserving('click', this.bAddCart);
        this.bAddCart = false;
      }

      new Ajax.Request(
        this.uri + this.sku,
        {
          method: "post",
          postBody: "custom=true&" + $('purUPC').serialize() + "&" + $('purQuantity').serialize() + "&left=" + Object.toJSON(this.options[1]) + "&right=" + Object.toJSON(this.options[5]) + "&back=" + Object.toJSON(this.options[6]),
          onComplete: this.purchase.bind(this)
        }
      )
    }
  },

  purchase: function(trans) {
    var response = trans.responseXML.documentElement;
    var commands = response.getElementsByTagName('command');
  
    for(var i=0;i<commands.length;i++)  {
      method = commands[i].getAttribute('method');
  
      switch(method)  {
        case 'setcontent':
          var target  = getNodeValue(commands[i],'target');
          var content = getNodeValue(commands[i],'content');
          var btarget = getNodeValue(commands[i],'btarget');
  
          if(target && content)  {
            if ($(target))  {
              $(target).innerHTML = content;
            } else if (btarget && content) {
              $(btarget).insert({ top: '<div id="' + target + '">' + content + '</div>'});
            }  
          }
          break;

        case 'setstyle':
          var target   = getNodeValue(commands[i],'target');
          var property = getNodeValue(commands[i],'property');
          var value    = getNodeValue(commands[i],'value');
          if(target && property && value)  {
            document.getElementById(target).style[property] = value;
          }
          break;
  
        case 'location':
          var url = getNodeValue(commands[i],'url');
          window.location = url;
          break;
      }
    }

    if ($('error') && this.personalize) {
      this.setMainTab('f');
    }

    this.displayButtons();
  }
});

var pScroll = Class.create({
  initialize: function(id,title,titleuri,app,val,sku) {
    this.id = id; this.title = title; this.titleuri = titleuri;

    if (app == 'style' || app == 'team' || app == 'sport') {
      this.app = app; this.val = val; this.sku = sku;

      var uri = window.location.href.toQueryParams();
      if (!isNaN(uri['cpoi' + this.id]) && Math.round(uri['cpoi' + this.id]) > 0) {
        this.cp = Math.round(uri['cpoi' + this.id]);
      } else {
        this.cp = 0;
      }
  
      this.tp = 0;
      this.pc = 0;
  
      this.prodObj = {};
      this.prodDrw = [];
  
      this.loadProducts();
    } else {
      this.cp = this.tp = 0;
      $('pScroll-' + this.id).remove();
    }
  },

  createpScroll: function() {
    $('pScroll-' + this.id).innerHTML = "<div class='pScroll-wrapper'><div class='title-link'><a href='" + this.titleuri + "'>View All &#187;</a></div><div class='title'>" + this.title + "</div><div class='pScroll'><a id='pScroll-l-" + this.id + "' class='l-off'></a><div class='pScroll-iw'><div id='pScroll-i-" + this.id + "' class='pScroll-i'><li id='pScroll-bp-" + this.id + "' style='display: none;'></li><li id='pScroll-e-" + this.id + "' style='display: none;'></li></div></div><a id='pScroll-r-" + this.id + "' class='r-off'></a></div><div style='clear: both; height: 20px;'> </div></div>";
    $('pScroll-i-' + this.id).setStyle({width: (555 * this.tp) + 'px'}); 
  },

  createObservers: function() {
    this.leftObserver  = this.scrollLeft.bindAsEventListener(this);
    this.rightObserver = this.scrollRight.bindAsEventListener(this);
  },

  startObservers: function() {
    if (this.cp > 1) {
      $('pScroll-l-' + this.id).removeClassName('l-off');
      $('pScroll-l-' + this.id).addClassName('l-on');
      $('pScroll-l-' + this.id).setStyle({cursor: 'pointer'}); 
      $('pScroll-l-' + this.id).observe('click', this.leftObserver); 
    } else if ($('pScroll-l-' + this.id).hasClassName('l-on')) {
      $('pScroll-l-' + this.id).removeClassName('l-on');
      $('pScroll-l-' + this.id).addClassName('l-off');
      $('pScroll-l-' + this.id).setStyle({cursor: 'default'}); 
    }

    if (this.cp < this.tp) {
      $('pScroll-r-' + this.id).removeClassName('r-off');
      $('pScroll-r-' + this.id).addClassName('r-on');
      $('pScroll-r-' + this.id).setStyle({cursor: 'pointer'}); 
      $('pScroll-r-' + this.id).observe('click', this.rightObserver); 
    } else if ($('pScroll-r-' + this.id).hasClassName('r-on')) {
      $('pScroll-r-' + this.id).removeClassName('r-on');
      $('pScroll-r-' + this.id).addClassName('r-off');
      $('pScroll-r-' + this.id).setStyle({cursor: 'default'}); 
    }
  },

  stopObservers: function() {
    $('pScroll-l-' + this.id).stopObserving('click', this.leftObserver); 
    $('pScroll-r-' + this.id).stopObserving('click', this.rightObserver); 
  },

  setProdObj: function(prodObj) {
    this.pc = 0;
    for(var i in prodObj) {
      this.prodObj[(++this.pc)] = prodObj[i];

      if (this.cp == 0 && this.sku == prodObj[i].sku) {
        this.cp = Math.ceil((this.pc / 5));
      } 
    }

    if (this.pc > 0)  {
      this.tp = Math.ceil((this.pc / 5));
      if (this.cp > this.tp) { this.cp = 1; } else if (!this.cp) { this.cp = 1; }

      this.createpScroll();
      this.createObservers();
      this.drawProducts();
      this.startObservers();
    } else {
      this.cp = this.tp = 0;
      $('pScroll-' + this.id).remove();
    }
  },

  loadProducts: function(trans) {
    new Ajax.Request(
      '/js/ajax/scroll.html',
      {
        method: "post",
        postBody: "app=" + this.app + "&val=" + this.val,
        onComplete: this.processResponse.bind(this)
      }
    );
  },

  processResponse: function(trans) {
    this.setProdObj(trans.responseJSON);
  },

  drawProducts: function() {
    var b = (this.cp * 5) - 4;

    if ((b + 4) <= this.pc)  {
      var e = b + 4;
    } else {
      var e = this.pc;
    }

    if ($('pScroll-b-' + this.id)) { $('pScroll-b-' + this.id).remove(); }
    $('pScroll-bp-' + this.id).insert({ after: "<li id='pScroll-b-" + this.id + "'></li>" });
    $('pScroll-b-' + this.id).hide();

    for (i=b;i<=e;i++)  {
      if (!this.prodDrw[i]) {
        if (i < this.prodDrw.length && this.prodDrw.length > 0) {
          if (this.prodObj[i].kb > 0) {
            $('pScroll-b-' + this.id).insert({ before: "<li><a href='/pid/" + this.prodObj[i].sku + "?cpoi" + this.id + "=" + this.cp + "'><img src='http://lf.hatworld.com/hwl?set=sku[" + this.prodObj[i].sku + "],d[" + this.prodObj[i].skud + "],c[2],w[107],h[80],kb[" + this.prodObj[i].kb + "]&load=url[file:product_kids]' style='border: 1px solid #D5D6D8;' title='" + this.prodObj[i].alt + "' alt='" + this.prodObj[i].alt + "' width=107 height=80></a></li>" });
          } else {
            $('pScroll-b-' + this.id).insert({ before: "<li><a href='/pid/" + this.prodObj[i].sku + "?cpoi" + this.id + "=" + this.cp + "'><img src='http://lf.hatworld.com/hwl?set=sku[" + this.prodObj[i].sku + "],d[" + this.prodObj[i].skud + "],c[2],w[107],h[80]&load=url[file:product]' style='border: 1px solid #D5D6D8;' title='" + this.prodObj[i].alt + "' alt='" + this.prodObj[i].alt + "' width=107 height=80></a></li>" });
          }
        } else {
          if (this.prodObj[i].kb > 0) {
            $('pScroll-e-' + this.id).insert({ before: "<li><a href='/pid/" + this.prodObj[i].sku + "?cpoi" + this.id + "=" + this.cp + "'><img src='http://lf.hatworld.com/hwl?set=sku[" + this.prodObj[i].sku + "],d[" + this.prodObj[i].skud + "],c[2],w[107],h[80],kb[" + this.prodObj[i].kb + "]&load=url[file:product_kids]' style='border: 1px solid #D5D6D8;' title='" + this.prodObj[i].alt + "' alt='" + this.prodObj[i].alt + "' width=107 height=80></a></li>" });
          } else {
            $('pScroll-e-' + this.id).insert({ before: "<li><a href='/pid/" + this.prodObj[i].sku + "?cpoi" + this.id + "=" + this.cp + "'><img src='http://lf.hatworld.com/hwl?set=sku[" + this.prodObj[i].sku + "],d[" + this.prodObj[i].skud + "],c[2],w[107],h[80]&load=url[file:product]' style='border: 1px solid #D5D6D8;' title='" + this.prodObj[i].alt + "' alt='" + this.prodObj[i].alt + "' width=107 height=80></a></li>" });
          }
        }

        this.prodDrw[i] = this.prodObj[i].sku;
      }
    }
  },

  scrollLeft: function() {
    this.stopObservers();
    this.cp--;

    if (!this.prodDrw[((this.cp * 5) - 4)])  {
      $('pScroll-i-' + this.id).setStyle({left: '-555px'}); 
    }

    this.drawProducts();
    new Effect.MoveBy('pScroll-i-' + this.id, 0, 555, { afterFinish: this.startObservers.bind(this), duration: 1.0, queue: {position: 'end', scope: 'scroll-' + this.id }});
  },

  scrollRight: function() {
    this.stopObservers();
    this.cp++;

    this.drawProducts();
    new Effect.MoveBy('pScroll-i-' + this.id, 0, -555, { duration: 1.0, queue: {position: 'end', scope: 'scroll-' + this.id }});
    this.startObservers();
  }
});
