// Cufon:
Cufon.replace("h1, h2, h3, p.toggle");
Cufon.replace("#nav > div > h2", {textShadow: '#333 0px 2px'});

var totalItems;
var itemsLoaded = 0;
var currentItem;
var intervalID;
var startPos;
var widths;
var currentHash;
var directLoad;
var ratio;
var oldFrom;
var isIE = (navigator.appName=="Microsoft Internet Explorer");
var intervalCounter = 0;

$(function(){
	// Afbeeldingen laden:
	totalItems  = $("#collectie div.item[rel=collectie] img").length;
	oldFrom     = parseInt($("var.oldFrom").text());
	itemsLoaded = 0;
	currentItem = 0;
	currentHash = window.location.hash;
	directLoad  = false;
	// Kijken of er een hash-tag is:
	if(currentHash != '#' && currentHash != '')
	{
		a = window.location.hash.split('/');
		var action = a[1];
		var id     = a[2];
		switch(action)
		{
			case 'collectie' :
				{
					currentItem = id;
					break;
				}
			default :
				{
					directLoad = '/' + action + '/';
					break;
				}
		}
	}
	
	// Kijken of de afbeeldingen geladen zijn:
	intervalID = setInterval("checkIfImagesAreLoaded()", 100);
});

// Functionaliteit koppelen zodra alle afbeeldingen geladen zijn:
function initialize()
{
	// Images clickable:
	$("#collectie div.item[rel=collectie] img, #collectie div.item.info div.inner").click(function(){
		currentItem = String($(this).parent().attr("id")).replace("item_", "");
		hideContentHolder();
		return false;
	});
	$("#collectie div.intro img").click(function(){
		currentItem = 1;
		hideContentHolder();
	});
	// Navigatie:
	$("#nav > div").hover(function(){
		$(this).stop().animate({bottom: -54}, 150);
		if(!$(this).hasClass("active"))
		{
			if(!isIE) {
				$("div.hover", this).show().css({opacity: 0}).stop().animate({opacity: 1});
			} else {
				$("div.hover", this).show();
			}
		}
	}, function(){
		$(this).stop().animate({bottom: -94}, 350);
		if(!$(this).hasClass("active"))
		{
			if(!isIE) {
				$("div.hover", this).stop().animate({opacity: 0});
			} else {
				$("div.hover", this).hide();
			}
		}
	}).click(function(){
		if($("a.logo", this).length == 1)
		{
			currentItem = 0;
			hideContentHolder();
			return false;
		} else {
			if($("a", this).length == 1)
			{
				// Content tonen:
				$("#nav div.hover").hide();
				$(this).addClass("active");
				$("div.hover", this).show().css({opacity: 1});
				showContentHolder($("a", this).attr("href"));
			}
		}
	});
	$("#nav div a").click(function(){
		if($(this).hasClass("logo")) {
			currentItem = 0;
			hideContentHolder();
			return false;
		} else {
			showContentHolder($(this).attr("href"));
			$("#nav div").removeClass("active");
			$(this).parent().parent().addClass("active");
			return false;
		}
	});
	// Holder:
	$("#holder a.close").click(function(){
		hideContentHolder();
		return false;
	});
	// Arrows:
	$("a.arrow.left").click(function(){
		currentItem--;
		if(currentItem < 0) { currentItem = 0; }
		hideContentHolder();
		return false;
	});
	$("a.arrow.right").click(function(){
		currentItem++;
		if(currentItem >= totalItems + 1) {	currentItem = totalItems + 1; } // +1 omdat er twee extra textslides tussen zitten
		hideContentHolder();
		return false;
	});
	// Labels:
	$("div.label a.close").click(function(){
		$(this).parent().parent().hide();
		if($("div.label:visible", $(this).parent().parent().parent()).length > 0)
		{
			$("a.toggle").removeClass("off");
		} else {
			$("a.toggle").addClass("off");
		}
		return false;
	});
	// Toggle:
	$("a.toggle").click(function(){
		// console.log($("div.label:visible", $(this).parent()).length);
		if($("div.label:visible", $(this).parent()).length == 0) {
			// Maak alles zichtbaar
			$("div.label", $(this).parent()).show();
			$(this).removeClass("off");
		} else {
			// Maak alles onzichtbaar:
			$("div.label", $(this).parent()).hide();
			$(this).addClass("off");
		}
		return false;
	});
}

// Toon de content-holder
function showContentHolder(url)
{
	// Holder correcte afmetingen geven (deze worden namelijk verwoest als er een keer een slideshow is getoond):
	
	$("#holder").removeClass("black").stop().css({width: 705, marginLeft: -352});
	
	// Alle afbeeldingen dimmen:
	$("#collectie div.item").stop().animate({opacity: .3});
	// Alle labels verbergen:
	$("#collectie div.item[rel=collectie] div.label").hide();
	// Alle togglers verbergen:
	$("#collectie div.item[rel=collectie] a.toggle").hide();
	// Content-holder tonen:
	var item = $("#collectie div.item:eq(" + currentItem + ")");
	
	// var currentItemWidth = item.width();
	item.stop().animate({opacity: .3, marginRight: 705});
	// Animeer de #collectie:
	var leftPos = startPos;
	// Positie juist instellen:
	for(i=0; i<currentItem; i++)
	{
		leftPos -= $("#collectie div.item:eq(" + i + ")").width();
	}
	// Nu lijnt alles links uit. Berekening uitvoeren dat alles gecentreerd wordt:
	leftPos += 500;
	leftPos -= $("#collectie div.item:eq(" + currentItem + ")").width() / 2;
	// Rekening houden met de breedte:
	leftPos -= 705 + ((parseInt(item.width()) - 705) / 2) - 12;
	
	$("#holder").stop().show();
	$("#collectie").animate({left: leftPos}, function(){
		$("#holder").css({zIndex: 2});
		$("#collectie").css({zIndex: 1});
	});
	
	$("#loader").fadeIn();
	$("#loader span").text("0 %");
	$("#holder div.inner").hide().load(url + ' #ajax>*', function(){
		$("#loader").text("100 %").fadeOut();
		$("#holder div.inner").fadeIn();
		initializeJavaScript(url);
	});
	window.location.hash = url;
	currentHash = window.location.hash;
	
}

// Verberg de content-holder:
function hideContentHolder()
{
	$("#holder").css({zIndex: 1}).fadeOut();
	$("#collectie").css({zIndex: 2});	
	$("#nav div").removeClass("active");
	$("#nav div.hover").hide();
	positionCollection();
}

// Animeer naar het huidige item:
function positionCollection(animate)
{
	// Linkerpositie:
	var leftPos = startPos;
	// Alle items resetten:	
	$("#collectie div.item").css({zIndex: 1}).stop().animate({marginRight: 0, opacity: .3});
    // Eerste item moet altijd volle opacity zijn bij item 0:
    if(currentItem == 0)
    {
        $("#item_1").stop().animate({opacity: 1});
    }
	// Alle labels verbergen:
	$("#collectie div.item[rel=collectie] div.label").hide();
	// Alle togglers verbergen:
	$("#collectie div.item[rel=collectie] a.toggle").hide();
	
	// Animeren naar het juiste item:
	var item = $("#collectie div.item:eq(" + currentItem + ")");
	item.css({zIndex: 2}).stop().animate({marginRight: 0, opacity: 1});
	
	window.location.hash = '/collectie/' + currentItem;
	currentHash = window.location.hash;
	
	// Positie juist instellen:
	for(i=0; i<currentItem; i++)
	{
		leftPos -= $("#collectie div.item:eq(" + i + ")").width();
	}
	// Nu lijnt alles links uit. Berekening uitvoeren dat alles gecentreerd wordt:
	leftPos += 500;
	leftPos -= $("#collectie div.item:eq(" + currentItem + ")").width() / 2;
	
	// Labels:
	$("div.label").removeClass("label-tr label-br label-tl label-bl");
	$("div.label", item).each(function(){
		var coords = $("var", this).text().split(',');
		var left = coords[0] * ratio;
		var top  = coords[1] * ratio;
		
		// Labels staan standaard rechtsonder
		// Als er geen ruimte rechts is, links
		// Als er geen ruimte onder is, boven
		var className = 'label-';			
		// Bereken de hoogte van de labels (dit moet handmatig, omdat $(this).height() 0 terug geeft:
		var labelHeight = 12 + ($("h3", this).length * 40);
		className += top < $(window).height() - labelHeight - 150 ? 'b' : 't';
		if(left > $(item).width() / 2)
		{
			// Voorkeur aan de rechterkant:
			className += left < $(window).width() - 423 ? 'r' : 'l';
		} else {
			// Voorkeur aan de linkerkant:
			className += left < $(window).width() - 850 ? 'l' : 'r';
		}
		
		switch(className)
		{
			case 'label-tr' :
				{
					$(this).css({marginLeft: left - 2, marginTop: top - 9 - labelHeight});						
					break;
				}
			case 'label-tl' :
				{
					$(this).css({marginLeft: left - 285, marginTop: top - labelHeight});
					break;
				}
			case 'label-br' :
				{
					$(this).css({marginLeft: left - 2, marginTop: top - 9});						
					break;
				}
			case 'label-bl' :
				{
					$(this).css({marginLeft: left - 285, marginTop: top - 38});						
					break;
				}
		}
		$(this).addClass(className).fadeIn();
	});
	
	if(leftPos > startPos) { leftPos = startPos; }
	
	if(animate == null || animate == true)
	{
		$("#collectie").stop().animate({left: leftPos});
	} else {
		$("#collectie").css({left: leftPos});
	}
}

// Functie die alle afbeeldingen schaalt en zo:
function recalculateCollection()
{
	var totalWidth = 500 + 705;
	
	// 948 = 100% (900 + 48 van footer)
	ratio = $(window).height() / 948;
	widths = [];
	
	// Resize de afbeeldingen naar de browser:
	$("#collectie div.item[rel=collectie]").each(function(){
		var image = $("img", this);
		image[0].width  = image[0].originalWidth * ratio;
		image[0].height = image[0].originalHeight * ratio;
		widths.push(Math.round(image[0].originalWidth * ratio));
		totalWidth += Math.round(image[0].originalWidth * ratio);
		$("a.toggle", this).css({marginLeft: (image[0].originalWidth * ratio) - 91});
	});
	$("#collectie").width(totalWidth);
	
	// Toon het huidige item:
	startPos = ($(window).width() / 2) - 512;
	
	if(directLoad != false)
	{
		// Dit gedeelte wordt alleen maar uitgevoerd als de pagina met en andere hash-tag begint dan
		// een collectie-hash tag. In dat geval moet namelijk content geladen worden:
		currentItem = 1;
		showContentHolder(directLoad);
		directLoad = false;
	} else {
		// Normale gang van zaken
		positionCollection(false);
	}
}


// Functie die checkt of alle afbeeldingen geladen zijn:
function checkIfImagesAreLoaded()
{
	intervalCounter++;
	
	if (intervalCounter == 50) {
		clearInterval(intervalID);
		// Initialiseren als alle afbeelingen zijn geladen:
		$("#loader").fadeOut(function(){
			recalculateCollection();
			initialize();
			$("#collectie div.item").fadeIn();
			// Bij window resize, de collectie goed positioneren:
			$(window).resize(recalculateCollection);
			// Interval voor de vorige- en volgende buttons:
			intervalID = setInterval("checkHashTags()", 250);
		});
	}
    $("#collectie div.item[rel=collectie]").each(function(){
		var img = $("img", this)[0];
		if(imageIsLoaded(img))
		{
			if(!$(this).hasClass("loaded"))
            {
                $(this).addClass("loaded");
                itemsLoaded++;
                $(this).show();
                img.originalWidth = img.width;
                img.originalHeight = img.height;
                // $(img).css({opacity: .3});
                $(this).hide();
                $("#loader span").text(Math.ceil((itemsLoaded / totalItems) * 100) + ' %');
                if(itemsLoaded == totalItems) {
                    clearInterval(intervalID);
                    // Initialiseren als alle afbeelingen zijn geladen:
                    $("#loader").fadeOut(function(){
                        recalculateCollection();
                        initialize();
                        $("#collectie div.item").fadeIn();
                        // Bij window resize, de collectie goed positioneren:
                        $(window).resize(recalculateCollection);
                        // Interval voor de vorige- en volgende buttons:
                        intervalID = setInterval("checkHashTags()", 250);
                    });
                }
            }
		}
	});
}

// Functie die gebruikt wordt door voorgaande functie:
function imageIsLoaded(img) {
    if (!img.complete) {
		return false;
	}
    if (typeof img.naturalWidth != "undefined" && img.naturalWidth == 0) {
        return false;
    }
    // No other way of checking: assume it’s ok.
    return true;
}

// Functie om de vorige- en volgende buttons te ondersteunen:
function checkHashTags()
{
	if(currentHash != window.location.hash)
	{
		currentHash = window.location.hash;
		a = window.location.hash.split('/');
		var action = a[1];
		var id     = a[2];
		switch(action)
		{
			case 'collectie' :
				{
					currentItem = id;
					hideContentHolder();
					// positionCollection();
					break;
				}
			default :
				{
					showContentHolder('/' + action + '/');
					break;
				}
		}
	}
}

// Voer JavaScript uit adhv een specifieke URL:
var topOffset;

function initializeJavaScript(url)
{
	switch(url)
	{
		case '/brand/' :
		case '/disclaimer/' :
		case '/gentiluomo-brands/' :
		case '/corporate-fashion-and-private-branding/' :
		case '/retail/' :
		case '/history/' :		
			{
				Cufon.replace("#holder h1, #holder h2, #holder h3");
				rearangeInner();
                $("#holder div.content").css({width: 445});
				$("#holder div.content").jScrollPane({showArrows: true});
				break;
			}
		case '/contact/' :
			{
				$("div.contact div.left a").click(function(){
					$("div.contact a").removeClass("active");
					$(this).addClass("active");
					$("div.contact div.right h1.choose").hide();
					$("div.contact div.right div").hide();
					$("div.contact div.right #" + $(this).attr("rel")).fadeIn();
					return false;
				});
				rearangeInner();
				Cufon.replace("#holder h1, #holder h2, #holder h3");
				$("div.left ul a").click();
				break;
			}
		case '/store-locator/' :
			{
				$("ul.country a").click(function(){
					$("ul.country a").removeClass("active");
					$(this).addClass("active");
					$("ul.plaats li").hide();
					$("ul.plaats").css({marginTop: 0});
					topOffset = 0;
					$("div.container, ul.plaats li[rel=" + $(this).attr("rel") + "]").show();
					$("ul.plaats a").removeClass("active");
					$("a.up, a.down").show();
					$("#holder div.container").height($(window).height() * 0.4);
					var top = parseInt($("#holder div.inner div.left").css("margin-top"));
					$("a.up").css({top: top - 50, opacity: .25});
					$("a.down").css({top: top + parseInt($("div.container").height()) + 15});
					return false;
				});
				$("ul.plaats a").click(function(){
					$("ul.plaats a").removeClass("active");
					$(this).addClass("active");
					$("div.stores div.right h1.choose").hide();
					$("div.stores div.right div").hide();
					$("div.stores div.right div[rel=" + $(this).attr("rel") + "]").fadeIn();
					return false;
				});
				$("a.up").click(function(){
					topOffset -= parseInt($("#holder div.container").height() * 0.5);
					if(topOffset <= 0) {
						topOffset = 0;
						$("a.up").stop().animate({opacity: .25}).css({cursor: "default"});
					} 
					$("a.down").stop().animate({opacity: 1}).css({cursor: "pointer"});					
					$("ul.plaats").stop().animate({marginTop: -topOffset});
					return false;
				});
				$("a.down").click(function(){
					topOffset += parseInt($("#holder div.container").height() * 0.5);
					if(topOffset >= parseInt($("ul.plaats").height()) - parseInt($("div.container").height()))
					{
						topOffset = parseInt($("ul.plaats").height()) - parseInt($("div.container").height());
						$("a.down").stop().animate({opacity: .25}).css({cursor: "default"});
					}
					$("a.up").stop().animate({opacity: 1}).css({cursor: "pointer"});
					$("ul.plaats").stop().animate({marginTop: -topOffset});
					return false;
				});
				Cufon.replace("#holder h1, #holder h2, #holder h3");
				// Nederland standaard activeren:
				rearangeInner();
				topOffset = 0;
				$("ul.plaats li, a.up, a.down").hide();
				$("ul.country a[rel=nederland]").click();
				break;
			}
	}
}

function rearangeInner()
{
	$("#holder div.inner div.left, #holder div.inner div.right").css({marginTop: $(window).height() * 0.2});
	// Set the scrollPane:
	
}



// Slides, voor als er een slideshow is in de #holder:
var currentSlide;
var totalSlides;
var slideWidths;

function setupSlides()
{
	totalSlides = $("#slideshow div.slide").length;
	slideWidths = [];
	currentSlide = 1;
	$("#slideshow a.next").click(function(){
		moveSlide(1);
		return false;
	});
	$("#slideshow a.prev").click(function(){
		moveSlide(-1);
		return false;
	});
	// Breedte van de slideshow instellen:
	var slideshowWidth = 0;
	$("#slideshow div.slide").each(function(){
		slideWidths.push($(this).width());
		slideshowWidth += $(this).width();
	});
	$("#slideshow").width(slideshowWidth);
	// Stel de breedte van de eerste slide in:
	moveSlide(0);
	// Maak de achtergrond van de holder zwart ipv de standaard streepjes:
	$("#holder").addClass("black");
	/*
	$("#slideshow div.info").each(function(){
		var offset = $(this).height();
		$(this).css({marginTop: -(offset / 2)});
	});
	*/
}


function moveSlide(amount)
{
	
	currentSlide += amount;
	if(currentSlide > totalSlides) { currentSlide = totalSlides; } 
	if(currentSlide < 1) { currentSlide = 1; }
	// Animeren:
	var offset = 0;
	for(i=0; i<currentSlide-1; i++)
	{
		offset += slideWidths[i];
	}
	// offset -= (705 - slideWidths[currentSlide-1]) / 2;
	$("#slideshow").stop().animate({marginLeft: -offset});
	// Buitenste kaders animeren:
	// Geef het huidige item een rechtermarge van dezelfde breedte als de slide pixels, zodat de contentholder zichtbaar wordt:
	$("#collectie div.item:eq(" + currentItem + ")").stop().animate({marginRight: slideWidths[currentSlide-1]});
	// Animeer de #collectie:
	// var leftPos = startPos - slideWidths[currentSlide-1]; // + ((705 - widths[currentItem - 1]) / 3);
	
	// var leftPos = parseInt($("#collectie").css("left")) - slideWidths[currentSlide-1] - ((705 - slideWidths[currentSlide-1]) / 2) + 12;
	/*
	var leftPos = startPos;
	if(currentItem > 0)
	{
		for(i=0; i<currentItem; i++)
		{
			leftPos -= widths[i];
		}
	}
	leftPos -= (slideWidths[currentSlide - 1] - 705) - 12;
	*/
	
	var leftPos = startPos;
	// Positie juist instellen:
	for(i=0; i<currentItem; i++)
	{
		leftPos -= $("#collectie div.item:eq(" + i + ")").width();
	}
	// Nu lijnt alles links uit. Berekening uitvoeren dat alles gecentreerd wordt:
	leftPos += 500;
	var item = $("#collectie div.item:eq(" + currentItem + ")");
	leftPos -= item.width() / 2;
	// Rekening houden met de breedte:
	leftPos -= slideWidths[currentSlide - 1] + ((parseInt(item.width()) - slideWidths[currentSlide - 1]) / 2) - 13;
	
	
	
	// leftPos += (705 - slideWidths[currentSlide-1]);
	// leftPos += 367 - ((705 - (slideWidths[currentSlide-1])) / 2);
	
	$("#collectie").stop().animate({left: leftPos}, function(){
		// Switch z-index:
		$("#holder").css({zIndex: 2});
		$("#collectie").css({zIndex: 1});
	});
	// Animeer de #holder:
	$("#holder").stop().animate({width: slideWidths[currentSlide-1], marginLeft: -352 + ((705 - slideWidths[currentSlide-1]) / 2)});
	
}

