var drinkCarousel,
    slideshows = [];

function Carousel(container, width, direction, initem, tooltip) {
	var carousel = this;
	this.itemWidth = width;
	this.direction = direction;
	this.current = 0;
	this.amount = $$("#"+container+" .itemlist .item").length;
	this.difference = 0;
	this.speed = 0.3;
	this.itemList = $$("#"+container+" .itemlist")[0];
	this.initem = initem;
	this.useTooltip = tooltip;

	var prev = $$("#"+container+" .prevlink")[0];
	var next = $$("#"+container+" .nextlink")[0];

	this.toggleLinks = function() {
		this.difference = this.current * this.itemWidth;

		if(!this.current)
			prev.hide();
		else
			prev.show();

		if(this.current>=Math.round(this.amount/this.initem)-3)
			next.hide();
		else {
			if(this.amount>3)
				next.show();
			else
				next.hide();
		}
	};

	this.moveRight = function() {
		this.current++;
		this.toggleLinks();
		if(this.direction=="x")
			new Effect.Move(this.itemList, { x: 0-this.difference, mode: 'absolute','duration':this.speed});
		else
			new Effect.Move(this.itemList, { y: 0-this.difference, mode: 'absolute','duration':this.speed});
	};

	this.moveLeft =  function() {
		this.current--;
		this.toggleLinks();
		if(this.direction=="x")
			new Effect.Move(this.itemList, { x: 0-this.difference, mode: 'absolute','duration':this.speed});
		else
			new Effect.Move(this.itemList, { y: 0-this.difference, mode: 'absolute','duration':this.speed});
	};

	this.applyTooltip =  function() {
		var items = $$("#"+container+" .itemlist .item");

		for(i=0; i<items.length; i++) {

			// Väliaikainen!
			items[i].alt=i;
			items[i].observe('mouseover', function(e) {

				$("tooltip").innerHTML = this.title;
				$("tooltip").show();
			});

			items[i].observe('mouseout', function(e) {
				$("tooltip").hide();
			});
		}
	};

	this.init = function() {

		carousel.amount = $$("#"+container+" .itemlist .item").length;
		carousel.current = 0;

        if (this.amount) {

    		if(this.direction=="y") {
    			this.itemList.style.height = ""+Math.round(this.amount/this.initem) * this.itemWidth+"px";
    		}
    		else {


    			if(this.amount>3)
    				this.itemList.style.width = ""+Math.ceil(this.amount/this.initem) * 100+"px";
    			else
    				this.itemList.style.width = ""+this.amount * this.itemWidth+"px";
    		}

    		this.itemList.show();
    		this.toggleLinks();
    		if(this.useTooltip)
    			this.applyTooltip();

    		prev.observe('click', function(e) {
    			carousel.moveLeft();
    			Event.stop(e);
    		});
    		next.observe('click', function(e) {
    			carousel.moveRight();
    			Event.stop(e);
    		});

        }
	};
	this.init();

	this.resetcarousel = function() {
		carousel.amount = $$("#"+container+" .itemlist .item").length;
		carousel.current = 0;

		if(this.direction=="y") {
			this.itemList.style.height = ""+Math.round(this.amount/this.initem) * this.itemWidth+"px";
		}
		else {
			if(this.amount>3)
				//this.itemList.style.width = ""+Math.ceil(this.amount/this.initem) * this.itemWidth+"px";
				this.itemList.style.width = ""+Math.ceil(this.amount/this.initem) * 100+"px";
			else
				this.itemList.style.width = ""+this.amount * this.itemWidth+"px";
		}

		this.toggleLinks();
	};
}

function Slideshow (el) {
	var slideshow = this;
	this.direction = 1;
	this.delay = 5000;
	this.index = 0;
    this.slides = el.select('a');
    this.el = el;
    this.navigation = el.previous('h3').select('.slideshow-navigation')[0];
    this.dots = [];
	this.container = el.select('.slideshow-container')[0];
    this.link = el.next('a');
    this.width = el.getWidth();
    this.interval = null;

    this.loopSlides = function ()
    {
        /* Loops index between 0 and the amount of highlights */
        slideshow.index = (slideshow.index + 1) % slideshow.slides.length;

        /* Reset position, if loop has started over */
        if (slideshow.index == 0) {
            slideshow.index++;
            slideshow.container.style.left = '0px';
        }

        slideshow.animate();
    };
	
	
    this.gotoSlide = function (e) {
	    Event.stop(e);
        if (slideshow.interval) {
            clearInterval(slideshow.interval);
            slideshow.interval = null;
        }
        slideshow.index = parseInt(this.href.split('#')[1], 10);

        slideshow.interval = setInterval(slideshow.loopSlides, slideshow.delay);
        slideshow.animate();
    };
	
	
    this.animate = function () {
        /* Update navigation and link */
        for (var i = 0; i < slideshow.dots.length; i++) {
            slideshow.dots[i].removeClassName('active');
        }
        var trueIndex = slideshow.index % (slideshow.slides.length - 1);
        
		slideshow.dots[trueIndex].addClassName('active');
        slideshow.link.href = slideshow.slides[trueIndex].href;
        slideshow.link.innerHTML = slideshow.slides[trueIndex].title;
		
		
        /* Do the slide animation */
        new Effect.Move(slideshow.container, { x: -(slideshow.index * slideshow.width), mode: 'absolute', duration: 1/*, afterFinish: function() {}*/});
    };

	this.constructor = (function() {
        if (slideshow.slides && slideshow.slides.length - 1 > 1) {
            /* Generate navigation */
            for (var i = 0; i < slideshow.slides.length - 1; i++) {
                var dot = new Element('a', {href: '#' + i});
                dot.observe('click', slideshow.gotoSlide);
                slideshow.navigation.insert(dot);
                slideshow.dots.push(dot);
            }
            slideshow.dots[slideshow.index].addClassName('active');

            /* Set container width */
            slideshow.container.style.width = slideshow.slides.length * slideshow.width + 'px';
            slideshow.interval = setInterval(slideshow.loopSlides, slideshow.delay);
        }
	})();
}

function showDrinks() {
	var valintalista = $$("#checkboxlist .product_selected"),
        i,
        drinks;

	if (valintalista.length>0) {
		drinks = $$("#drinkselector li a");
		for (i=0; i<drinks.length; i++) {
			drinks[i].parentNode.className = "hideditem";
		}

		for (i=0; i<drinks.length; i++) {

			for (var k=0; k<valintalista.length; k++) {
				var inrc = drinks[i].className.split(" ");

				for (var j=0; j<inrc.length; j++) {

					if(valintalista[k].parentNode.id==inrc[j]) {
						drinks[i].parentNode.className = "item";
					}
				}
			}

		}
	}

	else {
		drinks = $$("#drinkselector li");
		for (i=0; i<drinks.length; i++) {
			drinks[i].className = "hideditem";
		}
	}

	drinkCarousel.resetcarousel();
	//delete drinkCarousel;
	//drinkCarousel = new Carousel("drinkselector", 70, "x", 1, true);
}

function bakeCookies(drink, product, select) {
	vodkas = jar.get(drink);

	if(select=="product_selected" && vodkas) {
		if(vodkas) {
			for(i=0; i<vodkas.length; i++) {
				if(vodkas[i]==product) {
					delete vodkas[i];
					jar.put(drink, vodkas);
				}

			}
		}
	}
	else {
		if(!vodkas)
			jar.put(drink, []);
		vodkas = jar.get(drink);
		vodkas.push(product);

		jar.put(drink, vodkas);
	}
}

window.onload = function() {
	
    var agecheck = $$("#agecheck"),
        page = $$(".content")[0].id;

    if (agecheck.length) {
        initAgeCheck();
	
		$('age_d').focus();
		
        new Form.Element.Observer(
            'age_d',
            0.2,
            function(el, value){
                if (value > 3 || value.length == 2)
                    $('age_m').focus();
            }
        );

        new Form.Element.Observer(
            'age_m',
            0.2,
            function(el, value){
                if (value > 1 || value.length == 2)
                    $('age_y').focus();
            }
        );

        return;
    }
	
	if ($$("#bgContainer").length)
		flashSizing();

	if($("toggle_products_liqueur") && $("toggle_products_liqueur")) {
		$("toggle_products_liqueur").observe('click', function(e) {
			this.hide();
			$("thumb_products_vodka").hide();

			$("thumb_products_liqueur").show();
			$("toggle_products_vodka").show();

			Event.stop(e);
		});

		$("toggle_products_vodka").observe('click', function(e) {
			this.hide();
			$("thumb_products_liqueur").hide();

			$("thumb_products_vodka").show();
			$("toggle_products_liqueur").show();

			Event.stop(e);
		});
	}
	
	
    var els = $$('.slideshow');
	for (var i = 0; i < els.length; i++) {
		slideshows.push(new Slideshow(els[i])); 
	}
	
    

	if(page=="drinks" || page=="products") {
		drinkCarousel = new Carousel("drinkselector", 63, "x", 1, true);

		if(page=="drinks") {
			var drink = $("checkboxlist").title;
			var links = $$("#checkboxlist li a");

		    jar = new CookieJar({
				expires:3600,   // seconds
				path: '/'
			});

            if (location.hash) {
                var ingredient = location.hash.substr(1);
				for(i=0; i<links.length; i++) {
					if(links[i].parentNode.id==ingredient)
						links[i].className = "product_selected";
					else
						links[i].className = "";
				}
            } else {
			    vodkas = jar.get(drink);

			    if(vodkas) {
				    for(i=0; i<links.length; i++) {
					    for(j=0; j<vodkas.length; j++) {
						    if(links[i].parentNode.id==vodkas[j]) {
							    links[i].className = "";
							    break;
						    }
						    else
							    links[i].className = "product_selected";
					    }
				    }
			    }
            }

			showDrinks();
		}
	}
	else if (page=="barsevents") {
		var barCarousel = new Carousel("bars", 41, "y", 1);
		var eventCarousel = new Carousel("events", 41, "y", 1);
	}

	var plist = $$('.content ul#checkboxlist li a');
	if (plist.length) {
		for (var i=0; i<plist.length; i++) {
			plist[i].observe('click', function(e) {
				if(this.className != "product_selected") {
					this.className = "product_selected";
				}
				else {
					this.className = "";
				}


				$$('#drinkselector ul')[0].style.left = "0px";
				//drinkCarousel.current = 0;

				bakeCookies(this.parentNode.parentNode.title, this.parentNode.id, this.className);
				showDrinks();



				Event.stop(e);
			});
		}
	}
};

function fadeToBlack (duration) {
	
    $$('#footer h3,#footer a.txtlink,#footernav,#footernav .fitem').each(function (el) {
        el.removeClassName('inverse');
    });
	
	if($$('#nobelSticker').length) {
		$('nobelStickerNega').hide();
		$('nobelSticker').show(duration);
	}
    $(document.body).setStyle({backgroundColor: '#000000'});
    if ($$('body.english').length) {
        Cufon.replace('#footer h3.cufoni', {
            fontFamily: 'Helvetica Neue LT Pro',
            hover: true
        });
    }
}

function fadeToWhite (duration) {
    $$('#footer h3,#footer a.txtlink,#footernav,#footernav .fitem').each(function (el) {
        el.addClassName('inverse');
    });
	
	if($$('#nobelSticker').length) {
		$('nobelSticker').hide();
		$('nobelStickerNega').show(duration);
	}
	
    $(document.body).setStyle({backgroundColor: '#ffffff'});
    if ($$('body.english').length) {
        Cufon.replace('#footer h3.cufoni', {
            fontFamily: 'Helvetica Neue LT Pro',
            hover: true
        });
    }
}

function initAgeCheck() {
	var korkeus = parseInt($('footer').getStyle('top')) + $('footer').getHeight();
	var korkeus2 = $('wrapper').getHeight();
	if(korkeus > 0) {
		$("agecheck").setStyle({'height' : korkeus +'px'});
	} else {
		$("agecheck").setStyle({'height' : korkeus2 +'px'});	
	}
}

function flashSizing() {
	
	var korkeus = parseInt($('footer').getStyle('top')) + $('footer').getHeight();
	var korkeus2 = $('wrapper').getHeight();
	if(korkeus > 0) {
		$("bgContainer").setStyle({'height' : korkeus +'px'});
	} else {
		$("bgContainer").setStyle({'height' : korkeus2 +'px'});	
	}
	
}

