$(function() {
	
	if ($(window).width() >= 1280) {
		$("html").addClass("s1280");

		$("#items").find("script").remove();
		$("#contentWrapper #bookWrapper").after($("#items"));

		$("#catalog").find("script").remove();		
		$("#catalog").find(".banner").each(function() {
			if ($(this).find("*").length <= 0) {
				$(this).remove();
			}
		});
		
		$catalog = $("<div class=\"columnsAll\"></div>");
		$("#catalog").prepend($catalog);
		$("#catalog .column").find("section.category, div.banner").each(function() {
			$catalog.append($(this));
		});
		$catalog.masonry();
		
		
	}
});

/**
  * Alert configuration
**/
$(function() {
	$.alerts.overlayOpacity = 0.75;
	$.alerts.overlayColor = "#000";
});


Shadowbox.init({
	language: 'nl',
	displayNav: true,
	fadeDuration: 0,
	animateFade: false,
	animate: false,
	overlayOpacity: 0.6,
	players:  ['img', 'html', 'iframe', 'qt', 'wmp', 'swf', 'flv'],
	showOverlay: true,
	width: 680,
	onOpen: function() {
	},
	onClose: function() {
	}
});

function openPopup(url) {
	Shadowbox.open({
		content:	"<div id=\"shadowboxClose\" class=\"main\"></div><div class=\"iframeMain\"><iframe src=\"" + url + "\" id=\"shadowboxFrame\" width=\"949\" height=\"564\" class=\"main\" frameborder=\"0\"></iframe></div>",
		player:		"html",
		height:		600,
		width:		980,
		handleOversize: "none",
		options: {
			showOverlay: true
		}
	});
}

$(function() {
	$("a[rel='shadowbox']").click(function() {
		openPopup($(this).attr("href"));
		return false;
	});
});

// Text scroller
$(function() {
	$("nav#textTicker ul").liScroll({travelocity: 0.05});
});


$(function() {

	$("div#content object, div#content embed").attr("name", "geenInspiratie");
		
	$.history.init(historyCallback, { unescape: "/=" });
});


function historyCallback(hash) {
	if(hash == "") {
		// initialize your app
	} else {

		arrVars = hash.split("/");
		for (var i = 0; i < arrVars.length; i++) {

			if (arrVars[i] == "home") {
				// Home
				return false;
			}

			var valArr = arrVars[i].split("=");
			if (valArr.length == 2) {
				switch (valArr[0]) {
					case "wereld":
						document['geenInspiratie'].SetVariable("_root.thema", valArr[1]);
						// alert(valArr[1]);
						break;
					case "boek":
						document['geenInspiratie'].SetVariable("_root.selectedMagazine", valArr[1]);
						break;
				}
			}
			
		}
		if (document['geenInspiratie']) {
			document['geenInspiratie'].SetVariable("_root.functionVar", "trigger");
		}
		return false;
	}
}

function getTrigger() {
	var hash = (window.location.hash).replace(/^#/, '');
	try {
		hash =  $.browser.mozilla ? hash : decodeURIComponent(hash);
	}
	catch (error) {
	}
	historyCallback(hash);
}

$(function() {
	// Fix margins for aside images
	 $("div.block div.itemImage:nth-child(2n)").css({"margin": 0});

	// Toggle welInspiratieItemForm
	$("#directPlaatsen a").toggle(function() {
		$("#welInspiratieItemForm").slideDown();
		return false;
	}, function() {
		$("#welInspiratieItemForm").slideUp();
		return false;
	});

	// Detail images
	$("div.thumbnails div.thumb a").click(function() {
		$div = $("div.fullImage");
		$div.find("img").slideUp().remove();
		$div.append("<img src=\"" + $(this).attr("href") + "\">");
		return false;
	});

	// Scroll to top
	$("#toTop").click(function() {
		$.scrollTo(0, 800);
		return false;
	});

	// Print
	$("#iconPrint").click(function() {
		window.print();
		return false;
	});

});


// Toon laatste tweets
$(function(){
	$(".tweet").tweet({
		username: "geeninspiratie",
		join_text: null,
		count: 1,
		loading_text: "Laatste tweets laden..."
	});
});

// Fisheye - dock
$(function() {
	$("#imageTicker").Fisheye({
			maxWidth: 80,
			items: 'div',
			itemsText: 'span',
			container: '.fisheye',
			itemWidth: 70,
			proximity: 60,
			halign : 'center',
			valign: 'top',
			alignment : 'left'
		});
});


// Slideshow
$(function() {
	$('#scrollerWrapper .slideshow').each(function(index){
		var $pArr = $(this).find(" div.slideImg");
		var pArrLen = $pArr.length;
		var pPerDiv = 3;
		for (var i = 0; i < pArrLen; i += pPerDiv){
			$pArr.filter(':eq('+i+'),:lt('+(i+pPerDiv)+'):gt('+i+')').wrapAll('<div class=\"slide\">');
		}
		
		$cycle = $(this).parent(".cycle");
		$cycle.find(".page").addClass("page" + index);
		$cycle.find(".next").addClass("next" + index);
		$cycle.find(".prev").addClass("prev" + index);
		$(this).cycle({ 
			fx:     'scrollHorz', 
			speed:   900, 
			timeout: 8000, 
			pager:  '.page' + index,
			next:	'.next' + index,
			prev:   '.prev' + index,
			
			cleartype: true,
			cleartypeNoBg: true	
		});
	});


	$cycle = $("div.adFull .slideshow");
	var numThumbs = $cycle.find(".thumb").length;
	$cycle.attr("data-num_thumbs", numThumbs);
	$cycle.attr("data-current_thumb", 0);
	$prev = $("div.adFull div.thumbnails a.prev");
	$next = $("div.adFull div.thumbnails a.next");

	$prev.click(function() {
		if ($cycle.attr("data-current_thumb") > 0) {
			$cycle.stop(true, true).animate({
				"left": $cycle.position().left + 82
			});
			$cycle.attr("data-current_thumb", $cycle.attr("data-current_thumb") - 1);
		}
		return false;
	});
	$next.click(function() {
		if ($cycle.attr("data-current_thumb") < $cycle.attr("data-num_thumbs") - 4) {
			$cycle.stop(true, true).animate({
				"left": $cycle.position().left - 82
			});
			$cycle.attr("data-current_thumb", $cycle.attr("data-current_thumb") - -1);
		}
		return false;
	});
	if (numThumbs <= 4) {
		$prev.hide();
		$next.hide();
	}


});

// Animerende wolken 
function resizeClouds() {
	$("#clouds").width($(window).width());
}
$(window).bind("resize load", function() {
	resizeClouds();
});

$(function() {
	animateCloud1();
	animateCloud2();
	animateCloud3();
});
function animateCloud1() {
	var $cloud = $("#cloud1");
	$cloud.animate({
		left: -$cloud.width()
	}, 365000, "linear", function() {
			$(this).css({
				left: $(window).width() + 100
			});
			animateCloud1();
	});
}
function animateCloud2() {
	var $cloud = $("#cloud2");
	$cloud.animate({
		left: -$cloud.width()
	}, 100000, "linear", function() {
			$(this).css({
				left: $(window).width() + 100
			});
			animateCloud2();
	});
}
function animateCloud3() {
	var $cloud = $("#cloud3");
	$cloud.animate({
		left: -$cloud.width()
	}, 75000, "linear", function() {
			$(this).css({
				left: $(window).width() + 100
			});
			animateCloud3();
	});
}



// Mijn magazine
$(function() {
	$("#iconMagazine").click(function() {

		var $link = $(this);

		if ($(this).hasClass("favDisabled")) {

			return false;

		} else if ($(this).hasClass("delete")) {
			
				$.get($.actual.serverpad + "pageid=54/_ac=deleteproduct/prid=" + $.actual.productid, function() {
					jAlert("Het product is uit je magazine verwijderd", "Verwijderd uit eigen magazine");

					var img = new Image();
					img.onload = function() {
						linkImg.attr("src", addImage);
						linkImg.attr("title", "toevoegen aan favorieten");
						linkImg.attr("alt", "toevoegen aan favorieten");
						$link.removeClass("delete")
					};
					img.src = addImage;
					
				});

		} else {
		
			$.get($.actual.serverpad + "pageid=54/_ac=addproduct/prid=" + $.actual.productid, function(xml) {

				
				var loggedIn = $(xml).find("geenInspiratie>loggedin").attr("value") == "false" ? false : true;

				jAlert("Deze advertentie is toegevoegd in je eigen magazine", "Plaats in eigen magazine");

				var img = new Image();
				if (loggedIn) {
					img.onload = function() {
						linkImg.attr("src", deleteImage);
						linkImg.attr("title", "verwijderen uit favorieten");
						linkImg.attr("alt", "verwijderen uit favorieten");
						$link.addClass("delete");
					};
					img.src = deleteImage;
				} else {
					img.onload = function() {
						linkImg.attr("src", disabledImage);						
						linkImg.attr("title", "dit product staat al in je favorieten");
						linkImg.attr("alt", "dit product staat al in je favorieten");
						$link.addClass("favDisabled");
					};
					img.src = disabledImage;
				}

			});
		}
	});


	$("#mijnMagazineLink img").hover(function() {
		$(this).stop().animate({ height: 126}, "medium");
	}, function() {
		$(this).stop().animate({ height: 60}, "medium");
	});

});

// Plaats alle advertenties op de juiste manier in het boek
function mason() {
	// Masonry
	$bookPage = $("#bookOverview .page");
	if (($bookPage).length > 0) {

		if ($bookPage.find("div.ad").length <= 0) {			
			$("#bookOverview").removeClass("loading");
		} else {

			$bookPage.masonry({ columnWidth: 128 }, function() {

				// Scrolling
				$bookOverview = $("#bookOverview");
				$page = $("#bookOverview div.page");

				$("#paging a.next").click(function() {
					$bookOverview.stop(false, true).scrollTo({top: "+=" + paging.bookHeight / 3, left: 0}, 200, { onAfter: alterPage });
					return false;
				});
				$("#paging a.prev").click(function() {
					$bookOverview.stop(false, true).scrollTo({top: "-=" + paging.bookHeight / 3, left: 0}, 200, { onAfter: alterPage });
					return false;
				});
				$paging = $("#paging .pages");
				for (var i = 0; i < $bookOverview.find(".page").height() / paging.bookHeight; i++) {
					$("<div class=\"page\"></div>").appendTo($paging).html(i + 1).attr("data-number", i).click(function() {
						pagingClick($(this));
						return false;
					});
				}

				pagingClick($paging.find(":nth-child(1)"));

				
				$("#bookOverview").removeClass("loading");

				$scrollbar = $("<div id=\"scrollbar\"></div>").appendTo($bookOverview);
				$scrollbarScroller = $("<div id=\"scrollbarScroller\"></div>").appendTo($scrollbar);
				$scrollbarScroller.append("<div class=\"top\"></div>").append("<div class=\"scroll\"></div>").append("<div class=\"bottom\"></div>");

				paging.scrollerHeight = (paging.bookHeight / $page.height()) * paging.bookHeight;
				$scrollbarScroller.height(paging.scrollerHeight);
				if (paging.scrollerHeight > 480) {
					$scrollbarScroller.remove();
				}
				$scrollbarScroller.find(".scroll").height(paging.scrollerHeight - 8);

				$("#scrollbarScroller").draggable({ axis: "y", containment: "parent", drag: function(event, ui) {
					$bookOverview.scrollTop((ui.position.top / paging.bookHeight) * $page.height());
				}, stop: function(event, ui) {
					alterPage();
				} });

				$bookOverview.scroll(function() {
					var ratio = $bookOverview.scrollTop() / $page.height();
					$scrollbarScroller.css({ top: (ratio * paging.bookHeight) });
				});
				$bookOverview.mousewheel(function(event, delta) {
					if (delta > 0) {
						$("#paging a.prev").click();
					} else {
						$("#paging a.next").click();
					}
					return false;
				});

			});
		}
	}
}

var paging = {
	bookHeight: 480,
	currentPage: 0,
	scrollerHeight: 480
}
var $paging;

$(function() {
	// Bouw enige vertraing in voor het opbouwen van het boek
	window.setTimeout(mason, 1500);
});

// Scroll het boek aan de han van het pagina-nummer waarop is geklikt
function pagingClick($page) {
	paging.currentPage = $page.attr("data-number");

	$pages = $paging.find(".page");
	$paging.find("span").remove();
	$pages.removeClass("active").removeClass("visible");
	
	$page.addClass("active").addClass("visible");
		
	$pages.filter(function(index) {
		return index < 3 || index >= $pages.length - 3 || (index >= parseInt($page.attr("data-number")) - 2 && index <= parseInt($page.attr("data-number")) + 2);
	}).addClass("visible");
	$paging.find(".page:not(.visible) + .page.visible").before("<span>...</span>");
	
	$bookOverview.stop(false, true).scrollTo({top: $page.attr("data-number") * paging.bookHeight, left: 0 }, 800, {onAfter: lazyLoadImages });

	return false;
}

// Laat de afbeeldingen pas zien wanneer deze in de viewport zijn
function lazyLoadImages() {
	$mainPage = $("#bookOverview");
	var pageTop = $mainPage.scrollTop();
	var pageBottom = pageTop + 480;

	$("div.ad.loading").each(function() {

		var $ad = $(this);
		var adTop = parseInt($(this).css("top"));
		var adBottom = adTop + $(this).height();

		if ((adTop >= pageTop || adBottom >= pageTop) && adTop < pageBottom) {
			var $img = $(this).find("div.image");
			var src = $img.attr("data-image");

			if ($img.not(".loading")) {
				$img.addClass("loading");
				$("<img src=\"" + src + "\">").load(function() {
					$img.find("a").remove();
					$img.append("<a href=\"" + $ad.attr("data-url") + "\"><img src=\"" + src + "\"></a>").fadeIn("slow");
					$ad.removeClass("loading");
					$img.removeClass("loading");
				});
			}
		}
	});

}

// Pas de paging aan, aan de hand van de scroll-positie van het boek
function alterPage() {

	var newPage = Math.floor($bookOverview.scrollTop() / paging.bookHeight);
	if (newPage != paging.currentPage) {

		paging.currentPage = newPage;

		$pages = $paging.find(".page");
		$paging.find("span").remove();
		$pages.removeClass("active").removeClass("visible");

		var $page = $paging.find(".page[data-number=\"" + newPage + "\"]");
		
		$page.addClass("active").addClass("visible");
			
		$pages.filter(function(index) {
			return index < 3 || index >= $pages.length - 3 || (index >= parseInt($page.attr("data-number")) - 2 && index <= parseInt($page.attr("data-number")) + 2);
		}).addClass("visible");
		$paging.find(".page:not(.visible) + .page.visible").before("<span>...</span>");

		$.history.load("page=" + (newPage + 1));

	}

	lazyLoadImages();
}


// Blog 
$(function() {
	if ($("#blog").length > 0) {
		$.scrollTo($("#blog"), 800);
	}
});

// Placeholder
$(function() {
	$(":input[placeholder], textarea[placeholder]").placeholder();	
});
