document.observe("dom:loaded", initStock);
//Event.observe(window, 'load', initStock);

function initStock(){
  StockMobile = new App();
	document.fire("application:initialized");
}
var App = Class.create();
App.prototype = {
  initialize: function(){
  	this.ieBefore7 = false;
    if (Prototype.Browser.IE){
    	var agent = navigator.userAgent.toLowerCase();
  		var agentVer = parseFloat(agent.match(/msie.{1}(\d+.\d+)/)[1]); 
      if ( agentVer < 7.0) { 
  			this.ieBefore7 = true;
  		}
  	}
    if($("menuBack")){$("menuBack").observe("click", function(event){event.stop(); history.back();})}
    
	var flowElement = $("Flow");
    if(flowElement){
      var tabsIds = [];
      if(flowElement.down("ul.flowTabs")){
        tabsIds = flowElement.down("ul.flowTabs").select("li[id]").pluck("id");
        this.topTabs = new Tabs(tabsIds, [flowElement.id], "tab"+flowElement.className, function(id){
          if(id == "tabReviews" && 'ReviewParam' in window){
            setProductReviews(ReviewParam);
          }
        });
      }
      if(flowElement.down("ul.smallTabs")){
        tabsIds = flowElement.down("ul.smallTabs").select("li[id]").pluck("id");
        this.smallTabs = new Tabs(tabsIds, [flowElement.down("ul.smallTabs").up("div")], "tab"+flowElement.down("ul.smallTabs").up("div").className);
      }
      flowElement.select("span.productRating").each(function(element){new RateControl(element);});
    }
	
    this.modal = new Modal();
    if($("citySelector")){$("citySelector").observe("click", this.openCityDialog.bind(this));}
    if($("ChooseTitle") && $("ChooseTitle").down("a")){
      $("ChooseTitle").down("a").observe("click", function(event){
        event.stop();
        this.modal.show("modalChooseTitle");
      }.bind(this));
    }
    
    //if($("objectsList")){
    //  $("objectsList").select("a.compare").invoke("observe", "click", this.compare.bind(this));
    //}
    if($("Content")){
      $("Content").observe("click", function(event){
        if(event.target && event.target.id && event.target.id.startsWith("compare_btn_")){
          this.compare(event);
        }
      }.bind(this));
    }
    if($("assortment_form")){
      $("assortment_form").observe("click", function(event){
        var head = event.findElement("h5");
        if(head && head.next("fieldset")){
          event.stop();
          new Effect.toggle(head.next("fieldset"), "blind", {
            duration: 0.3,
			afterFinish: function(){head.toggleClassName("active");}
          });
          //head.toggleClassName("active");
          //head.next("fieldset").toggle();
        }
      }.bind(this));
    }
    this.stokCompare = $("stokCompare");
    if($("Compare")){$("Compare").observe("click", this.compare.bind(this));}
    
	if($("yourWatcher")){
      $("yourWatcher").observe("click", function(event){
		var target = $(event.target);
        var parent = $(event.findElement("tr"));
		if(target == parent.down("a.remove")){
			event.stop();
			parent.toggleClassName("removed");
			parent.select("input").each(function(item){
				item.disabled = !item.disabled;
			});
		}
	  });
	}
	
    if($("switchToAccessories")){$("switchToAccessories").observe("click", function(event){this.topTabs.switchTabs("tabAccessories", event);}.bind(this));}
    if($("switchToAccessoriesExtra")){$("switchToAccessoriesExtra").observe("click", function(event){this.topTabs.switchTabs("tabAccessories", event);}.bind(this));}
    if($("switchToSimilars")){$("switchToSimilars").observe("click", function(event){this.topTabs.switchTabs("tabSimilars", event);}.bind(this));}
    if($("reviewIcon")){$("reviewIcon").observe("click", function(event){this.topTabs.switchTabs("tabReviews", event);}.bind(this));}
    if($("toggleDetail") && $("toggleDetail").next("div.detailed")){
      $("toggleDetail").observe("click", function(){
        new Effect.toggle($("toggleDetail").next("div.detailed"), "blind", {
          duration: 0.4,
          afterFinish: function(){
            $("toggleDetail").toggleClassName("detailed");   
          }
        });
      }.bind(this));
    }
    if($("galleryThumbs")){
      this.stockLightbox = new Lightbox();
      $("outerImageContainer").insert('<div id="lightboxThumbs">'+$("galleryThumbs").innerHTML+'</div>');
      $("lightboxThumbs").select("a").each(function(element, index){
        element.rel = "lightbox[product]";
        element.index = index;
      });
      $("lightboxThumbs").observe("click", function(event){
        event.stop();
        var imgLink = event.findElement("a");
        if(imgLink){ this.stockLightbox.changeImage(imgLink.index); }
      }.bind(this));
      $("outerImageContainer").insert('<a href="#" id="stockLightboxClose"><img src="/img/icons/lightbox-close.png"/></a>');
      $("stockLightboxClose").observe("click", function(event){ event.stop(); this.stockLightbox.end(); }.bind(this));
      this.stockGallery = new Gallery("productGallery", "galleryThumbs");
      if($("showLightbox")){
        $("showLightbox").observe("click", function(event){
          event.stop();
          this.stockLightbox.start($("lightboxThumbs").down("a", this.stockGallery.thumbs.indexOf(this.stockGallery.curThumb)));
        }.bind(this));
      }
    }
    if($("listPOS")){
      this.modalPOS = new Modal("modalOverlay2");
      $("listPOS").observe("click", function(event){
        if(event.target.tagName.toUpperCase() == "A" && event.target.id.startsWith("showMap_")){
          event.stop();
          this.modalPOS.show(event.target.id.replace("showMap_", ""));
        }
      }.bind(this))
    }
    if($("menuSearch") && $("Search")){
      $("menuSearch").observe('click', function(event){
        event.stop(); 
        $("menuSearch").toggleClassName("current");
        new Effect.toggle($("Search"), 'blind', {duration: 0.3 });
      });
    }
    this.objectDesciption = $("objectDescription");
    if(this.objectDesciption){
      this.matchLayoutElement = $(document.body);
      this.matchLayout();
      Event.observe(window, "load", this.matchLayout.bind(this));
      Event.observe(window, "resize", this.matchLayout.bind(this));
    }
    if($("yourCart")){
      new Cart("yourCart");
    }
    if($("userSignin")){ new Authorization(); }
	},
  matchLayout: function(){
     this.matchLayoutElement[(this.objectDesciption.getWidth() > 1000 ? "add" : "remove")+"ClassName"]("wide");
  },
  openCityDialog: function(event){
    event.stop();
    this.modal.show("modalDialog");
  },
  onscroll: function(event){
    if(this.compareEffectRunning){event.stop();}
  },
  compare: function(event){
    event.stop();
    var eventTarget = $(event.target);
    if(eventTarget.hasClassName("incompare") || this.stokCompare.select("img").length == 3){
      Effect.Shake(eventTarget, {
        duration: 0.15,
        distance: 4
      });
      return;
    }
    eventTarget.addClassName("incompare");
    new Ajax.Request("/compare/ajax/add-remove", {
      parameters: {action: 'add', id_item: eventTarget[eventTarget.id=="Compare" ? "rel" : "id"].replace("compare_btn_", "")}
    });
    var source = eventTarget.id=="Compare" ? $("productGallery").down("img") : $(eventTarget).previous("a").down("img"); 
    if(source){
      if(this.topTabs){this.topTabs.switchTabs("tabDescription");}
      var imgwidth = source.getWidth() == source.getHeight() ? 50 : 25;
      var target = new Element("img").setStyle("width: "+imgwidth+"px; height: 50px; visibility: hidden;");
      target.src = source.src.replace("-m.", "-xs.").replace("-xl.", "-xs.").replace("-o.", "-xs.");
      this.stokCompare.appendChild(target);
      if(this.ieBefore7){
        target.style.visibility = "visible"; 
        if(!this.stokCompare.href && this.stokCompare.rel){this.stokCompare.href = this.stokCompare.rel;} 
        this.stokCompare.addClassName("notempty");
      }else{
        var image = source.clone();
        var targetClone = target.clone();
        //document.body.appendChild(image);
        //document.body.appendChild(targetClone);
        $("Content").appendChild(image);
        $("Content").appendChild(targetClone);
        targetClone.absolutize();
        targetClone.clonePosition(target);
        targetClone.setStyle({ top: (parseInt(targetClone.getStyle("top")) + document.viewport.getScrollOffsets().top)+"px" });
        image.absolutize().clonePosition(source).morph("width: "+imgwidth+"px; height: 50px; top: "+targetClone.getStyle("top")+"; left: "+targetClone.getStyle("left")+";", {
          duration: 0.5,
          afterFinish: function(){
            target.style.visibility = "visible"; 
            image.remove(); 
            targetClone.remove();
            if(!this.stokCompare.href && this.stokCompare.rel){this.stokCompare.href = this.stokCompare.rel;} 
            this.stokCompare.addClassName("notempty");
          }.bind(this)
        });
      }
    }
  }
};
var Tabs = Class.create();
Tabs.prototype = {
	initialize: function(tabs, elements, currentTab, afterOpen){
    //console.log("initialize");
    this.tabs = tabs;
		this.elements = elements;
    this.afterOpen = afterOpen;
    var hash = location.hash.replace("#", "");  
    if(hash && this.tabs.include("tab"+hash) && $("tab"+hash)){
      this.switchTabs("tab"+hash);
    }else{
      this.currentTab = currentTab;
    }
		this.tabsWidth = 0;
		this.tabs.each(function(tab){
			if(tab && $(tab)){
				$(tab).observe("click", this.switchTabs.bind(this, tab));
				if(!this.tabsContainer){this.tabsContainer = $(tab).up("ul")}
				this.tabsWidth += $(tab).getWidth();
			}	
		}.bind(this));
		
		if(this.tabsContainer && this.tabsWidth){
			Event.observe(window, "load", this.checkOverflow.bind(this));
			Event.observe(window, "resize", this.checkOverflow.bind(this));
		}
		
	},
	checkOverflow: function(){
		this.tabsContainer[(this.tabsWidth + 20 > this.tabsContainer.getWidth() ? "add" : "remove")+"ClassName"]("overflowed");
	},
	switchTabs: function(tab, event){
		//console.log("switchTabs");
    if(event){Event.stop(event);}
    /*
    console.log("location", location.hash);
    
    this.tabs.each(function(item){
      var hashname = item.replace("tab", "")+";?";
      //if(location.hash.include(hashname)){
        location.hash = location.hash.gsub(new RegExp(hashname), "");
      //}
    });
    console.log("location", location.hash);
      //if(!location.hash.include(tab.replace("tab", "")+";")){
        location.hash += tab.replace("tab", "")+";";
      //}
      */
    if(this.currentTab == tab || !$(tab)){return false;}
		this.currentTab = tab;
		//location.hash = tab.replace("tab", "");
    //var newHref = location.href.replace(/#.*/, "#"+tab.replace("tab", ""));
    //alert(newHref);
    location.replace("#"+tab.replace("tab", ""));
    //location.replace(newHref);
    this.elements.each(function(element){
			if($(element)){
				$(element).className = $(tab).id.replace("tab", "");
			}
		});
    if(this.afterOpen && typeof(this.afterOpen)=="function"){this.afterOpen(this.currentTab);}
    //console.log(this.currentTab);
    //document.fire("tab:activated", {id: this.currentTab});
	}
};
var Modal = Class.create();
Modal.prototype = {
	initialize: function(overlay){
    this.overlay = overlay ? $(overlay) : $("modalOverlay");
    this.curDialog = null;
    this.opened = false;
    Event.observe(document, 'keyup', this.checkClose.bind(this));
    Event.observe(document, 'click', this.checkCloseClick.bind(this));
  },
  show: function(dialog){
    //this.overlay.style.display = "block";
    //debugger;
    var oldDialog = this.curDialog;
    this.curDialog = $(dialog);
    if(!this.curDialog){return;}
    if(!this.opened && this.overlay){
      this.overlay.appear({
        duration: 0.2,
        to: 0.95,
        afterFinish: function(){
          this.curDialog.style.display = "block";
          this.opened = true;
        }.bind(this)
      });
    }else{
      if(oldDialog){oldDialog.hide();}
      this.curDialog.style.display = "block";
      this.opened = true;
    }
    $(document.body).addClassName("modalOn");
  },
  checkClose: function(event){
   	var key = event.keyCode || event.which;
  	if(key == 27){
  		event.stop();
     	this.close();
  	}
  },
  checkCloseClick: function(event){
    if(this.opened){
      var target = event.target;
      if(target && (target == this.curDialog.down("a.close") || target == this.overlay)){
        event.stop();
        this.close();
      }
    }
  },
  close: function(){
    if(this.opened){
      $(document.body).removeClassName("modalOn");
      this.curDialog.hide();
      this.overlay.hide();
      this.opened = false;
    }
  }
};
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.action = this.bigContainer.down("ins");
    this.thumbs = this.thumbsContainer.select("a"); 
    this.defaultThumb = this.curThumb = this.thumbsContainer.down("a.current") || this.thumbsContainer.down("a");
    if(!(this.bigImg && this.thumbs)){return;}
    this.thumbs.invoke("observe", "click", this.onclick.bind(this));
    this.bigImg.observe("load", this.onload.bind(this));
  },
  onclick: function(event){
    event.stop();
    if(event.findElement("a") == this.curThumb){return;}
    this.bigContainer.addClassName("loading");
    if(this.curThumb){this.curThumb.removeClassName("current");}
    this.curThumb = event.findElement("a");
    this.curThumb.addClassName("current");
    if(this.action){this.action.hide();}
    this.bigContainer.down("img").src = this.curThumb.href;
    if(this.action && this.defaultThumb == this.curThumb){this.action.show();}
  },
  onload: function(){
    this.bigContainer.removeClassName("loading");
  }
};
var RateControl = Class.create();
RateControl.prototype = {
	initialize: function(container){
    this.container = container;
    if(!this.container){return;}
    this.alreadyRated = false;
    this.container.observe("click", this.rate.bind(this));
  },
  rate: function(event){
    event.stop();
    if(this.alreadyRated){return;}
    if(event.target.tagName.toUpperCase() == "A"){
      this.alreadyRated = true;
      this.container.hide();
      var newElement = this.container.next("strong");
      if(newElement){
        newElement.className = event.target.className;
        var rating = newElement.down("span").innerHTML = event.target.className.replace("star", "");
        newElement.show();
      }
    }
    new Ajax.Request('/ext/product-vote', { parameters: {id_item: this.container.id.replace("rateProduct", ""), rating: rating} });
  }
};
var InputSpin = Class.create();
InputSpin.prototype = {
	initialize: function(container, arrowTag){
    this.container = container;
    if(!this.container){return;}
    this.arrowTag = arrowTag || "a";
    this.decrement = this.container.down(this.arrowTag, 1);
    this.increment = this.container.down(this.arrowTag);
    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 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 InputSpin(input.up("th"));
      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 = $("chCart").down("b");
    this.countIndicator2 = $("countNames").down("b");
    this.countIndicatorCaption = $("countNames").down("span");
    this.countIndicatorSum = $("countNames").down("i");
    this.saveChangesButton = $("cartSave");
    this.submitButton = $("placeOrder");
    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 a.remove")){
      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.updateTotalCount();
    if(!parseInt(input.value) || parseInt(input.value) < 1){input.value=1;}
  },
  removeItem: function(row, input){
    row.addClassName("removed");
    input.disabled = true;
    this.updateTotalCount();
  },
  updateTotalCount: function(){
    var oldCount = this.curCount;
    this.curCount = 0; 
    this.curSum = 0;
    this.container.down("tbody").select("th:nth-child(4) input:not([disabled])").each(function(input){
      input.value = input.value.gsub(/\D/, '');
      var itemCount = (parseInt(input.value) > 0 ? parseInt(input.value) : 0);
      this.curCount += itemCount;
      var price = parseFloat(input.up("th").previous("td").down("i").innerHTML.gsub(' ','').gsub(',',''));
      var sumElement = input.up("th").next("th").down("i");
      sumElement.innerHTML = itemCount * price;
      this.curSum += (parseFloat(sumElement.innerHTML.gsub(' ','').gsub(',','')) > 0 ? parseFloat(sumElement.innerHTML.gsub(' ','').gsub(',','')) : 0);
    }.bind(this));
    this.countIndicator1.innerHTML = this.curCount;
    if(this.countIndicator2){this.countIndicator2.innerHTML = this.curCount;}
    if(this.countIndicatorCaption){
      var endWord = (this.curCount%10 == 1 && !(this.curCount+'').endsWith('11'))? '' : 
        ((this.curCount%10 == 2 && !(this.curCount+'').endsWith('12')) || 
        (this.curCount%10 == 3 && !(this.curCount+'').endsWith('13')) || 
        (this.curCount%10 == 4 && !(this.curCount+'').endsWith('14'))) ? 'а' : 'ов';
      this.countIndicatorCaption.innerHTML = 'товар'+endWord;
    }
    this.countIndicatorSum.innerHTML = this.curSum;
    if(this.saveChangesButton && this.noChanges && oldCount != this.curCount){
      this.saveChangesButton.appear();
      this.noChanges = false;
    }
    if(this.submitButton){this.updateSubmitButton();}
  },
  updateSubmitButton: function(){
    this.submitButton.disabled = !this.curCount;
  }
};

var Authorization = Class.create();
Authorization.prototype = {
  initialize: function(){
    ["userSignin", "userSignup", "userCard", "userRecovery"].each(function(element){
      var form = $(element).down("form");
      form.observe("submit", this.submit.bind(this, form));
	  if(Prototype.Browser.IE){
		var inputs = form.select("input[type=text], input[type=password]");
		inputs.each(function(item){
			item.observe("focus", function(){item.addClassName("focused"); });
			item.observe("blur", function(){item.removeClassName("focused"); });
		});
	  }
    }.bind(this));
    new InputHelper("userLogin", "Ваш e-mail");
    new InputHelper("userName", "Имя или псевдоним");
    new InputHelper("userMail", "Ваш e-mail");
	new InputHelper("userMailRecovery", "Ваш e-mail");
    new InputHelper("userСard", "Номер карточки");
    new InputHelper("userСardRecovery", "Номер карточки");
  },
  submit: function(form, event){
    event.stop();
    form.request({
      onSuccess: this.processRequest.bind(this, form),
      onFailure: this.errorStatus.bind(this, form),
      onException: this.errorStatus.bind(this, form),
      on0: this.errorStatus.bind(this, form)
    });
    form.disable();
  },
  processRequest: function(form, xhr){
  	try{
  		var response = xhr.responseText.evalJSON();
  	}catch(e){};
  	
    if(response && response.status && response.status == "ok"){
      if(response.url && !response.url.blank()){location.href = response.url;}
      if(response.message && !response.message.blank()){
        this.showMessage(response.message, form);
      }
    }else if(response && response.status && response.status == "error"){
      this.showErrors(response, form);
    }
    form.enable();
  },
  showErrors: function(response, form){
    if(response.msg){
      form.down("fieldset").addClassName("error");
      $H(response.msg).each(function(item){
        var input = form.down("input[name='"+item.key+"']");
        if(!input){return;}
        var label = input.previous("label");
        if(!label){return;}
        var errorElement = label.down("span");
        errorElement.innerHTML = "<b>"+item.value+"</b>";
      });
    }
  }, 
  showMessage: function(message, form){
    var element = form.down("span.message");
    if(element){element.innerHTML = message;}
  },
  errorStatus: function(form){
    form.enable();
  }
};

var InputHelper = Class.create({
  initialize: function(input, helperText){
    this.input = $(input);
    if(!this.input){return;}
    this.helperText = helperText || "";
    this.input.value = this.helperText; 
    this.input.observe("focus", this.onFocus.bind(this));
    this.input.observe("blur", this.onBlur.bind(this));
    //this.input.up("form").observe("submit", this.onSubmit.bindAsEventListener(this));
  },
  onFocus: function(){
    if($F(this.input) == this.helperText){
		this.input.clear(); /*this.input.setStyle({color: '#636363'});*/
	}
  },
  onBlur: function(){
    if($F(this.input).blank()){
		this.input.value = this.helperText; /*this.input.setStyle({color: '#DEDEDE'});*/ 
	}
  },
  onSubmit: function(event){
    if($F(this.input).blank()){
      event.stop();
  		try {Effect.Shake(this.input.up("fieldset"), { 
        distance: 5,
        duration: 0.225
      });} catch(e){}
			try{new Effect.Highlight(this.input, {queue: {position:'end', scope: "sc"+this.input.id, limit:1}, duration: 0.4, startcolor: "#EB26A3"});} catch(e){}
      this.input.activate();
    }
  }
});

