// initialize when dom (not including images) have been loaded
document.observe("dom:loaded", function(){
	addEventsOnTakeaway();
	addEventsOnFAQ();
	imageRotator.initialize();
	fixedTakeawayBasket();
	activateDeliveryCalculate();
});

// initialize when everything have been loaded
Event.observe(window, "load", function(){
	correctColumns();
});


// correct column heights
/* function correctColumns(){
	var content = $("mainColumnsContainerTakeAway");
	if (content) {
		var columns = content.childElements();
		var heightCollection = columns.invoke("getHeight");
		columns.each(function(n){
			// set the correct column heights on the columnInner element - to respect the layout
			n.down().setStyle({
				height: heightCollection.max()+"px"
			});
		});
	}
}*/

// correct column heights for both textpages and takeaway pages
function correctColumns(){
	var content = $("mainColumnsContainerTakeAway");
	var basket = $("takeawayBasket");
	
	if (content) {
		var takeaway = content.up().hasClassName("takeawayPage")? true:false;
		var sushiAccount = content.up().hasClassName("sushiAccountPage")? true:false;
		var newHeight;
		var columns = content.childElements();
		columns.each(function(v){
			if (!v.hasClassName("mainContentTeaser")){
			v.down().setStyle({
				height: "auto"
			});	
			}
		})
		var mainLeftHeight = $$("div.mainLeftColumn .columnInner")[0].getHeight();
		var page = $$("div.content")[0].down();
		var setExtraLeftHeight = page.hasClassName("takeawayPage") || page.hasClassName("textPage")? true:false;
		
		var heightCollection = columns.invoke("getHeight");
	
		// if the takeaway basket is on the website, make sure to take the height of it into account
		if(basket) {
			heightCollection[heightCollection.length] = basket.getHeight()+10;
		}
		
		columns.each(function(n){
			if (!n.hasClassName("mainContentTeaser")){
				newHeight = heightCollection.max();
				if (setExtraLeftHeight && newHeight-mainLeftHeight < 366){ newHeight = mainLeftHeight+366; }
				if (takeaway && n.hasClassName("mainLeftColumn") && n.getHeight() != newHeight) newHeight+=118;
				if (sushiAccount && n.hasClassName("mainLeftColumn")) newHeight-=1;
				else if (takeaway && !n.hasClassName("mainLeftColumn") && columns[0].getHeight() == newHeight) newHeight-=118;
				// set the correct column heights on the columnInner element - to respect the layout
				n.down().setStyle({
					height: newHeight+"px"
				});
			}
		});
	}
}

function addEventsOnTakeaway(){
	var container = $("mainColumnsContainer");
	if (container){
		var modules = container.select("div.mTakeawayProductNarrow,div.mTakeawayProductWide");
		// for each relevant module on the page, run this function
		modules.each(function(n){
			// set events to show/hide "more text"
			var text = n.select("div.text");
			text.each(function(m){
				var more = m.select("span.more")[0];
				if (more){
					Event.observe(m.select("span.more")[0],"mouseover",function(){
						// activate the full text
						this.up().next().show();
						this.up().hide();
						m.up().up().up().setStyle({
							zIndex: 3
						});

						var selects = document.getElementsByTagName("select");
						for (var i=0,selMax=selects.length;i<selMax;i++){
							selects[i].blur(); // remove focus from any selectbox, so the overlay won't get covered by the options
							if (document.all){ // ie only - remove selectboxes when mouseover is activated
								selects[i].style.visibility = "hidden";
							}
						}
					});
					Event.observe(m.select("span.more")[0].up().next(),"mouseout",function(){
						// activate the full text
						this.previous().show();
						this.hide();
						m.up().up().up().setStyle({
							zIndex: 2
						});
						// ie only - insert selectboxes when mouseout is activated
						if (document.all){
							var selects = document.getElementsByTagName("select");
							for (var i=0,selMax=selects.length;i<selMax;i++){
								selects[i].style.visibility = "visible";
							}
						}
					});
				}
			});
			
			/* set events on selectboxes, so it's not possible to add products to the shopping basket unless a choice have been made */
			var selects = n.select("select");
			selects.each(function(o){
				if ($F(o)==0){
					o.up(".selection").next().childElements().each(function(v){
						v.addClassName("disabled");
						v.title="Knappen er deaktiveret. For at aktivere, skal du først vælge noget ovenfor";
					});
				}
				Event.observe(o,"change", function(){
					var thisVal = $F(this);
					this.up(".selection").next().childElements().each(function(v){
						if (thisVal > 0){
							v.title = "";
							v.removeClassName("disabled");
						}
						else {
							v.title = "Knappen er deaktiveret. For at aktivere, skal du først vælge noget ovenfor";
							v.addClassName("disabled");
						}
					});
				});

			});
			
						
		});
	}
}

function addEventsOnFAQ(){
	//alert('so far');
	var container = $("mainColumnsContainer");
	if (container){
		var modules = container.select("div.m004faq");
		// for each relevant module on the page, run this function
		modules.each(function(n){
			aDt = n.select("dt");
			
			// add an onclick event on all dt elements
			aDt.each(function(m){
				m.observe("click",function(e){
					if (!this.hasClassName("open")){ // open the faq item
						this.addClassName("open");
						this.next(".short").hide();
						this.next(".full").show();
						//correctColumns();
					} else { // close the faq item
						this.removeClassName("open");
						this.next(".full").hide();
						this.next(".short").show();
					}
					//correctColumns(); // make sure the column heights are re-rendered
				});
			});
		});
	}
}

var imageRotator = {
	activeImage:"",
	timer:3000,
	initialize:function(){
		var container = $("mainColumnsContainer");
		if (container){
			var rotators = container.select(".mainContentColumn")[0].select(".mImageRotator");
			rotators.each(function(n){
				var images = n.select("img");
				images.without(images.first()).invoke("hide");
				imageRotator.start(n);
			});
		}
	},
	start:function(n){
		var images = n.select("img");
		if (images.size()>1){
			images.each(function(m){
				if (m.getStyle("display") != "none"){
					imageRotator.activeImage = m;
					throw $break;
				}
			});
			this.nextImage();
		}
	},
	nextImage: function(){
		var nextImage = "";
		nextImage = this.activeImage.next();
		if (this.activeImage == this.activeImage.up().childElements().last()){
			nextImage = this.activeImage.siblings().first();
		}
		
		Effect.Fade(this.activeImage,{delay:2});
		Effect.Appear(nextImage,{delay:2});
		this.activeImage = nextImage;
		window.setTimeout("imageRotator.nextImage()",this.timer);
	}
}

function showPopup(url){
	window.open (url,"sushiPopup","toolbar=0,width=506,height=258");
}

/* make sure that the takeaway basket always stays at a fixed position on the website
 * used to force IE6 to fake the standards compliant browsers correct handling */
function fixedTakeawayBasket(){
	var basket = $("takeawayBasket"),
			parentTop = 248,
			maxLimit, newTopPosition, maxLimit, positionToBottom,viewportHeight, docScroll;
	
	if (!basket) return false; // if there are no basket, don't activate the script
	
  // basket.setStyle({
  //  position: "absolute"
  // });

	Event.observe(window,"scroll",function(){
		docScroll = document.documentElement.scrollTop;
		maxLimit = basket.up().getDimensions().height; // must be set on scroll, as the javascript can't read it before
		viewportHeight = document.viewport.getHeight();
		basketHeight = basket.getDimensions().height;
		positionToBottom = docScroll - parentTop + viewportHeight - basketHeight;
		
		basketBottomPosition = docScroll + basketHeight - parentTop - (basketHeight - viewportHeight)+7;
		if ((parentTop-14) >= docScroll || positionToBottom < 0){
			newTopPosition = 0;
		} else if (positionToBottom > 0 && basketHeight > viewportHeight && maxLimit >= basketBottomPosition) {
			newTopPosition = positionToBottom;
		} else if (positionToBottom > 0 && basketHeight > viewportHeight && maxLimit < basketBottomPosition){
			newTopPosition = maxLimit-basketHeight-7;
		} else {
			newTopPosition = docScroll - parentTop + 14;
		}
		
		basket.setStyle({
			top: newTopPosition + "px"
		});
	});
}



/* functions related to the credits windows */
function creditsWindow(oThis){
	window.open(oThis, 'credits', 'dependent,width=160,height=230')
}
function creditsToDwarf(oThis){
	window.open(oThis,'dwarf','toolbar,menubar,location,titlebar,resizable,directories,status');
	setTimeout('window.close()', 500);
}

/* delivery calculator activation */
function activateDeliveryCalculate(){
	var price = $('deliveryCalculatorPrice'),
			postal = $('deliveryPostal'),
			form = $('deliveryCalc');
	if (form){
		form.observe('submit', function(e){
			webpage = "?"+postal //needs a web address to the page, with the postalcode argument.
			new Ajax.Request(webpage, {
				onSuccess: function(data){
					// insert the postal code, city name and price from the data element
					// just inserted dummy text
					price.down('span').innerHTML = "2000 Frederiksberg";
					price.down('strong').innerHTML = "3000 kr";
				}
			});
			
			// block the forms normal submit function
			Event.stop(e);
		});
	}
}