if(! ("console" in window) ){
  console = { log: function(){}  };
}else{
  if(!console.log){console.log = function(){};}
}

document.observe("dom:loaded", initApplication);

function initApplication(){

    Inkerman = new App();

    var imgs = $$('#rotimages img');
    if(imgs.length){
        var i = 0;
        setInterval(function(){
            imgs[i].fade({duration: 2.0,  afterFinish: function(){
                if(i == imgs.length-1){i=-1;}
                imgs[++i].appear({duration: 2.0 });
            }})
        }, 6000);
    }

}

var App = Class.create();
App.prototype = {
    initialize: function(){
        if($("YearContainer") && $("timeline")){
            this.historyRotator = new HistoryRotator("YearContainer", "timeline");
        }
        if($("GuideContainer")){
            var dishGuideOptions = {
                guideContainer: $("GuideContainer"),
                dishClassContainer: $("DishClass"),
                dishTypeList: $("DishTypeList"),
                winesContainer: $("Wines"),
                winesTemplateContainer: $("winesTemplate"),
                wineItemTemplateContainer: $("wineItemTemplate"),
                wineDetailContainer: $("WineDetail")
            }
            this.dishGuide = new DishGuide(dishGuideOptions);
        }
        if($("guideWine")){
            var dishGuideOptions = {
                guideContainer: $("guideWine"),
                wineTypeContainer: $("WineTypeContainer"),
                wineColorContainer: $("WineColor"),
                dishesContainer: $("Dishes"),
                dishesListContainer: $("DishesListContainer"),
                winesContainer: $("WinesListContainer")
            }
            this.DishByWine = new DishByWine(dishGuideOptions);
        }
	this.initDialogs(["Social", "Legal", "Low18"]);
    },
	initDialogs: function(dialogsArray){
		dialogsArray.each(function(dialog){
			if($("dialogLink_"+dialog)){
	            $("dialogLink_"+dialog).observe("click", this.dialogLinkHandler.bind(this));
	        }
      if($("closeButton_"+dialog)){
          $("closeButton_"+dialog).observe("click", this.closeDialogHandler.bind(this));
      }
		}.bind(this));
	},
	dialogLinkHandler: function(event){
		if(event && event.target){
			var link = event.findElement("a");
			if(link && link.id){
				event.stop();
				var dialog = link.id.replace("dialogLink_", "");
				this.showDialog(dialog);
			}
		}
	},
	closeDialogHandler: function(){
		if(this.dialog){this.dialog.close();}
	},
	showDialog: function(dialog){
		if(!this.dialog){
			this.dialog = new Dialog();
		}
		this.dialog.show(dialog, "Overlay", "Appear");
	}
};

var HistoryRotator = Class.create();
HistoryRotator.prototype = {
    initialize: function(yearContainer, timeline){
        this.yearContainer = $(yearContainer);
        this.timeline = $(timeline);
        if(!(this.yearContainer && this.timeline)){return;}
        this.timelineList = this.timeline.down("ul");
        this.timelineItems = this.timeline.select("a");
        if(!(this.timelineList && this.timelineItems.length)){return;}
        this.timelineItemWidth = 90;
        this.timelineVisibleWidth = 920;
        this.timelineScrollIterationOffset = Prototype.Browser.IE ? 5 : 3;
        this.timelineScrollIterationDelay = 2;
        this.scrollTimer = {};
        this.timeline.observe("click", this.timelineClickHandler.bind(this));
        document.observe("mousemove", this.timelineMousemoveHandler.bind(this));
        this.yearPrevButton = $("YearPrev");
        this.yearNextButton = $("YearNext");
        this.scrollLeftArea = $("scrollLeftArea");
        this.scrollRightArea = $("scrollRightArea");
        if(this.yearPrevButton){
            this.yearPrevButton.observe("click", this.arrowClickHandler.bind(this, -1));
        }
        if(this.yearNextButton){
            this.yearNextButton.observe("click", this.arrowClickHandler.bind(this, 1));
        }
    },
    scrollAreaEnterHandler: function(direction, event){
        if(this.scrollTimer[direction]){return;}
        var curTimelineOffset = parseInt(this.timelineList.getStyle("marginLeft"));
        var offset = this.timelineScrollIterationOffset;
        if(direction == "left"){
            if(curTimelineOffset == - (this.timelineItemWidth*this.timelineItems.length - this.timelineVisibleWidth)){return;}
            offset *= -1;
        }else if(curTimelineOffset == 0){ return; }
        var delay = this.timelineScrollIterationDelay;
        this.scrollTimer[direction] = setInterval(this.scrollTimelineBy.bind(this, offset), delay);
    },
    timelineMousemoveHandler: function(event){
        if(Position.within(this.scrollLeftArea, event.pointerX(), event.pointerY())){
            this.scrollAreaEnterHandler("right");
            return;
        }
        if(Position.within(this.scrollRightArea, event.pointerX(), event.pointerY())){
            this.scrollAreaEnterHandler("left");
            return;
        }

        ["left", "right"].each(function(direction){
            if(this.scrollTimer[direction]){
                clearInterval(this.scrollTimer[direction]);
                this.scrollTimer[direction] = null;
            }
        }.bind(this));
    },
    timelineClickHandler: function(event){
        event.stop();
        var target = event.target;
        if(target.tagName.toLowerCase() == "a" && target.href && target.href.include("#Year")){
            var year = this.getElementYear(target);
            this.timeline.down("li.current").removeClassName("current");
            target.up("li").addClassName("current");
            this.showYear(year);
        }
    },
    arrowClickHandler: function(offset, event){
        event.stop();
        event.target.blur();
        if(this[offset>0 ? "yearNextButton" : "yearPrevButton"].hasClassName("disabled")){return;}
        var curTimelineListItem = this.timeline.down("li.current");
        var curTimelineElement = curTimelineListItem.down("a");
        if(!curTimelineElement){return;}
        var newTimelineListItem = curTimelineElement.up("li")[offset>0 ? "next" : "previous"]("li", Math.abs(offset)-1);
        if(!newTimelineListItem){
            this[offset>0 ? "yearNextButton" : "yearPrevButton"].addClassName("disabled");
            return;
        }
        var newTimelineElement = newTimelineListItem.down("a");
        if(newTimelineElement.href && newTimelineElement.href.include("#Year")){
            curTimelineListItem.removeClassName("current");
            var newYear = this.getElementYear(newTimelineElement);
            newTimelineListItem.addClassName("current");
            this.showYear(newYear);
        }
    },
    getElementYear: function(element){
        return element.href.replace(/.+#Year/, "");
    },
    showYear: function(year){
        var yearElement = $("Year"+year);
        var yearContent = yearElement ? yearElement.innerHTML : this.yearContainer.innerHTML;
        this.yearContainer.innerHTML = yearContent;
        var curTimelineElement = this.timeline.down("li.current a");
        if(this.yearPrevButton){this.yearPrevButton[curTimelineElement == this.timelineItems.first() ? "addClassName" : "removeClassName"]("disabled");}
        if(this.yearNextButton){this.yearNextButton[curTimelineElement == this.timelineItems.last() ? "addClassName" : "removeClassName"]("disabled");}
        this.scrollTimelineTo(curTimelineElement);
    },
    scrollTimelineTo: function(item){
        var itemIndex = this.timelineItems.indexOf(item);
        var curTimelineOffset = parseInt(this.timelineList.getStyle("marginLeft"));
        var rightOverlap = (itemIndex+1)*this.timelineItemWidth - (this.timelineVisibleWidth - curTimelineOffset);
        if(rightOverlap>0){
            this.timelineList.setStyle({marginLeft: (curTimelineOffset - rightOverlap)+"px" });
        }
        var leftOverlap = Math.abs(curTimelineOffset) - itemIndex*this.timelineItemWidth;
        if(leftOverlap > 0){
            this.timelineList.setStyle({marginLeft: (curTimelineOffset + leftOverlap)+"px" });
        }
    },
    scrollTimelineBy: function(deltaPixels){
        var curTimelineOffset = parseInt(this.timelineList.getStyle("marginLeft"));
        if(deltaPixels < 0){
            var rightOverlap = this.timelineItems.length*this.timelineItemWidth - (this.timelineVisibleWidth - curTimelineOffset);
            if(rightOverlap < Math.abs(deltaPixels)){ deltaPixels = -rightOverlap; }
        }
        if(deltaPixels > 0 && deltaPixels > Math.abs(curTimelineOffset)){ deltaPixels = Math.abs(curTimelineOffset); }
        this.timelineList.setStyle({marginLeft: (curTimelineOffset + deltaPixels)+"px" });
    }
};

var DishGuide = Class.create();
DishGuide.prototype = {
    initialize: function(guideOptions){
        Object.extend(this, guideOptions);
        if(!(this.guideContainer && this.dishClassContainer && this.dishTypeList && this.winesContainer)){return;}
        this.guideContainer.observe("click", this.clickHandler.bind(this));
        this.winesTemplate = this.winesTemplateContainer.innerHTML;
        this.wineItemTemplate = this.wineItemTemplateContainer.innerHTML;
        this.dialog = new Dialog();
        this.currentItemColomn1 = false;
    },
    clickHandler: function(event){
	if(!event){return;}
 	if(event.target && $(event.target).descendantOf(this.wineDetailContainer)){return;}
        event.stop();
        var listItem = event.findElement("li");
        if(listItem){
            var id = listItem.id;
            if(id && id.startsWith("dishClass_")){
                if(listItem.hasClassName("current")){return;}
                var dishClassId = id.replace("dishClass_", "");
                this.markCurrent(this.dishClassContainer, listItem);
                if ($('dishClass_info_'+dishClassId)) {
                  $('dishClass_info_'+dishClassId).show();
                }
                this.showDishTypes(dishClassId);
                if (this.currentItemColomn1 && $('dishClass_info_'+this.currentItemColomn1)) {
                  $('dishClass_info_'+this.currentItemColomn1).hide();
                }
                this.currentItemColomn1 = dishClassId;
            }

            if(listItem.descendantOf(this.dishTypeList)){
                var dishLink = listItem.down("a");
                if(dishLink && dishLink.href && dishLink.rel){
                    var winesIds = dishLink.rel.split(",");
                    if(winesIds && winesIds.length){
                        this.markCurrent(this.dishTypeList, listItem);
                        this.showDishWines(winesIds);
                    }
                }
            }
        }
        var wineItem = event.findElement("dd");
        if(wineItem){
            var wineItemId = wineItem.id;
            if(wineItemId && wineItemId.startsWith("wineItem_")){
                var wineId = wineItemId.replace("wineItem_", "");
                this.showWineDetails(wineId);
            }
        }
    },
    markCurrent: function(container, listItem){
        var curCurrentTypeItem = container.down("li.current");
        if(curCurrentTypeItem){curCurrentTypeItem.removeClassName("current");}
        listItem.addClassName("current");
    },
    showDishTypes: function(dishClassId){
        var dishClassTypesList = $("dishType_"+dishClassId);
        if(dishClassTypesList){
            this.guideContainer.className = "types";
            this.dishTypeList.innerHTML = dishClassTypesList.innerHTML;
        }else{
            this.guideContainer.className = "";
        }
        this.winesContainer.hide();
    },
    showDishWines: function(winesIds){
        this.winesContainer.innerHTML = this.winesTemplate;
        var curWinesSet = {};
        var type;
        var cat;
        winesIds.each(function(id){
            if(InkermanWines[id] && InkermanWines[id].type && InkermanWines[id].name && InkermanWines[id].category){
                type = InkermanWines[id].type;
                cat  = InkermanWines[id].category;
                if(!curWinesSet[type]){
                    curWinesSet[type] = [];
                }
                if(!curWinesSet[type][cat]){
                    curWinesSet[type][cat] = '<dt>' + InkermanCategories[cat].name + '</dt>';
                }
                curWinesSet[type][cat] += this.wineItemTemplate.interpolate(InkermanWines[id]);
            }
        }.bind(this));
        for(var type in curWinesSet){
            this.winesContainer.down("dl."+type).show().insert(curWinesSet[type].join(''));
        }
        this.winesContainer.show();
        this.guideContainer.className = "wines";
    },
    showWineDetails: function(wineId){
        var wineItemDetailsElement = $("wineItemDetails_"+wineId);
        if(!wineItemDetailsElement){return;}
        var wineItemDetailsHTML = wineItemDetailsElement.innerHTML;
        if(this.wineDetailContainer && wineItemDetailsHTML){
            this.wineDetailContainer.innerHTML = wineItemDetailsHTML;
            this.wineDetailContainer.className = "wine_"+wineId;
            this.wineDetailContainer.style.backgroundImage = "url('"+InkermanWines[wineId].image+"')";
            this.dialog.show(this.wineDetailContainer);
        }
    }
};
var Dialog = Class.create();
Dialog.prototype = {
  initialize: function(){
    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, overlay, effect){
    var oldDialog = this.curDialog;
    this.curDialog = $(dialog);
    if(!this.curDialog){return;}
    this.overlay = overlay ? $(overlay) : null;
    if(this.overlay){this.overlay.show();}
    if(!this.opened){
        //this.curDialog.style.display = "block";
		var effect = effect || "Grow";
        new Effect[effect](this.curDialog, { duration: 0.5, opacityTransition: Effect.Transitions.linear });
    }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"))){
        event.stop();
        this.close();
      }
    }
  },
  close: function(){
    if(this.opened){
      $(document.body).removeClassName("modalOn");
      //this.curDialog.hide();
        if(this.overlay){
          this.overlay.hide();
          this.overlay = null;
        }
        new Effect.Fade(this.curDialog, {
            duration: 0.3
//			,afterFinish: function(){
//		      if(this.overlay){
//		        this.overlay.hide();
//		        this.overlay = null;
//		      }
//			}.bind(this)
        });
      this.opened = false;
    }
  }
};


var DishByWine = Class.create();
DishByWine.prototype = {
    initialize: function(guideOptions){
        Object.extend(this, guideOptions);
        if(!(this.guideContainer && this.wineTypeContainer && this.dishesContainer && this.winesContainer)){return;}
        this.guideContainer.observe("click", this.clickHandler.bind(this));
        this.currentItemColomn1 = false;
    },
    clickHandler: function(event){
	if(!event){return;}
        event.stop();
        var listItem = event.findElement("li");
        if(listItem){

            var id = listItem.id;

            if(id && id.startsWith("dishClass_")){

                var dishClassId = id.replace("dishClass_", "");
                this.showWineTypes(dishClassId);
                this.winesContainer.innerHTML = '';
                this.dishesContainer.hide();
                this.markCurrent(this.wineColorContainer, listItem);

            }

            if(id && id.startsWith("wineType_")){

              var relId = id.replace("wineType_", "");
              this.showWines(relId);
              this.dishesContainer.hide();
              this.markCurrent(this.wineTypeContainer, listItem);

            }

            if(id && id.startsWith("wineId_")){

              var relId = id.replace("wineId_", "");
              this.showDishes(relId);
              this.dishesContainer.show();
              this.markCurrent(this.winesContainer, listItem);

            }
        }
    },
    markCurrent: function(container, listItem){
        var curCurrentTypeItem = container.down("li.current");
        if(curCurrentTypeItem){curCurrentTypeItem.removeClassName("current");}
        listItem.addClassName("current");
    },
    showWineTypes: function(dishClassId){

      if (InkermanRelWineTypes[dishClassId]) {
        var html = '';
        var val;
        for (var i=0; i < InkermanRelWineTypes[dishClassId].length; i++) {
          val = InkermanRelWineTypes[dishClassId][i];
          if (InkermanWineTypes[val]) {
            html += '<li id="wineType_'+val+':'+dishClassId+'"><a href="#">'+InkermanWineTypes[val]['name']+'</a></li>';
          }
        }
        this.wineTypeContainer.innerHTML = html;
      }
    },
    showWines: function(TypeColor){
      if (InkermanRelProducts[TypeColor]) {
        var html = '';
        var val;
        for (var i=0; i < InkermanRelProducts[TypeColor].length; i++) {
          val = InkermanRelProducts[TypeColor][i];
		  if (!InkermanRelDishes[val]) continue;
          if (InkermanWines[val]) {
            html += '<li id="wineId_'+val+'"><a href="#">'+InkermanWines[val]['name']+'</a></li>';
          }
        }
        this.winesContainer.innerHTML = html;
      }
    },
    showDishes: function(wineId){
      if (InkermanRelDishes[wineId]) {
        var html = '';
        var val;
        var info;
        var keys = [];
        var to_render = {};
        for (var i=0; i < InkermanRelDishes[wineId].length; i++) {
          val = InkermanRelDishes[wineId][i];
          if (InkermanDishes[val]) {
            info = InkermanDishes[val];

            if (!to_render[info['name']]) {
              keys.push(info['name']);
              to_render[info['name']] = [];
            }
            if (info['description']) {
              to_render[info['name']].push(info['description']);
            }
          }
        }
        if (keys.length) {
          for (var i=0; i < keys.length; i++) {

            html += '<dt>'+keys[i]+'</dt>';

            if (to_render[keys[i]].length) {
              for (var y=0; y < to_render[keys[i]].length; y++) {
                html += '<dd>'+to_render[keys[i]][y]+'</dd>';
              }
            }
          }
        }
        this.dishesListContainer.innerHTML = html;
      }
    }

};
