document.observe("dom:loaded", initApp);
//Event.observe(window, 'load', initApp);

function initApp(){
  if($("Inventory")){
    new Cart("Inventory");
    return;
  }
  if($("catalogNavigation")){
    var verticalAccordions = $("catalogNavigation").select('.accordion_toggle');
    var catalogNavigation = new accordion('catalogNavigation');    
    //if("activeAccordion" in window && verticalAccordions[activeAccordion]){
    //  catalogNavigation.activate(verticalAccordions[activeAccordion]);
    if("activeAccordion" in window && $(activeAccordion)){
      catalogNavigation.activate($(activeAccordion));
    }else{
      catalogNavigation.activate(verticalAccordions.first())
    }
  }
  if($("productGallery")){new Gallery("productGallery", "productGallery")}
  if($("productOrder")){new ProductSpin($("productOrder").down("fieldset"));}
  
}
var Cart = Class.create();
Cart.prototype = {
	initialize: function(container){
    this.container = $(container);
    if(!this.container){ return; }
    this.container.select("input[type=text]").each(function(input){
      new ProductSpin(input.up("td"), "button");
      input.observe("blur", function(){if(!parseInt(input.value) || parseInt(input.value) < 1){this.removeItem(input.up("tr"), input);}}.bind(this))
    }.bind(this));
    this.container.observe("click", this.toggleItem.bind(this));
    this.countIndicator1 = $("Cart").down("b");
    this.countIndicator2 = $("countTotal").down("b");
    this.countIndicatorWord = $("Cart").down("i");
    this.itemCountIndicator = $("countNames");
    this.curItemCount = parseInt(this.itemCountIndicator.down("b").innerHTML);
    this.saveChangesButton = $("cartSave");
    this.submitButton = $("placeOrder");
    this.login = $("login");
    this.password = $("pass");
    this.updateTotalCount();
    this.noChanges = true;
    this.form = this.container.up("form");
    if(this.form){
      new Form.Observer(this.form, 0.1, this.updateTotalCount.bind(this));
    }
    new PeriodicalExecuter(this.updateTotalCount.bind(this), 1); //force checking
  },
  toggleItem: function(event){
    if(!event){return;}
    event.stop();
    var row = event.findElement("tr");
    if(row && event.target == row.down("td.rem a")){
      var input = row.down("input[type=text]");
      if(row.hasClassName("removed")){
        this.restoreItem(row, input);
      }else{
        this.removeItem(row, input);
      }
    }
  },
  restoreItem: function(row, input){
    row.removeClassName("removed");
    input.disabled = false;
    this.updateItemCount(1);
    this.updateTotalCount();
    if(!parseInt(input.value) || parseInt(input.value) < 1){input.value=1;}
  },
  removeItem: function(row, input){
    row.addClassName("removed");
    input.disabled = true;
    this.updateItemCount(-1);
    this.updateTotalCount();
  },
  updateItemCount: function(delta){
    this.curItemCount += delta; 
    var endWord = (this.curItemCount%10 == 1 && !(this.curItemCount+'').endsWith('11'))? totalCountWord[0] : 
      ((this.curItemCount%10 == 2 && !(this.curItemCount+'').endsWith('12')) || 
      (this.curItemCount%10 == 3 && !(this.curItemCount+'').endsWith('13')) || 
      (this.curItemCount%10 == 4 && !(this.curItemCount+'').endsWith('14'))) ? totalCountWord[1] : totalCountWord[2];
    this.itemCountIndicator.innerHTML = '<b>'+this.curItemCount+'</b> '+endWord;
  },
  updateTotalCount: function(){
    var oldCount = this.curCount;
    this.curCount = 0; 
    this.container.down("tbody").select("td:nth-child(5) input:not([disabled])").each(function(input){
      input.value = input.value.gsub(/\D/, '');
      this.curCount += (parseInt(input.value) > 0 ? parseInt(input.value) : 0);
    }.bind(this));
    this.countIndicator1.innerHTML = this.countIndicator2.innerHTML = this.curCount;
    var countWord = (this.curCount%10 == 1 && !(this.curCount+'').endsWith('11'))? itemCountWord[0] : 
      ((this.curCount%10 == 2 && !(this.curCount+'').endsWith('12')) || 
      (this.curCount%10 == 3 && !(this.curCount+'').endsWith('13')) || 
      (this.curCount%10 == 4 && !(this.curCount+'').endsWith('14'))) ? itemCountWord[1] : itemCountWord[2];
		this.countIndicatorWord.innerHTML = countWord;
    if(this.noChanges && oldCount != this.curCount){
      this.saveChangesButton.appear();
      this.noChanges = false;
    }
    this.updateSubmitButton();
  },
  updateSubmitButton: function(){
    this.submitButton.disabled = !this.curCount || (this.login && (this.login.value.blank() || this.login.value == "Логин")) || (this.password && (this.password.value.blank() || this.password.value == "Логин"));
  }
};

var ProductSpin = Class.create();
ProductSpin.prototype = {
	initialize: function(container, arrowTag){
    this.container = container;
    if(!this.container){return;}
    this.arrowTag = arrowTag || "a";
    this.decrement = this.container.down(this.arrowTag);
    this.increment = this.container.down(this.arrowTag, 1);
    this.input = this.container.down("input");
    this.decrement.observe("click", this.update.bind(this, -1));
    this.increment.observe("click", this.update.bind(this, 1));
		document.observe("keydown", function(event) {
        if(event.target == this.input && (event.keyCode == 38 || event.keyCode == 39)) {
          this.update(1, event);
        }
        if(event.target == this.input && (event.keyCode == 37 || event.keyCode == 40)) {
          this.update(-1, event);
        }
    }.bind(this));

  },
  update: function(delta, event){
    event.stop();
    var curValue = $F(this.input);
    var newValue = parseInt(curValue)+delta;
    if(!newValue){
      if(delta > 0){this.input.value = 1; return;}
      new Effect.Highlight(this.input, { 
          duration: 0.5,
          startcolor: '#FF0000',
          queue: {position:'end', scope: "article", limit:1}
        }
      );
      return;
    }else{
      new Effect.Highlight(this.input, { 
          duration: 0.2,
          startcolor: '#ffcf25',
          queue: {position:'end', scope: "article", limit:1}
        }
      );
      this.input.value = newValue;
    }
  }
};
var Gallery = Class.create();
Gallery.prototype = {
	initialize: function(bigContainer, thumbsContainer){
    this.bigContainer = $(bigContainer);
    this.thumbsContainer = $(thumbsContainer);
    if(!(this.bigContainer && this.thumbsContainer)){return;}
    this.bigImg = this.bigContainer.down("img");
    this.thumbs = this.thumbsContainer.select("dd"); 
    this.curThumb = this.thumbsContainer.down("dd.current");
    if(!(this.bigImg && this.thumbs)){return;}
    this.thumbs.invoke("observe", "click", this.onclick.bind(this));
    this.bigImg.observe("load", this.onload.bind(this));
    this.inEffect = false;
    this.timer = null;
  },
  onclick: function(event){
    event.stop();
    if(this.inEffect){return;}
    if(event.findElement("dd") == this.curThumb){return;}
    this.inEffect = true;
    this.bigContainer.addClassName("loading");
    if(this.curThumb){this.curThumb.removeClassName("current");}
    this.curThumb = event.findElement("dd");
    this.curThumb.addClassName("current");
    var img = new Image();
    img.src = this.curThumb.down("a").href;
    new Effect.Fade(this.bigContainer.down("img"), {to: 0.2, duration: 0.8, afterFinish: function(){
      this.bigContainer.down("img").src = this.curThumb.down("a").href;
      this.timer = setTimeout(this.onload.bind(this), 500);
    }.bind(this)});
  },
  onload: function(){
    if(this.timer){
      clearTimeout(this.timer);
      this.timer = null;
    }    
    this.bigContainer.removeClassName("loading");
    new Effect.Appear(this.bigContainer.down("img"), {from: 0.2, duration: 0.5, afterFinish: function(){this.inEffect = false;}.bind(this)});
  }
};
